From c250d97950accff7a98ff060868fb06048f8c4d8 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:38:28 -0700 Subject: [PATCH 001/586] fix: make showItemInFolder a no-op for a path with no file URL --- src/main/platform/macos/cocoa-shell.ts | 4 ++++ tests/integration/macos/cocoa-shell.test.ts | 12 ++++++------ 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/main/platform/macos/cocoa-shell.ts b/src/main/platform/macos/cocoa-shell.ts index 86b06c24..185a752b 100644 --- a/src/main/platform/macos/cocoa-shell.ts +++ b/src/main/platform/macos/cocoa-shell.ts @@ -52,6 +52,10 @@ export const showItemInFolder = (path: string): void => { rt.selectors.get('fileURLWithPath:'), nsString(path), ); + // arrayWithObject:nil raises and aborts the process; an empty path yields a nil URL. + if (fileUrl === 0n) { + return; + } const urls = msgSendPtr(rt.classes.get('NSArray'), rt.selectors.get('arrayWithObject:'), fileUrl); msgSendPtr(sharedWorkspace(), rt.selectors.get('activateFileViewerSelectingURLs:'), urls); }; diff --git a/tests/integration/macos/cocoa-shell.test.ts b/tests/integration/macos/cocoa-shell.test.ts index af7ccf4e..24e49916 100644 --- a/tests/integration/macos/cocoa-shell.test.ts +++ b/tests/integration/macos/cocoa-shell.test.ts @@ -1,16 +1,16 @@ import { describe, expect, test } from 'bun:test'; import { currentPlatform } from '../../../src/common/platform'; -import { beep, openExternal, showItemInFolder } from '../../../src/main/platform/macos/cocoa-shell'; +import { beep, openPath, showItemInFolder } from '../../../src/main/platform/macos/cocoa-shell'; if (currentPlatform() === 'macos') { describe('cocoa-shell', () => { - // Not invoked: openExternal pops a LaunchServices dialog, showItemInFolder opens Finder. - test('openExternal resolves as a callable FFI export', () => { - expect(typeof openExternal).toBe('function'); + // An empty path makes a nil NSURL; neither call may reach Finder or LaunchServices. + test('showItemInFolder("") is a no-op instead of aborting on a nil URL', () => { + expect(() => showItemInFolder('')).not.toThrow(); }); - test('showItemInFolder resolves as a callable FFI export', () => { - expect(typeof showItemInFolder).toBe('function'); + test('openPath("") reports failure', () => { + expect(openPath('')).toBe(false); }); test('beep does not throw', () => { From 5544edd20017d71183d110de572e2b67e9fb96b1 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:40:51 -0700 Subject: [PATCH 002/586] fix: read a compiled app's package.json from beside its executable --- src/main/api/app-environment.ts | 24 ++++++++++++++---- src/main/api/app-metadata.ts | 15 ++++++----- src/main/api/app.ts | 2 +- tests/unit/main/api/app-environment.test.ts | 28 +++++++++++++++++++++ 4 files changed, 57 insertions(+), 12 deletions(-) diff --git a/src/main/api/app-environment.ts b/src/main/api/app-environment.ts index e4e3a235..ce892b5b 100644 --- a/src/main/api/app-environment.ts +++ b/src/main/api/app-environment.ts @@ -2,7 +2,7 @@ import { readFileSync } from 'node:fs'; import { homedir, tmpdir } from 'node:os'; import { dirname } from 'node:path'; import { currentPlatform, type Platform } from '../../common/platform'; -import { findManifest, type Manifest, type ManifestReader } from './app-metadata'; +import { findManifest, type Manifest, type ManifestReader, readManifest } from './app-metadata'; import { normalizeLocale, parsePreferredLanguages } from './app-locale'; /** @@ -32,7 +32,7 @@ export type AppEnvironment = { readonly home: string; readonly temp: string; readonly execPath: string; - /** Directory of the nearest `package.json`, else cwd. */ + /** A compiled binary's own directory, else the nearest `package.json` directory, else cwd. */ readonly appPath: string; readonly env: Readonly>; readonly manifest: Manifest | undefined; @@ -61,18 +61,32 @@ const computePreferredLanguages = ( return normalizedLocale.length > 0 ? [normalizedLocale] : []; }; -export const buildAppEnvironment = (deps: EnvironmentDeps): AppEnvironment => { +/** A `bun build --compile` binary runs its entry from Bun's embedded filesystem. */ +const COMPILED_ENTRY = /^(?:\/\$bunfs\/|[A-Za-z]:[\\/]~BUN[\\/])/; + +const locateApp = (deps: EnvironmentDeps): { dir: string; manifest: Manifest | undefined } => { + if (COMPILED_ENTRY.test(deps.mainScript)) { + // The build ships assets and package.json beside the binary; walking above it + // would adopt whatever package.json the install location happens to sit under. + const dir = dirname(deps.execPath); + return { dir, manifest: readManifest(dir, deps.readFile) }; + } const startDir = deps.mainScript.length > 0 ? dirname(deps.mainScript) : deps.cwd; const found = findManifest(startDir, deps.readFile); + return { dir: found?.dir ?? deps.cwd, manifest: found?.manifest }; +}; + +export const buildAppEnvironment = (deps: EnvironmentDeps): AppEnvironment => { + const app = locateApp(deps); const locale = normalizeLocale(deps.locale); return { platform: deps.platform, home: deps.home, temp: deps.temp, execPath: deps.execPath, - appPath: found?.dir ?? deps.cwd, + appPath: app.dir, env: deps.env, - manifest: found?.manifest, + manifest: app.manifest, locale, preferredLanguages: computePreferredLanguages(deps.env, locale), isPackaged: computeIsPackaged(deps.execPath), diff --git a/src/main/api/app-metadata.ts b/src/main/api/app-metadata.ts index 51f9f7f3..66362951 100644 --- a/src/main/api/app-metadata.ts +++ b/src/main/api/app-metadata.ts @@ -47,6 +47,12 @@ const parseManifest = (contents: string): Manifest | undefined => { }; }; +/** The PARSEABLE `package.json` in `dir`, else `undefined`. */ +export const readManifest = (dir: string, read: ManifestReader): Manifest | undefined => { + const contents = read(join(dir, 'package.json')); + return contents === undefined ? undefined : parseManifest(contents); +}; + /** * The first directory at or above `startDir` with a PARSEABLE `package.json`; * a malformed manifest is skipped and the walk continues upward. @@ -54,12 +60,9 @@ const parseManifest = (contents: string): Manifest | undefined => { export const findManifest = (startDir: string, read: ManifestReader): FoundManifest | undefined => { let dir = startDir; for (;;) { - const contents = read(join(dir, 'package.json')); - if (contents !== undefined) { - const manifest = parseManifest(contents); - if (manifest !== undefined) { - return { dir, manifest }; - } + const manifest = readManifest(dir, read); + if (manifest !== undefined) { + return { dir, manifest }; } const parent = dirname(dir); if (parent === dir) { diff --git a/src/main/api/app.ts b/src/main/api/app.ts index 11405169..3060e5d2 100644 --- a/src/main/api/app.ts +++ b/src/main/api/app.ts @@ -140,7 +140,7 @@ export class App extends EventEmitter { this.#userAgentFallback = value; } - /** The nearest directory with a `package.json`, else cwd. */ + /** A compiled binary's own directory, else the nearest `package.json` directory, else cwd. */ getAppPath(): string { return this.#environment().appPath; } diff --git a/tests/unit/main/api/app-environment.test.ts b/tests/unit/main/api/app-environment.test.ts index b1857392..81db6b73 100644 --- a/tests/unit/main/api/app-environment.test.ts +++ b/tests/unit/main/api/app-environment.test.ts @@ -52,6 +52,34 @@ describe('buildAppEnvironment — manifest & appPath', () => { }); }); +describe('buildAppEnvironment - compiled binary', () => { + const exeDir = '/Applications/Demo.app/Contents/MacOS'; + const compiled = (files: Record): AppEnvironment => + build({ + execPath: `${exeDir}/Demo`, + mainScript: '/$bunfs/root/Demo', + cwd: '/', + readFile: (path) => files[slash(path)], + }); + + test('reads the package.json beside the executable', () => { + const env = compiled({ + [`${exeDir}/package.json`]: JSON.stringify({ productName: 'Demo', version: '1.2.0' }), + }); + expect(env.manifest?.productName).toBe('Demo'); + expect(env.manifest?.version).toBe('1.2.0'); + }); + + test('uses the executable directory as appPath', () => { + expect(slash(compiled({}).appPath)).toBe(exeDir); + }); + + test('never adopts a package.json above the executable directory', () => { + const env = compiled({ '/Applications/package.json': JSON.stringify({ version: '9.9.9' }) }); + expect(env.manifest).toBeUndefined(); + }); +}); + describe('buildAppEnvironment — locale & languages', () => { test('normalizes the raw locale', () => { expect(build({ locale: 'en_US.UTF-8' }).locale).toBe('en-US'); From 7fae17a9d6e11892fd5c31eb9dd513d00f2dc23f Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:41:12 -0700 Subject: [PATCH 003/586] fix: keep menu items with enabled false disabled under autoenabling --- src/main/platform/macos/cocoa-menu.ts | 25 +++++--- tests/integration/macos/cocoa-menu.test.ts | 72 +++++++++++++++++----- 2 files changed, 76 insertions(+), 21 deletions(-) diff --git a/src/main/platform/macos/cocoa-menu.ts b/src/main/platform/macos/cocoa-menu.ts index 8fe45ba7..966b8943 100644 --- a/src/main/platform/macos/cocoa-menu.ts +++ b/src/main/platform/macos/cocoa-menu.ts @@ -5,6 +5,7 @@ import { msgSendPtr3, msgSendPtrPointPtrReturnsU8, msgSendReturnsI64, + msgSendReturnsU8, msgSendU8, } from './cocoa-msgsend-variants'; import { cocoa } from './cocoa-runtime'; @@ -63,6 +64,14 @@ const ensureTarget = (): Handle => { clickRegistry.get(sender)?.(); }, }, + { + // AppKit autoenabling overwrites setEnabled: with this answer on every menu update. + selector: 'validateMenuItem:', + typeEncoding: 'c@:@', + args: ['object'], + returns: 'bool', + impl: (_self, _cmd, item) => msgSendReturnsU8(item, rt.selectors.get('isEnabled')), + }, ]); sharedTarget = rt.msgSend( rt.msgSend(targetClass, rt.selectors.get('alloc')), @@ -81,12 +90,14 @@ const realizeItem = (spec: NativeMenuItemSpec): Handle => { // A role item's action is the native first-responder selector with a NIL target, // so AppKit routes it up the responder chain (no BunmaskaMenuTarget / clickRegistry). const isRole = spec.roleSelector !== undefined; - const hasClick = !isRole && (spec.type === 'normal' || checkable) && spec.onClick !== undefined; - const action = isRole - ? rt.selectors.get(spec.roleSelector as string) - : hasClick - ? rt.selectors.get('bunmaskaMenuAction:') - : 0n; + const targeted = !isRole && (spec.type === 'normal' || checkable); + // A nil action is the only way to keep a responder-chain role disabled under autoenabling. + const action = + isRole && spec.enabled + ? rt.selectors.get(spec.roleSelector as string) + : targeted + ? rt.selectors.get('bunmaskaMenuAction:') + : 0n; const item = msgSendPtr3( rt.msgSend(rt.classes.get('NSMenuItem'), rt.selectors.get('alloc')), rt.selectors.get('initWithTitle:action:keyEquivalent:'), @@ -95,7 +106,7 @@ const realizeItem = (spec: NativeMenuItemSpec): Handle => { nsString(spec.keyEquivalent), ); - if (hasClick) { + if (targeted) { msgSendPtr(item, rt.selectors.get('setTarget:'), ensureTarget()); if (spec.onClick !== undefined) { clickRegistry.set(item, spec.onClick); diff --git a/tests/integration/macos/cocoa-menu.test.ts b/tests/integration/macos/cocoa-menu.test.ts index 2a721878..7782c060 100644 --- a/tests/integration/macos/cocoa-menu.test.ts +++ b/tests/integration/macos/cocoa-menu.test.ts @@ -1,16 +1,38 @@ -import { describe, expect, test } from 'bun:test'; +import { beforeAll, describe, expect, test } from 'bun:test'; import { currentPlatform } from '../../../src/common/platform'; -import { msgSendI64 } from '../../../src/main/platform/macos/cocoa-msgsend-variants'; -import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; import { menuItemCount, + type NativeMenuItemSpec, performMenuItem, realizeMenu, setApplicationMenu, } from '../../../src/main/platform/macos/cocoa-menu'; +import { + msgSendI64, + msgSendReturnsU8, +} from '../../../src/main/platform/macos/cocoa-msgsend-variants'; +import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; +import type { Handle } from '../../../src/main/platform/macos/objc'; + +/** Realize one item and run AppKit's autoenable pass, as opening the menu or a key press does. */ +const realizeAndValidate = (spec: NativeMenuItemSpec): { menu: Handle; item: Handle } => { + const rt = cocoa(); + const menu = realizeMenu([spec]); + rt.msgSend(menu, rt.selectors.get('update')); + return { menu, item: msgSendI64(menu, rt.selectors.get('itemAtIndex:'), 0n) }; +}; + +const isEnabled = (item: Handle): boolean => + msgSendReturnsU8(item, cocoa().selectors.get('isEnabled')) === 1; if (currentPlatform() === 'macos') { describe('cocoa-menu', () => { + // performActionForItemAtIndex: dispatches through NSApp; without it nothing fires. + beforeAll(() => { + const rt = cocoa(); + rt.msgSend(rt.classes.get('NSApplication'), rt.selectors.get('sharedApplication')); + }); + test('realizeMenu builds a menu whose item count matches the spec', () => { const menu = realizeMenu([ { label: 'One', type: 'normal', enabled: true, keyEquivalent: '' }, @@ -61,23 +83,45 @@ if (currentPlatform() === 'macos') { expect(fired).toEqual(['beta', 'alpha']); }); - test('a disabled item does not fire when performed', () => { + test('a disabled item stays disabled through autoenable and does not fire', () => { let fired = false; - const menu = realizeMenu([ - { - label: 'Nope', - type: 'normal', - enabled: false, - keyEquivalent: '', - onClick: () => { - fired = true; - }, + const { menu, item } = realizeAndValidate({ + label: 'Save', + type: 'normal', + enabled: false, + keyEquivalent: 's', + modifierMask: 1n << 20n, + onClick: () => { + fired = true; }, - ]); + }); + expect(isEnabled(item)).toBe(false); performMenuItem(menu, 0); expect(fired).toBe(false); }); + test('a role item with enabled:false stays disabled through autoenable', () => { + const { item } = realizeAndValidate({ + label: 'Quit', + type: 'normal', + enabled: false, + keyEquivalent: 'q', + role: 'quit', + roleSelector: 'terminate:', + }); + expect(isEnabled(item)).toBe(false); + }); + + test('an enabled item without a click handler renders enabled', () => { + const { item } = realizeAndValidate({ + label: 'Info', + type: 'normal', + enabled: true, + keyEquivalent: '', + }); + expect(isEnabled(item)).toBe(true); + }); + test('a submenu is realized with its own items', () => { const rt = cocoa(); const menu = realizeMenu([ From 98bd449b9305794e6e7db34e4ac2dff75c705658 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:41:25 -0700 Subject: [PATCH 004/586] fix: give bare-key menu accelerators no modifier on macOS --- src/main/platform/macos/cocoa-menu.ts | 6 +++--- tests/integration/macos/cocoa-menu.test.ts | 11 +++++++++++ 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/src/main/platform/macos/cocoa-menu.ts b/src/main/platform/macos/cocoa-menu.ts index 966b8943..b19834a5 100644 --- a/src/main/platform/macos/cocoa-menu.ts +++ b/src/main/platform/macos/cocoa-menu.ts @@ -31,7 +31,7 @@ export type NativeMenuItemSpec = { readonly checked?: boolean; /** Single-character key equivalent (e.g. `'q'`), or `''` for none. */ readonly keyEquivalent: string; - /** `NSEventModifierFlags` mask for the key equivalent; absent ⇒ AppKit default (Command). */ + /** `NSEventModifierFlags` mask for the key equivalent; absent means no modifiers. */ readonly modifierMask?: bigint; /** A predefined role name (the item's behavior is native, not a JS click). */ readonly role?: string; @@ -115,8 +115,8 @@ const realizeItem = (spec: NativeMenuItemSpec): Handle => { // Apply the explicit modifier mask so multi-modifier accelerators (e.g. redo's // Shift+Cmd+Z) don't collapse to AppKit's Command-only default. - if (spec.modifierMask !== undefined && spec.keyEquivalent !== '') { - msgSendI64(item, rt.selectors.get('setKeyEquivalentModifierMask:'), spec.modifierMask); + if (spec.keyEquivalent !== '') { + msgSendI64(item, rt.selectors.get('setKeyEquivalentModifierMask:'), spec.modifierMask ?? 0n); } if (checkable) { diff --git a/tests/integration/macos/cocoa-menu.test.ts b/tests/integration/macos/cocoa-menu.test.ts index 7782c060..64d0381e 100644 --- a/tests/integration/macos/cocoa-menu.test.ts +++ b/tests/integration/macos/cocoa-menu.test.ts @@ -9,6 +9,7 @@ import { } from '../../../src/main/platform/macos/cocoa-menu'; import { msgSendI64, + msgSendReturnsI64, msgSendReturnsU8, } from '../../../src/main/platform/macos/cocoa-msgsend-variants'; import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; @@ -122,6 +123,16 @@ if (currentPlatform() === 'macos') { expect(isEnabled(item)).toBe(true); }); + test('a bare-key accelerator carries no Command modifier', () => { + const { item } = realizeAndValidate({ + label: 'Search', + type: 'normal', + enabled: true, + keyEquivalent: '/', + }); + expect(msgSendReturnsI64(item, cocoa().selectors.get('keyEquivalentModifierMask'))).toBe(0n); + }); + test('a submenu is realized with its own items', () => { const rt = cocoa(); const menu = realizeMenu([ From f76c5bc0358cf59b47e8091a1f238ccbed6a9e9e Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:41:28 -0700 Subject: [PATCH 005/586] fix: derive isPackaged from the compiled entry, not the runner name --- src/main/api/app-environment.ts | 12 +++--------- tests/unit/main/api/app-environment.test.ts | 18 ++++++++++++------ tests/unit/main/api/app.test.ts | 6 ++---- 3 files changed, 17 insertions(+), 19 deletions(-) diff --git a/src/main/api/app-environment.ts b/src/main/api/app-environment.ts index ce892b5b..0aca909c 100644 --- a/src/main/api/app-environment.ts +++ b/src/main/api/app-environment.ts @@ -44,11 +44,8 @@ export type AppEnvironment = { readonly relaunch: (execPath: string, args: string[]) => void; }; -/** Matches the dev-runner executables (`bun`, `bun-canary`, `node`). */ -const DEV_RUNNER = /[/\\](bun|bun-[^/\\]+|node)$/; - -/** Heuristic: a build is "packaged" unless it runs under the bun/node dev binary. */ -const computeIsPackaged = (execPath: string): boolean => !DEV_RUNNER.test(execPath); +/** A `bun build --compile` binary runs its entry from Bun's embedded filesystem. */ +const COMPILED_ENTRY = /^(?:\/\$bunfs\/|[A-Za-z]:[\\/]~BUN[\\/])/; const computePreferredLanguages = ( env: EnvironmentDeps['env'], @@ -61,9 +58,6 @@ const computePreferredLanguages = ( return normalizedLocale.length > 0 ? [normalizedLocale] : []; }; -/** A `bun build --compile` binary runs its entry from Bun's embedded filesystem. */ -const COMPILED_ENTRY = /^(?:\/\$bunfs\/|[A-Za-z]:[\\/]~BUN[\\/])/; - const locateApp = (deps: EnvironmentDeps): { dir: string; manifest: Manifest | undefined } => { if (COMPILED_ENTRY.test(deps.mainScript)) { // The build ships assets and package.json beside the binary; walking above it @@ -89,7 +83,7 @@ export const buildAppEnvironment = (deps: EnvironmentDeps): AppEnvironment => { manifest: app.manifest, locale, preferredLanguages: computePreferredLanguages(deps.env, locale), - isPackaged: computeIsPackaged(deps.execPath), + isPackaged: COMPILED_ENTRY.test(deps.mainScript), exit: deps.exit, relaunch: deps.relaunch, }; diff --git a/tests/unit/main/api/app-environment.test.ts b/tests/unit/main/api/app-environment.test.ts index 81db6b73..43663855 100644 --- a/tests/unit/main/api/app-environment.test.ts +++ b/tests/unit/main/api/app-environment.test.ts @@ -106,16 +106,22 @@ describe('buildAppEnvironment — isPackaged', () => { expect(build({ execPath: '/opt/homebrew/bin/bun' }).isPackaged).toBe(false); }); - test('is false when launched via node', () => { - expect(build({ execPath: '/usr/local/bin/node' }).isPackaged).toBe(false); + test('is false under bun.exe on Windows', () => { + const env = build({ + execPath: 'C:\\Users\\ada\\.bun\\bin\\bun.exe', + mainScript: 'C:\\proj\\src\\main.ts', + }); + expect(env.isPackaged).toBe(false); }); - test('is true inside a packaged macOS .app bundle', () => { - expect(build({ execPath: '/Applications/Demo.app/Contents/MacOS/Demo' }).isPackaged).toBe(true); + test('is true for a compiled binary', () => { + const env = build({ execPath: '/opt/demo/demo', mainScript: '/$bunfs/root/demo' }); + expect(env.isPackaged).toBe(true); }); - test('is true for a compiled standalone binary', () => { - expect(build({ execPath: '/opt/demo/demo' }).isPackaged).toBe(true); + test('is true for a compiled Windows binary', () => { + const env = build({ execPath: 'C:\\Demo\\demo.exe', mainScript: 'B:\\~BUN\\root\\demo.exe' }); + expect(env.isPackaged).toBe(true); }); }); diff --git a/tests/unit/main/api/app.test.ts b/tests/unit/main/api/app.test.ts index f4d4fae4..310b7dd3 100644 --- a/tests/unit/main/api/app.test.ts +++ b/tests/unit/main/api/app.test.ts @@ -309,10 +309,8 @@ describe('App.isPackaged', () => { expect(appWith({ execPath: '/opt/homebrew/bin/bun' }).isPackaged).toBe(false); }); - test('is true inside a packaged bundle', () => { - expect(appWith({ execPath: '/Applications/Demo.app/Contents/MacOS/Demo' }).isPackaged).toBe( - true, - ); + test('is true inside a compiled binary', () => { + expect(appWith({ mainScript: '/$bunfs/root/Demo' }).isPackaged).toBe(true); }); }); From 8df7496173381b240149fc19273bb97993cf76be Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:41:49 -0700 Subject: [PATCH 006/586] fix: drop the embedded entry path from compiled relaunch args --- src/main/api/app.ts | 3 ++- tests/unit/main/api/app.test.ts | 41 ++++++++++++++++++++++----------- 2 files changed, 30 insertions(+), 14 deletions(-) diff --git a/src/main/api/app.ts b/src/main/api/app.ts index 3060e5d2..acac24e5 100644 --- a/src/main/api/app.ts +++ b/src/main/api/app.ts @@ -268,7 +268,8 @@ export class App extends EventEmitter { relaunch(options?: { args?: string[]; execPath?: string }): void { const env = this.#environment(); const execPath = options?.execPath ?? env.execPath; - const args = options?.args ?? process.argv.slice(1); + // A compiled binary's argv[1] is its embedded entry, which Bun re-injects on launch. + const args = options?.args ?? process.argv.slice(env.isPackaged ? 2 : 1); env.relaunch(execPath, args); } diff --git a/tests/unit/main/api/app.test.ts b/tests/unit/main/api/app.test.ts index 310b7dd3..491876b6 100644 --- a/tests/unit/main/api/app.test.ts +++ b/tests/unit/main/api/app.test.ts @@ -315,19 +315,34 @@ describe('App.isPackaged', () => { }); describe('App.relaunch', () => { - test('relaunches with the env execPath and current args by default', () => { - const calls: Array<[string, string[]]> = []; - const a = new App(); - a.setEnvironmentForTesting( - fakeEnv({ - execPath: '/bin/myapp', - relaunch: (execPath, args) => { - calls.push([execPath, args]); - }, - }), - ); - a.relaunch(); - expect(calls).toEqual([['/bin/myapp', process.argv.slice(1)]]); + /** Relaunch with default args while `process.argv` is `argv`; returns the args passed on. */ + const relaunchArgs = (argv: string[], mainScript: string): string[] => { + const calls: string[][] = []; + const a = appWith({ mainScript, relaunch: (_execPath, args) => calls.push(args) }); + const saved = process.argv; + process.argv = argv; + try { + a.relaunch(); + } finally { + process.argv = saved; + } + return calls[0] ?? []; + }; + + test('keeps the script path under the dev runner', () => { + const argv = ['/opt/homebrew/bin/bun', '/proj/src/main.ts', '--flag']; + expect(relaunchArgs(argv, '/proj/src/main.ts')).toEqual(['/proj/src/main.ts', '--flag']); + }); + + test('drops the embedded entry path in a compiled binary', () => { + const argv = ['bun', '/$bunfs/root/Demo', '--flag']; + expect(relaunchArgs(argv, '/$bunfs/root/Demo')).toEqual(['--flag']); + }); + + test('relaunches with the env execPath', () => { + const calls: string[] = []; + appWith({ execPath: '/bin/myapp', relaunch: (execPath) => calls.push(execPath) }).relaunch(); + expect(calls).toEqual(['/bin/myapp']); }); test('honors execPath and args overrides', () => { From 415fb8a65059b7397809554bc530ceb5fb19ddde Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:42:16 -0700 Subject: [PATCH 007/586] fix: run the relaunch spawn before the Windows TerminateProcess hook --- src/main/api/app-environment.ts | 3 ++- tests/unit/main/api/app-environment.test.ts | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/main/api/app-environment.ts b/src/main/api/app-environment.ts index 0aca909c..e75a2070 100644 --- a/src/main/api/app-environment.ts +++ b/src/main/api/app-environment.ts @@ -111,7 +111,8 @@ export const defaultAppEnvironment = (): AppEnvironment => readFile: safeRead, exit: (code) => process.exit(code), relaunch: (execPath, args) => { - process.once('exit', () => { + // Prepended: the Windows backend's exit listener TerminateProcess-es (D043). + process.prependOnceListener('exit', () => { try { Bun.spawn({ cmd: [execPath, ...args], stdio: ['ignore', 'ignore', 'ignore'] }).unref(); } catch { diff --git a/tests/unit/main/api/app-environment.test.ts b/tests/unit/main/api/app-environment.test.ts index 43663855..bdfb73c3 100644 --- a/tests/unit/main/api/app-environment.test.ts +++ b/tests/unit/main/api/app-environment.test.ts @@ -2,6 +2,7 @@ import { describe, expect, test } from 'bun:test'; import { type AppEnvironment, buildAppEnvironment, + defaultAppEnvironment, type EnvironmentDeps, } from '../../../../src/main/api/app-environment'; @@ -150,3 +151,21 @@ describe('buildAppEnvironment — passthrough', () => { expect(calls).toEqual([['/bin/app', ['--flag']]]); }); }); + +describe('defaultAppEnvironment - relaunch', () => { + test('spawns ahead of exit listeners registered earlier', () => { + const earlier = (): void => undefined; + process.on('exit', earlier); + const before = new Set(process.listeners('exit')); + defaultAppEnvironment().relaunch('/bin/true', []); + const added = process.listeners('exit').filter((listener) => !before.has(listener)); + try { + expect(added).toHaveLength(1); + expect(process.listeners('exit')[0]).toBe(added[0]); + } finally { + for (const listener of [earlier, ...added]) { + process.removeListener('exit', listener); + } + } + }); +}); From 8e06b15e539d1e096805e75837235b3fb0c8cc05 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:42:19 -0700 Subject: [PATCH 008/586] fix: toggle checkbox and radio menu items on click on macOS --- src/main/platform/macos/cocoa-menu.ts | 41 ++++++++++++++++++---- tests/integration/macos/cocoa-menu.test.ts | 39 ++++++++++++++++++++ 2 files changed, 73 insertions(+), 7 deletions(-) diff --git a/src/main/platform/macos/cocoa-menu.ts b/src/main/platform/macos/cocoa-menu.ts index b19834a5..642007d6 100644 --- a/src/main/platform/macos/cocoa-menu.ts +++ b/src/main/platform/macos/cocoa-menu.ts @@ -45,11 +45,37 @@ export type NativeMenuItemSpec = { readonly onClick?: () => void; }; -const clickRegistry = new Map void>(); +const clickRegistry = new Map(); let targetClass: Handle | undefined; let sharedTarget: Handle | undefined; +const setState = (item: Handle, on: boolean): void => { + msgSendI64(item, cocoa().selectors.get('setState:'), on ? 1n : 0n); +}; + +/** Electron semantics: a checkbox flips; a radio turns on and clears its adjacent radios. */ +const toggleChecked = (item: Handle, type: 'checkbox' | 'radio'): void => { + const rt = cocoa(); + if (type === 'checkbox') { + setState(item, msgSendReturnsI64(item, rt.selectors.get('state')) === 0n); + return; + } + const menu = rt.msgSend(item, rt.selectors.get('menu')); + const index = Number(msgSendPtr(menu, rt.selectors.get('indexOfItem:'), item)); + const count = Number(msgSendReturnsI64(menu, rt.selectors.get('numberOfItems'))); + const at = (i: number): Handle => msgSendI64(menu, rt.selectors.get('itemAtIndex:'), BigInt(i)); + for (const step of [-1, 1]) { + for (let i = index + step; i >= 0 && i < count; i += step) { + if (clickRegistry.get(at(i))?.type !== 'radio') { + break; + } + setState(at(i), false); + } + } + setState(item, true); +}; + const ensureTarget = (): Handle => { if (sharedTarget !== undefined) { return sharedTarget; @@ -61,7 +87,11 @@ const ensureTarget = (): Handle => { typeEncoding: 'v@:@', args: ['object'], impl: (_self, _cmd, sender) => { - clickRegistry.get(sender)?.(); + const spec = clickRegistry.get(sender); + if (spec?.type === 'checkbox' || spec?.type === 'radio') { + toggleChecked(sender, spec.type); + } + spec?.onClick?.(); }, }, { @@ -108,9 +138,7 @@ const realizeItem = (spec: NativeMenuItemSpec): Handle => { if (targeted) { msgSendPtr(item, rt.selectors.get('setTarget:'), ensureTarget()); - if (spec.onClick !== undefined) { - clickRegistry.set(item, spec.onClick); - } + clickRegistry.set(item, spec); } // Apply the explicit modifier mask so multi-modifier accelerators (e.g. redo's @@ -120,8 +148,7 @@ const realizeItem = (spec: NativeMenuItemSpec): Handle => { } if (checkable) { - // NSControlStateValueOn = 1, Off = 0 — renders a checkmark for checked items. - msgSendI64(item, rt.selectors.get('setState:'), spec.checked ? 1n : 0n); + setState(item, spec.checked === true); } // For role items, let AppKit auto-enable via the responder chain (Copy greys out diff --git a/tests/integration/macos/cocoa-menu.test.ts b/tests/integration/macos/cocoa-menu.test.ts index 64d0381e..dbf7f2c3 100644 --- a/tests/integration/macos/cocoa-menu.test.ts +++ b/tests/integration/macos/cocoa-menu.test.ts @@ -26,6 +26,16 @@ const realizeAndValidate = (spec: NativeMenuItemSpec): { menu: Handle; item: Han const isEnabled = (item: Handle): boolean => msgSendReturnsU8(item, cocoa().selectors.get('isEnabled')) === 1; +const itemStates = (menu: Handle): bigint[] => { + const rt = cocoa(); + return Array.from({ length: menuItemCount(menu) }, (_, i) => + msgSendReturnsI64( + msgSendI64(menu, rt.selectors.get('itemAtIndex:'), BigInt(i)), + rt.selectors.get('state'), + ), + ); +}; + if (currentPlatform() === 'macos') { describe('cocoa-menu', () => { // performActionForItemAtIndex: dispatches through NSApp; without it nothing fires. @@ -133,6 +143,35 @@ if (currentPlatform() === 'macos') { expect(msgSendReturnsI64(item, cocoa().selectors.get('keyEquivalentModifierMask'))).toBe(0n); }); + test('clicking a checkbox toggles its check mark', () => { + const menu = realizeMenu([ + { label: 'Wrap', type: 'checkbox', enabled: true, checked: false, keyEquivalent: '' }, + ]); + performMenuItem(menu, 0); + expect(itemStates(menu)).toEqual([1n]); + performMenuItem(menu, 0); + expect(itemStates(menu)).toEqual([0n]); + }); + + test('clicking a radio checks it and clears only its adjacent radio group', () => { + const radio = (checked: boolean): NativeMenuItemSpec => ({ + label: 'R', + type: 'radio', + enabled: true, + checked, + keyEquivalent: '', + }); + const separator: NativeMenuItemSpec = { + label: '', + type: 'separator', + enabled: true, + keyEquivalent: '', + }; + const menu = realizeMenu([radio(false), radio(true), separator, radio(true)]); + performMenuItem(menu, 0); + expect(itemStates(menu)).toEqual([1n, 0n, 0n, 1n]); + }); + test('a submenu is realized with its own items', () => { const rt = cocoa(); const menu = realizeMenu([ From a515406772c334c854a70962b5dcaa016388ead9 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:44:20 -0700 Subject: [PATCH 009/586] fix: make every macOS window and contents call a no-op after close --- src/main/platform/macos/cocoa-backend.ts | 17 ++++- tests/integration/macos/cocoa-backend.test.ts | 73 +++++++++++++++++++ 2 files changed, 88 insertions(+), 2 deletions(-) diff --git a/src/main/platform/macos/cocoa-backend.ts b/src/main/platform/macos/cocoa-backend.ts index 6e2d805e..1de25b87 100644 --- a/src/main/platform/macos/cocoa-backend.ts +++ b/src/main/platform/macos/cocoa-backend.ts @@ -193,7 +193,7 @@ const styleFromOptions = (options: NativeWindowOptions): CocoaWindowStyle => : { ...STANDARD_WINDOW_STYLE, resizable: options.resizable !== false }; class MacOSWebContents implements NativeWebContents { - readonly #webview: Handle; + #webview: Handle; readonly #isolatedWorld: Handle; #envelopeCallback: ((envelopeJson: string) => void) | undefined; #didFinishLoad = false; @@ -252,6 +252,8 @@ class MacOSWebContents implements NativeWebContents { */ rejectPendingExecs(): void { this.#destroyed = true; + // Messaging nil is a no-op, so every later call is safe once the view is released. + this.#webview = 0n; for (const [, pending] of this.#pendingExecs) { clearTimeout(pending.timer); pending.resolve(undefined); @@ -491,6 +493,9 @@ class MacOSWebContents implements NativeWebContents { } sendEnvelopeToRenderer(envelopeJson: string): void { + if (this.#destroyed) { + return; + } if (!this.#didFinishLoad) { this.#pendingEnvelopes.push(envelopeJson); return; @@ -530,7 +535,7 @@ class MacOSWebContents implements NativeWebContents { } class MacOSWindow implements NativeWindow { - readonly #window: Handle; + #window: Handle; readonly #contents: MacOSWebContents; readonly #teardown: () => void; readonly #releaseNative: () => void; @@ -581,6 +586,8 @@ class MacOSWindow implements NativeWindow { return; } this.#tornDown = true; + // Messaging nil is a no-op, so every later call is safe once the window is released. + this.#window = 0n; this.#teardown(); this.#onClosed?.(); // Balance our alloc of the NSWindow + WKWebView (both kept alive by @@ -599,6 +606,9 @@ class MacOSWindow implements NativeWindow { #zoomed = false; emitEvent(type: WindowEventType): void { + if (this.#tornDown) { + return; + } // AppKit posts no zoom notification, so maximize/unmaximize are derived by // diffing isZoomed across resizes - the only hook that fires on both. if (type === 'resize') { @@ -702,6 +712,9 @@ class MacOSWindow implements NativeWindow { } show(): void { + if (this.#tornDown) { + return; + } const rt = cocoa(); if (isDevRestart()) { // A dev respawn orders the window in behind the editor instead of on top. diff --git a/tests/integration/macos/cocoa-backend.test.ts b/tests/integration/macos/cocoa-backend.test.ts index 97d97415..15d1edab 100644 --- a/tests/integration/macos/cocoa-backend.test.ts +++ b/tests/integration/macos/cocoa-backend.test.ts @@ -4,6 +4,13 @@ import { createMacOSApplication } from '../../../src/main/platform/macos/cocoa-b const delay = (ms: number): Promise => new Promise((resolve) => setTimeout(resolve, ms)); +const waitFor = async (predicate: () => boolean, ms = 3_000): Promise => { + const deadline = performance.now() + ms; + while (!predicate() && performance.now() < deadline) { + await Bun.sleep(20); + } +}; + if (currentPlatform() === 'macos') { describe('MacOSApplication', () => { test('onReady fires synchronously once started', () => { @@ -170,6 +177,72 @@ if (currentPlatform() === 'macos') { } }); + test('every window and contents call after close is a safe no-op', async () => { + const app = createMacOSApplication(); + app.start(); + try { + const win = app.createWindow({ width: 320, height: 240, title: 'closing', show: true }); + win.webContents.loadHTML('

x

', 'about:blank'); + await waitFor(() => win.webContents.getURL() === 'about:blank'); + const events: string[] = []; + for (const type of ['show', 'hide', 'blur', 'focus', 'resize'] as const) { + win.onWindowEvent(type, () => events.push(type)); + } + win.close(); + const callEverything = (): void => { + win.show(); + win.hide(); + win.focus(); + win.setTitle('after'); + win.setBounds({ x: 10, y: 10, width: 200, height: 100 }); + win.setSize(300, 200); + win.setPosition(5, 5); + win.setResizable(false); + win.setOpacity(0.5); + win.setMinimumSize(100, 100); + win.center(); + win.minimize(); + win.restore(); + win.maximize(); + win.unmaximize(); + win.setFullScreen(true); + win.setAlwaysOnTop(true); + win.close(); + win.destroy(); + const contents = win.webContents; + contents.loadURL('about:blank'); + contents.loadHTML('

y

'); + contents.reload(); + contents.reloadIgnoringCache(); + contents.stop(); + contents.goBack(); + contents.goForward(); + contents.setZoomFactor(2); + contents.setUserAgent('ua'); + contents.openDevTools(); + contents.closeDevTools(); + contents.sendEnvelopeToRenderer('{}'); + expect(win.getTitle()).toBe(''); + expect(win.isVisible()).toBe(false); + expect(win.isFocused()).toBe(false); + expect(win.isMaximized()).toBe(false); + expect(win.isMinimized()).toBe(false); + expect(win.isFullScreen()).toBe(false); + expect(contents.getURL()).toBe(''); + expect(contents.getTitle()).toBe(''); + expect(contents.canGoBack()).toBe(false); + expect(contents.canGoForward()).toBe(false); + }; + callEverything(); + // The native objects are released on a later tick; call again once they are gone. + await Bun.sleep(100); + callEverything(); + expect(events).toEqual([]); + } finally { + app.quit(); + } + }); + test('close fires the onClosed callback once', () => { const app = createMacOSApplication(); app.start(); From 81d255891079631374d91def2251987546196dbc Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:44:25 -0700 Subject: [PATCH 010/586] fix: reject whenReady and allow a retry when the native start fails --- src/main/api/app.ts | 6 +++++- src/main/bootstrap.ts | 7 ++++++- tests/unit/main/api/app.test.ts | 8 ++++++++ tests/unit/main/bootstrap.test.ts | 18 ++++++++++++++++++ 4 files changed, 37 insertions(+), 2 deletions(-) diff --git a/src/main/api/app.ts b/src/main/api/app.ts index acac24e5..6f86df1c 100644 --- a/src/main/api/app.ts +++ b/src/main/api/app.ts @@ -75,7 +75,11 @@ export class App extends EventEmitter { /** The first call triggers the native bootstrap, if a start hook is wired. */ whenReady(): Promise { if (!this.#ready) { - this.#startHook?.(); + try { + this.#startHook?.(); + } catch (error) { + return Promise.reject(error); + } } if (this.#ready) { return Promise.resolve(); diff --git a/src/main/bootstrap.ts b/src/main/bootstrap.ts index 60198535..60a99d5a 100644 --- a/src/main/bootstrap.ts +++ b/src/main/bootstrap.ts @@ -37,7 +37,12 @@ export const ensureNativeStarted = (): void => { native.onOpenFile?.((path) => { app.emit('open-file', makeCancelableEvent(), path); }); - native.start(); + try { + native.start(); + } catch (error) { + started = false; + throw error; + } }; /** Reset the one-shot guard. Test-only. */ diff --git a/tests/unit/main/api/app.test.ts b/tests/unit/main/api/app.test.ts index 491876b6..91f0395c 100644 --- a/tests/unit/main/api/app.test.ts +++ b/tests/unit/main/api/app.test.ts @@ -132,6 +132,14 @@ describe('App.whenReady', () => { await a.whenReady(); expect(a.isReady()).toBe(true); }); + + test('rejects instead of throwing when the start hook fails', async () => { + const a = new App(); + a.setStartHook(() => { + throw new Error('no display'); + }); + await expect(a.whenReady()).rejects.toThrow('no display'); + }); }); describe('App event surface', () => { diff --git a/tests/unit/main/bootstrap.test.ts b/tests/unit/main/bootstrap.test.ts index c1e8de6e..513fe749 100644 --- a/tests/unit/main/bootstrap.test.ts +++ b/tests/unit/main/bootstrap.test.ts @@ -83,6 +83,24 @@ describe('bootstrap native wiring', () => { expect(app.isReady()).toBe(true); }); + test('retries the native start after a failed one', () => { + const { native } = makeNative(); + let starts = 0; + resetBootstrapForTesting(); + setNativeAppForTesting({ + ...native, + start: () => { + starts += 1; + if (starts === 1) { + throw new Error('no display'); + } + }, + }); + expect(() => ensureNativeStarted()).toThrow('no display'); + ensureNativeStarted(); + expect(starts).toBe(2); + }); + test('forwards native open-url to the app open-url event', () => { installSafeAppExit(); const { native, openUrl } = makeNative(); From ec3295d73c238775da908defc793db585164b45e Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:44:41 -0700 Subject: [PATCH 011/586] fix: pass by-value CGRect args on the stack on x86_64 --- .../platform/macos/cocoa-msgsend-variants.ts | 97 ++++++------------- .../platform/macos/core-graphics-image-ffi.ts | 30 ++++-- .../macos/cocoa-init-window.test.ts | 85 ++++++++++------ .../macos/core-graphics-image-ffi.test.ts | 39 ++++++++ .../macos/cocoa-msgsend-variants.test.ts | 13 ++- 5 files changed, 157 insertions(+), 107 deletions(-) create mode 100644 tests/integration/macos/core-graphics-image-ffi.test.ts diff --git a/src/main/platform/macos/cocoa-msgsend-variants.ts b/src/main/platform/macos/cocoa-msgsend-variants.ts index 2726a760..467e65d7 100644 --- a/src/main/platform/macos/cocoa-msgsend-variants.ts +++ b/src/main/platform/macos/cocoa-msgsend-variants.ts @@ -21,19 +21,27 @@ import { type Handle, LIBOBJC_PATH, macOSLibraryAccessor } from './objc'; * on other platforms. */ +export type CGRectArgs = readonly [x: number, y: number, width: number, height: number]; + +// D018: arm64 passes a 4-double CGRect (an HFA) in d0-d3, exactly like four doubles. +// x86_64 SysV classes a 32-byte struct MEMORY and copies it to the stack, so eight +// dummy doubles fill xmm0-7 first and the real four spill to the stack in field order. +const rectPadding = (arch: string): number => (arch === 'x64' ? 8 : 0); + +/** The f64 values that pass `rect` by value on `arch` (D018). */ +export const cgRectArgs = (rect: CGRectArgs, arch: string = process.arch): number[] => [ + ...new Array(rectPadding(arch)).fill(0), + ...rect, +]; + +/** The FFI slots matching {@link cgRectArgs} on this host. */ +export const RECT_F64: readonly FFIType.f64[] = new Array( + rectPadding(process.arch) + 4, +).fill(FFIType.f64); + const INIT_WITH_CONTENT_RECT_VARIANT = { objc_msgSend: { - args: [ - FFIType.u64, - FFIType.u64, - FFIType.f64, - FFIType.f64, - FFIType.f64, - FFIType.f64, - FFIType.u64, - FFIType.u64, - FFIType.u8, - ], + args: [FFIType.u64, FFIType.u64, ...RECT_F64, FFIType.u64, FFIType.u64, FFIType.u8], returns: FFIType.u64, }, } as const; @@ -110,32 +118,15 @@ const PTR_RETURNS_U8_VARIANT = { const FRAME_CONFIG_VARIANT = { objc_msgSend: { - args: [ - FFIType.u64, - FFIType.u64, - FFIType.f64, - FFIType.f64, - FFIType.f64, - FFIType.f64, - FFIType.u64, - ], + args: [FFIType.u64, FFIType.u64, ...RECT_F64, FFIType.u64], returns: FFIType.u64, }, } as const; -// (receiver, selector, NSRect{x,y,w,h} as four doubles (D018), BOOL) -> void. -// For -[NSWindow setFrame:display:]. +// (receiver, selector, NSRect by value (D018), BOOL) -> void. const RECT_U8_VARIANT = { objc_msgSend: { - args: [ - FFIType.u64, - FFIType.u64, - FFIType.f64, - FFIType.f64, - FFIType.f64, - FFIType.f64, - FFIType.u8, - ], + args: [FFIType.u64, FFIType.u64, ...RECT_F64, FFIType.u8], returns: FFIType.void, }, } as const; @@ -198,16 +189,7 @@ const getPtrReturnsU8Lib = macOSLibraryAccessor('msgSendPtrReturnsU8', () => const getSizeLib = macOSLibraryAccessor('msgSendSize', () => dlopen(LIBOBJC_PATH, SIZE_VARIANT)); -export type CGRectArgs = readonly [x: number, y: number, width: number, height: number]; - -/** - * Send `initWithContentRect:styleMask:backing:defer:` to an NSWindow receiver. - * - * On both macOS ABIs (ARM64 and x86_64 SysV) a `CGRect` (struct of four - * `double`s) is passed in exactly the same registers as four separate `double` - * args, so this variant declares raw f64×4 in place of the CGRect struct — no - * C shim required (D018). - */ +/** Send `initWithContentRect:styleMask:backing:defer:`; the rect goes by value (D018). */ export const msgSendInitWithContentRect = ( receiver: Handle, selector: Handle, @@ -219,31 +201,20 @@ export const msgSendInitWithContentRect = ( getInitWithContentRectLib().symbols.objc_msgSend( receiver, selector, - rect[0], - rect[1], - rect[2], - rect[3], + ...cgRectArgs(rect), styleMask, backing, defer ? 1 : 0, ); -/** Send a message with an NSRect (four doubles, D018) plus a trailing BOOL. */ +/** Send a message with an NSRect by value (D018) plus a trailing BOOL. */ export const msgSendRectU8 = ( receiver: Handle, selector: Handle, rect: CGRectArgs, flag: boolean, ): void => { - getRectU8Lib().symbols.objc_msgSend( - receiver, - selector, - rect[0], - rect[1], - rect[2], - rect[3], - flag ? 1 : 0, - ); + getRectU8Lib().symbols.objc_msgSend(receiver, selector, ...cgRectArgs(rect), flag ? 1 : 0); }; export const msgSendPtr = (receiver: Handle, selector: Handle, arg: Handle): Handle => @@ -274,26 +245,14 @@ export const msgSendPtrPtr = ( arg1: Handle, ): Handle => getPtrPtrLib().symbols.objc_msgSend(receiver, selector, arg0, arg1); -/** - * Send `initWithFrame:configuration:` to a WKWebView receiver: a `CGRect` - * (four `double`s via the struct-as-doubles trick, D018) plus a trailing - * configuration pointer. - */ +/** Send `initWithFrame:configuration:`; the rect goes by value (D018). */ export const msgSendInitWithFrameConfig = ( receiver: Handle, selector: Handle, frame: CGRectArgs, configuration: Handle, ): Handle => - getFrameConfigLib().symbols.objc_msgSend( - receiver, - selector, - frame[0], - frame[1], - frame[2], - frame[3], - configuration, - ); + getFrameConfigLib().symbols.objc_msgSend(receiver, selector, ...cgRectArgs(frame), configuration); export const msgSendPtr3 = ( receiver: Handle, diff --git a/src/main/platform/macos/core-graphics-image-ffi.ts b/src/main/platform/macos/core-graphics-image-ffi.ts index 454f9bda..060064b2 100644 --- a/src/main/platform/macos/core-graphics-image-ffi.ts +++ b/src/main/platform/macos/core-graphics-image-ffi.ts @@ -1,5 +1,6 @@ -import { FFIType } from 'bun:ffi'; +import { FFIType, type Pointer } from 'bun:ffi'; import { dlopen } from '../dlopen'; +import { cgRectArgs, RECT_F64 } from './cocoa-msgsend-variants'; import { macOSLibraryAccessor } from './objc'; /** @@ -11,8 +12,7 @@ import { macOSLibraryAccessor } from './objc'; * * Everything here is an opaque pointer (CGContextRef/CGImageRef/CGColorSpaceRef) * — no struct is ever returned (D030). The one struct ARG, the `CGRect` passed to - * `CGContextDrawImage`, is supplied as four `double`s (D018 struct-as-doubles); - * on arm64 a 4-double homogeneous-FP struct occupies d0–d3 identically. + * `CGContextDrawImage`, goes through {@link cgRectArgs} (D018). */ const CORE_GRAPHICS_PATH = '/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics'; @@ -40,14 +40,28 @@ const CORE_GRAPHICS_SYMBOLS = { CGColorSpaceRelease: { args: [FFIType.pointer], returns: FFIType.void }, CGContextRelease: { args: [FFIType.pointer], returns: FFIType.void }, CGImageRelease: { args: [FFIType.pointer], returns: FFIType.void }, - // (ctx, CGRect{x,y,w,h} BY VALUE as 4 doubles (D018), image) -> void. + // (ctx, CGRect BY VALUE (D018), image) -> void; called through the wrapper below. CGContextDrawImage: { - args: [FFIType.pointer, FFIType.f64, FFIType.f64, FFIType.f64, FFIType.f64, FFIType.pointer], + args: [FFIType.pointer, ...RECT_F64, FFIType.pointer], returns: FFIType.void, }, } as const; /** Open CoreGraphics and expose the offscreen-bitmap symbols (memoised; macOS-only). */ -export const loadCoreGraphicsImageFFI = macOSLibraryAccessor('CoreGraphics nativeImage', () => - dlopen(CORE_GRAPHICS_PATH, CORE_GRAPHICS_SYMBOLS), -); +export const loadCoreGraphicsImageFFI = macOSLibraryAccessor('CoreGraphics nativeImage', () => { + const { symbols } = dlopen(CORE_GRAPHICS_PATH, CORE_GRAPHICS_SYMBOLS); + const draw = symbols.CGContextDrawImage; + return { + symbols: { + ...symbols, + CGContextDrawImage: ( + ctx: Pointer | null, + x: number, + y: number, + width: number, + height: number, + image: Pointer | null, + ): void => draw(ctx, ...cgRectArgs([x, y, width, height]), image), + }, + }; +}); diff --git a/tests/integration/macos/cocoa-init-window.test.ts b/tests/integration/macos/cocoa-init-window.test.ts index 47344f82..04347000 100644 --- a/tests/integration/macos/cocoa-init-window.test.ts +++ b/tests/integration/macos/cocoa-init-window.test.ts @@ -1,40 +1,67 @@ import { describe, expect, test } from 'bun:test'; import { currentPlatform } from '../../../src/common/platform'; -import { msgSendInitWithContentRect } from '../../../src/main/platform/macos/cocoa-msgsend-variants'; -import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; +import { nsString, nsStringToString } from '../../../src/main/platform/macos/cocoa-foundation'; import { - STANDARD_WINDOW_STYLE, - computeWindowStyleMask, -} from '../../../src/main/platform/macos/cocoa-style-mask'; + msgSendInitWithContentRect, + msgSendInitWithFrameConfig, + msgSendPtr, + msgSendRectU8, +} from '../../../src/main/platform/macos/cocoa-msgsend-variants'; +import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; +import { loadWebKit } from '../../../src/main/platform/macos/cocoa-webkit'; const NS_BACKING_STORE_BUFFERED = 2n; +const BORDERLESS = 0n; -if (currentPlatform() === 'macos') { - describe('NSWindow initWithContentRect:styleMask:backing:defer:', () => { - test('returns a non-zero initialized window via the struct-as-doubles variant', () => { - const rt = cocoa(); - const nsWindow = rt.classes.get('NSWindow'); - const allocSel = rt.selectors.get('alloc'); - const initSel = rt.selectors.get('initWithContentRect:styleMask:backing:defer:'); - const releaseSel = rt.selectors.get('release'); - - const allocated = rt.msgSend(nsWindow, allocSel); - expect(allocated).not.toBe(0n); +/** The receiver's `frame` as NSValue prints it: KVC boxes the struct, so no struct return. */ +const frameOf = (receiver: bigint): string => { + const rt = cocoa(); + const boxed = msgSendPtr(receiver, rt.selectors.get('valueForKey:'), nsString('frame')); + return nsStringToString(rt.msgSend(boxed, rt.selectors.get('description'))); +}; - const styleMask = BigInt(computeWindowStyleMask(STANDARD_WINDOW_STYLE)); +const borderlessWindow = (rect: readonly [number, number, number, number]): bigint => { + const rt = cocoa(); + return msgSendInitWithContentRect( + rt.msgSend(rt.classes.get('NSWindow'), rt.selectors.get('alloc')), + rt.selectors.get('initWithContentRect:styleMask:backing:defer:'), + rect, + BORDERLESS, + NS_BACKING_STORE_BUFFERED, + false, + ); +}; - const window = msgSendInitWithContentRect( - allocated, - initSel, - [100, 100, 400, 300], - styleMask, - NS_BACKING_STORE_BUFFERED, - false, - ); +describe.skipIf(currentPlatform() !== 'macos')('CGRect by value (D018)', () => { + test('initWithContentRect:styleMask:backing:defer: receives the rect intact', () => { + const window = borderlessWindow([100, 110, 400, 300]); + expect(frameOf(window)).toBe('NSRect: {{100, 110}, {400, 300}}'); + cocoa().msgSend(window, cocoa().selectors.get('release')); + }); - expect(window).not.toBe(0n); + test('setFrame:display: receives the rect intact', () => { + const rt = cocoa(); + const window = borderlessWindow([0, 0, 50, 50]); + msgSendRectU8(window, rt.selectors.get('setFrame:display:'), [10, 20, 300, 200], false); + expect(frameOf(window)).toBe('NSRect: {{10, 20}, {300, 200}}'); + rt.msgSend(window, rt.selectors.get('release')); + }); - rt.msgSend(window, releaseSel); - }); + test('WKWebView initWithFrame:configuration: receives the rect intact', () => { + loadWebKit(); + const rt = cocoa(); + const config = rt.msgSend( + rt.msgSend(rt.classes.get('WKWebViewConfiguration'), rt.selectors.get('alloc')), + rt.selectors.get('init'), + ); + const webview = msgSendInitWithFrameConfig( + rt.msgSend(rt.classes.get('WKWebView'), rt.selectors.get('alloc')), + rt.selectors.get('initWithFrame:configuration:'), + [5, 6, 320, 240], + config, + ); + expect(frameOf(webview)).toBe('NSRect: {{5, 6}, {320, 240}}'); + rt.msgSend(webview, rt.selectors.get('release')); + rt.msgSend(config, rt.selectors.get('release')); }); -} +}); diff --git a/tests/integration/macos/core-graphics-image-ffi.test.ts b/tests/integration/macos/core-graphics-image-ffi.test.ts new file mode 100644 index 00000000..270e6901 --- /dev/null +++ b/tests/integration/macos/core-graphics-image-ffi.test.ts @@ -0,0 +1,39 @@ +import { ptr } from 'bun:ffi'; +import { expect, test } from 'bun:test'; +import { currentPlatform } from '../../../src/common/platform'; +import { + KCG_ALPHA_PREMULTIPLIED_LAST, + loadCoreGraphicsImageFFI, +} from '../../../src/main/platform/macos/core-graphics-image-ffi'; + +test.skipIf(currentPlatform() !== 'macos')( + 'CGContextDrawImage draws into the CGRect it was given (D018)', + () => { + const cg = loadCoreGraphicsImageFFI().symbols; + const colorSpace = cg.CGColorSpaceCreateDeviceRGB(); + const context = (pixels: Uint8Array, width: number) => + cg.CGBitmapContextCreate( + ptr(pixels), + BigInt(width), + 1n, + 8n, + BigInt(width * 4), + colorSpace, + KCG_ALPHA_PREMULTIPLIED_LAST, + ); + + const red = new Uint8Array([255, 0, 0, 255]); + const source = context(red, 1); + const image = cg.CGBitmapContextCreateImage(source); + const target = new Uint8Array(8); + const destination = context(target, 2); + + cg.CGContextDrawImage(destination, 1, 0, 1, 1, image); + + expect([...target]).toEqual([0, 0, 0, 0, 255, 0, 0, 255]); + cg.CGImageRelease(image); + cg.CGContextRelease(source); + cg.CGContextRelease(destination); + cg.CGColorSpaceRelease(colorSpace); + }, +); diff --git a/tests/unit/main/platform/macos/cocoa-msgsend-variants.test.ts b/tests/unit/main/platform/macos/cocoa-msgsend-variants.test.ts index eaca3999..7150b8f3 100644 --- a/tests/unit/main/platform/macos/cocoa-msgsend-variants.test.ts +++ b/tests/unit/main/platform/macos/cocoa-msgsend-variants.test.ts @@ -1,7 +1,8 @@ -import { expect, test } from 'bun:test'; +import { describe, expect, test } from 'bun:test'; import { BunmaskaError } from '../../../../../src/common/errors'; import { currentPlatform } from '../../../../../src/common/platform'; import { + cgRectArgs, msgSendF64, msgSendI64, msgSendI64Ptr, @@ -54,3 +55,13 @@ test.skipIf(currentPlatform() === 'macos')( expect(unguarded).toEqual([]); }, ); + +describe('cgRectArgs (D018)', () => { + test('arm64 passes a CGRect as four doubles in d0-d3', () => { + expect(cgRectArgs([1, 2, 3, 4], 'arm64')).toEqual([1, 2, 3, 4]); + }); + + test('x86_64 fills xmm0-7 first so the CGRect spills to the stack like a MEMORY struct', () => { + expect(cgRectArgs([1, 2, 3, 4], 'x64')).toEqual([0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4]); + }); +}); From aa95f1d87efd01db481b56496babf7618968c7c2 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:44:50 -0700 Subject: [PATCH 012/586] fix: throw Object has been destroyed on a closed window or webContents --- src/main/api/browser-window.ts | 16 +++++- src/main/api/web-contents.ts | 29 +++++++--- tests/integration/macos/window-events.test.ts | 4 +- tests/unit/main/api/browser-window.test.ts | 34 ++++++++++- tests/unit/main/api/web-contents.test.ts | 57 +++++++++++++++++++ 5 files changed, 124 insertions(+), 16 deletions(-) diff --git a/src/main/api/browser-window.ts b/src/main/api/browser-window.ts index 1347fed3..a5eb1f01 100644 --- a/src/main/api/browser-window.ts +++ b/src/main/api/browser-window.ts @@ -10,7 +10,7 @@ import { app } from './app'; import { installWindowResolver, type PopupTarget } from './menu'; import { loadPreloadScript } from './preload'; import { session } from './session'; -import { type LoadFileOptions, WebContents } from './web-contents'; +import { type LoadFileOptions, objectDestroyedError, WebContents } from './web-contents'; /** * A top-level application window — the drop-in equivalent of Electron's @@ -104,7 +104,7 @@ export class BrowserWindow extends EventEmitter { /** Process-unique and never reused within a run. */ readonly id: number; readonly webContents: WebContents; - readonly #native: NativeWindow; + readonly #window: NativeWindow; #destroyed = false; #resizable: boolean; #opacity = 1; @@ -136,7 +136,7 @@ export class BrowserWindow extends EventEmitter { options = { ...options, width: devBounds.width, height: devBounds.height }; } const preloadScript = loadPreloadScript(options.webPreferences?.preload); - this.#native = nativeApp().createWindow({ + this.#window = nativeApp().createWindow({ width: options.width ?? DEFAULT_WIDTH, height: options.height ?? DEFAULT_HEIGHT, title: options.title ?? DEFAULT_TITLE, @@ -175,6 +175,9 @@ export class BrowserWindow extends EventEmitter { }); for (const type of WINDOW_EVENT_TYPES) { this.#native.onWindowEvent(type, () => { + if (this.#destroyed) { + return; + } this.emit(type); if (type === 'focus') { app.emit('browser-window-focus', makeCancelableEvent(), this); @@ -195,6 +198,13 @@ export class BrowserWindow extends EventEmitter { app.emit('browser-window-created', makeCancelableEvent(), this); } + get #native(): NativeWindow { + if (this.#destroyed) { + throw objectDestroyedError(); + } + return this.#window; + } + /** * When the last window closes, emit `app`'s `window-all-closed`. Replicating * Electron's default: if no listener handles it, quit the app (a subscriber diff --git a/src/main/api/web-contents.ts b/src/main/api/web-contents.ts index 3a77407d..ed2072ac 100644 --- a/src/main/api/web-contents.ts +++ b/src/main/api/web-contents.ts @@ -29,6 +29,9 @@ export type LoadFileOptions = { readonly search?: string; }; +/** Electron's error for a call on a destroyed window or web contents. */ +export const objectDestroyedError = (): TypeError => new TypeError('Object has been destroyed'); + let nextId = 1; /** @internal */ @@ -56,7 +59,7 @@ const buildRemoveCssScript = (key: string): string => export class WebContents extends EventEmitter { /** Process-unique and never reused within a run. */ readonly id: number; - readonly #native: NativeWebContents; + readonly #view: NativeWebContents; #cssCounter = 0; #zoomFactor = 1; #userAgent = ''; @@ -68,11 +71,14 @@ export class WebContents extends EventEmitter { super(); this.id = nextId; nextId += 1; - this.#native = native; - this.#native.onRendererEnvelope((json) => { + this.#view = native; + native.onRendererEnvelope((json) => { void this.#handleRendererEnvelope(json); }); - this.#native.onNavigation((event) => { + native.onNavigation((event) => { + if (this.#destroyed) { + return; + } if (event.type === 'did-start-loading') { this.#isLoading = true; } else if ( @@ -92,6 +98,13 @@ export class WebContents extends EventEmitter { }); } + get #native(): NativeWebContents { + if (this.#destroyed) { + throw objectDestroyedError(); + } + return this.#view; + } + loadURL(url: string): void { this.#native.loadURL(url); } @@ -165,7 +178,7 @@ export class WebContents extends EventEmitter { * Resolves to the script's COMPLETION value; a returned Promise is awaited. * Only JSON-serializable results survive (`JSON.stringify` semantics). */ - executeJavaScript(code: string): Promise { + async executeJavaScript(code: string): Promise { return this.#native.executeJavaScript(code); } @@ -310,12 +323,12 @@ export class WebContents extends EventEmitter { log.warn('dropping malformed renderer envelope', error); return; } - if (envelope.kind !== 'send' && envelope.kind !== 'invoke') { + if ((envelope.kind !== 'send' && envelope.kind !== 'invoke') || this.#destroyed) { return; } const reply = await ipcMain.dispatch(envelope, { sender: this }); - if (reply !== undefined) { - this.#native.sendEnvelopeToRenderer(encodeEnvelope(reply)); + if (reply !== undefined && !this.#destroyed) { + this.#view.sendEnvelopeToRenderer(encodeEnvelope(reply)); } } } diff --git a/tests/integration/macos/window-events.test.ts b/tests/integration/macos/window-events.test.ts index 163bb0dc..9175fe4a 100644 --- a/tests/integration/macos/window-events.test.ts +++ b/tests/integration/macos/window-events.test.ts @@ -141,8 +141,8 @@ if (currentPlatform() === 'macos') { win.close(); await delay(50); expect(closed).toBe(1); - // Idempotent: a second close does not re-fire closed or crash. - win.close(); + // A second close throws (Electron parity) instead of reaching the freed NSWindow. + expect(() => win.close()).toThrow('Object has been destroyed'); await delay(20); expect(closed).toBe(1); }); diff --git a/tests/unit/main/api/browser-window.test.ts b/tests/unit/main/api/browser-window.test.ts index 9cb99c96..38be3d1b 100644 --- a/tests/unit/main/api/browser-window.test.ts +++ b/tests/unit/main/api/browser-window.test.ts @@ -555,15 +555,43 @@ describe('BrowserWindow lifecycle events', () => { expect(win.isDestroyed()).toBe(false); }); - test('teardown runs exactly once across repeated close attempts (idempotent)', () => { - const win = new BrowserWindow(); + test('teardown runs exactly once across repeated native close requests', () => { + new BrowserWindow(); windows[0]?.fireCloseRequest(); - win.close(); windows[0]?.fireCloseRequest(); expect(windows[0]?.teardownCount()).toBe(1); }); }); +describe('BrowserWindow after closed', () => { + test('methods throw Electron TypeError without reaching the native window', () => { + const win = new BrowserWindow({ title: 'before' }); + win.close(); + expect(() => win.setTitle('after')).toThrow(new TypeError('Object has been destroyed')); + expect(() => win.close()).toThrow(TypeError); + expect(windows[0]?.getTitle()).toBe('before'); + expect(windows[0]?.teardownCount()).toBe(1); + }); + + test('isDestroyed keeps answering', () => { + const win = new BrowserWindow(); + win.destroy(); + expect(win.isDestroyed()).toBe(true); + expect(win.webContents.isDestroyed()).toBe(true); + }); + + test('native window events after closed are not re-emitted', () => { + const win = new BrowserWindow(); + let moved = 0; + win.on('move', () => { + moved += 1; + }); + win.close(); + windows[0]?.fireEvent('move'); + expect(moved).toBe(0); + }); +}); + describe('App-level window events', () => { test('constructing a window emits browser-window-created with the window', () => { let received: BrowserWindow | undefined; diff --git a/tests/unit/main/api/web-contents.test.ts b/tests/unit/main/api/web-contents.test.ts index b2fc3651..33af3318 100644 --- a/tests/unit/main/api/web-contents.test.ts +++ b/tests/unit/main/api/web-contents.test.ts @@ -266,6 +266,63 @@ describe('WebContents.devtools + isDestroyed', () => { }); }); +describe('WebContents after destroy', () => { + test('methods throw Electron TypeError without reaching the native view', () => { + const { native, sent } = makeFakeNative(); + const loaded: string[] = []; + const wc = new WebContents({ ...native, loadURL: (url: string) => loaded.push(url) }); + wc.markDestroyed(); + expect(() => wc.send('tick')).toThrow(new TypeError('Object has been destroyed')); + expect(() => wc.loadURL('https://x.test/')).toThrow(TypeError); + expect(sent).toEqual([]); + expect(loaded).toEqual([]); + }); + + test('executeJavaScript rejects instead of throwing synchronously', async () => { + const wc = new WebContents(makeFakeNative().native); + wc.markDestroyed(); + await expect(wc.executeJavaScript('1')).rejects.toThrow('Object has been destroyed'); + }); + + test('an invoke reply that settles after destroy is dropped', async () => { + const { native, sent, fireRenderer } = makeFakeNative(); + const wc = new WebContents(native); + let finish: (value: number) => void = () => undefined; + ipcMain.handle('add', () => new Promise((resolve) => (finish = resolve))); + fireRenderer(encodeEnvelope({ kind: 'invoke', id: 7, channel: 'add', args: [] })); + await flush(); + wc.markDestroyed(); + finish(1); + await flush(); + expect(sent).toEqual([]); + }); + + test('a renderer envelope arriving after destroy is not dispatched', async () => { + const { native, fireRenderer } = makeFakeNative(); + const wc = new WebContents(native); + let calls = 0; + ipcMain.on('late', () => { + calls += 1; + }); + wc.markDestroyed(); + fireRenderer(encodeEnvelope({ kind: 'send', channel: 'late', args: [] })); + await flush(); + expect(calls).toBe(0); + }); + + test('navigation events after destroy are not re-emitted', () => { + const { native, fireNavigation } = makeFakeNative(); + const wc = new WebContents(native); + let fired = 0; + wc.on('did-navigate', () => { + fired += 1; + }); + wc.markDestroyed(); + fireNavigation({ type: 'did-navigate' }); + expect(fired).toBe(0); + }); +}); + describe('WebContents.setUserAgent / getUserAgent', () => { test('defaults to an empty override', () => { expect(new WebContents(makeFakeNative().native).getUserAgent()).toBe(''); From 2bb83d69d4de8d1e761b16363e390e75f0667e19 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:44:53 -0700 Subject: [PATCH 013/586] fix: contain throwing GTK signal handlers instead of unwinding GLib --- src/main/platform/linux/gtk-signals.ts | 108 ++++++++++++------ .../main/platform/linux/gtk-signals.test.ts | 41 ++++++- 2 files changed, 111 insertions(+), 38 deletions(-) diff --git a/src/main/platform/linux/gtk-signals.ts b/src/main/platform/linux/gtk-signals.ts index cbce2b45..86629383 100644 --- a/src/main/platform/linux/gtk-signals.ts +++ b/src/main/platform/linux/gtk-signals.ts @@ -1,4 +1,5 @@ import { CString, JSCallback, type Pointer } from 'bun:ffi'; +import { createLogger } from '../../../common/logger'; import type { NativeNavigationEvent } from '../native'; import { cstr } from '../cstr'; import { loadGlibFFI } from './glib-ffi'; @@ -26,6 +27,24 @@ import { * constant (unit-testable in pure JS) and reused by the factory below. */ +const log = createLogger('gtk-signals'); + +/** + * Wrap a signal handler so a JS throw is logged and `fallback` returned. An + * exception left pending in a JSCallback silently skips every later callback in + * the same `g_main_context_iteration` (URI-scheme requests, async completions). + */ +export const guarded = + (fn: (...args: A) => R, fallback: R) => + (...args: A): R => { + try { + return fn(...args); + } catch (error) { + log.error('signal handler threw', error); + return fallback; + } + }; + /** ABI shape for `GtkWindow::close-request`: `(self, user_data) -> gboolean`. */ export const CLOSE_REQUEST_CB_DEF = { args: ['ptr', 'ptr'], returns: 'i32' } as const; /** ABI shape for `GtkWidget::destroy`: `(self, user_data) -> void`. */ @@ -65,7 +84,10 @@ export const closeRequestDecision = (onCloseRequest: () => boolean): number => */ export const makeCloseRequestCallback = (onCloseRequest: () => boolean): JSCallback => new JSCallback( - (_self: Pointer, _userData: Pointer): number => closeRequestDecision(onCloseRequest), + guarded( + (_self: Pointer, _userData: Pointer): number => closeRequestDecision(onCloseRequest), + 0, + ), CLOSE_REQUEST_CB_DEF, ); @@ -75,9 +97,12 @@ export const makeCloseRequestCallback = (onCloseRequest: () => boolean): JSCallb * tracked flag. The `GParamSpec*` second arg is ignored. */ export const makeNotifyCallback = (onNotify: () => void): JSCallback => - new JSCallback((_gobject: Pointer, _pspec: Pointer, _userData: Pointer): void => { - onNotify(); - }, NOTIFY_CB_DEF); + new JSCallback( + guarded((_gobject: Pointer, _pspec: Pointer, _userData: Pointer): void => { + onNotify(); + }, undefined), + NOTIFY_CB_DEF, + ); /** * `GtkWidget::destroy` handler. Fires `onClosed` bookkeeping + drops retained @@ -91,16 +116,19 @@ export const makeDestroyCallback = (onClosed: () => void): JSCallback => export const makeLoadChangedCallback = ( onNavigation: (event: NativeNavigationEvent) => void, ): JSCallback => - new JSCallback((_self: Pointer, loadEvent: number, _userData: Pointer): void => { - if (loadEvent === WEBKIT_LOAD_STARTED) { - onNavigation({ type: 'did-start-loading' }); - } else if (loadEvent === WEBKIT_LOAD_COMMITTED) { - onNavigation({ type: 'did-navigate' }); - } else if (loadEvent === WEBKIT_LOAD_FINISHED) { - onNavigation({ type: 'did-finish-load' }); - onNavigation({ type: 'did-stop-loading' }); - } - }, LOAD_CHANGED_CB_DEF); + new JSCallback( + guarded((_self: Pointer, loadEvent: number, _userData: Pointer): void => { + if (loadEvent === WEBKIT_LOAD_STARTED) { + onNavigation({ type: 'did-start-loading' }); + } else if (loadEvent === WEBKIT_LOAD_COMMITTED) { + onNavigation({ type: 'did-navigate' }); + } else if (loadEvent === WEBKIT_LOAD_FINISHED) { + onNavigation({ type: 'did-finish-load' }); + onNavigation({ type: 'did-stop-loading' }); + } + }, undefined), + LOAD_CHANGED_CB_DEF, + ); /** * `WebKitWebView::load-failed` handler. Emits `did-fail-load` then @@ -111,17 +139,20 @@ export const makeLoadFailedCallback = ( onNavigation: (event: NativeNavigationEvent) => void, ): JSCallback => new JSCallback( - ( - _self: Pointer, - _loadEvent: number, - _uri: Pointer, - _error: Pointer, - _userData: Pointer, - ): number => { - onNavigation({ type: 'did-fail-load', errorCode: -1, errorDescription: '' }); - onNavigation({ type: 'did-stop-loading' }); - return 0; - }, + guarded( + ( + _self: Pointer, + _loadEvent: number, + _uri: Pointer, + _error: Pointer, + _userData: Pointer, + ): number => { + onNavigation({ type: 'did-fail-load', errorCode: -1, errorDescription: '' }); + onNavigation({ type: 'did-stop-loading' }); + return 0; + }, + 0, + ), LOAD_FAILED_CB_DEF, ); @@ -133,7 +164,7 @@ export const makeLoadFailedCallback = ( export const makeCreateCallback = (onWindowOpen: (url: string) => void): JSCallback => { const webkit = loadWebKitGtkFFI(); return new JSCallback( - (_webView: Pointer, navigationAction: Pointer, _userData: Pointer): Pointer | null => { + guarded((_webView: Pointer, navigationAction: Pointer, _userData: Pointer): Pointer | null => { const request = webkit.symbols.webkit_navigation_action_get_request(navigationAction); if (request !== null) { const uri = webkit.symbols.webkit_uri_request_get_uri(request); @@ -142,7 +173,7 @@ export const makeCreateCallback = (onWindowOpen: (url: string) => void): JSCallb } } return null; - }, + }, null), CREATE_CB_DEF, ); }; @@ -159,16 +190,19 @@ export const makeCreateCallback = (onWindowOpen: (url: string) => void): JSCallb export const makeScriptMessageCallback = (onMessage: (json: string) => void): JSCallback => { const jsc = loadJscFFI(); const glib = loadGlibFFI(); - return new JSCallback((_manager: Pointer, value: Pointer, _userData: Pointer): void => { - const ptr = jsc.symbols.jsc_value_to_string(value); - // A NULL conversion would deliver an unparseable '' to the IPC layer; drop it. - if (ptr === null) { - return; - } - const json = new CString(ptr).toString(); - glib.symbols.g_free(ptr); - onMessage(json); - }, SCRIPT_MESSAGE_CB_DEF); + return new JSCallback( + guarded((_manager: Pointer, value: Pointer, _userData: Pointer): void => { + const ptr = jsc.symbols.jsc_value_to_string(value); + // A NULL conversion would deliver an unparseable '' to the IPC layer; drop it. + if (ptr === null) { + return; + } + const json = new CString(ptr).toString(); + glib.symbols.g_free(ptr); + onMessage(json); + }, undefined), + SCRIPT_MESSAGE_CB_DEF, + ); }; /** Anything with a native trampoline that must be freed off the current stack. */ diff --git a/tests/unit/main/platform/linux/gtk-signals.test.ts b/tests/unit/main/platform/linux/gtk-signals.test.ts index ee2812c8..8357ab38 100644 --- a/tests/unit/main/platform/linux/gtk-signals.test.ts +++ b/tests/unit/main/platform/linux/gtk-signals.test.ts @@ -1,4 +1,6 @@ -import { describe, expect, it } from 'bun:test'; +import { CFunction, type FFITypeOrString, type JSCallback } from 'bun:ffi'; +import { describe, expect, it, test } from 'bun:test'; +import { type LogRecord, resetLogger, setLogSink } from '../../../../../src/common/logger'; import { CLOSE_REQUEST_CB_DEF, closeRequestDecision, @@ -93,6 +95,43 @@ describe('gtk-signals JSCallback factories (constructible + closable)', () => { }); }); +describe('a throwing handler never unwinds into GLib', () => { + const nativeCall = ( + cb: JSCallback, + def: { args: readonly FFITypeOrString[]; returns: FFITypeOrString }, + ) => { + if (cb.ptr === null) { + throw new Error('no thunk'); + } + return CFunction({ ptr: cb.ptr, args: [...def.args], returns: def.returns }); + }; + const boom = (): never => { + throw new Error('boom'); + }; + + test('a throwing notify handler returns normally and logs the error', () => { + const records: LogRecord[] = []; + setLogSink((record) => records.push(record)); + const cb = makeNotifyCallback(boom); + try { + expect(() => nativeCall(cb, NOTIFY_CB_DEF)(null, null, null)).not.toThrow(); + expect(records.map((r) => r.level)).toContain('error'); + } finally { + cb.close(); + resetLogger(); + } + }); + + test('a throwing close-request handler allows the close (returns 0)', () => { + const cb = makeCloseRequestCallback(boom); + try { + expect(nativeCall(cb, CLOSE_REQUEST_CB_DEF)(null, null)).toBe(0); + } finally { + cb.close(); + } + }); +}); + describe('SignalRegistry', () => { it('starts empty and disconnectAll is a no-op when empty', () => { const registry = new SignalRegistry(); From 6691bfafcd5f15dad89b478d6438bb1139eed0c7 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:44:55 -0700 Subject: [PATCH 014/586] fix: route WM_CLOSE through the close veto in the frame proc --- src/main/platform/windows/windows-backend.ts | 17 +--- .../platform/windows/windows-native-window.ts | 96 +++++++++---------- src/main/platform/windows/windows-run-loop.ts | 7 +- .../windows/windows-native-window.test.ts | 41 +++++++- 4 files changed, 90 insertions(+), 71 deletions(-) diff --git a/src/main/platform/windows/windows-backend.ts b/src/main/platform/windows/windows-backend.ts index bd930a03..a9ac4546 100644 --- a/src/main/platform/windows/windows-backend.ts +++ b/src/main/platform/windows/windows-backend.ts @@ -11,12 +11,7 @@ import type { import { loadUser32 } from './win32-ffi'; import { windowsGlobalShortcutBackend } from './windows-global-shortcut'; import { type AppMenuWindow, windowsMenuRealizer } from './windows-menu'; -import { - dispatchPostedWindowMessage, - ensureOleInitialized, - NativeWin32Window, - pollWindows, -} from './windows-native-window'; +import { ensureOleInitialized, NativeWin32Window, pollWindows } from './windows-native-window'; import { createWindowsDrain } from './windows-run-loop'; import { WindowsWebContents } from './windows-web-contents'; @@ -409,13 +404,9 @@ export class WindowsApplication implements NativeApplication { callback(); } this.#readyCallbacks.length = 0; - // Each tick: drain the message queue (routing the preventable close and the - // global-shortcut WM_HOTKEY), then poll window state to surface the sent-only - // lifecycle events. - const drainMessages = createWindowsDrain( - (hwnd, message, wParam) => - dispatchPostedWindowMessage(hwnd, message, wParam) || - windowsGlobalShortcutBackend.dispatchHotkeyMessage(message, wParam), + // WM_HOTKEY is a thread message with no window proc, so only the drain sees it. + const drainMessages = createWindowsDrain((_hwnd, message, wParam) => + windowsGlobalShortcutBackend.dispatchHotkeyMessage(message, wParam), ); this.#pump = new CooperativePump(() => { drainMessages(); diff --git a/src/main/platform/windows/windows-native-window.ts b/src/main/platform/windows/windows-native-window.ts index 9b49e67e..eeb0540a 100644 --- a/src/main/platform/windows/windows-native-window.ts +++ b/src/main/platform/windows/windows-native-window.ts @@ -22,6 +22,7 @@ const RECT_SIZE = 16; const IDC_ARROW = 32512; /** `WM_COMMAND` — a menu selection (or control/accelerator) notification. */ const WM_COMMAND = 0x0111; +const WM_CLOSE = 0x0010; const CW_USEDEFAULT = -0x80000000; const WS_OVERLAPPEDWINDOW = 0x00cf0000; @@ -41,12 +42,6 @@ const SW_SHOW = 5; const WM_NCLBUTTONDOWN = 0x00a1; const HTCAPTION = 2; -const WM_SYSCOMMAND = 0x0112; -/** `wParam` low bits for the title-bar Close command. */ -const SC_CLOSE = 0xf060; -/** System-command type bits (the low 4 bits are reserved by Windows). */ -const SC_MASK = 0xfff0; - let oleInitialized = false; let classRegistered = false; // Pinned for the process lifetime: the window class references the name buffer. @@ -111,19 +106,14 @@ const ensureFrameWindowClass = (): bigint => { const user32 = loadUser32(); frameWndProc = new JSCallback( (hwnd: bigint, message: number, wParam: bigint, lParam: bigint): bigint => { - // A menu selection: HIWORD(wParam)=0 and lParam=0 (controls/accelerators differ). - if (message === WM_COMMAND && lParam === 0n && wParam >> 16n === 0n) { - const handlers = windowRegistry.get(hwnd); - if (handlers?.menuCommand !== undefined) { - try { - handlers.menuCommand(Number(wParam & 0xffffn)); - } catch { - // A throwing JS handler must never propagate into the native WndProc. - } - return 0n; - } + let handled: boolean; + try { + handled = handleFrameMessage(hwnd, message, wParam, lParam); + } catch { + // A throwing JS handler must never propagate into the native WndProc. + handled = true; } - return user32.symbols.DefWindowProcW(hwnd, message, wParam, lParam); + return handled ? 0n : user32.symbols.DefWindowProcW(hwnd, message, wParam, lParam); }, { args: [FFIType.u64, FFIType.u32, FFIType.u64, FFIType.i64], returns: FFIType.i64 }, ); @@ -215,6 +205,42 @@ const newHandlers = (destroyOnClose: boolean): NativeWindowHandlers => ({ const windowRegistry = new Map(); +/** Frame-proc messages handled here; `false` falls through to `DefWindowProcW`. */ +const handleFrameMessage = ( + hwnd: bigint, + message: number, + wParam: bigint, + lParam: bigint, +): boolean => { + const handlers = windowRegistry.get(hwnd); + if (message === WM_CLOSE) { + // Never forward: DefWindowProcW would DestroyWindow a live WebKit host (D043). + if (handlers !== undefined) { + requestClose(hwnd, handlers); + } + return true; + } + // A menu selection: HIWORD(wParam)=0 and lParam=0 (controls/accelerators differ). + if ( + message === WM_COMMAND && + lParam === 0n && + wParam >> 16n === 0n && + handlers?.menuCommand !== undefined + ) { + handlers.menuCommand(Number(wParam & 0xffffn)); + return true; + } + return false; +}; + +/** Consult the veto, then commit; a no-op once closed. */ +const requestClose = (hwnd: bigint, handlers: NativeWindowHandlers): void => { + if (handlers.closed || handlers.onClose?.() === true) { + return; + } + commitClose(hwnd, handlers); +}; + /** Run the committed-close path once: tear down the view, then destroy the window. */ const commitClose = (hwnd: bigint, handlers: NativeWindowHandlers): void => { if (handlers.closed) { @@ -242,30 +268,6 @@ const commitClose = (hwnd: bigint, handlers: NativeWindowHandlers): void => { windowRegistry.delete(hwnd); }; -/** - * Route a POSTED message to its window's lifecycle handlers. Called by the pump - * for every message before it is dispatched; returns `true` when it fully handled - * the message (the pump then skips the default dispatch). - */ -export const dispatchPostedWindowMessage = ( - hwnd: bigint, - message: number, - wParam: bigint, -): boolean => { - if (message !== WM_SYSCOMMAND || (Number(wParam) & SC_MASK) !== SC_CLOSE) { - return false; - } - const handlers = windowRegistry.get(hwnd); - if (handlers === undefined || handlers.closed) { - return false; - } - if (handlers.onClose?.() === true) { - return true; // vetoed — swallow the close so DefWindowProc never destroys it - } - commitClose(hwnd, handlers); - return true; -}; - /** * Poll every live window and fire the changed non-preventable lifecycle events * (resize / maximize / unmaximize / minimize / restore / focus / blur). Called @@ -490,15 +492,9 @@ export class NativeWin32Window { return loadUser32().symbols.IsWindowVisible(this.#hwnd) !== 0; } - /** Preventable close: consults the veto, then destroys (mirrors the title-bar path). */ + /** Preventable close: consults the veto, then commits (the same path as `WM_CLOSE`). */ close(): void { - if (this.#handlers.closed) { - return; - } - if (this.#handlers.onClose?.() === true) { - return; - } - commitClose(this.#hwnd, this.#handlers); + requestClose(this.#hwnd, this.#handlers); } /** Force-close, bypassing the veto. Idempotent. */ diff --git a/src/main/platform/windows/windows-run-loop.ts b/src/main/platform/windows/windows-run-loop.ts index f0d2e0ba..4fc7c680 100644 --- a/src/main/platform/windows/windows-run-loop.ts +++ b/src/main/platform/windows/windows-run-loop.ts @@ -23,12 +23,7 @@ const MSG_SIZE = 48; /** Max messages dispatched per tick before yielding back to Bun's loop. */ const DRAIN_BUDGET = 256; -/** - * Inspect a posted message before it is dispatched. Returns `true` when the - * message was fully handled (the drain then SKIPS the default dispatch). This is - * how the Windows backend routes window lifecycle (e.g. the preventable close) - * without a JSCallback WndProc — see `windows-native-window.ts`. - */ +/** Sees each posted message before dispatch; `true` means handled, so the drain skips it. */ export type MessageInspector = (hwnd: bigint, message: number, wParam: bigint) => boolean; /** diff --git a/tests/integration/windows/windows-native-window.test.ts b/tests/integration/windows/windows-native-window.test.ts index 51a69e96..faa22a8d 100644 --- a/tests/integration/windows/windows-native-window.test.ts +++ b/tests/integration/windows/windows-native-window.test.ts @@ -2,7 +2,6 @@ import { describe, expect, test } from 'bun:test'; import { currentPlatform } from '../../../src/common/platform'; import { loadUser32 } from '../../../src/main/platform/windows/win32-ffi'; import { - dispatchPostedWindowMessage, NativeWin32Window, pollWindows, } from '../../../src/main/platform/windows/windows-native-window'; @@ -18,6 +17,7 @@ const SWP_NOMOVE_NOZORDER_NOACTIVATE = 0x0002 | 0x0004 | 0x0010; * (a posted `WM_SYSCOMMAND`/`SC_CLOSE`), not a JSCallback WndProc. */ const isWindows = currentPlatform() === 'windows'; +const WM_CLOSE = 0x0010; const WM_SYSCOMMAND = 0x0112; const SC_CLOSE = 0xf060; @@ -73,7 +73,7 @@ describe.skipIf(!isWindows)('NativeWin32Window on Windows', () => { }); test('a posted title-bar close is vetoable, then commits with onClosed firing once', () => { - const drain = createWindowsDrain(dispatchPostedWindowMessage); + const drain = createWindowsDrain(); const win = new NativeWin32Window({ title: 'Close', width: 320, height: 240, show: false }); let closeRequests = 0; let closed = 0; @@ -101,6 +101,43 @@ describe.skipIf(!isWindows)('NativeWin32Window on Windows', () => { expect(closed).toBe(1); }); + test('a sent WM_CLOSE or SC_CLOSE goes through the veto and never destroys a WebKit host', () => { + const win = new NativeWin32Window({ + title: 'SentClose', + width: 320, + height: 240, + show: true, + destroyOnClose: false, + }); + const user32 = loadUser32().symbols; + let closeRequests = 0; + let closed = 0; + let veto = true; + win.onClose(() => { + closeRequests += 1; + return veto; + }); + win.onClosed(() => { + closed += 1; + }); + try { + user32.SendMessageW(win.hwnd(), WM_CLOSE, 0n, 0n); + expect(closeRequests).toBe(1); + expect(win.isVisible()).toBe(true); + veto = false; + user32.SendMessageW(win.hwnd(), WM_SYSCOMMAND, BigInt(SC_CLOSE), 0n); + expect(closeRequests).toBe(2); + expect(closed).toBe(1); + expect(win.isVisible()).toBe(false); + user32.SendMessageW(win.hwnd(), WM_CLOSE, 0n, 0n); + expect(closed).toBe(1); + // Still a live HWND: GetClientRect reads 0x0 once a window is destroyed. + expect(win.getClientSize().width).toBeGreaterThan(0); + } finally { + win.destroy(); + } + }); + test('programmatic close() honours the veto; destroy() forces it and is idempotent', () => { const win = new NativeWin32Window({ title: 'Prog', width: 320, height: 240, show: false }); let closed = 0; From 82794ad995f1859b6e261b41782b6c293a0512b6 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:45:03 -0700 Subject: [PATCH 015/586] fix: emit app ready after the current tick like Electron --- src/main/api/app.ts | 4 +++- tests/unit/main/api/app.test.ts | 22 ++++++++++++++++++---- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/src/main/api/app.ts b/src/main/api/app.ts index 6f86df1c..053cdcb5 100644 --- a/src/main/api/app.ts +++ b/src/main/api/app.ts @@ -98,7 +98,9 @@ export class App extends EventEmitter { return; } this.#ready = true; - this.emit('ready'); + // Deferred like Electron's post-first-tick `ready`: a listener added later this + // tick still fires, and a throwing listener cannot abort the backend's start(). + queueMicrotask(() => this.emit('ready')); } /** diff --git a/tests/unit/main/api/app.test.ts b/tests/unit/main/api/app.test.ts index 91f0395c..a86b8f29 100644 --- a/tests/unit/main/api/app.test.ts +++ b/tests/unit/main/api/app.test.ts @@ -69,7 +69,7 @@ describe('App.isReady', () => { }); describe('App.markReady', () => { - test('emits ready exactly once when called multiple times', () => { + test('emits ready exactly once when called multiple times', async () => { const a = new App(); let calls = 0; a.on('ready', () => { @@ -78,26 +78,40 @@ describe('App.markReady', () => { a.markReady(); a.markReady(); a.markReady(); + await Promise.resolve(); expect(calls).toBe(1); }); - test('fires handlers registered before markReady', () => { + test('emits ready after markReady returns, not inside it', async () => { const a = new App(); + const order: string[] = []; + a.on('ready', () => order.push('ready')); + a.markReady(); + order.push('returned'); + await Promise.resolve(); + expect(order).toEqual(['returned', 'ready']); + }); + + test('fires a handler registered in the same tick as markReady', async () => { + const a = new App(); + a.markReady(); let fired = false; a.on('ready', () => { fired = true; }); - a.markReady(); + await Promise.resolve(); expect(fired).toBe(true); }); - test('does not fire handlers registered after markReady', () => { + test('does not fire handlers registered after ready was emitted', async () => { const a = new App(); a.markReady(); + await Promise.resolve(); let fired = false; a.on('ready', () => { fired = true; }); + await Promise.resolve(); expect(fired).toBe(false); }); }); From 34c2c27e72c5415aa84ad405364ccd42b70a5d1c Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:45:15 -0700 Subject: [PATCH 016/586] fix: finish a Windows close even when a closed listener throws --- src/main/platform/windows/windows-backend.ts | 9 +++++--- .../platform/windows/windows-native-window.ts | 21 +++++++++++-------- .../windows/windows-native-window.test.ts | 15 +++++++++++++ 3 files changed, 33 insertions(+), 12 deletions(-) diff --git a/src/main/platform/windows/windows-backend.ts b/src/main/platform/windows/windows-backend.ts index a9ac4546..c9b62dad 100644 --- a/src/main/platform/windows/windows-backend.ts +++ b/src/main/platform/windows/windows-backend.ts @@ -97,9 +97,12 @@ class WindowsWindow implements NativeWindow { // execs, release the view) before surfacing `closed` to the api layer. this.#native.onClosed(() => { windowsMenuRealizer.unregisterAppMenuWindow(this.#appMenuTarget); - this.#webContents.dispose(); - for (const callback of this.#closedCallbacks) { - callback(); + try { + this.#webContents.dispose(); + } finally { + for (const callback of this.#closedCallbacks) { + callback(); + } } }); // `ready-to-show` fires once, when the page first reaches dom-ready. diff --git a/src/main/platform/windows/windows-native-window.ts b/src/main/platform/windows/windows-native-window.ts index eeb0540a..b248a3a0 100644 --- a/src/main/platform/windows/windows-native-window.ts +++ b/src/main/platform/windows/windows-native-window.ts @@ -256,16 +256,19 @@ const commitClose = (hwnd: bigint, handlers: NativeWindowHandlers): void => { } // Quiesce the hosted view first (the onClosed handler clears WebKit's clients // and detaches the view), THEN finish the window. - handlers.onClosed?.(); - if (handlers.destroyOnClose) { - loadUser32().symbols.DestroyWindow(hwnd); - } else { - // A WebKit-hosting window: synchronously destroying it crashes WebKit's - // multi-process teardown through bun:ffi, so hide it and let the OS reclaim - // the view + its WebProcess at process exit (see `.admin/WINDOWS.md`). - loadUser32().symbols.ShowWindow(hwnd, SW_HIDE); + try { + handlers.onClosed?.(); + } finally { + if (handlers.destroyOnClose) { + loadUser32().symbols.DestroyWindow(hwnd); + } else { + // A WebKit-hosting window: synchronously destroying it crashes WebKit's + // multi-process teardown through bun:ffi, so hide it and let the OS reclaim + // the view + its WebProcess at process exit (see `.admin/WINDOWS.md`). + loadUser32().symbols.ShowWindow(hwnd, SW_HIDE); + } + windowRegistry.delete(hwnd); } - windowRegistry.delete(hwnd); }; /** diff --git a/tests/integration/windows/windows-native-window.test.ts b/tests/integration/windows/windows-native-window.test.ts index faa22a8d..17efa48d 100644 --- a/tests/integration/windows/windows-native-window.test.ts +++ b/tests/integration/windows/windows-native-window.test.ts @@ -138,6 +138,21 @@ describe.skipIf(!isWindows)('NativeWin32Window on Windows', () => { } }); + test('a throwing onClosed still hides the window', () => { + const win = new NativeWin32Window({ + title: 'Throw', + width: 320, + height: 240, + show: true, + destroyOnClose: false, + }); + win.onClosed(() => { + throw new Error('closed listener'); + }); + expect(() => win.close()).toThrow('closed listener'); + expect(win.isVisible()).toBe(false); + }); + test('programmatic close() honours the veto; destroy() forces it and is idempotent', () => { const win = new NativeWin32Window({ title: 'Prog', width: 320, height: 240, show: false }); let closed = 0; From 5a5abb49c7b9b4ab9d9cfb33b813b0f5895614d1 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:45:23 -0700 Subject: [PATCH 017/586] fix: keep a cancelled block alive until the runtime invokes it --- src/main/platform/macos/cocoa-block.ts | 58 ++++++------------- .../macos/cocoa-block-cancel.test.ts | 44 +++++++++----- 2 files changed, 49 insertions(+), 53 deletions(-) diff --git a/src/main/platform/macos/cocoa-block.ts b/src/main/platform/macos/cocoa-block.ts index 370ebb49..3f5455e1 100644 --- a/src/main/platform/macos/cocoa-block.ts +++ b/src/main/platform/macos/cocoa-block.ts @@ -60,9 +60,8 @@ const descriptorPtr = (): Pointer => { return ptr(sharedDescriptor); }; -type RetainedBlock = { readonly literal: Uint8Array; readonly cb: JSCallback }; -const retained = new Set(); -const cancelable = new Map(); +type RetainedBlock = { readonly literal: Uint8Array; readonly cb: JSCallback; cancelled: boolean }; +const retained = new Map(); /** Number of blocks still awaiting their callback. Test-only. */ export const retainedBlockCount = (): number => retained.size; @@ -84,29 +83,21 @@ export const makeOneShotBlock = ( handler: (...args: BlockArg[]) => void, argTypes: readonly FFIType[] = [], ): Handle => { - let entry: RetainedBlock | undefined; + let blockPtr = 0n; const cb = new JSCallback( (...all: BlockArg[]) => { + const entry = retained.get(blockPtr); try { - // Drop the leading block pointer; hand the real args to the caller. - handler(...all.slice(1)); + if (entry !== undefined && !entry.cancelled) { + // Drop the leading block pointer; hand the real args to the caller. + handler(...all.slice(1)); + } } finally { // Deferred close: never free the trampoline inside its own invocation. - const settle = setTimeout(() => { - if (entry !== undefined) { - retained.delete(entry); - for (const [key, value] of cancelable) { - if (value === entry) { - cancelable.delete(key); - } - } - } + setTimeout(() => { + retained.delete(blockPtr); cb.close(); - }, 0); - // Don't let the cleanup timer keep the process alive on its own. - if (typeof settle === 'object' && settle !== null && 'unref' in settle) { - (settle as { unref: () => void }).unref(); - } + }, 0).unref(); } }, { args: [FFIType.ptr, ...argTypes], returns: FFIType.void }, @@ -125,30 +116,19 @@ export const makeOneShotBlock = ( view.setBigUint64(16, BigInt(invokePtr), true); // invoke view.setBigUint64(24, BigInt(descriptorPtr()), true); // descriptor - entry = { literal, cb }; - retained.add(entry); - const blockPtr = BigInt(ptr(literal)); - cancelable.set(blockPtr, entry); + blockPtr = BigInt(ptr(literal)); + retained.set(blockPtr, { literal, cb, cancelled: false }); return blockPtr; }; /** - * Release a one-shot block that will never fire (a timed-out completion). - * Without this, every timeout leaked the retained literal AND its JSCallback. - * Deferred close, same discipline as the fired path: the native side may still - * be mid-call with the trampoline. + * Silence a block whose caller gave up on it (a timed-out completion). The callee + * still holds the pointer and may invoke it later, so it stays retained until it + * fires and is then freed as usual; freeing it now would be a use-after-free. */ export const cancelOneShotBlock = (blockPtr: Handle): void => { - const entry = cancelable.get(blockPtr); - if (entry === undefined) { - return; - } - cancelable.delete(blockPtr); - const settle = setTimeout(() => { - retained.delete(entry); - entry.cb.close(); - }, 0); - if (typeof settle === 'object' && settle !== null && 'unref' in settle) { - (settle as { unref: () => void }).unref(); + const entry = retained.get(blockPtr); + if (entry !== undefined) { + entry.cancelled = true; } }; diff --git a/tests/integration/macos/cocoa-block-cancel.test.ts b/tests/integration/macos/cocoa-block-cancel.test.ts index b6c7b029..5bb49338 100644 --- a/tests/integration/macos/cocoa-block-cancel.test.ts +++ b/tests/integration/macos/cocoa-block-cancel.test.ts @@ -1,3 +1,4 @@ +import { FFIType } from 'bun:ffi'; import { describe, expect, test } from 'bun:test'; import { currentPlatform } from '../../../src/common/platform'; import { @@ -5,24 +6,39 @@ import { makeOneShotBlock, retainedBlockCount, } from '../../../src/main/platform/macos/cocoa-block'; +import { nsString } from '../../../src/main/platform/macos/cocoa-foundation'; +import { msgSendPtr } from '../../../src/main/platform/macos/cocoa-msgsend-variants'; +import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; const delay = (ms: number): Promise => new Promise((resolve) => setTimeout(resolve, ms)); -describe('cancelOneShotBlock', () => { - test.skipIf(currentPlatform() !== 'macos')( - 'a cancelled never-fired block returns retention to baseline', - async () => { - // Every timed-out printToPDF/capturePage leaked its block before this. - const baseline = retainedBlockCount(); - const block = makeOneShotBlock(() => undefined, []); - expect(retainedBlockCount()).toBe(baseline + 1); - cancelOneShotBlock(block); - await delay(20); // the close is deferred one tick by design - expect(retainedBlockCount()).toBe(baseline); - }, - ); +describe.skipIf(currentPlatform() !== 'macos')('cancelOneShotBlock', () => { + test('a cancelled block stays alive and silent until the runtime invokes it', async () => { + const rt = cocoa(); + const array = msgSendPtr( + rt.classes.get('NSArray'), + rt.selectors.get('arrayWithObject:'), + nsString('late'), + ); + await delay(20); + const baseline = retainedBlockCount(); + let fired = 0; + // ^(id obj, NSUInteger idx, BOOL *stop) + const block = makeOneShotBlock(() => { + fired += 1; + }, [FFIType.u64, FFIType.u64, FFIType.ptr]); - test.skipIf(currentPlatform() !== 'macos')('cancelling an unknown pointer is a no-op', () => { + cancelOneShotBlock(block); + await delay(20); + expect(retainedBlockCount()).toBe(baseline + 1); + + msgSendPtr(array, rt.selectors.get('enumerateObjectsUsingBlock:'), block); + expect(fired).toBe(0); + await delay(20); + expect(retainedBlockCount()).toBe(baseline); + }); + + test('cancelling an unknown pointer is a no-op', () => { expect(() => cancelOneShotBlock(0x1234n)).not.toThrow(); }); }); From 48ce2f19ead2f92de5897e641647f77d364b425f Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:45:27 -0700 Subject: [PATCH 018/586] fix: start the native app when only a ready listener waits --- src/main/bootstrap.ts | 7 +++++++ tests/unit/main/bootstrap.test.ts | 16 ++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/src/main/bootstrap.ts b/src/main/bootstrap.ts index 60a99d5a..36d5c494 100644 --- a/src/main/bootstrap.ts +++ b/src/main/bootstrap.ts @@ -51,6 +51,13 @@ export const resetBootstrapForTesting = (): void => { }; app.setStartHook(ensureNativeStarted); +// Electron starts on its own, so a bare `app.on('ready', ...)` must not let the process +// exit; the timer keeps code later in this tick ahead of the start, as in Electron. +app.on('newListener', (event: string | symbol) => { + if (event === 'ready' && !started) { + setTimeout(ensureNativeStarted, 0); + } +}); // `quit` fires only after `before-quit` and `will-quit` had their chance to veto, // so a vetoed quit leaves the run loop pumping (stopping it on `will-quit` killed // every later native callback in an app that cancelled its own quit). diff --git a/tests/unit/main/bootstrap.test.ts b/tests/unit/main/bootstrap.test.ts index 513fe749..f39987e9 100644 --- a/tests/unit/main/bootstrap.test.ts +++ b/tests/unit/main/bootstrap.test.ts @@ -101,6 +101,22 @@ describe('bootstrap native wiring', () => { expect(starts).toBe(2); }); + test('a bare ready listener starts the native app after the current tick', async () => { + const { native } = makeNative(); + let starts = 0; + resetBootstrapForTesting(); + setNativeAppForTesting({ ...native, start: () => (starts += 1) }); + const listener = (): void => undefined; + app.on('ready', listener); + try { + expect(starts).toBe(0); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(starts).toBe(1); + } finally { + app.removeListener('ready', listener); + } + }); + test('forwards native open-url to the app open-url event', () => { installSafeAppExit(); const { native, openUrl } = makeNative(); From 132d9a74842a1398661014b7726efb9472d09926 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:45:51 -0700 Subject: [PATCH 019/586] fix: contain throwing IPC listeners and unserializable invoke replies --- src/main/api/ipc-main.ts | 20 +++++++++++++++--- src/main/api/web-contents.ts | 23 +++++++++++++++++--- tests/unit/main/api/web-contents.test.ts | 26 +++++++++++++++++++++++ tests/unit/main/ipc/ipc-main.test.ts | 27 ++++++++++++++++++++++++ 4 files changed, 90 insertions(+), 6 deletions(-) diff --git a/src/main/api/ipc-main.ts b/src/main/api/ipc-main.ts index 16468737..6afb74fa 100644 --- a/src/main/api/ipc-main.ts +++ b/src/main/api/ipc-main.ts @@ -1,3 +1,4 @@ +import { createLogger } from '../../common/logger'; import type { InvokeEnvelope, ReplyEnvelope, SendEnvelope } from '../ipc/ipc-protocol'; /** @@ -15,6 +16,16 @@ export type IpcMainInvokeEvent = { readonly sender: unknown; }; +const log = createLogger('ipc-main'); + +const describeError = (error: unknown): string => { + try { + return error instanceof Error ? error.message : String(error); + } catch { + return 'non-printable error'; + } +}; + type Listener = (event: IpcMainEvent, ...args: readonly unknown[]) => void; type Handler = (event: IpcMainInvokeEvent, ...args: readonly unknown[]) => unknown; @@ -78,7 +89,11 @@ export class IpcMainImpl { ): Promise { if (envelope.kind === 'send') { for (const listener of [...(this.#listeners.get(envelope.channel) ?? [])]) { - listener(event, ...envelope.args); + try { + listener(event, ...envelope.args); + } catch (error) { + log.error(`ipcMain listener for '${envelope.channel}' threw`, error); + } } return undefined; } @@ -102,8 +117,7 @@ export class IpcMainImpl { const result = await handler(event, ...envelope.args); return { kind: 'reply', id: envelope.id, ok: true, result }; } catch (error) { - const message = error instanceof Error ? error.message : String(error); - return { kind: 'reply', id: envelope.id, ok: false, error: message }; + return { kind: 'reply', id: envelope.id, ok: false, error: describeError(error) }; } } } diff --git a/src/main/api/web-contents.ts b/src/main/api/web-contents.ts index ed2072ac..3d8e15a9 100644 --- a/src/main/api/web-contents.ts +++ b/src/main/api/web-contents.ts @@ -2,7 +2,7 @@ import { EventEmitter } from 'node:events'; import { isAbsolute, resolve } from 'node:path'; import { pathToFileURL } from 'node:url'; import { createLogger } from '../../common/logger'; -import { decodeEnvelope, encodeEnvelope } from '../ipc/ipc-protocol'; +import { decodeEnvelope, encodeEnvelope, type ReplyEnvelope } from '../ipc/ipc-protocol'; import type { KeyboardInputEvent, MouseInputEvent, @@ -32,6 +32,21 @@ export type LoadFileOptions = { /** Electron's error for a call on a destroyed window or web contents. */ export const objectDestroyedError = (): TypeError => new TypeError('Object has been destroyed'); +/** An unserializable result rejects the renderer's invoke instead of leaving it pending. */ +const encodeReply = (reply: ReplyEnvelope): string => { + try { + return encodeEnvelope(reply); + } catch (error) { + const reason = error instanceof Error ? error.message : 'unknown error'; + return encodeEnvelope({ + kind: 'reply', + id: reply.id, + ok: false, + error: `reply could not be serialized: ${reason}`, + }); + } +}; + let nextId = 1; /** @internal */ @@ -73,7 +88,9 @@ export class WebContents extends EventEmitter { nextId += 1; this.#view = native; native.onRendererEnvelope((json) => { - void this.#handleRendererEnvelope(json); + this.#handleRendererEnvelope(json).catch((error: unknown) => { + log.error('renderer envelope dispatch failed', error); + }); }); native.onNavigation((event) => { if (this.#destroyed) { @@ -328,7 +345,7 @@ export class WebContents extends EventEmitter { } const reply = await ipcMain.dispatch(envelope, { sender: this }); if (reply !== undefined && !this.#destroyed) { - this.#view.sendEnvelopeToRenderer(encodeEnvelope(reply)); + this.#view.sendEnvelopeToRenderer(encodeReply(reply)); } } } diff --git a/tests/unit/main/api/web-contents.test.ts b/tests/unit/main/api/web-contents.test.ts index 33af3318..115f6452 100644 --- a/tests/unit/main/api/web-contents.test.ts +++ b/tests/unit/main/api/web-contents.test.ts @@ -394,6 +394,32 @@ describe('WebContents <-> ipcMain auto-wiring', () => { }); }); + test('a handler result that cannot be serialized sends an error reply', async () => { + const { native, sent, fireRenderer } = makeFakeNative(); + new WebContents(native); + ipcMain.handle('add', () => ({ id: 1n })); + + fireRenderer(encodeEnvelope({ kind: 'invoke', id: 3, channel: 'add', args: [] })); + await flush(); + + const reply = decodeEnvelope(sent[0] ?? ''); + expect(reply).toMatchObject({ kind: 'reply', id: 3, ok: false }); + expect(reply.kind === 'reply' && !reply.ok ? reply.error : '').toContain('bigint'); + }); + + test('a native failure while replying is contained', async () => { + const { native, fireRenderer } = makeFakeNative(); + new WebContents({ + ...native, + sendEnvelopeToRenderer: () => { + throw new Error('view gone'); + }, + }); + ipcMain.handle('add', () => 1); + fireRenderer(encodeEnvelope({ kind: 'invoke', id: 4, channel: 'add', args: [] })); + await flush(); + }); + test('a malformed renderer envelope is dropped without throwing', async () => { const { native, sent, fireRenderer } = makeFakeNative(); new WebContents(native); diff --git a/tests/unit/main/ipc/ipc-main.test.ts b/tests/unit/main/ipc/ipc-main.test.ts index 7592c5c0..d4ec862a 100644 --- a/tests/unit/main/ipc/ipc-main.test.ts +++ b/tests/unit/main/ipc/ipc-main.test.ts @@ -126,3 +126,30 @@ describe('ipcMain.handle / dispatch invoke', () => { expect(await ipc.dispatch(invoke(6, 'x'), event)).toMatchObject({ ok: true, result: 2 }); }); }); + +describe('ipcMain dispatch containment', () => { + test('a throwing listener does not reject dispatch and later listeners still run', async () => { + let later = 0; + ipc.on('e', () => { + throw new Error('listener bug'); + }); + ipc.on('e', () => { + later += 1; + }); + expect(await ipc.dispatch(send('e'), event)).toBeUndefined(); + expect(later).toBe(1); + }); + + test('an args array too large to spread does not reject a send', async () => { + ipc.on('e', () => undefined); + const huge: SendEnvelope = { kind: 'send', channel: 'e', args: new Array(1e6) }; + expect(await ipc.dispatch(huge, event)).toBeUndefined(); + }); + + test('a handler throwing a non-printable value still replies with an error', async () => { + ipc.handle('odd', () => { + throw Object.create(null); + }); + expect(await ipc.dispatch(invoke(7, 'odd'), event)).toMatchObject({ id: 7, ok: false }); + }); +}); From aba3fab509dd4a0582153aaf793987e37e3d3c25 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:45:54 -0700 Subject: [PATCH 020/586] fix: stop minimize from resizing the Windows web view to 0x0 --- .../platform/windows/windows-native-window.ts | 29 ++++++++-------- .../windows/windows-native-window.test.ts | 33 +++++++++++++++++++ 2 files changed, 49 insertions(+), 13 deletions(-) diff --git a/src/main/platform/windows/windows-native-window.ts b/src/main/platform/windows/windows-native-window.ts index b248a3a0..4151c1ba 100644 --- a/src/main/platform/windows/windows-native-window.ts +++ b/src/main/platform/windows/windows-native-window.ts @@ -290,25 +290,28 @@ export const pollWindows = (): void => { if (h.closed) { continue; } - user32.symbols.GetClientRect(hwnd, rectPtr); - const width = read.i32(rectPtr, 8); - const height = read.i32(rectPtr, 12); - if (width !== h.width || height !== h.height) { - h.width = width; - h.height = height; - h.resizeHook?.(width, height); // keep the hosted view filling the client area - h.events.get('resize')?.(); + const minimized = user32.symbols.IsIconic(hwnd) !== 0; + if (minimized !== h.minimized) { + h.minimized = minimized; + h.events.get(minimized ? 'minimize' : 'restore')?.(); + } + // An iconic window's client rect is 0x0: never size the view (or fire resize) from it. + if (!minimized) { + user32.symbols.GetClientRect(hwnd, rectPtr); + const width = read.i32(rectPtr, 8); + const height = read.i32(rectPtr, 12); + if (width !== h.width || height !== h.height) { + h.width = width; + h.height = height; + h.resizeHook?.(width, height); + h.events.get('resize')?.(); + } } const maximized = user32.symbols.IsZoomed(hwnd) !== 0; if (maximized !== h.maximized) { h.maximized = maximized; h.events.get(maximized ? 'maximize' : 'unmaximize')?.(); } - const minimized = user32.symbols.IsIconic(hwnd) !== 0; - if (minimized !== h.minimized) { - h.minimized = minimized; - h.events.get(minimized ? 'minimize' : 'restore')?.(); - } const focused = foreground === hwnd; if (focused !== h.focused) { h.focused = focused; diff --git a/tests/integration/windows/windows-native-window.test.ts b/tests/integration/windows/windows-native-window.test.ts index 17efa48d..d3983cb4 100644 --- a/tests/integration/windows/windows-native-window.test.ts +++ b/tests/integration/windows/windows-native-window.test.ts @@ -8,6 +8,7 @@ import { import { createWindowsDrain } from '../../../src/main/platform/windows/windows-run-loop'; const SW_MAXIMIZE = 3; +const SW_MINIMIZE = 6; const SW_RESTORE = 9; const SWP_NOMOVE_NOZORDER_NOACTIVATE = 0x0002 | 0x0004 | 0x0010; @@ -216,6 +217,38 @@ describe.skipIf(!isWindows)('NativeWin32Window on Windows', () => { } }); + test('minimize and restore fire without resizing the view to 0x0', () => { + const win = new NativeWin32Window({ title: 'Min', width: 400, height: 300, show: false }); + let minimizes = 0; + let restores = 0; + let resizes = 0; + let hookCalls = 0; + win.onWindowEvent('minimize', () => { + minimizes += 1; + }); + win.onWindowEvent('restore', () => { + restores += 1; + }); + win.onWindowEvent('resize', () => { + resizes += 1; + }); + win.setResizeHook(() => { + hookCalls += 1; + }); + try { + loadUser32().symbols.ShowWindow(win.hwnd(), SW_MINIMIZE); + pollWindows(); + expect(minimizes).toBe(1); + loadUser32().symbols.ShowWindow(win.hwnd(), SW_RESTORE); + pollWindows(); + expect(restores).toBe(1); + expect(resizes).toBe(0); + expect(hookCalls).toBe(0); + } finally { + win.destroy(); + } + }); + test('show() and hide() emit show/hide synchronously', () => { const win = new NativeWin32Window({ title: 'Vis2', width: 320, height: 240, show: false }); let shows = 0; From 0cc81292ba96f60959edcba2ad56105b4255aa82 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:46:06 -0700 Subject: [PATCH 021/586] fix: report Linux load failures once, with GError detail --- src/main/platform/linux/gtk-signals.ts | 41 +++--- src/main/platform/linux/linux-backend.ts | 34 ++--- .../main/platform/linux/gtk-signals.test.ts | 124 ++++++++++++++---- 3 files changed, 136 insertions(+), 63 deletions(-) diff --git a/src/main/platform/linux/gtk-signals.ts b/src/main/platform/linux/gtk-signals.ts index 86629383..840ae3ac 100644 --- a/src/main/platform/linux/gtk-signals.ts +++ b/src/main/platform/linux/gtk-signals.ts @@ -1,4 +1,4 @@ -import { CString, JSCallback, type Pointer } from 'bun:ffi'; +import { CString, JSCallback, type Pointer, read } from 'bun:ffi'; import { createLogger } from '../../../common/logger'; import type { NativeNavigationEvent } from '../native'; import { cstr } from '../cstr'; @@ -113,41 +113,46 @@ export const makeDestroyCallback = (onClosed: () => void): JSCallback => onClosed(); }, DESTROY_CB_DEF); -export const makeLoadChangedCallback = ( +/** + * `load-changed` + `load-failed` handlers sharing one failed flag: WebKitGTK always + * emits `load-changed` FINISHED right after `load-failed`, and that FINISHED must + * not report `did-finish-load`. `load-failed` returns 0 so WebKit shows its error page. + */ +export const makeLoadCallbacks = ( onNavigation: (event: NativeNavigationEvent) => void, -): JSCallback => - new JSCallback( +): { readonly changed: JSCallback; readonly failed: JSCallback } => { + let failed = false; + const changed = new JSCallback( guarded((_self: Pointer, loadEvent: number, _userData: Pointer): void => { if (loadEvent === WEBKIT_LOAD_STARTED) { + failed = false; onNavigation({ type: 'did-start-loading' }); } else if (loadEvent === WEBKIT_LOAD_COMMITTED) { onNavigation({ type: 'did-navigate' }); - } else if (loadEvent === WEBKIT_LOAD_FINISHED) { + } else if (loadEvent === WEBKIT_LOAD_FINISHED && !failed) { onNavigation({ type: 'did-finish-load' }); onNavigation({ type: 'did-stop-loading' }); } }, undefined), LOAD_CHANGED_CB_DEF, ); - -/** - * `WebKitWebView::load-failed` handler. Emits `did-fail-load` then - * `did-stop-loading`. Returns 0 so WebKit still shows its default error page. - * Error detail is not parsed from the `GError` yet (best-effort on Linux). - */ -export const makeLoadFailedCallback = ( - onNavigation: (event: NativeNavigationEvent) => void, -): JSCallback => - new JSCallback( + const failedCallback = new JSCallback( guarded( ( _self: Pointer, _loadEvent: number, _uri: Pointer, - _error: Pointer, + error: Pointer | null, _userData: Pointer, ): number => { - onNavigation({ type: 'did-fail-load', errorCode: -1, errorDescription: '' }); + failed = true; + // GError { GQuark domain @0; gint code @4; gchar *message @8 }. + const message = error === null ? 0 : read.ptr(error, 8); + onNavigation({ + type: 'did-fail-load', + errorCode: error === null ? -1 : read.i32(error, 4), + errorDescription: message === 0 ? '' : new CString(message as Pointer).toString(), + }); onNavigation({ type: 'did-stop-loading' }); return 0; }, @@ -155,6 +160,8 @@ export const makeLoadFailedCallback = ( ), LOAD_FAILED_CB_DEF, ); + return { changed, failed: failedCallback }; +}; /** * `WebKitWebView::create` handler (`window.open` / `target=_blank`). Reads the diff --git a/src/main/platform/linux/linux-backend.ts b/src/main/platform/linux/linux-backend.ts index 44602fa8..b43de2c0 100644 --- a/src/main/platform/linux/linux-backend.ts +++ b/src/main/platform/linux/linux-backend.ts @@ -29,8 +29,7 @@ import { createLinuxDrain } from './gtk-run-loop'; import { makeCloseRequestCallback, makeCreateCallback, - makeLoadChangedCallback, - makeLoadFailedCallback, + makeLoadCallbacks, makeNotifyCallback, SignalRegistry, } from './gtk-signals'; @@ -109,26 +108,19 @@ class LinuxWebContents implements NativeWebContents { webkit.symbols.webkit_web_view_get_settings(this.#view), GTK_TRUE, ); - this.#registry.connect( - this.#view, - 'load-changed', - makeLoadChangedCallback((event) => { - if (event.type === 'did-finish-load') { - this.#didFinishLoad = true; - const queued = [...this.#pendingEnvelopes]; - this.#pendingEnvelopes.length = 0; - for (const json of queued) { - sendToRenderer(this.#view, json); - } + const load = makeLoadCallbacks((event) => { + if (event.type === 'did-finish-load') { + this.#didFinishLoad = true; + const queued = [...this.#pendingEnvelopes]; + this.#pendingEnvelopes.length = 0; + for (const json of queued) { + sendToRenderer(this.#view, json); } - this.#dispatchNavigation(event); - }), - ); - this.#registry.connect( - this.#view, - 'load-failed', - makeLoadFailedCallback((event) => this.#dispatchNavigation(event)), - ); + } + this.#dispatchNavigation(event); + }); + this.#registry.connect(this.#view, 'load-changed', load.changed); + this.#registry.connect(this.#view, 'load-failed', load.failed); this.#registry.connect( this.#view, 'create', diff --git a/tests/unit/main/platform/linux/gtk-signals.test.ts b/tests/unit/main/platform/linux/gtk-signals.test.ts index 8357ab38..5f081d30 100644 --- a/tests/unit/main/platform/linux/gtk-signals.test.ts +++ b/tests/unit/main/platform/linux/gtk-signals.test.ts @@ -1,6 +1,7 @@ -import { CFunction, type FFITypeOrString, type JSCallback } from 'bun:ffi'; +import { CFunction, type FFITypeOrString, type JSCallback, type Pointer, ptr } from 'bun:ffi'; import { describe, expect, it, test } from 'bun:test'; import { type LogRecord, resetLogger, setLogSink } from '../../../../../src/common/logger'; +import type { NativeNavigationEvent } from '../../../../../src/main/platform/native'; import { CLOSE_REQUEST_CB_DEF, closeRequestDecision, @@ -10,17 +11,31 @@ import { LOAD_CHANGED_CB_DEF, LOAD_FAILED_CB_DEF, makeCloseRequestCallback, - makeDestroyCallback, - makeLoadChangedCallback, - makeLoadFailedCallback, + makeLoadCallbacks, makeNotifyCallback, NOTIFY_CB_DEF, SCRIPT_MESSAGE_CB_DEF, SignalRegistry, } from '../../../../../src/main/platform/linux/gtk-signals'; +import { + WEBKIT_LOAD_COMMITTED, + WEBKIT_LOAD_FINISHED, + WEBKIT_LOAD_STARTED, +} from '../../../../../src/main/platform/linux/webkitgtk-ffi'; const noop = (): void => undefined; +/** Invoke a JSCallback through its native thunk, as GLib would. */ +const nativeCall = ( + cb: JSCallback, + def: { args: readonly FFITypeOrString[]; returns: FFITypeOrString }, +) => { + if (cb.ptr === null) { + throw new Error('no thunk'); + } + return CFunction({ ptr: cb.ptr, args: [...def.args], returns: def.returns }); +}; + describe('gtk-signals callback ABI definitions (shape-only)', () => { it('close-request returns i32 (inverted gboolean) with two pointer args', () => { expect(CLOSE_REQUEST_CB_DEF.args).toEqual(['ptr', 'ptr']); @@ -76,18 +91,6 @@ describe('gtk-signals JSCallback factories (constructible + closable)', () => { cb.close(); }); - it('builds destroy, load-changed, and load-failed callbacks without throwing', () => { - const destroy = makeDestroyCallback(noop); - const loadChanged = makeLoadChangedCallback(noop); - const loadFailed = makeLoadFailedCallback(noop); - expect(typeof destroy.ptr).toBe('number'); - expect(typeof loadChanged.ptr).toBe('number'); - expect(typeof loadFailed.ptr).toBe('number'); - destroy.close(); - loadChanged.close(); - loadFailed.close(); - }); - it('builds a notify callback exposing a native ptr', () => { const cb = makeNotifyCallback(noop); expect(typeof cb.ptr).toBe('number'); @@ -96,15 +99,6 @@ describe('gtk-signals JSCallback factories (constructible + closable)', () => { }); describe('a throwing handler never unwinds into GLib', () => { - const nativeCall = ( - cb: JSCallback, - def: { args: readonly FFITypeOrString[]; returns: FFITypeOrString }, - ) => { - if (cb.ptr === null) { - throw new Error('no thunk'); - } - return CFunction({ ptr: cb.ptr, args: [...def.args], returns: def.returns }); - }; const boom = (): never => { throw new Error('boom'); }; @@ -132,6 +126,86 @@ describe('a throwing handler never unwinds into GLib', () => { }); }); +describe('makeLoadCallbacks', () => { + const record = () => { + const events: NativeNavigationEvent[] = []; + const { changed, failed } = makeLoadCallbacks((event) => events.push(event)); + const loadChanged = nativeCall(changed, LOAD_CHANGED_CB_DEF); + const loadFailed = nativeCall(failed, LOAD_FAILED_CB_DEF); + return { + events, + emitChanged: (loadEvent: number) => loadChanged(null, loadEvent, null), + emitFailed: (error: Pointer | null) => loadFailed(null, 0, null, error, null), + close: () => { + changed.close(); + failed.close(); + }, + }; + }; + + /** A hand-built 64-bit `GError { GQuark domain; gint code; gchar *message }`. */ + const gError = (code: number, message: string): { ptr: Pointer; keep: unknown[] } => { + const text = Buffer.from(`${message}\0`); + const buf = new ArrayBuffer(16); + const view = new DataView(buf); + view.setUint32(0, 1, true); + view.setInt32(4, code, true); + view.setBigUint64(8, BigInt(ptr(text)), true); + return { ptr: ptr(buf), keep: [text, buf] }; + }; + + test('a successful load emits start, navigate, finish, stop', () => { + const load = record(); + load.emitChanged(WEBKIT_LOAD_STARTED); + load.emitChanged(WEBKIT_LOAD_COMMITTED); + load.emitChanged(WEBKIT_LOAD_FINISHED); + load.close(); + expect(load.events.map((e) => e.type)).toEqual([ + 'did-start-loading', + 'did-navigate', + 'did-finish-load', + 'did-stop-loading', + ]); + }); + + test('a failed load never emits did-finish-load for the FINISHED that follows it', () => { + const load = record(); + const error = gError(302, 'Load request cancelled'); + load.emitChanged(WEBKIT_LOAD_STARTED); + load.emitFailed(error.ptr); + load.emitChanged(WEBKIT_LOAD_FINISHED); + load.close(); + expect(load.events).toEqual([ + { type: 'did-start-loading' }, + { type: 'did-fail-load', errorCode: 302, errorDescription: 'Load request cancelled' }, + { type: 'did-stop-loading' }, + ]); + }); + + test('the next load after a failure finishes normally', () => { + const load = record(); + load.emitFailed(null); + load.emitChanged(WEBKIT_LOAD_FINISHED); + load.emitChanged(WEBKIT_LOAD_STARTED); + load.emitChanged(WEBKIT_LOAD_FINISHED); + load.close(); + expect(load.events.map((e) => e.type)).toEqual([ + 'did-fail-load', + 'did-stop-loading', + 'did-start-loading', + 'did-finish-load', + 'did-stop-loading', + ]); + }); + + test('a NULL GError reports code -1 with an empty description', () => { + const load = record(); + load.emitFailed(null); + load.close(); + expect(load.events[0]).toEqual({ type: 'did-fail-load', errorCode: -1, errorDescription: '' }); + }); +}); + describe('SignalRegistry', () => { it('starts empty and disconnectAll is a no-op when empty', () => { const registry = new SignalRegistry(); From 928399b2d5e52ed245024ae2701b654ba39f773d Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:46:40 -0700 Subject: [PATCH 022/586] fix: never let a callback exception unwind through native frames --- src/main/platform/macos/cocoa-block.ts | 22 ++--- .../platform/macos/cocoa-runtime-class.ts | 42 +++++----- src/main/platform/macos/objc.ts | 16 ++++ .../fixtures/native-callback-throw-probe.ts | 84 +++++++++++++++++++ .../macos/native-callback-throw.test.ts | 22 +++++ 5 files changed, 150 insertions(+), 36 deletions(-) create mode 100644 tests/integration/macos/fixtures/native-callback-throw-probe.ts create mode 100644 tests/integration/macos/native-callback-throw.test.ts diff --git a/src/main/platform/macos/cocoa-block.ts b/src/main/platform/macos/cocoa-block.ts index 3f5455e1..88ab7dd9 100644 --- a/src/main/platform/macos/cocoa-block.ts +++ b/src/main/platform/macos/cocoa-block.ts @@ -1,7 +1,7 @@ import { FFIType, JSCallback, type Pointer, ptr } from 'bun:ffi'; import { dlopen } from '../dlopen'; import { cstr } from '../cstr'; -import type { Handle } from './objc'; +import { callFromNative, type Handle } from './objc'; /** * Hand-built ObjC **Blocks** for bun:ffi — the primitive that unblocks every @@ -86,19 +86,15 @@ export const makeOneShotBlock = ( let blockPtr = 0n; const cb = new JSCallback( (...all: BlockArg[]) => { - const entry = retained.get(blockPtr); - try { - if (entry !== undefined && !entry.cancelled) { - // Drop the leading block pointer; hand the real args to the caller. - handler(...all.slice(1)); - } - } finally { - // Deferred close: never free the trampoline inside its own invocation. - setTimeout(() => { - retained.delete(blockPtr); - cb.close(); - }, 0).unref(); + if (retained.get(blockPtr)?.cancelled === false) { + // Drop the leading block pointer; hand the real args to the caller. + callFromNative(undefined, () => handler(...all.slice(1))); } + // Deferred close: never free the trampoline inside its own invocation. + setTimeout(() => { + retained.delete(blockPtr); + cb.close(); + }, 0).unref(); }, { args: [FFIType.ptr, ...argTypes], returns: FFIType.void }, ); diff --git a/src/main/platform/macos/cocoa-runtime-class.ts b/src/main/platform/macos/cocoa-runtime-class.ts index 4a251387..0d448a35 100644 --- a/src/main/platform/macos/cocoa-runtime-class.ts +++ b/src/main/platform/macos/cocoa-runtime-class.ts @@ -3,7 +3,7 @@ import { FFIType, JSCallback } from 'bun:ffi'; import { dlopen } from '../dlopen'; import { cstr } from '../cstr'; import { cocoa } from './cocoa-runtime'; -import { type Handle, LIBOBJC_PATH, macOSLibraryAccessor } from './objc'; +import { callFromNative, type Handle, LIBOBJC_PATH, macOSLibraryAccessor } from './objc'; /** * Define Objective-C classes at runtime with JS-backed methods: @@ -18,8 +18,8 @@ import { type Handle, LIBOBJC_PATH, macOSLibraryAccessor } from './objc'; * A JS-backed method to attach to a runtime class. * * `returns` defaults to `'void'`. A `'bool'` method's `impl` must return `0`/`1` - * (NO/YES) — used for delegate predicates like `windowShouldClose:` whose BOOL - * answer flows back to AppKit through the IMP's return register. + * (NO/YES); a throwing one answers YES, as in Electron a throwing listener cannot + * veto. A throwing `'object'` method answers nil. See {@link callFromNative}. */ export type ObjcMethodSpec = { /** The selector name, e.g. `userContentController:didReceiveScriptMessage:`. */ @@ -61,37 +61,33 @@ const getRuntime = macOSLibraryAccessor('objc runtime class', () => const retainedCallbacks: JSCallback[] = []; const buildCallback = (method: ObjcMethodSpec): JSCallback => { - const argTypes = [FFIType.u64, FFIType.u64, ...method.args.map(() => FFIType.u64)]; + const args = [FFIType.u64, FFIType.u64, ...method.args.map(() => FFIType.u64)]; + const impl = method.impl as (...handles: Handle[]) => unknown; + const call = (raw: ReadonlyArray): unknown => + impl(...raw.map((value) => BigInt(value))); if (method.returns === 'bool') { return new JSCallback( - (...raw: number[]): number => { - const handles = raw.map((value) => BigInt(value)) as [Handle, Handle, ...Handle[]]; - // A BOOL IMP must return 0/1; the spec types `impl` as `void` for the - // common case, so read the runtime value through `unknown` and coerce a - // stray non-1 to 0 (NO) defensively. - const result = (method.impl as (...a: Handle[]) => unknown)(...handles); - return result === 1 ? 1 : 0; - }, - { args: argTypes, returns: FFIType.u8 }, + (...raw: number[]): number => callFromNative(1, () => (call(raw) === 1 ? 1 : 0)), + { args, returns: FFIType.u8 }, ); } if (method.returns === 'object') { return new JSCallback( - (...raw: number[]): bigint => { - const handles = raw.map((value) => BigInt(value)) as [Handle, Handle, ...Handle[]]; - // An object-returning IMP yields a Handle (0n = nil); coerce defensively. - const result = (method.impl as (...a: Handle[]) => unknown)(...handles); - return typeof result === 'bigint' ? result : 0n; - }, - { args: argTypes, returns: FFIType.u64 }, + (...raw: number[]): bigint => + callFromNative(0n, () => { + const result = call(raw); + return typeof result === 'bigint' ? result : 0n; + }), + { args, returns: FFIType.u64 }, ); } return new JSCallback( (...raw: number[]) => { - const handles = raw.map((value) => BigInt(value)) as [Handle, Handle, ...Handle[]]; - method.impl(...handles); + callFromNative(undefined, () => { + call(raw); + }); }, - { args: argTypes, returns: FFIType.void }, + { args, returns: FFIType.void }, ); }; diff --git a/src/main/platform/macos/objc.ts b/src/main/platform/macos/objc.ts index dca7f99e..5321ed53 100644 --- a/src/main/platform/macos/objc.ts +++ b/src/main/platform/macos/objc.ts @@ -22,6 +22,22 @@ export const ptrIn = (handle: Handle): Pointer => Number(handle) as Pointer; export const bigIntOut = (pointer: Pointer | null): Handle => pointer === null ? 0n : BigInt(pointer); +/** + * Run JS that native code called. A throw must never unwind through native frames + * (Bun then skips every later JSCallback in that native call), so it is rethrown on + * a microtask as an ordinary uncaught exception and `fallback` goes back to native. + */ +export const callFromNative = (fallback: T, run: () => T): T => { + try { + return run(); + } catch (error) { + queueMicrotask(() => { + throw error; + }); + return fallback; + } +}; + /** * Build a memoising accessor for a macOS-only resource. The accessor opens the * resource on first call and caches it; it throws {@link UnsupportedPlatformError} diff --git a/tests/integration/macos/fixtures/native-callback-throw-probe.ts b/tests/integration/macos/fixtures/native-callback-throw-probe.ts new file mode 100644 index 00000000..e727a307 --- /dev/null +++ b/tests/integration/macos/fixtures/native-callback-throw-probe.ts @@ -0,0 +1,84 @@ +/** + * Probe: IMPs and Blocks whose JS throws. Runs in its own process because the + * rethrown errors are uncaught by design. Prints one JSON line. + */ +import { FFIType } from 'bun:ffi'; +import { makeOneShotBlock } from '../../../../src/main/platform/macos/cocoa-block'; +import { nsString } from '../../../../src/main/platform/macos/cocoa-foundation'; +import { + msgSendPtr, + msgSendReturnsU8, +} from '../../../../src/main/platform/macos/cocoa-msgsend-variants'; +import { cocoa } from '../../../../src/main/platform/macos/cocoa-runtime'; +import { defineObjcClass } from '../../../../src/main/platform/macos/cocoa-runtime-class'; + +const uncaught: string[] = []; +process.on('uncaughtException', (error) => { + uncaught.push(error.message); +}); + +const escaped: string[] = []; +const native = (label: string, call: () => T): T | undefined => { + try { + return call(); + } catch { + escaped.push(label); + return undefined; + } +}; + +const rt = cocoa(); +const sel = (name: string): bigint => rt.selectors.get(name); +let voidCalls = 0; +const cls = defineObjcClass('BunmaskaThrowProbe', 'NSObject', [ + { + selector: 'probeVoid', + typeEncoding: 'v@:', + args: [], + impl: () => { + voidCalls += 1; + throw new Error(`void ${voidCalls}`); + }, + }, + { + selector: 'probeBool', + typeEncoding: 'c@:', + args: [], + returns: 'bool', + impl: () => { + throw new Error('bool'); + }, + }, + { + selector: 'probeObject', + typeEncoding: '@@:', + args: [], + returns: 'object', + impl: () => { + throw new Error('object'); + }, + }, +]); + +const instances = rt.msgSend(rt.classes.get('NSMutableArray'), sel('new')); +for (let i = 0; i < 2; i += 1) { + msgSendPtr(instances, sel('addObject:'), rt.msgSend(rt.msgSend(cls, sel('alloc')), sel('init'))); +} +const instance = msgSendPtr(instances, sel('objectAtIndex:'), 0n); + +native('void', () => msgSendPtr(instances, sel('makeObjectsPerformSelector:'), sel('probeVoid'))); +const boolResult = native('bool', () => msgSendReturnsU8(instance, sel('probeBool'))); +const objectResult = native('object', () => rt.msgSend(instance, sel('probeObject'))); + +const one = msgSendPtr(rt.classes.get('NSArray'), sel('arrayWithObject:'), nsString('x')); +const block = makeOneShotBlock(() => { + throw new Error('block'); +}, [FFIType.u64, FFIType.u64, FFIType.ptr]); +native('block', () => msgSendPtr(one, sel('enumerateObjectsUsingBlock:'), block)); + +setTimeout(() => { + process.stdout.write( + `${JSON.stringify({ voidCalls, boolResult, objectResult: String(objectResult), escaped, uncaught })}\n`, + ); + process.exit(0); +}, 50); diff --git a/tests/integration/macos/native-callback-throw.test.ts b/tests/integration/macos/native-callback-throw.test.ts new file mode 100644 index 00000000..38c5f688 --- /dev/null +++ b/tests/integration/macos/native-callback-throw.test.ts @@ -0,0 +1,22 @@ +import { expect, test } from 'bun:test'; +import { currentPlatform } from '../../../src/common/platform'; + +test.skipIf(currentPlatform() !== 'macos')( + 'a throwing IMP or Block never unwinds through native frames and surfaces as uncaught', + async () => { + const proc = Bun.spawn( + [process.execPath, 'run', `${import.meta.dir}/fixtures/native-callback-throw-probe.ts`], + { stdout: 'pipe', stderr: 'pipe' }, + ); + const stdout = await new Response(proc.stdout).text(); + expect(await proc.exited).toBe(0); + expect(JSON.parse(stdout.trim().split('\n').at(-1) ?? '{}')).toEqual({ + voidCalls: 2, + boolResult: 1, + objectResult: '0', + escaped: [], + uncaught: ['void 1', 'void 2', 'bool', 'object', 'block'], + }); + }, + 20000, +); From 2b2ed3730f523a56af0f13b2238743650dcd4d39 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:47:08 -0700 Subject: [PATCH 023/586] fix: report restored bounds for a minimized Windows window --- src/main/platform/windows/win32-ffi.ts | 2 ++ src/main/platform/windows/win32.ts | 14 +++++++++++ src/main/platform/windows/windows-backend.ts | 10 +------- .../platform/windows/windows-native-window.ts | 24 +++++++++++++++++-- .../windows/windows-native-window.test.ts | 13 ++++++++++ .../unit/main/platform/windows/win32.test.ts | 9 +++++++ 6 files changed, 61 insertions(+), 11 deletions(-) diff --git a/src/main/platform/windows/win32-ffi.ts b/src/main/platform/windows/win32-ffi.ts index 1f3c6f91..930fe1db 100644 --- a/src/main/platform/windows/win32-ffi.ts +++ b/src/main/platform/windows/win32-ffi.ts @@ -99,6 +99,8 @@ const USER32_SYMBOLS = { IsZoomed: { args: [FFIType.u64], returns: FFIType.i32 }, // (HWND, LPRECT) -> BOOL — the window's bounds in screen coordinates. GetWindowRect: { args: [FFIType.u64, FFIType.ptr], returns: FFIType.i32 }, + // (HWND, WINDOWPLACEMENT *) -> BOOL - set `length` first; rcNormalPosition is the restored rect. + GetWindowPlacement: { args: [FFIType.u64, FFIType.ptr], returns: FFIType.i32 }, // (HWND) -> BOOL — bring the window to the foreground and focus it. SetForegroundWindow: { args: [FFIType.u64], returns: FFIType.i32 }, // () -> HWND — the window the user is currently working with. diff --git a/src/main/platform/windows/win32.ts b/src/main/platform/windows/win32.ts index 7011f62e..9c358243 100644 --- a/src/main/platform/windows/win32.ts +++ b/src/main/platform/windows/win32.ts @@ -7,8 +7,10 @@ * pointers (struct buffers, wide strings) are passed with `ptr()` as usual. */ +import { type Pointer, read } from 'bun:ffi'; import { UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; +import type { Rect } from '../native'; /** Opaque pointer-width Win32 handle (`HWND`/`HMENU`/`HINSTANCE`/...). */ export type WinHandle = bigint; @@ -35,6 +37,18 @@ export const wstr = (input: string): Uint8Array => { return out; }; +/** Read a native `RECT` (left, top, right, bottom as LONGs) at `offset` as a {@link Rect}. */ +export const readRect = (pointer: Pointer, offset: number): Rect => { + const left = read.i32(pointer, offset); + const top = read.i32(pointer, offset + 4); + return { + x: left, + y: top, + width: read.i32(pointer, offset + 8) - left, + height: read.i32(pointer, offset + 12) - top, + }; +}; + /** * Build a memoising accessor for a Windows-only resource. The accessor opens the * resource on first call and caches it; it throws {@link UnsupportedPlatformError} diff --git a/src/main/platform/windows/windows-backend.ts b/src/main/platform/windows/windows-backend.ts index c9b62dad..841a038c 100644 --- a/src/main/platform/windows/windows-backend.ts +++ b/src/main/platform/windows/windows-backend.ts @@ -24,7 +24,6 @@ import { WindowsWebContents } from './windows-web-contents'; const SW_MAXIMIZE = 3; const SW_MINIMIZE = 6; const SW_RESTORE = 9; -const RECT_SIZE = 16; const SWP_NOSIZE = 0x0001; const SWP_NOMOVE = 0x0002; @@ -171,14 +170,7 @@ class WindowsWindow implements NativeWindow { } getBounds(): Rect { - const rect = new Uint8Array(RECT_SIZE); - loadUser32().symbols.GetWindowRect(this.#hwnd(), ptr(rect)); - const dv = new DataView(rect.buffer); - const left = dv.getInt32(0, true); - const top = dv.getInt32(4, true); - const right = dv.getInt32(8, true); - const bottom = dv.getInt32(12, true); - return { x: left, y: top, width: right - left, height: bottom - top }; + return this.#native.getBounds(); } setResizable(resizable: boolean): void { diff --git a/src/main/platform/windows/windows-native-window.ts b/src/main/platform/windows/windows-native-window.ts index 4151c1ba..ed85f11b 100644 --- a/src/main/platform/windows/windows-native-window.ts +++ b/src/main/platform/windows/windows-native-window.ts @@ -2,8 +2,8 @@ import { FFIType, JSCallback, ptr, read } from 'bun:ffi'; import { isDevRestart } from '../../dev-reload'; import { FFIError } from '../../../common/errors'; import { cstr } from '../cstr'; -import type { WindowEventType } from '../native'; -import { wstr } from './win32'; +import type { Rect, WindowEventType } from '../native'; +import { readRect, wstr } from './win32'; import { loadKernel32, loadOle32, loadUser32 } from './win32-ffi'; /** @@ -19,6 +19,9 @@ const NATIVE_WINDOW_CLASS_NAME = 'BunmaskaNativeWindow'; const FRAME_WINDOW_CLASS_NAME = 'BunmaskaFrameWindow'; const WNDCLASSEXW_SIZE = 80; const RECT_SIZE = 16; +/** `sizeof(WINDOWPLACEMENT)`: length, flags, showCmd, two POINTs, then rcNormalPosition@28. */ +const WINDOWPLACEMENT_SIZE = 44; +const RC_NORMAL_POSITION_OFFSET = 28; const IDC_ARROW = 32512; /** `WM_COMMAND` — a menu selection (or control/accelerator) notification. */ const WM_COMMAND = 0x0111; @@ -475,6 +478,23 @@ export class NativeWin32Window { return { width: read.i32(rectPtr, 8), height: read.i32(rectPtr, 12) }; } + /** Outer bounds in screen pixels; while minimized, the restored rect (Electron on Windows). */ + getBounds(): Rect { + const user32 = loadUser32().symbols; + if (user32.IsIconic(this.#hwnd) !== 0) { + const placement = new Uint8Array(WINDOWPLACEMENT_SIZE); + new DataView(placement.buffer).setUint32(0, WINDOWPLACEMENT_SIZE, true); + const placementPtr = ptr(placement); + user32.GetWindowPlacement(this.#hwnd, placementPtr); + // ponytail: workspace coords, off by a top/left-docked taskbar; upgrade = add rcWork - rcMonitor + return readRect(placementPtr, RC_NORMAL_POSITION_OFFSET); + } + const rect = new Uint8Array(RECT_SIZE); + const rectPtr = ptr(rect); + user32.GetWindowRect(this.#hwnd, rectPtr); + return readRect(rectPtr, 0); + } + show(): void { const user32 = loadUser32().symbols; // A dev respawn must not take focus from the editor. diff --git a/tests/integration/windows/windows-native-window.test.ts b/tests/integration/windows/windows-native-window.test.ts index d3983cb4..4312cc21 100644 --- a/tests/integration/windows/windows-native-window.test.ts +++ b/tests/integration/windows/windows-native-window.test.ts @@ -11,6 +11,7 @@ const SW_MAXIMIZE = 3; const SW_MINIMIZE = 6; const SW_RESTORE = 9; const SWP_NOMOVE_NOZORDER_NOACTIVATE = 0x0002 | 0x0004 | 0x0010; +const SWP_NOZORDER_NOACTIVATE = 0x0004 | 0x0010; /** * Windows-only. Drives REAL native-WndProc top-level windows (the kind that can @@ -249,6 +250,18 @@ describe.skipIf(!isWindows)('NativeWin32Window on Windows', () => { } }); + test('getBounds reports the restored rect while minimized, not the -32000 icon slot', () => { + const win = new NativeWin32Window({ title: 'Bounds', width: 400, height: 300, show: true }); + try { + loadUser32().symbols.SetWindowPos(win.hwnd(), 0n, 120, 90, 500, 380, SWP_NOZORDER_NOACTIVATE); + expect(win.getBounds()).toEqual({ x: 120, y: 90, width: 500, height: 380 }); + loadUser32().symbols.ShowWindow(win.hwnd(), SW_MINIMIZE); + expect(win.getBounds()).toEqual({ x: 120, y: 90, width: 500, height: 380 }); + } finally { + win.destroy(); + } + }); + test('show() and hide() emit show/hide synchronously', () => { const win = new NativeWin32Window({ title: 'Vis2', width: 320, height: 240, show: false }); let shows = 0; diff --git a/tests/unit/main/platform/windows/win32.test.ts b/tests/unit/main/platform/windows/win32.test.ts index 7f6f57ea..d1ee3a64 100644 --- a/tests/unit/main/platform/windows/win32.test.ts +++ b/tests/unit/main/platform/windows/win32.test.ts @@ -1,8 +1,10 @@ import { describe, expect, test } from 'bun:test'; +import { ptr } from 'bun:ffi'; import { UnsupportedPlatformError } from '../../../../../src/common/errors'; import { currentPlatform } from '../../../../../src/common/platform'; import { NULL_HANDLE, + readRect, type WinHandle, winLibraryAccessor, wstr, @@ -42,6 +44,13 @@ describe('wstr', () => { }); }); +describe('readRect', () => { + test('turns a RECT (left, top, right, bottom) at an offset into x/y/width/height', () => { + const buffer = new Int32Array([7, 7, -30, 110, 220, 330]); + expect(readRect(ptr(buffer), 8)).toEqual({ x: -30, y: 110, width: 250, height: 220 }); + }); +}); + describe('NULL_HANDLE', () => { test('is the zero bigint handle', () => { const handle: WinHandle = NULL_HANDLE; From 7ef18d0330f0b82f91e5720b78a5b941a18b1c1f Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:47:12 -0700 Subject: [PATCH 024/586] fix: reject built-in and invalid schemes in protocol.handle --- src/main/api/protocol.ts | 29 +++++++++++++++++++++++++++- tests/unit/main/api/protocol.test.ts | 19 ++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/src/main/api/protocol.ts b/src/main/api/protocol.ts index a81530db..2754ef2f 100644 --- a/src/main/api/protocol.ts +++ b/src/main/api/protocol.ts @@ -1,3 +1,5 @@ +import { InvalidArgumentError } from '../../common/errors'; + /** * Custom URL-scheme registration — the drop-in equivalent of Electron's * `protocol` module (v1). Custom schemes MUST be registered on the web-view @@ -67,6 +69,22 @@ export const buildProtocolResponse = ( const registry = new Map(); +/** WKWebView raises an uncatchable NSInvalidArgumentException for these (`+handlesURLScheme:`). */ +const ENGINE_SCHEMES: ReadonlySet = new Set([ + 'http', + 'https', + 'file', + 'about', + 'data', + 'blob', + 'ws', + 'wss', + 'javascript', + 'ftp', + 'applewebdata', + 'webkit-fake-url', +]); + /** * Register `handler` to serve requests for `scheme`; re-registering replaces it. * @@ -74,7 +92,16 @@ const registry = new Map(); * created — the backends read {@link getRegisteredSchemes} at view creation. */ const handle = (scheme: string, handler: ProtocolHandler): void => { - registry.set(normalizeScheme(scheme), handler); + const normalized = normalizeScheme(scheme); + if (!/^[a-z][a-z0-9+.-]*$/.test(normalized)) { + throw new InvalidArgumentError(`protocol.handle: '${scheme}' is not a valid URL scheme`); + } + if (ENGINE_SCHEMES.has(normalized)) { + throw new InvalidArgumentError( + `protocol.handle: WebKit serves '${normalized}' itself and cannot intercept it; use a custom scheme`, + ); + } + registry.set(normalized, handler); }; /** Remove the handler for `scheme`. No-op if it was not registered. */ diff --git a/tests/unit/main/api/protocol.test.ts b/tests/unit/main/api/protocol.test.ts index 535b828c..e8050c93 100644 --- a/tests/unit/main/api/protocol.test.ts +++ b/tests/unit/main/api/protocol.test.ts @@ -1,4 +1,5 @@ import { afterEach, describe, expect, test } from 'bun:test'; +import { InvalidArgumentError } from '../../../../src/common/errors'; import { buildProtocolResponse, normalizeScheme, @@ -95,6 +96,24 @@ describe('protocol registry', () => { expect(protocol.getRegisteredSchemes()).toContain('app'); }); + test('handle rejects schemes WebKit serves natively, before registering', () => { + for (const scheme of ['https', 'HTTP://', 'file', 'about', 'data', 'blob', 'wss', 'ftp']) { + expect(() => protocol.handle(scheme, () => undefined)).toThrow(InvalidArgumentError); + } + expect(protocol.getRegisteredSchemes()).toEqual([]); + }); + + test('handle rejects names that are not valid URL schemes', () => { + for (const scheme of ['my_app', '1app', '', 'a b', 'app/x']) { + expect(() => protocol.handle(scheme, () => undefined)).toThrow(InvalidArgumentError); + } + }); + + test('handle accepts a custom scheme using + - and .', () => { + protocol.handle('my-app+v1.x', () => undefined); + expect(protocol.isProtocolHandled('my-app+v1.x')).toBe(true); + }); + test('unhandle removes the scheme', () => { protocol.handle('app', () => ({ data: 'x' })); protocol.unhandle('app'); From 64d9f6dfd6af14ebfe2193295faf4f54041aebf2 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:47:16 -0700 Subject: [PATCH 025/586] refactor: inject the page evaluator into the Linux exec channel --- src/main/platform/linux/eval-js.ts | 54 ++++--------------- src/main/platform/linux/linux-backend.ts | 9 ++-- .../unit/main/platform/linux/eval-js.test.ts | 44 +++++++++++++++ 3 files changed, 57 insertions(+), 50 deletions(-) create mode 100644 tests/unit/main/platform/linux/eval-js.test.ts diff --git a/src/main/platform/linux/eval-js.ts b/src/main/platform/linux/eval-js.ts index 3411a214..e3d49979 100644 --- a/src/main/platform/linux/eval-js.ts +++ b/src/main/platform/linux/eval-js.ts @@ -1,54 +1,26 @@ -import type { Pointer } from 'bun:ffi'; import { createLogger } from '../../../common/logger'; import { buildExecWrapper, EXEC_TIMEOUT_MS } from '../../ipc/exec-wrapper'; -import { EXEC_HANDLER_NAME, evalInPageWorld } from './webkit-ipc'; - -/** - * `WebContents.executeJavaScript` on Linux (WebKitGTK 6.0). - * - * The result returns out-of-band through a PAGE-world `bunmaskaExec` - * script-message handler — EXACTLY mirroring the macOS implementation. A - * per-call `GAsyncReadyCallback` (a `bun:ffi` {@link JSCallback}) cannot be used: - * closing it during its own invocation frees the native trampoline WebKit is - * still returning into → SIGSEGV. Instead a wrapper runs the user code and posts - * `{ execId, ok, result?, error? }` to the `bunmaskaExec` handler (registered once - * in `createWebViewWithIpc` and closed only on window teardown), which settles - * the matching pending Promise here. - * - * The wrapper is injected via the EXISTING fire-and-forget page-world eval path - * ({@link evalInPageWorld}) — NO native callback, so there is nothing to free. - */ +import { EXEC_HANDLER_NAME } from './webkit-ipc'; const log = createLogger('linux-eval-js'); -/** A pending `executeJavaScript` awaiting its page-world result message. */ type PendingExec = { readonly resolve: (value: unknown) => void; readonly reject: (reason: Error) => void; readonly timer: ReturnType; }; -/** - * Per-`LinuxWebContents` registry of in-flight `executeJavaScript` calls. Issues - * a monotonic `execId`, injects the wrapper, and settles each Promise when the - * matching `bunmaskaExec` message arrives (or on timeout / teardown). There is NO - * native callback to close — the page-world handler is shared and torn down with - * the window — so this is SAFE. - */ +/** In-flight `executeJavaScript` calls, settled by the execId the page-world wrapper posts back. */ export class ExecResultChannel { - readonly #view: Pointer; + readonly #evalInPage: (source: string) => void; readonly #pending = new Map(); #nextExecId = 1; #destroyed = false; - constructor(view: Pointer) { - this.#view = view; + constructor(evalInPage: (source: string) => void) { + this.#evalInPage = evalInPage; } - /** - * Evaluate `code` in the PAGE world and resolve to its completion value - * (Electron semantics). The outcome arrives via {@link deliverExecResult}. - */ executeJavaScript(code: string): Promise { if (this.#destroyed) { return Promise.reject(new Error('executeJavaScript failed: web contents destroyed')); @@ -61,14 +33,11 @@ export class ExecResultChannel { reject(new Error(`executeJavaScript timed out after ${EXEC_TIMEOUT_MS}ms`)); }, EXEC_TIMEOUT_MS); this.#pending.set(execId, { resolve, reject, timer }); - evalInPageWorld(this.#view, buildExecWrapper(execId, EXEC_HANDLER_NAME, code)); + this.#evalInPage(buildExecWrapper(execId, EXEC_HANDLER_NAME, code)); }); } - /** - * Settle the pending exec for the `{ execId, ok, result?, error? }` JSON the - * page-world `bunmaskaExec` handler posted. Malformed / unknown ids are dropped. - */ + /** Settle the exec named by a posted `{ execId, ok, result?, error? }`; malformed or unknown ids are dropped. */ deliverExecResult(json: string): void { let outcome: { execId?: number; ok?: boolean; result?: unknown; error?: string }; try { @@ -94,13 +63,10 @@ export class ExecResultChannel { } /** - * Mark destroyed and settle every still-pending exec; called on window close - * BEFORE the view is finalized. In-flight execs resolve to `undefined` — a - * normally closed window is not a hard error and a fire-and-forget caller must - * not receive an unhandled rejection. Any later `executeJavaScript` is rejected - * by the `#destroyed` guard without touching the freed view. + * Block new execs and resolve in-flight ones to `undefined`: a rejection here + * would reach fire-and-forget callers as an unhandled rejection, which kills Bun. */ - rejectPending(): void { + destroy(): void { this.#destroyed = true; for (const [, pending] of this.#pending) { clearTimeout(pending.timer); diff --git a/src/main/platform/linux/linux-backend.ts b/src/main/platform/linux/linux-backend.ts index b43de2c0..f33e243a 100644 --- a/src/main/platform/linux/linux-backend.ts +++ b/src/main/platform/linux/linux-backend.ts @@ -33,7 +33,7 @@ import { makeNotifyCallback, SignalRegistry, } from './gtk-signals'; -import { createWebViewWithIpc, sendToRenderer } from './webkit-ipc'; +import { createWebViewWithIpc, evalInPageWorld, sendToRenderer } from './webkit-ipc'; import { capturePage as webkitCapturePage } from './webkit-snapshot'; import { registerAllSchemes } from './webkit-uri-scheme'; import { loadWebKitGtkFFI, readGetUriResult } from './webkitgtk-ffi'; @@ -60,7 +60,7 @@ const GTK_ORIENTATION_VERTICAL = 1; class LinuxWebContents implements NativeWebContents { readonly #view: Pointer; readonly #registry: SignalRegistry; - readonly #exec: ExecResultChannel; + readonly #exec = new ExecResultChannel((source) => evalInPageWorld(this.#view, source)); #didFinishLoad = false; readonly #pendingEnvelopes: string[] = []; readonly #navigationCallbacks: Array<(event: NativeNavigationEvent) => void> = []; @@ -84,8 +84,6 @@ class LinuxWebContents implements NativeWebContents { callback(json); } }, - // The page-world `bunmaskaExec` return channel for `executeJavaScript`. The - // exec channel is constructed below (it needs the view), so forward late. onExecMessage: (json: string) => { this.#exec.deliverExecResult(json); }, @@ -95,7 +93,6 @@ class LinuxWebContents implements NativeWebContents { }); this.#view = wired.view; this.#registry = wired.registry; - this.#exec = new ExecResultChannel(this.#view); // Wire every custom scheme registered via `protocol.handle` onto THIS view's // WebKitWebContext before any load, so `app://…` loads are served. Each // scheme registers once per process (the dedup guard inside); the request @@ -244,7 +241,7 @@ class LinuxWebContents implements NativeWebContents { /** @internal Reject every still-pending exec; called on window close. */ rejectPendingExecs(): void { - this.#exec.rejectPending(); + this.#exec.destroy(); } openDevTools(): void { diff --git a/tests/unit/main/platform/linux/eval-js.test.ts b/tests/unit/main/platform/linux/eval-js.test.ts new file mode 100644 index 00000000..22b5bccf --- /dev/null +++ b/tests/unit/main/platform/linux/eval-js.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, test } from 'bun:test'; +import { ExecResultChannel } from '../../../../../src/main/platform/linux/eval-js'; + +/** A channel whose injected evaluator records the execId of each wrapper it runs. */ +const channel = () => { + const ids: number[] = []; + const exec = new ExecResultChannel((source) => { + const match = /execId: (\d+)/.exec(source); + ids.push(Number(match?.[1])); + }); + const deliver = (execId: number | undefined, ok: boolean, result?: unknown) => + exec.deliverExecResult(JSON.stringify({ execId, ok, result, error: 'page threw' })); + return { exec, ids, deliver }; +}; + +describe('ExecResultChannel', () => { + test('settles the pending call whose execId the page posts back', async () => { + const { exec, ids, deliver } = channel(); + const result = exec.executeJavaScript('1 + 1'); + deliver(ids[0], true, 2); + expect(await result).toBe(2); + }); + + test('rejects with the page error when the wrapper reports ok: false', async () => { + const { exec, ids, deliver } = channel(); + const result = exec.executeJavaScript('boom()'); + deliver(ids[0], false); + await expect(result).rejects.toThrow('page threw'); + }); + + test('malformed and unknown results are dropped without throwing', () => { + const { exec } = channel(); + expect(() => exec.deliverExecResult('{not json')).not.toThrow(); + expect(() => exec.deliverExecResult('{"ok":true}')).not.toThrow(); + }); + + test('destroy resolves in-flight calls to undefined and rejects later ones', async () => { + const { exec } = channel(); + const inFlight = exec.executeJavaScript('1'); + exec.destroy(); + expect(await inFlight).toBeUndefined(); + await expect(exec.executeJavaScript('2')).rejects.toThrow('destroyed'); + }); +}); From 4057551d86069132ef8c5f94b676ebab9d697117 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:47:07 -0700 Subject: [PATCH 026/586] fix: throw when defineObjcClass cannot install an IMP --- .../platform/macos/cocoa-runtime-class.ts | 20 ++++++++++++------- .../macos/cocoa-runtime-class.test.ts | 12 +++++++++++ 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/src/main/platform/macos/cocoa-runtime-class.ts b/src/main/platform/macos/cocoa-runtime-class.ts index 0d448a35..95262b77 100644 --- a/src/main/platform/macos/cocoa-runtime-class.ts +++ b/src/main/platform/macos/cocoa-runtime-class.ts @@ -115,13 +115,19 @@ export const defineObjcClass = ( for (const method of methods) { const callback = buildCallback(method); retainedCallbacks.push(callback); - const imp = callback.ptr === null ? 0n : BigInt(callback.ptr); - runtime.symbols.class_addMethod( - cls, - rt.selectors.get(method.selector), - imp, - cstr(method.typeEncoding), - ); + if ( + callback.ptr === null || + runtime.symbols.class_addMethod( + cls, + rt.selectors.get(method.selector), + BigInt(callback.ptr), + cstr(method.typeEncoding), + ) === 0 + ) { + throw new BunmaskaError( + `defineObjcClass: could not add ${method.selector} to ${name} (a duplicate selector, or no IMP)`, + ); + } } runtime.symbols.objc_registerClassPair(cls); diff --git a/tests/integration/macos/cocoa-runtime-class.test.ts b/tests/integration/macos/cocoa-runtime-class.test.ts index 9d23ad83..eb339bc1 100644 --- a/tests/integration/macos/cocoa-runtime-class.test.ts +++ b/tests/integration/macos/cocoa-runtime-class.test.ts @@ -66,5 +66,17 @@ if (currentPlatform() === 'macos') { expect(msgSendReturnsU8(instance, rt.selectors.get('bunmaskaShouldYes'))).toBe(1); expect(msgSendReturnsU8(instance, rt.selectors.get('bunmaskaShouldNo'))).toBe(0); }); + + test('throws when a selector is added twice instead of dropping the second impl', () => { + const spec = { + selector: 'bunmaskaTwice', + typeEncoding: 'v@:', + args: [], + impl: () => undefined, + }; + expect(() => defineObjcClass('BunmaskaTestClassTwice', 'NSObject', [spec, spec])).toThrow( + /bunmaskaTwice/, + ); + }); }); } From 3643ccdc41eba42065d83ca360f7fd3cb660e1e5 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:47:24 -0700 Subject: [PATCH 027/586] fix: free replaced macOS menus and their click handlers --- src/main/platform/macos/cocoa-menu.ts | 69 ++++++++++++++++++---- src/main/platform/macos/cocoa-tray.ts | 6 ++ tests/helpers/objc-weak.ts | 18 ++++++ tests/integration/macos/cocoa-menu.test.ts | 68 +++++++++++++++++---- tests/integration/macos/cocoa-tray.test.ts | 37 ++++++++++++ 5 files changed, 177 insertions(+), 21 deletions(-) create mode 100644 tests/helpers/objc-weak.ts diff --git a/src/main/platform/macos/cocoa-menu.ts b/src/main/platform/macos/cocoa-menu.ts index 642007d6..a0e6a833 100644 --- a/src/main/platform/macos/cocoa-menu.ts +++ b/src/main/platform/macos/cocoa-menu.ts @@ -162,6 +162,7 @@ const realizeItem = (spec: NativeMenuItemSpec): Handle => { if (spec.type === 'submenu' && spec.submenu !== undefined) { const submenu = realizeMenu(spec.submenu); msgSendPtr(item, rt.selectors.get('setSubmenu:'), submenu); + rt.msgSend(submenu, rt.selectors.get('release')); } return item; @@ -175,19 +176,59 @@ export const realizeMenu = (items: ReadonlyArray): Handle => rt.selectors.get('init'), ); for (const spec of items) { - msgSendPtr(menu, rt.selectors.get('addItem:'), realizeItem(spec)); + const item = realizeItem(spec); + msgSendPtr(menu, rt.selectors.get('addItem:'), item); + if (spec.type !== 'separator') { + rt.msgSend(item, rt.selectors.get('release')); // separatorItem is +0 + } } return menu; }; +const forgetItems = (menu: Handle): void => { + const rt = cocoa(); + for (let i = menuItemCount(menu) - 1; i >= 0; i -= 1) { + const item = msgSendI64(menu, rt.selectors.get('itemAtIndex:'), BigInt(i)); + clickRegistry.delete(item); + const submenu = rt.msgSend(item, rt.selectors.get('submenu')); + if (submenu !== 0n) { + forgetItems(submenu); + } + } +}; + +/** + * Drop a realized menu's handlers and our +1 on it. Deferred a tick, never inline: + * a click handler may be replacing the very menu AppKit is dispatching from. + */ +export const disposeMenu = (menu: Handle): void => { + if (menu === 0n) { + return; + } + setTimeout(() => { + forgetItems(menu); + cocoa().msgSend(menu, cocoa().selectors.get('release')); + }, 0); +}; + +let mainMenu: Handle = 0n; +let lastPopup: Handle = 0n; + /** Install `menu` as the application's main menu bar. */ /** Install `menu` as the main menu; `0n` (nil) clears the menu bar. */ export const setApplicationMenu = (menu: Handle): void => { const rt = cocoa(); const app = rt.msgSend(rt.classes.get('NSApplication'), rt.selectors.get('sharedApplication')); msgSendPtr(app, rt.selectors.get('setMainMenu:'), menu); + if (mainMenu !== menu) { + disposeMenu(mainMenu); + mainMenu = menu; + } }; +/** @internal */ +export const clickRegistrySize = (): number => clickRegistry.size; + /** Number of items in a realized menu. Used for verification. */ export const menuItemCount = (menu: Handle): number => Number(msgSendReturnsI64(menu, cocoa().selectors.get('numberOfItems'))); @@ -209,15 +250,23 @@ export const performMenuItem = (menu: Handle, index: number): void => { * AppKit-owned nested loop). Item clicks route through the shared `BunmaskaMenuTarget` registry * exactly as for an application menu. `item = nil` anchors the menu's top-left at the location. */ -export const popUpMenu = (menu: Handle, view: Handle, x: number, y: number): boolean => - msgSendPtrPointPtrReturnsU8( - menu, - cocoa().selectors.get('popUpMenuPositioningItem:atLocation:inView:'), - 0n, // item = nil - x, - y, - view, - ) === 1; +export const popUpMenu = (menu: Handle, view: Handle, x: number, y: number): boolean => { + // ponytail: the previous popup tree lives until the next popup; freeing it on return would race a click AppKit may still deliver. + if (lastPopup !== menu) { + disposeMenu(lastPopup); + lastPopup = menu; + } + return ( + msgSendPtrPointPtrReturnsU8( + menu, + cocoa().selectors.get('popUpMenuPositioningItem:atLocation:inView:'), + 0n, // item = nil + x, + y, + view, + ) === 1 + ); +}; /** Cancel an in-progress context-menu tracking session (`-[NSMenu cancelTracking]`). */ export const cancelMenuTracking = (menu: Handle): void => { diff --git a/src/main/platform/macos/cocoa-tray.ts b/src/main/platform/macos/cocoa-tray.ts index 2bee5af8..eac63139 100644 --- a/src/main/platform/macos/cocoa-tray.ts +++ b/src/main/platform/macos/cocoa-tray.ts @@ -1,6 +1,7 @@ import type { Menu } from '../../api/menu'; import type { TrayBackend, TrayInstance, TrayImageOptions } from '../../api/tray'; import { nsString } from './cocoa-foundation'; +import { disposeMenu } from './cocoa-menu'; import { msgSendF64, msgSendPtr, msgSendU8 } from './cocoa-msgsend-variants'; import { cocoa } from './cocoa-runtime'; import { defineObjcClass } from './cocoa-runtime-class'; @@ -98,6 +99,7 @@ const create = (image: string, options?: TrayImageOptions): TrayInstance => { applyImage(image, options?.template === true); let destroyed = false; + let contextMenu: Handle = 0n; return { setToolTip: (toolTip) => { @@ -120,6 +122,8 @@ const create = (image: string, options?: TrayImageOptions): TrayInstance => { // BunmaskaMenuTarget registry, exactly like an application menu. const nsMenu: Handle = menu === null ? 0n : menu.realize(); msgSendPtr(item, rt.selectors.get('setMenu:'), nsMenu); + disposeMenu(contextMenu); + contextMenu = nsMenu; }, onClick: (cb) => { const btn = button(); @@ -141,6 +145,8 @@ const create = (image: string, options?: TrayImageOptions): TrayInstance => { } msgSendPtr(systemStatusBar(), rt.selectors.get('removeStatusItem:'), item); rt.msgSend(item, rt.selectors.get('release')); + disposeMenu(contextMenu); + contextMenu = 0n; }, isDestroyed: () => destroyed, }; diff --git a/tests/helpers/objc-weak.ts b/tests/helpers/objc-weak.ts new file mode 100644 index 00000000..5d8c077a --- /dev/null +++ b/tests/helpers/objc-weak.ts @@ -0,0 +1,18 @@ +import { dlopen, FFIType, ptr } from 'bun:ffi'; +import { LIBOBJC_PATH } from '../../src/main/platform/macos/objc'; + +let lib: ReturnType | undefined; +const open = () => + dlopen(LIBOBJC_PATH, { + objc_storeWeak: { args: [FFIType.pointer, FFIType.u64], returns: FFIType.u64 }, + objc_loadWeakRetained: { args: [FFIType.pointer], returns: FFIType.u64 }, + }); + +/** A zeroing weak reference to an ObjC object: the getter reads 0n once it is deallocated. macOS only. */ +export const objcWeakRef = (object: bigint): (() => bigint) => { + lib ??= open(); + const { symbols } = lib; + const slot = new BigUint64Array(1); + symbols.objc_storeWeak(ptr(slot), object); + return () => symbols.objc_loadWeakRetained(ptr(slot)); +}; diff --git a/tests/integration/macos/cocoa-menu.test.ts b/tests/integration/macos/cocoa-menu.test.ts index dbf7f2c3..18083a72 100644 --- a/tests/integration/macos/cocoa-menu.test.ts +++ b/tests/integration/macos/cocoa-menu.test.ts @@ -1,6 +1,8 @@ import { beforeAll, describe, expect, test } from 'bun:test'; import { currentPlatform } from '../../../src/common/platform'; import { + clickRegistrySize, + disposeMenu, menuItemCount, type NativeMenuItemSpec, performMenuItem, @@ -14,6 +16,7 @@ import { } from '../../../src/main/platform/macos/cocoa-msgsend-variants'; import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; import type { Handle } from '../../../src/main/platform/macos/objc'; +import { objcWeakRef } from '../../helpers/objc-weak'; /** Realize one item and run AppKit's autoenable pass, as opening the menu or a key press does. */ const realizeAndValidate = (spec: NativeMenuItemSpec): { menu: Handle; item: Handle } => { @@ -23,6 +26,19 @@ const realizeAndValidate = (spec: NativeMenuItemSpec): { menu: Handle; item: Han return { menu, item: msgSendI64(menu, rt.selectors.get('itemAtIndex:'), 0n) }; }; +const appSubmenu = (): NativeMenuItemSpec => ({ + label: 'App', + type: 'submenu', + enabled: true, + keyEquivalent: '', + submenu: [ + { label: 'About', type: 'normal', enabled: true, keyEquivalent: '', onClick: () => undefined }, + ], +}); + +/** Bun.sleep(0) resolves before a pending setTimeout(0); this waits for it. */ +const nextTick = (): Promise => new Promise((resolve) => setTimeout(resolve, 0)); + const isEnabled = (item: Handle): boolean => msgSendReturnsU8(item, cocoa().selectors.get('isEnabled')) === 1; @@ -192,17 +208,47 @@ if (currentPlatform() === 'macos') { expect(menuItemCount(submenu)).toBe(2); }); - test('setApplicationMenu installs the menu without throwing', () => { - const menu = realizeMenu([ - { - label: 'App', - type: 'submenu', - enabled: true, - keyEquivalent: '', - submenu: [{ label: 'Quit', type: 'normal', enabled: true, keyEquivalent: 'q' }], - }, - ]); - expect(() => setApplicationMenu(menu)).not.toThrow(); + test('setApplicationMenu installs the menu as the main menu', () => { + const rt = cocoa(); + const menu = realizeMenu([appSubmenu()]); + setApplicationMenu(menu); + const app = rt.msgSend( + rt.classes.get('NSApplication'), + rt.selectors.get('sharedApplication'), + ); + expect(rt.msgSend(app, rt.selectors.get('mainMenu'))).toBe(menu); + }); + + test('disposeMenu frees the whole tree and forgets its handlers', async () => { + const rt = cocoa(); + await nextTick(); + const registered = clickRegistrySize(); + const menu = realizeMenu([appSubmenu()]); + const submenu = rt.msgSend( + msgSendI64(menu, rt.selectors.get('itemAtIndex:'), 0n), + rt.selectors.get('submenu'), + ); + const menuRef = objcWeakRef(menu); + const itemRef = objcWeakRef(msgSendI64(submenu, rt.selectors.get('itemAtIndex:'), 0n)); + + disposeMenu(menu); + await nextTick(); + + expect(menuRef()).toBe(0n); + expect(itemRef()).toBe(0n); + expect(clickRegistrySize()).toBe(registered); + }); + + // AppKit may hold the outgoing main menu past a tick, so this checks our side only. + test('replacing the application menu disposes the old one', async () => { + setApplicationMenu(realizeMenu([appSubmenu()])); + await nextTick(); + const registered = clickRegistrySize(); + + setApplicationMenu(realizeMenu([appSubmenu()])); + await nextTick(); + + expect(clickRegistrySize()).toBe(registered); }); }); } diff --git a/tests/integration/macos/cocoa-tray.test.ts b/tests/integration/macos/cocoa-tray.test.ts index 8d1b5072..d1584762 100644 --- a/tests/integration/macos/cocoa-tray.test.ts +++ b/tests/integration/macos/cocoa-tray.test.ts @@ -4,6 +4,18 @@ import { Menu } from '../../../src/main/api/menu'; import { Tray } from '../../../src/main/api/tray'; import { resetBootstrapForTesting } from '../../../src/main/bootstrap'; import { nativeApp, setNativeAppForTesting } from '../../../src/main/native-app'; +import { clickRegistrySize, realizeMenu } from '../../../src/main/platform/macos/cocoa-menu'; +import { macosTrayBackend } from '../../../src/main/platform/macos/cocoa-tray'; + +/** A Menu whose realize() yields a pre-built NSMenu, so the test can watch that handle. */ +const menuRealizingTo = (handle: bigint): Menu => ({ realize: () => handle }) as unknown as Menu; + +const nextTick = (): Promise => new Promise((resolve) => setTimeout(resolve, 0)); + +const realizeClickableMenu = (): bigint => + realizeMenu([ + { label: 'A', type: 'normal', enabled: true, keyEquivalent: '', onClick: () => undefined }, + ]); /** * Real NSStatusItem lifecycle on a macOS host. A status-bar click cannot be @@ -69,6 +81,31 @@ if (currentPlatform() === 'macos') { expect(tray.isDestroyed()).toBe(true); }); + // AppKit may hold a status item's menu past a tick, so these check our side only. + test('replacing the context menu disposes the previous one', async () => { + const tray = macosTrayBackend.create('/tmp/icon.png'); + try { + await nextTick(); + const registered = clickRegistrySize(); + tray.setContextMenu(menuRealizingTo(realizeClickableMenu())); + tray.setContextMenu(null); + await nextTick(); + expect(clickRegistrySize()).toBe(registered); + } finally { + tray.destroy(); + } + }); + + test('destroy disposes the context menu', async () => { + const tray = macosTrayBackend.create('/tmp/icon.png'); + await nextTick(); + const registered = clickRegistrySize(); + tray.setContextMenu(menuRealizingTo(realizeClickableMenu())); + tray.destroy(); + await nextTick(); + expect(clickRegistrySize()).toBe(registered); + }); + test('destroy is idempotent on the real backend', () => { const tray = new Tray('/tmp/icon.png'); tray.destroy(); From a105e46212b6b230fb9fba15ff32cd2d49e251e3 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:47:33 -0700 Subject: [PATCH 028/586] fix: remove the single-instance lock when the process exits --- src/main/api/single-instance-backend.ts | 31 ++++++++++--------- .../single-instance-backend.test.ts | 29 +++++++++++++++++ 2 files changed, 45 insertions(+), 15 deletions(-) diff --git a/src/main/api/single-instance-backend.ts b/src/main/api/single-instance-backend.ts index a9b85743..c831f811 100644 --- a/src/main/api/single-instance-backend.ts +++ b/src/main/api/single-instance-backend.ts @@ -14,12 +14,13 @@ type UnixSocketListener = { stop(closeActiveConnections?: boolean): void }; export const createLockBackend = (): LockBackend => { let server: UnixSocketListener | undefined; + let removeLockOnExit: (() => void) | undefined; - const removeSocketFile = (socketPath: string): void => { + const removeFile = (path: string): void => { try { - rmSync(socketPath, { force: true }); + rmSync(path, { force: true }); } catch (error) { - log.warn('could not remove stale socket', error); + log.warn(`could not remove ${path}`, error); } }; @@ -29,6 +30,10 @@ export const createLockBackend = (): LockBackend => { mkdirSync(dirname(lockPath), { recursive: true }); // `wx` fails if the file already exists — the atomic acquire. writeFileSync(lockPath, String(pid), { flag: 'wx' }); + // A lock left behind names a pid the OS will reuse, blocking every later launch. + // Prepended so it runs before the Windows TerminateProcess exit hook (D043). + removeLockOnExit = () => removeFile(lockPath); + process.prependOnceListener('exit', removeLockOnExit); return true; } catch { return false; @@ -56,16 +61,12 @@ export const createLockBackend = (): LockBackend => { }, clearLock(lockPath) { - try { - rmSync(lockPath, { force: true }); - } catch (error) { - log.warn('could not clear stale lock', error); - } + removeFile(lockPath); }, startServer(socketPath, onMessage) { // A leftover socket file from a crashed primary would block bind. - removeSocketFile(socketPath); + removeFile(socketPath); const chunks = new WeakMap(); server = Bun.listen({ unix: socketPath, @@ -109,14 +110,14 @@ export const createLockBackend = (): LockBackend => { }, stop(lockPath, socketPath) { + if (removeLockOnExit !== undefined) { + process.removeListener('exit', removeLockOnExit); + removeLockOnExit = undefined; + } server?.stop(true); server = undefined; - try { - rmSync(lockPath, { force: true }); - } catch (error) { - log.warn('could not remove lock on release', error); - } - removeSocketFile(socketPath); + removeFile(lockPath); + removeFile(socketPath); }, }; }; diff --git a/tests/integration/single-instance-backend.test.ts b/tests/integration/single-instance-backend.test.ts index 48a5c9a9..713eafac 100644 --- a/tests/integration/single-instance-backend.test.ts +++ b/tests/integration/single-instance-backend.test.ts @@ -61,6 +61,35 @@ describe('createLockBackend — pidfile', () => { backend.clearLock(lockPath); expect(existsSync(lockPath)).toBe(false); }); + + /** Run `body` in a child Bun process with `backend` = a fresh live backend. */ + const runChild = (body: string): number | null => { + const backendModule = join(import.meta.dir, '../../src/main/api/single-instance-backend.ts'); + const script = [ + `import { writeFileSync } from 'node:fs';`, + `import { createLockBackend } from ${JSON.stringify(backendModule)};`, + 'const backend = createLockBackend();', + `const lockPath = ${JSON.stringify(lockPath)};`, + body, + 'process.exit(0);', + ].join('\n'); + return Bun.spawnSync([process.execPath, '-e', script]).exitCode; + }; + + test('a lock still held when the process exits is removed', () => { + expect(runChild('backend.tryCreateLock(lockPath, process.pid);')).toBe(0); + expect(existsSync(lockPath)).toBe(false); + }); + + test("exit leaves alone a lock another instance took after this one's release", () => { + const body = [ + 'backend.tryCreateLock(lockPath, process.pid);', + `backend.stop(lockPath, lockPath + '.sock');`, + `writeFileSync(lockPath, '1');`, + ].join('\n'); + expect(runChild(body)).toBe(0); + expect(existsSync(lockPath)).toBe(true); + }); }); describe('createLockBackend — socket hand-off', () => { From 23e891a86efdb0f7876c2314c7448a05a1c6f5fd Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:47:34 -0700 Subject: [PATCH 029/586] fix: use unguessable executeJavaScript ids on Linux --- src/main/platform/linux/eval-js.ts | 10 +++++++--- tests/unit/main/platform/linux/eval-js.test.ts | 16 ++++++++++++++++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/src/main/platform/linux/eval-js.ts b/src/main/platform/linux/eval-js.ts index e3d49979..75c3594a 100644 --- a/src/main/platform/linux/eval-js.ts +++ b/src/main/platform/linux/eval-js.ts @@ -4,6 +4,12 @@ import { EXEC_HANDLER_NAME } from './webkit-ipc'; const log = createLogger('linux-eval-js'); +/** Unguessable, because every frame can post to the page-world `bunmaskaExec` handler. */ +const randomExecId = (): number => { + const [high = 0, low = 0] = crypto.getRandomValues(new Uint32Array(2)); + return (high >>> 11) * 2 ** 32 + low; +}; + type PendingExec = { readonly resolve: (value: unknown) => void; readonly reject: (reason: Error) => void; @@ -14,7 +20,6 @@ type PendingExec = { export class ExecResultChannel { readonly #evalInPage: (source: string) => void; readonly #pending = new Map(); - #nextExecId = 1; #destroyed = false; constructor(evalInPage: (source: string) => void) { @@ -25,8 +30,7 @@ export class ExecResultChannel { if (this.#destroyed) { return Promise.reject(new Error('executeJavaScript failed: web contents destroyed')); } - const execId = this.#nextExecId; - this.#nextExecId += 1; + const execId = randomExecId(); return new Promise((resolve, reject) => { const timer = setTimeout(() => { this.#pending.delete(execId); diff --git a/tests/unit/main/platform/linux/eval-js.test.ts b/tests/unit/main/platform/linux/eval-js.test.ts index 22b5bccf..2a17b3bd 100644 --- a/tests/unit/main/platform/linux/eval-js.test.ts +++ b/tests/unit/main/platform/linux/eval-js.test.ts @@ -13,6 +13,11 @@ const channel = () => { return { exec, ids, deliver }; }; +const isPending = async (promise: Promise): Promise => { + const marker = Symbol('pending'); + return (await Promise.race([promise, Promise.resolve(marker)])) === marker; +}; + describe('ExecResultChannel', () => { test('settles the pending call whose execId the page posts back', async () => { const { exec, ids, deliver } = channel(); @@ -28,6 +33,17 @@ describe('ExecResultChannel', () => { await expect(result).rejects.toThrow('page threw'); }); + test('a guessed sequential execId cannot settle a pending call', async () => { + const { exec, ids, deliver } = channel(); + const result = exec.executeJavaScript('document.title'); + for (let guess = 0; guess < 100; guess += 1) { + deliver(guess, true, 'forged'); + } + expect(await isPending(result)).toBe(true); + deliver(ids[0], true, 'real'); + expect(await result).toBe('real'); + }); + test('malformed and unknown results are dropped without throwing', () => { const { exec } = channel(); expect(() => exec.deliverExecResult('{not json')).not.toThrow(); From c237372d9b7fbeaeccf0eb43faaa077653e70b16 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:47:40 -0700 Subject: [PATCH 030/586] fix: emit move for Windows windows --- src/main/platform/windows/windows-backend.ts | 2 +- .../platform/windows/windows-native-window.ts | 17 +++++++- .../windows/windows-native-window.test.ts | 39 +++++++++++++++++++ 3 files changed, 56 insertions(+), 2 deletions(-) diff --git a/src/main/platform/windows/windows-backend.ts b/src/main/platform/windows/windows-backend.ts index 841a038c..463746c2 100644 --- a/src/main/platform/windows/windows-backend.ts +++ b/src/main/platform/windows/windows-backend.ts @@ -338,7 +338,7 @@ class WindowsWindow implements NativeWindow { } onWindowEvent(type: WindowEventType, callback: () => void): void { - // focus/blur/resize/maximize/minimize/restore are surfaced by the pump poll + // focus/blur/move/resize/maximize/minimize/restore are surfaced by the pump poll // (pollWindows); show/hide fire from the window directly; ready-to-show fires // on the first dom-ready. The close/closed pair flows through onClose/onClosed. this.#native.onWindowEvent(type, callback); diff --git a/src/main/platform/windows/windows-native-window.ts b/src/main/platform/windows/windows-native-window.ts index ed85f11b..16029061 100644 --- a/src/main/platform/windows/windows-native-window.ts +++ b/src/main/platform/windows/windows-native-window.ts @@ -188,6 +188,8 @@ interface NativeWindowHandlers { /** Whether the committed close destroys the window (false = hide; see commitClose). */ destroyOnClose: boolean; /** Last-observed state for the pump's change detection (see {@link pollWindows}). */ + x: number; + y: number; width: number; height: number; focused: boolean; @@ -198,6 +200,8 @@ interface NativeWindowHandlers { const newHandlers = (destroyOnClose: boolean): NativeWindowHandlers => ({ closed: false, events: new Map(), + x: 0, + y: 0, width: 0, height: 0, focused: false, @@ -276,7 +280,7 @@ const commitClose = (hwnd: bigint, handlers: NativeWindowHandlers): void => { /** * Poll every live window and fire the changed non-preventable lifecycle events - * (resize / maximize / unmaximize / minimize / restore / focus / blur). Called + * (move / resize / maximize / unmaximize / minimize / restore / focus / blur). Called * each pump tick: WebKit's host uses a native WndProc, so these SENT-only state * changes never reach the message queue and must be observed by polling. `show` * and `hide` are fired directly from {@link NativeWin32Window.show}/`hide`. @@ -309,6 +313,14 @@ export const pollWindows = (): void => { h.resizeHook?.(width, height); h.events.get('resize')?.(); } + user32.symbols.GetWindowRect(hwnd, rectPtr); + const x = read.i32(rectPtr, 0); + const y = read.i32(rectPtr, 4); + if (x !== h.x || y !== h.y) { + h.x = x; + h.y = y; + h.events.get('move')?.(); + } } const maximized = user32.symbols.IsZoomed(hwnd) !== 0; if (maximized !== h.maximized) { @@ -395,6 +407,9 @@ export class NativeWin32Window { user32.symbols.GetClientRect(this.#hwnd, rectPtr); this.#handlers.width = read.i32(rectPtr, 8); this.#handlers.height = read.i32(rectPtr, 12); + user32.symbols.GetWindowRect(this.#hwnd, rectPtr); + this.#handlers.x = read.i32(rectPtr, 0); + this.#handlers.y = read.i32(rectPtr, 4); this.#handlers.maximized = user32.symbols.IsZoomed(this.#hwnd) !== 0; this.#handlers.minimized = user32.symbols.IsIconic(this.#hwnd) !== 0; } diff --git a/tests/integration/windows/windows-native-window.test.ts b/tests/integration/windows/windows-native-window.test.ts index 4312cc21..a698899d 100644 --- a/tests/integration/windows/windows-native-window.test.ts +++ b/tests/integration/windows/windows-native-window.test.ts @@ -12,6 +12,7 @@ const SW_MINIMIZE = 6; const SW_RESTORE = 9; const SWP_NOMOVE_NOZORDER_NOACTIVATE = 0x0002 | 0x0004 | 0x0010; const SWP_NOZORDER_NOACTIVATE = 0x0004 | 0x0010; +const SWP_NOSIZE_NOZORDER_NOACTIVATE = 0x0001 | 0x0004 | 0x0010; /** * Windows-only. Drives REAL native-WndProc top-level windows (the kind that can @@ -196,6 +197,39 @@ describe.skipIf(!isWindows)('NativeWin32Window on Windows', () => { } }); + test('pollWindows fires move once for a position-only change', () => { + const win = new NativeWin32Window({ title: 'Move', width: 400, height: 300, show: false }); + let moves = 0; + let resizes = 0; + win.onWindowEvent('move', () => { + moves += 1; + }); + win.onWindowEvent('resize', () => { + resizes += 1; + }); + try { + pollWindows(); + expect(moves).toBe(0); + const { x, y } = win.getBounds(); + loadUser32().symbols.SetWindowPos( + win.hwnd(), + 0n, + x + 40, + y + 30, + 0, + 0, + SWP_NOSIZE_NOZORDER_NOACTIVATE, + ); + pollWindows(); + expect(moves).toBe(1); + expect(resizes).toBe(0); + pollWindows(); + expect(moves).toBe(1); + } finally { + win.destroy(); + } + }); + test('pollWindows fires maximize then unmaximize', () => { const win = new NativeWin32Window({ title: 'Max', width: 400, height: 300, show: false }); let maximized = 0; @@ -220,6 +254,10 @@ describe.skipIf(!isWindows)('NativeWin32Window on Windows', () => { test('minimize and restore fire without resizing the view to 0x0', () => { const win = new NativeWin32Window({ title: 'Min', width: 400, height: 300, show: false }); + let moves = 0; + win.onWindowEvent('move', () => { + moves += 1; + }); let minimizes = 0; let restores = 0; let resizes = 0; @@ -245,6 +283,7 @@ describe.skipIf(!isWindows)('NativeWin32Window on Windows', () => { expect(restores).toBe(1); expect(resizes).toBe(0); expect(hookCalls).toBe(0); + expect(moves).toBe(0); } finally { win.destroy(); } From 949f3c856e81ddc05e383b4edf71253d475f87c0 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:47:47 -0700 Subject: [PATCH 031/586] fix: read BOOL IMP arguments as one byte --- .../platform/macos/cocoa-runtime-class.ts | 10 ++++--- .../macos/cocoa-runtime-class.test.ts | 26 ++++++++++++++++++- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/src/main/platform/macos/cocoa-runtime-class.ts b/src/main/platform/macos/cocoa-runtime-class.ts index 95262b77..8e03c2c3 100644 --- a/src/main/platform/macos/cocoa-runtime-class.ts +++ b/src/main/platform/macos/cocoa-runtime-class.ts @@ -26,8 +26,8 @@ export type ObjcMethodSpec = { readonly selector: string; /** The ObjC type encoding, e.g. `v@:@` (void; self, _cmd, one object arg). */ readonly typeEncoding: string; - /** The declared (post-`self`/`_cmd`) argument kinds; currently all objects. */ - readonly args: ReadonlyArray<'object'>; + /** The declared (post-`self`/`_cmd`) argument kinds; a BOOL is only defined in its low byte. */ + readonly args: ReadonlyArray<'object' | 'bool'>; /** Return kind; defaults to `'void'`. */ readonly returns?: 'void' | 'bool' | 'object'; /** @@ -61,7 +61,11 @@ const getRuntime = macOSLibraryAccessor('objc runtime class', () => const retainedCallbacks: JSCallback[] = []; const buildCallback = (method: ObjcMethodSpec): JSCallback => { - const args = [FFIType.u64, FFIType.u64, ...method.args.map(() => FFIType.u64)]; + const args = [ + FFIType.u64, + FFIType.u64, + ...method.args.map((kind) => (kind === 'bool' ? FFIType.u8 : FFIType.u64)), + ]; const impl = method.impl as (...handles: Handle[]) => unknown; const call = (raw: ReadonlyArray): unknown => impl(...raw.map((value) => BigInt(value))); diff --git a/tests/integration/macos/cocoa-runtime-class.test.ts b/tests/integration/macos/cocoa-runtime-class.test.ts index eb339bc1..16b7e1f2 100644 --- a/tests/integration/macos/cocoa-runtime-class.test.ts +++ b/tests/integration/macos/cocoa-runtime-class.test.ts @@ -1,6 +1,9 @@ import { describe, expect, test } from 'bun:test'; import { currentPlatform } from '../../../src/common/platform'; -import { msgSendReturnsU8 } from '../../../src/main/platform/macos/cocoa-msgsend-variants'; +import { + msgSendPtr, + msgSendReturnsU8, +} from '../../../src/main/platform/macos/cocoa-msgsend-variants'; import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; import { defineObjcClass } from '../../../src/main/platform/macos/cocoa-runtime-class'; @@ -67,6 +70,27 @@ if (currentPlatform() === 'macos') { expect(msgSendReturnsU8(instance, rt.selectors.get('bunmaskaShouldNo'))).toBe(0); }); + test('a BOOL argument reads only its low byte, ignoring junk in the upper register bits', () => { + const rt = cocoa(); + let received: bigint | undefined; + const cls = defineObjcClass('BunmaskaTestClassBoolArg', 'NSObject', [ + { + selector: 'bunmaskaTakeBool:', + typeEncoding: 'v@:c', + args: ['bool'], + impl: (_self, _cmd, flag) => { + received = flag; + }, + }, + ]); + const instance = rt.msgSend( + rt.msgSend(cls, rt.selectors.get('alloc')), + rt.selectors.get('init'), + ); + msgSendPtr(instance, rt.selectors.get('bunmaskaTakeBool:'), 0x1_0000_0001n); + expect(received).toBe(1n); + }); + test('throws when a selector is added twice instead of dropping the second impl', () => { const spec = { selector: 'bunmaskaTwice', From f30d6d643187bf00d32cb428bb9ea9820a341ba9 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:47:53 -0700 Subject: [PATCH 032/586] fix: report a minimized Windows window as not visible --- src/main/platform/windows/windows-native-window.ts | 4 +++- .../integration/windows/windows-native-window.test.ts | 10 ++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/main/platform/windows/windows-native-window.ts b/src/main/platform/windows/windows-native-window.ts index 16029061..97938afc 100644 --- a/src/main/platform/windows/windows-native-window.ts +++ b/src/main/platform/windows/windows-native-window.ts @@ -529,8 +529,10 @@ export class NativeWin32Window { this.emit('hide'); } + /** Shown and not minimized (Electron's Windows semantics). */ isVisible(): boolean { - return loadUser32().symbols.IsWindowVisible(this.#hwnd) !== 0; + const user32 = loadUser32().symbols; + return user32.IsWindowVisible(this.#hwnd) !== 0 && user32.IsIconic(this.#hwnd) === 0; } /** Preventable close: consults the veto, then commits (the same path as `WM_CLOSE`). */ diff --git a/tests/integration/windows/windows-native-window.test.ts b/tests/integration/windows/windows-native-window.test.ts index a698899d..e88bba98 100644 --- a/tests/integration/windows/windows-native-window.test.ts +++ b/tests/integration/windows/windows-native-window.test.ts @@ -289,6 +289,16 @@ describe.skipIf(!isWindows)('NativeWin32Window on Windows', () => { } }); + test('a minimized window is not visible', () => { + const win = new NativeWin32Window({ title: 'MinVis', width: 320, height: 240, show: true }); + try { + loadUser32().symbols.ShowWindow(win.hwnd(), SW_MINIMIZE); + expect(win.isVisible()).toBe(false); + } finally { + win.destroy(); + } + }); + test('getBounds reports the restored rect while minimized, not the -32000 icon slot', () => { const win = new NativeWin32Window({ title: 'Bounds', width: 400, height: 300, show: true }); try { From 7a05814873797766ce5b6a03be353ad7a3ba3163 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:47:54 -0700 Subject: [PATCH 033/586] fix: reject executeJavaScript at once when its result is unserializable --- src/main/ipc/exec-wrapper.ts | 13 ++++++++++--- tests/unit/main/ipc/exec-wrapper.test.ts | 15 +++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/src/main/ipc/exec-wrapper.ts b/src/main/ipc/exec-wrapper.ts index 4d0e55b3..bfdd5633 100644 --- a/src/main/ipc/exec-wrapper.ts +++ b/src/main/ipc/exec-wrapper.ts @@ -23,16 +23,23 @@ export const buildExecWrapper = (execId: number, handlerName: string, code: stri const name = JSON.stringify(handlerName); const src = JSON.stringify(code); return `(function(){ + var __msg = function(e){ + try { return String((e && e.message) || e); } catch (x) { return 'non-printable error'; } + }; var __post = function(payload){ - try { window.webkit.messageHandlers[${name}].postMessage(JSON.stringify(payload)); } catch (e) {} + var json; + try { json = JSON.stringify(payload); } catch (e) { + json = JSON.stringify({ execId: ${id}, ok: false, error: 'result is not JSON-serializable: ' + __msg(e) }); + } + try { window.webkit.messageHandlers[${name}].postMessage(json); } catch (e) {} }; try { Promise.resolve((0, eval)(${src})).then( function(v){ __post({ execId: ${id}, ok: true, result: v }); }, - function(e){ __post({ execId: ${id}, ok: false, error: String((e && e.message) || e) }); } + function(e){ __post({ execId: ${id}, ok: false, error: __msg(e) }); } ); } catch (e) { - __post({ execId: ${id}, ok: false, error: String((e && e.message) || e) }); + __post({ execId: ${id}, ok: false, error: __msg(e) }); } })();`; }; diff --git a/tests/unit/main/ipc/exec-wrapper.test.ts b/tests/unit/main/ipc/exec-wrapper.test.ts index bf663763..234c6081 100644 --- a/tests/unit/main/ipc/exec-wrapper.test.ts +++ b/tests/unit/main/ipc/exec-wrapper.test.ts @@ -59,6 +59,21 @@ describe('buildExecWrapper', () => { ).toMatchObject({ execId: 5, ok: true, result: 'hi' }); }); + test('reports a result JSON cannot encode instead of posting nothing', async () => { + for (const code of ['10n', '(() => { const o = {}; o.self = o; return o; })()']) { + const outcome = await runWrapper(buildExecWrapper(3, 'bunmaskaExec', code)); + expect(outcome).toMatchObject({ execId: 3, ok: false }); + expect(outcome.error).toContain('not JSON-serializable'); + } + }); + + test('reports a rejection with a non-printable reason', async () => { + const outcome = await runWrapper( + buildExecWrapper(4, 'bunmaskaExec', 'Promise.reject(Object.create(null))'), + ); + expect(outcome).toMatchObject({ execId: 4, ok: false }); + }); + test('reports a thrown error as an unsuccessful outcome', async () => { const outcome = await runWrapper( buildExecWrapper(9, 'bunmaskaExec', 'throw new Error("boom")'), From cdef902e9af1e49492b20e49df1f567f77a0a91c Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:47:55 -0700 Subject: [PATCH 034/586] fix: reject second-instance payloads whose argv is not all strings --- src/main/api/single-instance.ts | 7 +++++-- tests/unit/main/api/single-instance.test.ts | 4 ++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/main/api/single-instance.ts b/src/main/api/single-instance.ts index f98997ef..8f1167cb 100644 --- a/src/main/api/single-instance.ts +++ b/src/main/api/single-instance.ts @@ -36,6 +36,9 @@ export type LockBackend = { export const encodePayload = (payload: SecondInstancePayload): string => JSON.stringify(payload); +const isStringArray = (value: unknown): value is string[] => + Array.isArray(value) && value.every((item) => typeof item === 'string'); + /** `undefined` if malformed or missing `argv`. */ export const decodePayload = (json: string): SecondInstancePayload | undefined => { let parsed: unknown; @@ -50,10 +53,10 @@ export const decodePayload = (json: string): SecondInstancePayload | undefined = const record = parsed as Record; const argv = record['argv']; const cwd = record['cwd']; - if (!Array.isArray(argv) || typeof cwd !== 'string') { + if (!isStringArray(argv) || typeof cwd !== 'string') { return undefined; } - return { argv: argv as string[], cwd, additionalData: record['additionalData'] }; + return { argv, cwd, additionalData: record['additionalData'] }; }; export class SingleInstanceManager { diff --git a/tests/unit/main/api/single-instance.test.ts b/tests/unit/main/api/single-instance.test.ts index 1ecd8b59..a73caeb8 100644 --- a/tests/unit/main/api/single-instance.test.ts +++ b/tests/unit/main/api/single-instance.test.ts @@ -59,6 +59,10 @@ describe('encode/decode payload', () => { test('decode returns undefined when argv is missing', () => { expect(decodePayload(JSON.stringify({ cwd: '/x' }))).toBeUndefined(); }); + + test('decode returns undefined when argv holds a non-string', () => { + expect(decodePayload(JSON.stringify({ argv: ['a', 1, {}], cwd: '/x' }))).toBeUndefined(); + }); }); describe('SingleInstanceManager.request', () => { From 4dc59bacb03a80d7cf9804afa3ffefd174d017ea Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:48:34 -0700 Subject: [PATCH 035/586] fix: probe Keychain availability without reading the key --- src/main/platform/macos/cocoa-safe-storage.ts | 7 +++---- tests/integration/macos/safe-storage.test.ts | 7 +++++++ 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/main/platform/macos/cocoa-safe-storage.ts b/src/main/platform/macos/cocoa-safe-storage.ts index a3619c1c..ff5ffef2 100644 --- a/src/main/platform/macos/cocoa-safe-storage.ts +++ b/src/main/platform/macos/cocoa-safe-storage.ts @@ -100,12 +100,11 @@ export const makeMacosKeychainBackend = (service: string, account: string): Keyr }; return { - // A non-throwing read probe: the login Keychain is reachable iff a lookup does - // not error (a null result — no item yet — still means "available"). + // Never request the secret here: reading data can raise a blocking Keychain ACL prompt. isAvailable: () => { try { - lookupKey(); - return true; + const status = loadSecurityFFI().symbols.SecItemCopyMatching(baseQuery(), null); + return status === ERR_SEC_SUCCESS || status === ERR_SEC_ITEM_NOT_FOUND; } catch { return false; } diff --git a/tests/integration/macos/safe-storage.test.ts b/tests/integration/macos/safe-storage.test.ts index ed6ced3e..dcde8ba3 100644 --- a/tests/integration/macos/safe-storage.test.ts +++ b/tests/integration/macos/safe-storage.test.ts @@ -26,6 +26,13 @@ if (currentPlatform() === 'macos') { expect(new Set(values).size).toBe(values.length); }); + test('isAvailable is true before and after the key item exists', () => { + const backend = makeMacosKeychainBackend(PROBE_SERVICE, PROBE_ACCOUNT); + expect(backend.isAvailable()).toBe(true); + backend.getOrCreateKey(); + expect(backend.isAvailable()).toBe(true); + }); + test('getOrCreateKey creates then returns the SAME 32-byte key', () => { const backend = makeMacosKeychainBackend(PROBE_SERVICE, PROBE_ACCOUNT); expect(backend.isAvailable()).toBe(true); From de169e44887c91329b98a9c5078e43b460726c11 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:48:36 -0700 Subject: [PATCH 036/586] fix: declare Carbon ItemCount and ByteCount params as u64 --- src/main/platform/macos/carbon-ffi.ts | 8 ++++---- tests/unit/main/platform/macos/carbon-ffi.test.ts | 10 ++++++++++ 2 files changed, 14 insertions(+), 4 deletions(-) create mode 100644 tests/unit/main/platform/macos/carbon-ffi.test.ts diff --git a/src/main/platform/macos/carbon-ffi.ts b/src/main/platform/macos/carbon-ffi.ts index 167faa65..7262b529 100644 --- a/src/main/platform/macos/carbon-ffi.ts +++ b/src/main/platform/macos/carbon-ffi.ts @@ -31,7 +31,7 @@ import { macOSLibraryAccessor } from './objc'; const CARBON_PATH = '/System/Library/Frameworks/Carbon.framework/Carbon'; -const CARBON_SYMBOLS = { +export const CARBON_FFI_SYMBOLS = { // (UInt32 keyCode, UInt32 modifiers, EventHotKeyID id BY VALUE as packed u64, // EventTargetRef target, OptionBits options, EventHotKeyRef *outRef) -> OSStatus RegisterEventHotKey: { @@ -51,7 +51,7 @@ const CARBON_SYMBOLS = { // (EventTargetRef, EventHandlerUPP, ItemCount numTypes, const EventTypeSpec *typeList, // void *userData, EventHandlerRef *outRef) -> OSStatus InstallEventHandler: { - args: [FFIType.ptr, FFIType.ptr, FFIType.u32, FFIType.ptr, FFIType.ptr, FFIType.ptr], + args: [FFIType.ptr, FFIType.ptr, FFIType.u64, FFIType.ptr, FFIType.ptr, FFIType.ptr], returns: FFIType.i32, }, // (EventRef, OSType name, OSType desiredType, OSType *actualType, ByteCount bufferSize, @@ -62,7 +62,7 @@ const CARBON_SYMBOLS = { FFIType.u32, FFIType.u32, FFIType.ptr, - FFIType.u32, + FFIType.u64, FFIType.ptr, FFIType.ptr, ], @@ -76,5 +76,5 @@ const CARBON_SYMBOLS = { * accessor) so the module stays importable everywhere. */ export const loadCarbonFFI = macOSLibraryAccessor('Carbon global shortcut', () => - dlopen(CARBON_PATH, CARBON_SYMBOLS), + dlopen(CARBON_PATH, CARBON_FFI_SYMBOLS), ); diff --git a/tests/unit/main/platform/macos/carbon-ffi.test.ts b/tests/unit/main/platform/macos/carbon-ffi.test.ts new file mode 100644 index 00000000..b33996c9 --- /dev/null +++ b/tests/unit/main/platform/macos/carbon-ffi.test.ts @@ -0,0 +1,10 @@ +import { FFIType } from 'bun:ffi'; +import { expect, test } from 'bun:test'; +import { CARBON_FFI_SYMBOLS } from '../../../../../src/main/platform/macos/carbon-ffi'; + +// ItemCount and ByteCount are `unsigned long` (MacTypes.h): 64-bit, unlike the +// UInt32/OSType params beside them. A u32 leaves the callee's upper half to chance. +test('Carbon ItemCount and ByteCount params are u64', () => { + expect(CARBON_FFI_SYMBOLS.InstallEventHandler.args[2]).toBe(FFIType.u64); + expect(CARBON_FFI_SYMBOLS.GetEventParameter.args[4]).toBe(FFIType.u64); +}); From 6de895989ee1114bfebec1b3bb5bb92ca56143e2 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:48:40 -0700 Subject: [PATCH 037/586] fix: emit second-instance after ready and outside the socket handler --- src/main/api/app.ts | 12 +++++++++++- tests/unit/main/api/app.test.ts | 22 +++++++++++++++++++++- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/src/main/api/app.ts b/src/main/api/app.ts index 053cdcb5..bb9ae5ec 100644 --- a/src/main/api/app.ts +++ b/src/main/api/app.ts @@ -302,7 +302,17 @@ export class App extends EventEmitter { requestSingleInstanceLock(additionalData: unknown = undefined): boolean { const payload = { argv: [...process.argv], cwd: process.cwd(), additionalData }; return this.#singleInstanceManager().request(payload, (p) => { - this.emit('second-instance', makeCancelableEvent(), p.argv, p.cwd, p.additionalData); + // Out of the socket handler, which swallows throws, and never before `ready` (Electron). + const emit = (): void => { + queueMicrotask(() => { + this.emit('second-instance', makeCancelableEvent(), p.argv, p.cwd, p.additionalData); + }); + }; + if (this.#ready) { + emit(); + } else { + this.once('ready', emit); + } }); } diff --git a/tests/unit/main/api/app.test.ts b/tests/unit/main/api/app.test.ts index a86b8f29..29eb7fc7 100644 --- a/tests/unit/main/api/app.test.ts +++ b/tests/unit/main/api/app.test.ts @@ -430,8 +430,11 @@ describe('App single-instance lock', () => { expect(a.hasSingleInstanceLock()).toBe(false); }); - test('emits second-instance with argv/cwd/data when a peer connects', () => { + const flush = (): Promise => new Promise((resolve) => setTimeout(resolve, 0)); + + test('emits second-instance with argv/cwd/data when a peer connects', async () => { const a = new App(); + a.markReady(); const fixture = managerWith({ acquire: [true] }); a.setSingleInstanceForTesting(fixture.manager); let captured: { argv: string[]; cwd: string; data: unknown } | undefined; @@ -440,9 +443,26 @@ describe('App single-instance lock', () => { }); a.requestSingleInstanceLock(); fixture.deliver(encodePayload({ argv: ['p', 'q'], cwd: '/peer', additionalData: { z: 1 } })); + expect(captured).toBeUndefined(); + await flush(); expect(captured).toEqual({ argv: ['p', 'q'], cwd: '/peer', data: { z: 1 } }); }); + test('holds second-instance until after ready', async () => { + const a = new App(); + const fixture = managerWith({ acquire: [true] }); + a.setSingleInstanceForTesting(fixture.manager); + const order: string[] = []; + a.on('ready', () => order.push('ready')); + a.on('second-instance', () => order.push('second-instance')); + a.requestSingleInstanceLock(); + fixture.deliver(encodePayload({ argv: [], cwd: '/peer', additionalData: undefined })); + await flush(); + a.markReady(); + await flush(); + expect(order).toEqual(['ready', 'second-instance']); + }); + test('releaseSingleInstanceLock releases the lock', () => { const a = new App(); const fixture = managerWith({ acquire: [true] }); From 47330de7f81727890efa4e178c7c16568ccfab32 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:48:32 -0700 Subject: [PATCH 038/586] fix: close Linux windows cleanly when a close listener throws --- src/main/platform/linux/linux-backend.ts | 39 ++++++++------ tests/integration/linux/window-events.test.ts | 54 +++++++++++++++++++ 2 files changed, 78 insertions(+), 15 deletions(-) diff --git a/src/main/platform/linux/linux-backend.ts b/src/main/platform/linux/linux-backend.ts index f33e243a..13d9b790 100644 --- a/src/main/platform/linux/linux-backend.ts +++ b/src/main/platform/linux/linux-backend.ts @@ -1,6 +1,7 @@ import { type Pointer, ptr } from 'bun:ffi'; import { isDevRestart } from '../../dev-reload'; import { UnsupportedPlatformError } from '../../../common/errors'; +import { createLogger } from '../../../common/logger'; import { generateChannelId, generateIsolatedChannelSetup, @@ -48,6 +49,8 @@ import { loadWebKitGtkFFI, readGetUriResult } from './webkitgtk-ffi'; * or `g_main_loop_run`, which would block Bun's thread (D020). */ +const log = createLogger('linux-backend'); + const GTK_TRUE = 1; const GTK_FALSE = 0; /** `GtkOrientation`: stack the menu bar above the webview vertically. */ @@ -312,6 +315,7 @@ class LinuxWindow implements NativeWindow { #activePopover: Pointer | null = null; readonly #closedCallbacks: Array<() => void> = []; #onClose: (() => boolean) | undefined; + #releaseAppMenu: (() => void) | undefined; readonly #eventHandlers = new Map void>(); /** Surface a non-preventable lifecycle event to its registered handler. */ @@ -390,7 +394,7 @@ class LinuxWindow implements NativeWindow { const bar = menu.symbols.gtk_popover_menu_bar_new_from_model(model); menu.symbols.gtk_box_append(box, bar); menu.symbols.gtk_box_append(box, view); - onAppMenuCleared(() => { + this.#releaseAppMenu = onAppMenuCleared(() => { if (!this.#closed) { menu.symbols.gtk_box_remove(box, bar); } @@ -481,13 +485,23 @@ class LinuxWindow implements NativeWindow { // allow GTK to finish destroying. return false; } - if (this.#onClose?.() === true) { + if (this.#vetoed()) { return true; } this.#handleClosed(); return false; } + /** A throwing `close` listener does not veto: the window still closes, as in Electron. */ + #vetoed(): boolean { + try { + return this.#onClose?.() === true; + } catch (error) { + log.error("a 'close' listener threw; closing anyway", error); + return false; + } + } + #handleClosed(): void { if (this.#closed) { return; @@ -496,8 +510,13 @@ class LinuxWindow implements NativeWindow { this.#visible = false; this.#closeActivePopover(); // drop any open context-menu popover before teardown. for (const callback of this.#closedCallbacks) { - callback(); + try { + callback(); + } catch (error) { + log.error("a 'closed' listener threw", error); + } } + this.#releaseAppMenu?.(); // Reject any executeJavaScript Promise still awaiting a `bunmaskaExec` result // it can no longer receive, THEN disconnect signals + close the retained // JSCallbacks (including the shared exec handler) — never per-call. @@ -646,20 +665,10 @@ class LinuxWindow implements NativeWindow { } close(): void { - if (this.#closed) { - return; - } - // Preventable: consult the JS `close` listener (same veto the native - // `close-request` path uses). If vetoed, leave the window fully alive. - if (this.#onClose?.() === true) { + if (this.#closed || this.#vetoed()) { return; } - const gtk = loadGtkFFI(); - // Disconnect handlers and tear down web contents while the GObjects are - // still alive, then destroy the window. Teardown runs OUTSIDE any signal - // callback here, so closing the retained thunks is safe. - this.#handleClosed(); - gtk.symbols.gtk_window_destroy(this.#window); + this.destroy(); // no-op when a `close` listener already destroyed the window } destroy(): void { diff --git a/tests/integration/linux/window-events.test.ts b/tests/integration/linux/window-events.test.ts index f8ca121a..ad356165 100644 --- a/tests/integration/linux/window-events.test.ts +++ b/tests/integration/linux/window-events.test.ts @@ -92,4 +92,58 @@ describe.skipIf(!isLinux)('Linux window lifecycle events end-to-end', () => { app.quit(); }); + + test('a throwing close listener still closes and tears the window down', async () => { + if (loadGtkFFI().symbols.gtk_init_check() === 0) { + return; + } + const app = createLinuxApplication(); + app.start(); + const window = app.createWindow({ + width: 200, + height: 120, + title: 'Throwing Close', + show: true, + }); + let closed = 0; + window.onClosed(() => { + closed += 1; + }); + window.onClose(() => { + throw new Error('listener bug'); + }); + + window.close(); + + expect(closed).toBe(1); + await expect(window.webContents.executeJavaScript('1')).rejects.toThrow('destroyed'); + app.quit(); + }); + + test('a close listener that destroys the window does not destroy it twice', () => { + if (loadGtkFFI().symbols.gtk_init_check() === 0) { + return; + } + const app = createLinuxApplication(); + app.start(); + const window = app.createWindow({ + width: 200, + height: 120, + title: 'Destroy In Close', + show: true, + }); + let closed = 0; + window.onClosed(() => { + closed += 1; + }); + window.onClose(() => { + window.destroy(); + return false; + }); + + window.close(); + + expect(closed).toBe(1); + app.quit(); + }); }); From 90b0873d1ffc6a87b273edd25605e0e87183af50 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:48:41 -0700 Subject: [PATCH 039/586] fix: emit dom-ready for the main frame only --- src/main/platform/dom-ready.ts | 3 ++ tests/unit/main/platform/dom-ready.test.ts | 38 ++++++++++++++++++---- 2 files changed, 35 insertions(+), 6 deletions(-) diff --git a/src/main/platform/dom-ready.ts b/src/main/platform/dom-ready.ts index da03d2a4..9e2c0479 100644 --- a/src/main/platform/dom-ready.ts +++ b/src/main/platform/dom-ready.ts @@ -10,6 +10,9 @@ export const DOM_READY_HANDLER_NAME = 'bunmaskaDomReady'; /** The page-world script that fires once the document is ready. */ export const generateDomReadyScript = (): string => `(() => { + if (window !== window.top) { + return; + } const post = () => { try { window.webkit.messageHandlers.${DOM_READY_HANDLER_NAME}.postMessage(''); diff --git a/tests/unit/main/platform/dom-ready.test.ts b/tests/unit/main/platform/dom-ready.test.ts index e4efbc7a..01f50dc2 100644 --- a/tests/unit/main/platform/dom-ready.test.ts +++ b/tests/unit/main/platform/dom-ready.test.ts @@ -4,14 +4,40 @@ import { generateDomReadyScript, } from '../../../../src/main/platform/dom-ready'; +/** Run the script against a fake frame; returns the post count and the DOMContentLoaded hook. */ +const runInFrame = (readyState: string, isTop = true) => { + let posts = 0; + let onLoaded: (() => void) | undefined; + const win: Record = { + webkit: { messageHandlers: { [DOM_READY_HANDLER_NAME]: { postMessage: () => posts++ } } }, + }; + win['top'] = isTop ? win : {}; + const doc = { + readyState, + addEventListener: (_type: string, listener: () => void) => { + onLoaded = listener; + }, + }; + new Function('window', 'document', generateDomReadyScript())(win, doc); + return { posts: () => posts, fireLoaded: () => onLoaded?.() }; +}; + describe('generateDomReadyScript', () => { - test('posts to the dom-ready handler on DOMContentLoaded', () => { - const script = generateDomReadyScript(); - expect(script).toContain(`messageHandlers.${DOM_READY_HANDLER_NAME}.postMessage`); - expect(script).toContain('DOMContentLoaded'); + test('posts at once when the document is past loading', () => { + expect(runInFrame('complete').posts()).toBe(1); + }); + + test('posts on DOMContentLoaded while the document is loading', () => { + const frame = runInFrame('loading'); + expect(frame.posts()).toBe(0); + frame.fireLoaded(); + expect(frame.posts()).toBe(1); }); - test('fires immediately when the document is already past loading', () => { - expect(generateDomReadyScript()).toContain("document.readyState === 'loading'"); + test('a sub-frame never posts', () => { + const frame = runInFrame('loading', false); + frame.fireLoaded(); + expect(frame.posts()).toBe(0); + expect(runInFrame('complete', false).posts()).toBe(0); }); }); From 7b6c2893c39b96d9c8cf545781b5f808b4a12afe Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:48:53 -0700 Subject: [PATCH 040/586] fix: enforce setMinimumSize on Windows through WM_GETMINMAXINFO --- src/main/platform/windows/windows-backend.ts | 5 ++-- .../platform/windows/windows-native-window.ts | 26 ++++++++++++++++++- .../windows/windows-native-window.test.ts | 20 ++++++++++++++ 3 files changed, 47 insertions(+), 4 deletions(-) diff --git a/src/main/platform/windows/windows-backend.ts b/src/main/platform/windows/windows-backend.ts index 463746c2..b05a9a46 100644 --- a/src/main/platform/windows/windows-backend.ts +++ b/src/main/platform/windows/windows-backend.ts @@ -199,9 +199,8 @@ class WindowsWindow implements NativeWindow { user32.SetLayeredWindowAttributes(hwnd, 0, alpha, LWA_ALPHA); } - setMinimumSize(_width: number, _height: number): void { - // A true minimum requires WM_GETMINMAXINFO, which a native-WndProc window - // cannot intercept from the pump; left for a poll-based follow-up. + setMinimumSize(width: number, height: number): void { + this.#native.setMinimumSize(width, height); } center(): void { diff --git a/src/main/platform/windows/windows-native-window.ts b/src/main/platform/windows/windows-native-window.ts index 97938afc..1e5f1836 100644 --- a/src/main/platform/windows/windows-native-window.ts +++ b/src/main/platform/windows/windows-native-window.ts @@ -1,4 +1,4 @@ -import { FFIType, JSCallback, ptr, read } from 'bun:ffi'; +import { FFIType, JSCallback, type Pointer, ptr, read, toArrayBuffer } from 'bun:ffi'; import { isDevRestart } from '../../dev-reload'; import { FFIError } from '../../../common/errors'; import { cstr } from '../cstr'; @@ -26,6 +26,9 @@ const IDC_ARROW = 32512; /** `WM_COMMAND` — a menu selection (or control/accelerator) notification. */ const WM_COMMAND = 0x0111; const WM_CLOSE = 0x0010; +const WM_GETMINMAXINFO = 0x0024; +/** `MINMAXINFO` is five POINTs; ptMinTrackSize is the fourth (x@24, y@28). */ +const MINMAXINFO_SIZE = 40; const CW_USEDEFAULT = -0x80000000; const WS_OVERLAPPEDWINDOW = 0x00cf0000; @@ -181,6 +184,9 @@ interface NativeWindowHandlers { readonly events: Map void>; /** Internal resize sink (resizes the hosted view) — fired before the `resize` event. */ resizeHook?: (width: number, height: number) => void; + /** Minimum outer size in pixels; 0 leaves the system default. */ + minWidth: number; + minHeight: number; /** Menu-bar command sink: fired by the frame proc with the chosen `WM_COMMAND` id. */ menuCommand?: (commandId: number) => void; /** The current menu-bar HMENU (owned by this window; destroyed when replaced/closed). */ @@ -200,6 +206,8 @@ interface NativeWindowHandlers { const newHandlers = (destroyOnClose: boolean): NativeWindowHandlers => ({ closed: false, events: new Map(), + minWidth: 0, + minHeight: 0, x: 0, y: 0, width: 0, @@ -227,6 +235,16 @@ const handleFrameMessage = ( } return true; } + if (message === WM_GETMINMAXINFO && handlers !== undefined) { + const info = new Int32Array(toArrayBuffer(Number(lParam) as Pointer, 0, MINMAXINFO_SIZE)); + if (handlers.minWidth > 0) { + info[6] = handlers.minWidth; + } + if (handlers.minHeight > 0) { + info[7] = handlers.minHeight; + } + return false; + } // A menu selection: HIWORD(wParam)=0 and lParam=0 (controls/accelerators differ). if ( message === WM_COMMAND && @@ -436,6 +454,12 @@ export class NativeWin32Window { this.#handlers.events.get(type)?.(); } + /** Enforced through `WM_GETMINMAXINFO`; 0 leaves that dimension unconstrained. */ + setMinimumSize(width: number, height: number): void { + this.#handlers.minWidth = width; + this.#handlers.minHeight = height; + } + setResizeHook(hook: (width: number, height: number) => void): void { this.#handlers.resizeHook = hook; } diff --git a/tests/integration/windows/windows-native-window.test.ts b/tests/integration/windows/windows-native-window.test.ts index e88bba98..75be15cd 100644 --- a/tests/integration/windows/windows-native-window.test.ts +++ b/tests/integration/windows/windows-native-window.test.ts @@ -289,6 +289,26 @@ describe.skipIf(!isWindows)('NativeWin32Window on Windows', () => { } }); + test('setMinimumSize stops the window shrinking below the minimum', () => { + const win = new NativeWin32Window({ title: 'MinSize', width: 600, height: 500, show: false }); + try { + win.setMinimumSize(500, 400); + loadUser32().symbols.SetWindowPos( + win.hwnd(), + 0n, + 0, + 0, + 200, + 100, + SWP_NOMOVE_NOZORDER_NOACTIVATE, + ); + const { width, height } = win.getBounds(); + expect({ width, height }).toEqual({ width: 500, height: 400 }); + } finally { + win.destroy(); + } + }); + test('a minimized window is not visible', () => { const win = new NativeWin32Window({ title: 'MinVis', width: 320, height: 240, show: true }); try { From d6c90df7627e50086b8a60b5d540c81abf068282 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:49:05 -0700 Subject: [PATCH 041/586] refactor: reuse NSData helpers and one identity query in safeStorage --- src/main/platform/macos/cocoa-safe-storage.ts | 59 ++++++------------- 1 file changed, 18 insertions(+), 41 deletions(-) diff --git a/src/main/platform/macos/cocoa-safe-storage.ts b/src/main/platform/macos/cocoa-safe-storage.ts index ff5ffef2..3d78696a 100644 --- a/src/main/platform/macos/cocoa-safe-storage.ts +++ b/src/main/platform/macos/cocoa-safe-storage.ts @@ -1,10 +1,11 @@ import { randomBytes } from 'node:crypto'; -import { ptr, toArrayBuffer } from 'bun:ffi'; +import { ptr } from 'bun:ffi'; import type { KeyringBackend } from '../../api/safe-storage'; import { nsString } from './cocoa-foundation'; -import { msgSendPtrI64, msgSendPtrPtr } from './cocoa-msgsend-variants'; +import { msgSendPtrPtr } from './cocoa-msgsend-variants'; +import { nsDataFromBytes, nsDataToBytes } from './cocoa-native-image'; import { cocoa } from './cocoa-runtime'; -import { type Handle, ptrIn } from './objc'; +import type { Handle } from './objc'; import { loadSecurityFFI, secConstants } from './security-ffi'; /** @@ -22,43 +23,31 @@ const ERR_SEC_SUCCESS = 0; const ERR_SEC_ITEM_NOT_FOUND = -25300; const ERR_SEC_DUPLICATE_ITEM = -25299; -/** `[[NSData alloc] initWithBytes:length:]` from a Buffer (copies the bytes). */ -const nsDataFromBytes = (bytes: Buffer): Handle => { - const rt = cocoa(); - const alloc = rt.msgSend(rt.classes.get('NSData'), rt.selectors.get('alloc')); - const dataPtr = bytes.length === 0 ? 0n : BigInt(ptr(bytes)); - return msgSendPtrI64( - alloc, - rt.selectors.get('initWithBytes:length:'), - dataPtr, - BigInt(bytes.length), - ); -}; - /** `[dict setObject:value forKey:key]`. */ const dictSet = (dict: Handle, value: Handle, key: Handle): void => { const rt = cocoa(); msgSendPtrPtr(dict, rt.selectors.get('setObject:forKey:'), value, key); }; +/** The {class, service, account} identity dictionary every Keychain op starts from. */ +const identityQuery = (service: string, account: string): Handle => { + const k = secConstants(); + const rt = cocoa(); + const dict = rt.msgSend(rt.classes.get('NSMutableDictionary'), rt.selectors.get('dictionary')); + dictSet(dict, k.kSecClassGenericPassword, k.kSecClass); + dictSet(dict, nsString(service), k.kSecAttrService); + dictSet(dict, nsString(account), k.kSecAttrAccount); + return dict; +}; + /** Build a macOS Keychain backend bound to a specific service + account. */ export const makeMacosKeychainBackend = (service: string, account: string): KeyringBackend => { - /** The {class, service, account} identity dictionary shared by every op. */ - const baseQuery = (): Handle => { - const k = secConstants(); - const rt = cocoa(); - const dict = rt.msgSend(rt.classes.get('NSMutableDictionary'), rt.selectors.get('dictionary')); - dictSet(dict, k.kSecClassGenericPassword, k.kSecClass); - dictSet(dict, nsString(service), k.kSecAttrService); - dictSet(dict, nsString(account), k.kSecAttrAccount); - return dict; - }; + const baseQuery = (): Handle => identityQuery(service, account); /** Read the stored key, or null if the item does not exist. Throws on real errors. */ const lookupKey = (): Buffer | null => { const sec = loadSecurityFFI(); const k = secConstants(); - const rt = cocoa(); const query = baseQuery(); dictSet(query, k.kCFBooleanTrue, k.kSecReturnData); dictSet(query, k.kSecMatchLimitOne, k.kSecMatchLimit); @@ -71,12 +60,7 @@ export const makeMacosKeychainBackend = (service: string, account: string): Keyr throw new Error(`safeStorage: SecItemCopyMatching failed (OSStatus ${status})`); } const cfData = out[0] ?? 0n; - const len = Number(rt.msgSend(cfData, rt.selectors.get('length'))); - const bytesPtr = rt.msgSend(cfData, rt.selectors.get('bytes')); - const copy = - len > 0 && bytesPtr !== 0n - ? Buffer.from(toArrayBuffer(ptrIn(bytesPtr), 0, len).slice(0)) - : Buffer.alloc(0); + const copy = Buffer.from(nsDataToBytes(cfData)); sec.symbols.CFRelease(cfData); // Copy ownership rule: the caller releases. return copy; }; @@ -130,14 +114,7 @@ export const makeMacosKeychainBackend = (service: string, account: string): Keyr /** Delete the Keychain item for `service`/`account` (test cleanup). Best-effort. */ export const deleteMacosKeychainItem = (service: string, account: string): void => { - const sec = loadSecurityFFI(); - const k = secConstants(); - const rt = cocoa(); - const query = rt.msgSend(rt.classes.get('NSMutableDictionary'), rt.selectors.get('dictionary')); - dictSet(query, k.kSecClassGenericPassword, k.kSecClass); - dictSet(query, nsString(service), k.kSecAttrService); - dictSet(query, nsString(account), k.kSecAttrAccount); - sec.symbols.SecItemDelete(query); + loadSecurityFFI().symbols.SecItemDelete(identityQuery(service, account)); }; /** The production macOS Keychain backend. */ From a9f801fb1a7a358840f61fae663ad0be175edf81 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:49:31 -0700 Subject: [PATCH 042/586] fix: match host-only cookies to their exact host --- src/main/api/cookie-util.ts | 10 +++++++--- tests/unit/main/api/cookie-util.test.ts | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/main/api/cookie-util.ts b/src/main/api/cookie-util.ts index a75d3950..bf50881e 100644 --- a/src/main/api/cookie-util.ts +++ b/src/main/api/cookie-util.ts @@ -41,6 +41,10 @@ export const domainMatches = (cookieDomain: string, host: string): boolean => { return host === domain || host.endsWith(`.${domain}`); }; +/** A cookie domain without a leading dot is host-only: it matches its host exactly. */ +const sentToHost = (cookieDomain: string, host: string): boolean => + cookieDomain.startsWith('.') ? domainMatches(cookieDomain, host) : host === cookieDomain; + /** RFC 6265 path-match: equal, or prefix on a `/` label boundary. */ const pathMatches = (cookiePath: string, urlPath: string): boolean => urlPath === cookiePath || @@ -56,7 +60,7 @@ const parseUrl = (url: string, context: string): URL => { }; const sentToUrl = (cookie: Cookie, url: URL): boolean => - domainMatches(cookie.domain, url.hostname) && + sentToHost(cookie.domain, url.hostname) && pathMatches(cookie.path, url.pathname) && (!cookie.secure || url.protocol === 'https:' || url.protocol === 'wss:'); @@ -86,7 +90,7 @@ export const cookiesToRemove = ( return cookies.filter( (cookie) => cookie.name === name && - domainMatches(cookie.domain, parsed.hostname) && + sentToHost(cookie.domain, parsed.hostname) && pathMatches(cookie.path, parsed.pathname), ); }; @@ -97,7 +101,7 @@ export const cookieFromSetDetails = (details: CookieSetDetails): Cookie => { return { name: details.name ?? '', value: details.value ?? '', - domain: details.domain ?? url.hostname, + domain: details.domain ? `.${stripDot(details.domain)}` : url.hostname, path: details.path ?? '/', secure: details.secure ?? false, httpOnly: details.httpOnly ?? false, diff --git a/tests/unit/main/api/cookie-util.test.ts b/tests/unit/main/api/cookie-util.test.ts index 653da370..d1d0b192 100644 --- a/tests/unit/main/api/cookie-util.test.ts +++ b/tests/unit/main/api/cookie-util.test.ts @@ -81,6 +81,11 @@ describe('filterCookies', () => { ]); }); + test('a host-only cookie is not reported for a subdomain url', () => { + const names = filterCookies(jar, { url: 'http://api.example.com/app/x' }).map((c) => c.name); + expect(names).toEqual(['scoped']); + }); + test('unparsable filter url throws InvalidArgumentError', () => { expect(() => filterCookies(jar, { url: 'not a url' })).toThrow(InvalidArgumentError); }); @@ -99,6 +104,11 @@ describe('cookiesToRemove', () => { expect(hits.map((c) => c.domain)).toEqual(['example.com', '.example.com']); }); + test('a subdomain url leaves the parent host-only cookie alone', () => { + const hits = cookiesToRemove(jar, 'https://api.example.com/app/page', 'sid'); + expect(hits.map((c) => c.domain)).toEqual(['.example.com']); + }); + test('a secure cookie is removable through a matching http url', () => { const jar2 = [cookie({ name: 'sid', secure: true })]; expect(cookiesToRemove(jar2, 'http://example.com/', 'sid')).toHaveLength(1); @@ -140,6 +150,11 @@ describe('cookieFromSetDetails', () => { expect(c.expirationDate).toBe(4102444800); }); + test('an explicit domain is dot-prefixed so subdomains receive it', () => { + const c = cookieFromSetDetails({ url: 'https://example.com/', domain: 'example.com' }); + expect(c.domain).toBe('.example.com'); + }); + test('name and value default to empty strings', () => { const c = cookieFromSetDetails({ url: 'https://example.com/' }); expect(c.name).toBe(''); From 2f3dd191ace63963beef74635162a27d7c544444 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:49:36 -0700 Subject: [PATCH 043/586] fix: refit the Windows view when the menu bar changes --- .../platform/windows/windows-native-window.ts | 10 +++++-- .../windows/windows-native-window.test.ts | 27 +++++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/src/main/platform/windows/windows-native-window.ts b/src/main/platform/windows/windows-native-window.ts index 1e5f1836..8d8e00e6 100644 --- a/src/main/platform/windows/windows-native-window.ts +++ b/src/main/platform/windows/windows-native-window.ts @@ -485,8 +485,7 @@ export class NativeWin32Window { /** * Attach `menuBar` (an HMENU) as this window's menu bar, or remove it with * `null`. Takes ownership: the previous bar is destroyed, and so is this one when - * the window closes. Adding/removing a bar changes the client area, which the - * pump's resize poll then propagates to the hosted view. + * the window closes. */ setMenuBar(menuBar: bigint | null): void { const user32 = loadUser32().symbols; @@ -501,6 +500,13 @@ export class NativeWin32Window { } else { this.#handlers.menuBar = menuBar; } + // The bar resizes the client area, not the window: refit the view without a 'resize'. + if (user32.IsIconic(this.#hwnd) === 0) { + const { width, height } = this.getClientSize(); + this.#handlers.width = width; + this.#handlers.height = height; + this.#handlers.resizeHook?.(width, height); + } } setTitle(title: string): void { diff --git a/tests/integration/windows/windows-native-window.test.ts b/tests/integration/windows/windows-native-window.test.ts index 75be15cd..6d093f37 100644 --- a/tests/integration/windows/windows-native-window.test.ts +++ b/tests/integration/windows/windows-native-window.test.ts @@ -1,5 +1,7 @@ import { describe, expect, test } from 'bun:test'; +import { ptr } from 'bun:ffi'; import { currentPlatform } from '../../../src/common/platform'; +import { wstr } from '../../../src/main/platform/windows/win32'; import { loadUser32 } from '../../../src/main/platform/windows/win32-ffi'; import { NativeWin32Window, @@ -331,6 +333,31 @@ describe.skipIf(!isWindows)('NativeWin32Window on Windows', () => { } }); + test('attaching a menu bar resizes the view at once, without a resize event', () => { + const win = new NativeWin32Window({ title: 'Bar', width: 400, height: 300, show: false }); + const user32 = loadUser32().symbols; + let resizes = 0; + let hookHeight = 0; + win.onWindowEvent('resize', () => { + resizes += 1; + }); + win.setResizeHook((_width, height) => { + hookHeight = height; + }); + try { + const before = win.getClientSize().height; + const bar = user32.CreateMenu(); + user32.AppendMenuW(bar, 0, 1n, ptr(wstr('File'))); + win.setMenuBar(bar); + expect(hookHeight).toBe(win.getClientSize().height); + expect(hookHeight).toBeLessThan(before); + pollWindows(); + expect(resizes).toBe(0); + } finally { + win.destroy(); + } + }); + test('show() and hide() emit show/hide synchronously', () => { const win = new NativeWin32Window({ title: 'Vis2', width: 320, height: 240, show: false }); let shows = 0; From b75d66d7f394cf55c108857dc4326cb0e201fe92 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:49:39 -0700 Subject: [PATCH 044/586] refactor: share one data-symbol lookup between blocks and safeStorage --- src/main/platform/macos/cocoa-block.ts | 22 ++++--------------- src/main/platform/macos/objc.ts | 23 +++++++++++++++++++- src/main/platform/macos/security-ffi.ts | 29 +++---------------------- tests/integration/macos/objc.test.ts | 16 ++++++++++++++ 4 files changed, 45 insertions(+), 45 deletions(-) create mode 100644 tests/integration/macos/objc.test.ts diff --git a/src/main/platform/macos/cocoa-block.ts b/src/main/platform/macos/cocoa-block.ts index 88ab7dd9..503e707a 100644 --- a/src/main/platform/macos/cocoa-block.ts +++ b/src/main/platform/macos/cocoa-block.ts @@ -1,7 +1,5 @@ import { FFIType, JSCallback, type Pointer, ptr } from 'bun:ffi'; -import { dlopen } from '../dlopen'; -import { cstr } from '../cstr'; -import { callFromNative, type Handle } from './objc'; +import { callFromNative, dataSymbolAddress, type Handle } from './objc'; /** * Hand-built ObjC **Blocks** for bun:ffi — the primitive that unblocks every @@ -35,22 +33,10 @@ const BLOCK_IS_GLOBAL = 1 << 28; const BLOCK_LITERAL_SIZE = 32; let cachedIsa: Pointer | undefined; -/** Resolve `&_NSConcreteGlobalBlock` (the isa every global block points at), once. */ +/** `&_NSConcreteGlobalBlock`, the isa every global block points at. */ const globalBlockIsa = (): Pointer => { - if (cachedIsa !== undefined) { - return cachedIsa; - } - const libc = dlopen('/usr/lib/libSystem.B.dylib', { - dlopen: { args: [FFIType.cstring, FFIType.i32], returns: FFIType.ptr }, - dlsym: { args: [FFIType.ptr, FFIType.cstring], returns: FFIType.ptr }, - }); - const handle = libc.symbols.dlopen(cstr('/usr/lib/libSystem.B.dylib'), 2); - const isa = libc.symbols.dlsym(handle, cstr('_NSConcreteGlobalBlock')); - if (isa === null) { - throw new Error('cocoa-block: could not resolve _NSConcreteGlobalBlock'); - } - cachedIsa = isa; - return isa; + cachedIsa ??= dataSymbolAddress('/usr/lib/libSystem.B.dylib', '_NSConcreteGlobalBlock'); + return cachedIsa; }; let sharedDescriptor: BigUint64Array | undefined; diff --git a/src/main/platform/macos/objc.ts b/src/main/platform/macos/objc.ts index 5321ed53..5bad9815 100644 --- a/src/main/platform/macos/objc.ts +++ b/src/main/platform/macos/objc.ts @@ -1,6 +1,8 @@ -import type { Pointer } from 'bun:ffi'; +import { FFIType, type Pointer } from 'bun:ffi'; import { UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; +import { cstr } from '../cstr'; +import { dlopen } from '../dlopen'; /** * Shared Objective-C FFI primitives for the macOS backend. @@ -55,3 +57,22 @@ export const macOSLibraryAccessor = (name: string, open: () => T): (() => T) return cached; }; }; + +const RTLD_NOW = 2; + +const loadDl = macOSLibraryAccessor('libSystem dlsym', () => + dlopen('/usr/lib/libSystem.B.dylib', { + dlopen: { args: [FFIType.cstring, FFIType.i32], returns: FFIType.pointer }, + dlsym: { args: [FFIType.pointer, FFIType.cstring], returns: FFIType.pointer }, + }), +); + +/** The address of data symbol `name` in the image at `path`: bun's dlopen binds only functions. */ +export const dataSymbolAddress = (path: string, name: string): Pointer => { + const dl = loadDl().symbols; + const address = dl.dlsym(dl.dlopen(cstr(path), RTLD_NOW), cstr(name)); + if (address === null) { + throw new Error(`dlsym('${name}') in ${path} returned null`); + } + return address; +}; diff --git a/src/main/platform/macos/security-ffi.ts b/src/main/platform/macos/security-ffi.ts index 49bda131..02caec15 100644 --- a/src/main/platform/macos/security-ffi.ts +++ b/src/main/platform/macos/security-ffi.ts @@ -1,7 +1,6 @@ import { FFIType, read } from 'bun:ffi'; import { dlopen } from '../dlopen'; -import { cstr } from '../cstr'; -import { macOSLibraryAccessor } from './objc'; +import { dataSymbolAddress, macOSLibraryAccessor } from './objc'; /** * Security.framework + CoreFoundation symbols behind the macOS Keychain backend @@ -19,17 +18,8 @@ import { macOSLibraryAccessor } from './objc'; * `BigInt(read.ptr(...))`, which round-trips through a lossy JS number — D029). */ -const LIBSYSTEM_PATH = '/usr/lib/libSystem.B.dylib'; const SECURITY_PATH = '/System/Library/Frameworks/Security.framework/Security'; const CORE_FOUNDATION_PATH = '/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation'; -const RTLD_NOW = 2; - -const loadDl = macOSLibraryAccessor('libSystem dlsym', () => - dlopen(LIBSYSTEM_PATH, { - dlopen: { args: [FFIType.cstring, FFIType.i32], returns: FFIType.pointer }, - dlsym: { args: [FFIType.pointer, FFIType.cstring], returns: FFIType.pointer }, - }), -); export const loadSecurityFFI = macOSLibraryAccessor('Security.framework safeStorage', () => dlopen(SECURITY_PATH, { @@ -41,16 +31,6 @@ export const loadSecurityFFI = macOSLibraryAccessor('Security.framework safeStor }), ); -/** Resolve a data symbol (a `CFTypeRef` global) to its value, pointer-precisely. */ -const dataSymbol = (handle: number, name: string): bigint => { - const dl = loadDl(); - const addr = dl.symbols.dlsym(handle as never, cstr(name)); - if (addr === null) { - throw new Error(`safeStorage: dlsym('${name}') returned null`); - } - return read.u64(addr, 0); -}; - /** The `kSec*` / `kCF*` constants the Keychain query dictionary needs (as `CFTypeRef` handles). */ export type SecConstants = { kSecClass: bigint; @@ -72,10 +52,7 @@ export const secConstants = (): SecConstants => { if (cached !== undefined) { return cached; } - const dl = loadDl(); - const secH = dl.symbols.dlopen(cstr(SECURITY_PATH), RTLD_NOW) as unknown as number; - const cfH = dl.symbols.dlopen(cstr(CORE_FOUNDATION_PATH), RTLD_NOW) as unknown as number; - const s = (n: string): bigint => dataSymbol(secH, n); + const s = (name: string): bigint => read.u64(dataSymbolAddress(SECURITY_PATH, name), 0); cached = { kSecClass: s('kSecClass'), kSecClassGenericPassword: s('kSecClassGenericPassword'), @@ -87,7 +64,7 @@ export const secConstants = (): SecConstants => { kSecMatchLimitOne: s('kSecMatchLimitOne'), kSecAttrAccessible: s('kSecAttrAccessible'), kSecAttrAccessibleWhenUnlockedThisDeviceOnly: s('kSecAttrAccessibleWhenUnlockedThisDeviceOnly'), - kCFBooleanTrue: dataSymbol(cfH, 'kCFBooleanTrue'), + kCFBooleanTrue: read.u64(dataSymbolAddress(CORE_FOUNDATION_PATH, 'kCFBooleanTrue'), 0), }; return cached; }; diff --git a/tests/integration/macos/objc.test.ts b/tests/integration/macos/objc.test.ts new file mode 100644 index 00000000..a2f7c8c3 --- /dev/null +++ b/tests/integration/macos/objc.test.ts @@ -0,0 +1,16 @@ +import { read } from 'bun:ffi'; +import { describe, expect, test } from 'bun:test'; +import { currentPlatform } from '../../../src/common/platform'; +import { msgSendU8 } from '../../../src/main/platform/macos/cocoa-msgsend-variants'; +import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; +import { dataSymbolAddress } from '../../../src/main/platform/macos/objc'; + +const CORE_FOUNDATION = '/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation'; + +describe.skipIf(currentPlatform() !== 'macos')('dataSymbolAddress', () => { + test('resolves a data global to its address', () => { + const rt = cocoa(); + const yes = msgSendU8(rt.classes.get('NSNumber'), rt.selectors.get('numberWithBool:'), 1); + expect(read.u64(dataSymbolAddress(CORE_FOUNDATION, 'kCFBooleanTrue'), 0)).toBe(yes); + }); +}); From d75adbbb16e06d6b8c5267b44f927190c1ca0d63 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:49:55 -0700 Subject: [PATCH 045/586] fix: validate setPath and reset setAppLogsPath to the platform default --- src/main/api/app-paths.ts | 4 +++- src/main/api/app.ts | 16 +++++++++++++--- tests/unit/main/api/app.test.ts | 17 +++++++++++++++++ 3 files changed, 33 insertions(+), 4 deletions(-) diff --git a/src/main/api/app-paths.ts b/src/main/api/app-paths.ts index 6f67860c..0c112281 100644 --- a/src/main/api/app-paths.ts +++ b/src/main/api/app-paths.ts @@ -62,6 +62,8 @@ const KNOWN_NAMES: ReadonlySet = new Set([ 'crashDumps', ]); +export const isAppPathName = (name: string): name is AppPathName => KNOWN_NAMES.has(name); + const envDir = (env: PathEnvironment['env'], variable: string, fallback: string): string => { const value = env[variable]; return value !== undefined && value.length > 0 ? value : fallback; @@ -184,7 +186,7 @@ const resolveWindows = (name: AppPathName, e: PathEnvironment): string => { /** Throws {@link InvalidArgumentError} on an unrecognized name, matching Electron. */ export const resolveAppPath = (name: AppPathName, environment: PathEnvironment): string => { - if (!KNOWN_NAMES.has(name)) { + if (!isAppPathName(name)) { throw new InvalidArgumentError(`Failed to get '${name}' path: unknown path name`); } switch (environment.platform) { diff --git a/src/main/api/app.ts b/src/main/api/app.ts index bb9ae5ec..79cc69cf 100644 --- a/src/main/api/app.ts +++ b/src/main/api/app.ts @@ -1,10 +1,11 @@ import { EventEmitter } from 'node:events'; -import { join } from 'node:path'; +import { isAbsolute, join } from 'node:path'; import { makeCancelableEvent } from '../../common/cancelable-event'; +import { InvalidArgumentError } from '../../common/errors'; import { type AppEnvironment, defaultAppEnvironment } from './app-environment'; import { localeCountryCode } from './app-locale'; import { resolveAppName, resolveAppVersion } from './app-metadata'; -import { type AppPathName, resolveAppPath } from './app-paths'; +import { type AppPathName, isAppPathName, resolveAppPath } from './app-paths'; import * as desktop from './app-desktop'; import { Menu } from './menu'; import { createLockBackend } from './single-instance-backend'; @@ -168,12 +169,21 @@ export class App extends EventEmitter { }); } + /** Throws {@link InvalidArgumentError} on an unknown name or a relative path, like Electron. */ setPath(name: AppPathName, path: string): void { + if (!isAppPathName(name)) { + throw new InvalidArgumentError(`Failed to set '${name}' path: unknown path name`); + } + if (!isAbsolute(path)) { + throw new InvalidArgumentError(`Failed to set '${name}' path: path must be absolute`); + } this.#pathOverrides.set(name, path); } + /** Without `path`, pins `logs` to the platform default. */ setAppLogsPath(path?: string): void { - this.#pathOverrides.set('logs', path ?? this.getPath('logs')); + this.#pathOverrides.delete('logs'); + this.setPath('logs', path ?? this.getPath('logs')); } /** A normalized BCP-47 tag. */ diff --git a/tests/unit/main/api/app.test.ts b/tests/unit/main/api/app.test.ts index 29eb7fc7..1199c34d 100644 --- a/tests/unit/main/api/app.test.ts +++ b/tests/unit/main/api/app.test.ts @@ -14,6 +14,8 @@ import { SingleInstanceManager, } from '../../../../src/main/api/single-instance'; import { Menu, resetApplicationMenuForTesting } from '../../../../src/main/api/menu'; +import type { AppPathName } from '../../../../src/main/api/app-paths'; +import { InvalidArgumentError } from '../../../../src/common/errors'; /** Normalize host separators to POSIX so path comparisons match on any host. */ const slash = (s: string): string => s.replaceAll('\\', '/'); @@ -302,6 +304,21 @@ describe('App paths', () => { a.setPath('userData', '/custom/data'); expect(a.getPath('userData')).toBe('/custom/data'); }); + + test('setPath rejects a name getPath does not know', () => { + expect(() => appWith().setPath('bogus' as AppPathName, '/x')).toThrow(InvalidArgumentError); + }); + + test('setPath rejects a relative path', () => { + expect(() => appWith().setPath('userData', 'data')).toThrow(InvalidArgumentError); + }); + + test('setAppLogsPath without a path restores the platform default', () => { + const a = appWith(); + a.setAppLogsPath('/var/log/custom'); + a.setAppLogsPath(); + expect(a.getPath('logs')).toBe('/Users/ada/Library/Logs/Demo App'); + }); }); describe('App locale', () => { From b458bea904f98716a931098e66fe8044966c9421 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:50:01 -0700 Subject: [PATCH 046/586] fix: name the image when a data-symbol dlopen fails --- src/main/platform/macos/objc.ts | 10 +++++++--- tests/integration/macos/objc.test.ts | 6 ++++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/main/platform/macos/objc.ts b/src/main/platform/macos/objc.ts index 5bad9815..3262f57b 100644 --- a/src/main/platform/macos/objc.ts +++ b/src/main/platform/macos/objc.ts @@ -1,5 +1,5 @@ import { FFIType, type Pointer } from 'bun:ffi'; -import { UnsupportedPlatformError } from '../../../common/errors'; +import { FFIError, UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; import { cstr } from '../cstr'; import { dlopen } from '../dlopen'; @@ -70,9 +70,13 @@ const loadDl = macOSLibraryAccessor('libSystem dlsym', () => /** The address of data symbol `name` in the image at `path`: bun's dlopen binds only functions. */ export const dataSymbolAddress = (path: string, name: string): Pointer => { const dl = loadDl().symbols; - const address = dl.dlsym(dl.dlopen(cstr(path), RTLD_NOW), cstr(name)); + const image = dl.dlopen(cstr(path), RTLD_NOW); + if (image === null) { + throw new FFIError(`dlopen('${path}') failed`); + } + const address = dl.dlsym(image, cstr(name)); if (address === null) { - throw new Error(`dlsym('${name}') in ${path} returned null`); + throw new FFIError(`dlsym('${name}') in ${path} returned null`); } return address; }; diff --git a/tests/integration/macos/objc.test.ts b/tests/integration/macos/objc.test.ts index a2f7c8c3..429ec23d 100644 --- a/tests/integration/macos/objc.test.ts +++ b/tests/integration/macos/objc.test.ts @@ -13,4 +13,10 @@ describe.skipIf(currentPlatform() !== 'macos')('dataSymbolAddress', () => { const yes = msgSendU8(rt.classes.get('NSNumber'), rt.selectors.get('numberWithBool:'), 1); expect(read.u64(dataSymbolAddress(CORE_FOUNDATION, 'kCFBooleanTrue'), 0)).toBe(yes); }); + + test('names the image, not the symbol, when the image cannot be opened', () => { + expect(() => dataSymbolAddress('/nonexistent/Missing.framework/Missing', 'kMissing')).toThrow( + /dlopen\('\/nonexistent\/Missing.framework\/Missing'\) failed/, + ); + }); }); From d93b3c2d9d52dfa36d1bf07977ea335f3d69a399 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:50:01 -0700 Subject: [PATCH 047/586] fix: drain an inter-tick autorelease pool so closed windows are freed --- src/main/platform/macos/cocoa-run-loop.ts | 24 ++++++++- .../integration/macos/cocoa-run-loop.test.ts | 51 ++++++++++++++++++- .../integration/macos/window-release.test.ts | 32 ++++++++++++ 3 files changed, 105 insertions(+), 2 deletions(-) create mode 100644 tests/integration/macos/window-release.test.ts diff --git a/src/main/platform/macos/cocoa-run-loop.ts b/src/main/platform/macos/cocoa-run-loop.ts index a18d23aa..ede1bb0a 100644 --- a/src/main/platform/macos/cocoa-run-loop.ts +++ b/src/main/platform/macos/cocoa-run-loop.ts @@ -1,4 +1,4 @@ -import { FFIType } from 'bun:ffi'; +import { FFIType, type Pointer } from 'bun:ffi'; import { dlopen } from '../dlopen'; import { cstr } from '../cstr'; import { bigIntOut, LIBOBJC_PATH, macOSLibraryAccessor, ptrIn } from './objc'; @@ -44,6 +44,23 @@ const getAutoreleasePool = macOSLibraryAccessor('libobjc autorelease pool', () = }), ); +/** Run `fn` in its own autorelease pool, releasing what it autoreleased when it returns. */ +export const withAutoreleasePool = (fn: () => T): T => { + const pool = getAutoreleasePool(); + const token = pool.symbols.objc_autoreleasePoolPush(); + try { + return fn(); + } finally { + pool.symbols.objc_autoreleasePoolPop(token); + } +}; + +// Bun's thread has no ambient pool, so everything JS autoreleases between ticks +// lands in this rolling pool, which each tick drains the way NSApp drains one pool +// per event. One token for every drain: a per-drain token is popped by another +// drain's tick first, and popping it again is an objc fatal abort. +let jsPool: Pointer | null | undefined; + /** * Create the macOS drain function. Throws {@link UnsupportedPlatformError} on * any non-macOS host (via the lazy accessors). The returned function is cheap @@ -60,7 +77,11 @@ export const createMacOSDrain = (pumpEvents?: () => void): ((timeoutMs: number) ), ); + jsPool ??= pool.symbols.objc_autoreleasePoolPush(); return (timeoutMs: number) => { + if (jsPool !== undefined) { + pool.symbols.objc_autoreleasePoolPop(jsPool); + } const poolToken = pool.symbols.objc_autoreleasePoolPush(); try { pumpEvents?.(); @@ -80,6 +101,7 @@ export const createMacOSDrain = (pumpEvents?: () => void): ((timeoutMs: number) return handled; } finally { pool.symbols.objc_autoreleasePoolPop(poolToken); + jsPool = pool.symbols.objc_autoreleasePoolPush(); } }; }; diff --git a/tests/integration/macos/cocoa-run-loop.test.ts b/tests/integration/macos/cocoa-run-loop.test.ts index 0bd57999..a4fa82b2 100644 --- a/tests/integration/macos/cocoa-run-loop.test.ts +++ b/tests/integration/macos/cocoa-run-loop.test.ts @@ -1,6 +1,9 @@ import { describe, expect, test } from 'bun:test'; import { currentPlatform } from '../../../src/common/platform'; -import { createMacOSDrain } from '../../../src/main/platform/macos/cocoa-run-loop'; +import { + createMacOSDrain, + withAutoreleasePool, +} from '../../../src/main/platform/macos/cocoa-run-loop'; import { msgSendI64, msgSendInitWithContentRect, @@ -26,6 +29,52 @@ if (currentPlatform() === 'macos') { expect(typeof drain).toBe('function'); }); + test('each tick of any drain releases what JS autoreleased since the last tick', () => { + const rt = cocoa(); + const retainCount = (handle: bigint): bigint => + rt.msgSend(handle, rt.selectors.get('retainCount')); + const first = createMacOSDrain(); + const second = createMacOSDrain(); + const object = rt.msgSend( + rt.msgSend(rt.classes.get('NSObject'), rt.selectors.get('alloc')), + rt.selectors.get('init'), + ); + try { + for (const drain of [first, second, first, second]) { + rt.msgSend( + rt.msgSend(object, rt.selectors.get('retain')), + rt.selectors.get('autorelease'), + ); + expect(retainCount(object)).toBe(2n); + drain(0); + expect(retainCount(object)).toBe(1n); + } + } finally { + rt.msgSend(object, rt.selectors.get('release')); + } + }); + + test('withAutoreleasePool releases what its callback autoreleased and returns its value', () => { + const rt = cocoa(); + const object = rt.msgSend( + rt.msgSend(rt.classes.get('NSObject'), rt.selectors.get('alloc')), + rt.selectors.get('init'), + ); + try { + const count = withAutoreleasePool(() => { + rt.msgSend( + rt.msgSend(object, rt.selectors.get('retain')), + rt.selectors.get('autorelease'), + ); + return rt.msgSend(object, rt.selectors.get('retainCount')); + }); + expect(count).toBe(2n); + expect(rt.msgSend(object, rt.selectors.get('retainCount'))).toBe(1n); + } finally { + rt.msgSend(object, rt.selectors.get('release')); + } + }); + test('pumping the drain makes a real NSWindow visible', () => { const rt = cocoa(); const app = rt.msgSend( diff --git a/tests/integration/macos/window-release.test.ts b/tests/integration/macos/window-release.test.ts new file mode 100644 index 00000000..0a17152b --- /dev/null +++ b/tests/integration/macos/window-release.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, test } from 'bun:test'; +import { currentPlatform } from '../../../src/common/platform'; +import { createMacOSApplication } from '../../../src/main/platform/macos/cocoa-backend'; +import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; + +const liveWindowCount = (): bigint => { + const rt = cocoa(); + const app = rt.msgSend(rt.classes.get('NSApplication'), rt.selectors.get('sharedApplication')); + return rt.msgSend(rt.msgSend(app, rt.selectors.get('windows')), rt.selectors.get('count')); +}; + +describe.skipIf(currentPlatform() !== 'macos')('closed windows are freed', () => { + test('a shown then closed window leaves the NSApp window list', async () => { + const app = createMacOSApplication(); + app.start(); + try { + await Bun.sleep(100); + const before = liveWindowCount(); + const win = app.createWindow({ width: 320, height: 240, title: 'release', show: true }); + await Bun.sleep(200); + expect(liveWindowCount()).toBe(before + 1n); + win.close(); + const deadline = performance.now() + 3_000; + while (liveWindowCount() > before && performance.now() < deadline) { + await Bun.sleep(50); + } + expect(liveWindowCount()).toBe(before); + } finally { + app.quit(); + } + }, 10_000); +}); From 2f0bb89c132d4b9cb1c5537b0d7dfd538365084c Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:50:04 -0700 Subject: [PATCH 048/586] fix: reject a zoom factor that is not a finite number above 0 --- src/main/api/web-contents.ts | 6 +++++- tests/unit/main/api/web-contents.test.ts | 12 ++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/main/api/web-contents.ts b/src/main/api/web-contents.ts index 3d8e15a9..b98d5711 100644 --- a/src/main/api/web-contents.ts +++ b/src/main/api/web-contents.ts @@ -1,6 +1,7 @@ import { EventEmitter } from 'node:events'; import { isAbsolute, resolve } from 'node:path'; import { pathToFileURL } from 'node:url'; +import { InvalidArgumentError } from '../../common/errors'; import { createLogger } from '../../common/logger'; import { decodeEnvelope, encodeEnvelope, type ReplyEnvelope } from '../ipc/ipc-protocol'; import type { @@ -226,8 +227,11 @@ export class WebContents extends EventEmitter { /** `1` is 100%. */ setZoomFactor(factor: number): void { - this.#zoomFactor = factor; + if (!Number.isFinite(factor) || factor <= 0) { + throw new InvalidArgumentError("'zoomFactor' must be a double greater than 0.0"); + } this.#native.setZoomFactor(factor); + this.#zoomFactor = factor; } getZoomFactor(): number { diff --git a/tests/unit/main/api/web-contents.test.ts b/tests/unit/main/api/web-contents.test.ts index 115f6452..db7844ba 100644 --- a/tests/unit/main/api/web-contents.test.ts +++ b/tests/unit/main/api/web-contents.test.ts @@ -194,6 +194,18 @@ describe('WebContents.setZoomFactor / getZoomFactor', () => { expect(wc.getZoomFactor()).toBe(1.5); }); + test('setZoomFactor rejects a factor that is not a finite number above 0', () => { + const { native, zooms } = makeFakeNative(); + const wc = new WebContents(native); + for (const factor of [0, -1, Number.NaN, Number.POSITIVE_INFINITY]) { + expect(() => wc.setZoomFactor(factor)).toThrow( + "'zoomFactor' must be a double greater than 0.0", + ); + } + expect(zooms).toEqual([]); + expect(wc.getZoomFactor()).toBe(1); + }); + test('setZoomLevel applies factor 1.2**level; getZoomLevel inverts it', () => { const { native, zooms } = makeFakeNative(); const wc = new WebContents(native); From d412d7bfd60661bcb518fc7629875d491923f180 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:50:23 -0700 Subject: [PATCH 049/586] fix: resolve getPath('module') to the executable like Electron --- src/main/api/app-paths.ts | 11 +++-------- src/main/api/app.ts | 1 - tests/unit/main/api/app-paths.test.ts | 9 +++------ 3 files changed, 6 insertions(+), 15 deletions(-) diff --git a/src/main/api/app-paths.ts b/src/main/api/app-paths.ts index 0c112281..2969bef0 100644 --- a/src/main/api/app-paths.ts +++ b/src/main/api/app-paths.ts @@ -38,8 +38,6 @@ export type PathEnvironment = { readonly appName: string; /** `process.execPath`. */ readonly execPath: string; - /** `app.getAppPath()`. */ - readonly appPath: string; /** Consulted for the Linux XDG overrides. */ readonly env: Readonly>; }; @@ -88,9 +86,8 @@ const resolveMacOS = (name: AppPathName, e: PathEnvironment): string => { case 'temp': return e.temp; case 'exe': - return e.execPath; case 'module': - return e.appPath; + return e.execPath; case 'desktop': return join(e.home, 'Desktop'); case 'documents': @@ -125,9 +122,8 @@ const resolveLinux = (name: AppPathName, e: PathEnvironment): string => { case 'temp': return e.temp; case 'exe': - return e.execPath; case 'module': - return e.appPath; + return e.execPath; case 'desktop': return xdgDir(e.env, 'XDG_DESKTOP_DIR', e.home, 'Desktop'); case 'documents': @@ -162,9 +158,8 @@ const resolveWindows = (name: AppPathName, e: PathEnvironment): string => { case 'temp': return e.temp; case 'exe': - return e.execPath; case 'module': - return e.appPath; + return e.execPath; case 'desktop': return join(e.home, 'Desktop'); case 'documents': diff --git a/src/main/api/app.ts b/src/main/api/app.ts index 79cc69cf..c74c207c 100644 --- a/src/main/api/app.ts +++ b/src/main/api/app.ts @@ -164,7 +164,6 @@ export class App extends EventEmitter { temp: env.temp, appName: this.getName(), execPath: env.execPath, - appPath: env.appPath, env: env.env, }); } diff --git a/tests/unit/main/api/app-paths.test.ts b/tests/unit/main/api/app-paths.test.ts index 5dc5a231..7f22ac30 100644 --- a/tests/unit/main/api/app-paths.test.ts +++ b/tests/unit/main/api/app-paths.test.ts @@ -9,7 +9,6 @@ const macEnv = (overrides: Partial = {}): PathEnvironment => ({ temp: '/var/folders/tmp', appName: 'MyApp', execPath: '/Applications/MyApp.app/Contents/MacOS/MyApp', - appPath: '/Applications/MyApp.app/Contents/Resources/app', env: {}, ...overrides, }); @@ -20,7 +19,6 @@ const linuxEnv = (overrides: Partial = {}): PathEnvironment => temp: '/tmp', appName: 'MyApp', execPath: '/opt/myapp/myapp', - appPath: '/opt/myapp/resources/app', env: {}, ...overrides, }); @@ -31,7 +29,6 @@ const winEnv = (overrides: Partial = {}): PathEnvironment => ({ temp: 'C:\\Users\\ada\\AppData\\Local\\Temp', appName: 'MyApp', execPath: 'C:\\Program Files\\MyApp\\MyApp.exe', - appPath: 'C:\\Program Files\\MyApp\\resources\\app', env: { APPDATA: 'C:\\Users\\ada\\AppData\\Roaming' }, ...overrides, }); @@ -51,8 +48,8 @@ describe('resolveAppPath — cross-platform names', () => { expect(resolveAppPath('exe', macEnv())).toBe('/Applications/MyApp.app/Contents/MacOS/MyApp'); }); - test('module is the app path', () => { - expect(resolveAppPath('module', linuxEnv())).toBe('/opt/myapp/resources/app'); + test('module is the executable path, as in Electron', () => { + expect(resolveAppPath('module', linuxEnv())).toBe('/opt/myapp/myapp'); }); }); @@ -168,7 +165,7 @@ describe('resolveAppPath — Windows conventions', () => { test('exe and module pass through', () => { expect(resolveAppPath('exe', winEnv())).toBe('C:\\Program Files\\MyApp\\MyApp.exe'); - expect(resolveAppPath('module', winEnv())).toBe('C:\\Program Files\\MyApp\\resources\\app'); + expect(resolveAppPath('module', winEnv())).toBe('C:\\Program Files\\MyApp\\MyApp.exe'); }); }); From 89f725e042a4b64e1849a28059b98813e8e2d4a8 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:50:26 -0700 Subject: [PATCH 050/586] fix: refuse a lossy ptrIn conversion of a tagged handle --- src/main/platform/macos/objc.ts | 11 +++++++++-- tests/unit/main/platform/macos/objc.test.ts | 7 ++++++- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/src/main/platform/macos/objc.ts b/src/main/platform/macos/objc.ts index 3262f57b..f0815819 100644 --- a/src/main/platform/macos/objc.ts +++ b/src/main/platform/macos/objc.ts @@ -17,8 +17,15 @@ export type Handle = bigint; export const LIBOBJC_PATH = 'libobjc.A.dylib'; -/** Convert a `bigint` handle to the branded `Pointer` Bun FFI expects. */ -export const ptrIn = (handle: Handle): Pointer => Number(handle) as Pointer; +const MAX_EXACT_POINTER = BigInt(Number.MAX_SAFE_INTEGER); + +/** Convert a real C pointer to a `Pointer`; throws on a tagged or too-wide handle (D029). */ +export const ptrIn = (handle: Handle): Pointer => { + if (handle > MAX_EXACT_POINTER) { + throw new FFIError(`ptrIn: 0x${handle.toString(16)} does not fit a JS number (tagged?)`); + } + return Number(handle) as Pointer; +}; /** Convert a `Pointer` (or `null`) returned by FFI to a `bigint` handle (`0n` for null). */ export const bigIntOut = (pointer: Pointer | null): Handle => diff --git a/tests/unit/main/platform/macos/objc.test.ts b/tests/unit/main/platform/macos/objc.test.ts index 38fd0d23..1f27139d 100644 --- a/tests/unit/main/platform/macos/objc.test.ts +++ b/tests/unit/main/platform/macos/objc.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from 'bun:test'; -import { UnsupportedPlatformError } from '../../../../../src/common/errors'; +import { FFIError, UnsupportedPlatformError } from '../../../../../src/common/errors'; import { currentPlatform } from '../../../../../src/common/platform'; import { bigIntOut, @@ -23,6 +23,11 @@ describe('ptrIn', () => { test('converts 0n to 0', () => { expect(Number(ptrIn(0n))).toBe(0); }); + + test('refuses a handle a JS number cannot hold exactly, such as a tagged pointer', () => { + expect(() => ptrIn(0x8000_0000_0000_0011n)).toThrow(FFIError); + expect(() => ptrIn(2n ** 53n + 1n)).toThrow(FFIError); + }); }); describe('bigIntOut', () => { From be74331db417b44e64abf9b38cd89c5aa69f915d Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:50:37 -0700 Subject: [PATCH 051/586] fix: encode gray+alpha images via an RGBA redraw on macOS --- src/main/platform/macos/cocoa-native-image.ts | 50 +++++++++++-------- .../macos/cocoa-native-image.test.ts | 10 ++++ 2 files changed, 39 insertions(+), 21 deletions(-) diff --git a/src/main/platform/macos/cocoa-native-image.ts b/src/main/platform/macos/cocoa-native-image.ts index 4053bb79..f582619d 100644 --- a/src/main/platform/macos/cocoa-native-image.ts +++ b/src/main/platform/macos/cocoa-native-image.ts @@ -183,27 +183,41 @@ const crop = ( return redraw(handle, width, height, -x, -(srcH - y - height), srcW, srcH); }; +/** `representationUsingType:properties:` bytes; empty for a nil handle or a failed encode. */ +const encode = (handle: NativeImageHandle, type: bigint, properties: Handle): Uint8Array => { + if (handle === 0n) { + return new Uint8Array(0); + } + const rt = cocoa(); + const represent = (rep: Handle): Uint8Array => + nsDataToBytes( + msgSendI64Ptr(rep, rt.selectors.get('representationUsingType:properties:'), type, properties), + ); + const bytes = represent(handle); + if (bytes.length > 0) { + return bytes; + } + // ImageIO rejects some decoded layouts (e.g. 8-bit gray+alpha); encode an RGBA redraw instead. + const width = Number(msgSendReturnsI64(handle, rt.selectors.get('pixelsWide'))); + const height = Number(msgSendReturnsI64(handle, rt.selectors.get('pixelsHigh'))); + const rgba = redraw(handle, width, height, 0, 0, width, height); + if (rgba.empty) { + return bytes; + } + const redrawn = represent(rgba.handle); + rt.msgSend(rgba.handle, rt.selectors.get('release')); + return redrawn; +}; + export const cocoaNativeImageBackend: NativeImageBackend = { decode: (source) => (typeof source === 'string' ? decodePath(source) : decodeBuffer(source)), - encodePng: (handle: NativeImageHandle): Uint8Array => { - if (handle === 0n) { - return new Uint8Array(0); - } - const rt = cocoa(); - const data = msgSendI64Ptr( - handle, - rt.selectors.get('representationUsingType:properties:'), - NS_BITMAP_IMAGE_FILE_TYPE_PNG, - 0n, - ); - return nsDataToBytes(data); - }, + encodePng: (handle: NativeImageHandle): Uint8Array => + encode(handle, NS_BITMAP_IMAGE_FILE_TYPE_PNG, 0n), encodeJpeg: (handle: NativeImageHandle, quality: number): Uint8Array => { if (handle === 0n) { return new Uint8Array(0); } const rt = cocoa(); - // Properties dict { NSImageCompressionFactor: quality/100 } (0.0–1.0). const factor = Math.max(0, Math.min(100, quality)) / 100; const number = msgSendF64( rt.classes.get('NSNumber'), @@ -216,13 +230,7 @@ export const cocoaNativeImageBackend: NativeImageBackend = { number, nsString('NSImageCompressionFactor'), ); - const data = msgSendI64Ptr( - handle, - rt.selectors.get('representationUsingType:properties:'), - NS_BITMAP_IMAGE_FILE_TYPE_JPEG, - properties, - ); - return nsDataToBytes(data); + return encode(handle, NS_BITMAP_IMAGE_FILE_TYPE_JPEG, properties); }, resize, crop, diff --git a/tests/integration/macos/cocoa-native-image.test.ts b/tests/integration/macos/cocoa-native-image.test.ts index 11af135d..4a975937 100644 --- a/tests/integration/macos/cocoa-native-image.test.ts +++ b/tests/integration/macos/cocoa-native-image.test.ts @@ -9,6 +9,10 @@ import { writeTinyPngFile, } from '../../fixtures/tiny-png'; +/** 1x1 8-bit gray+alpha PNG; AppKit's PNG encoder fails on such a rep directly. */ +const GRAY_ALPHA_1X1_PNG = + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=='; + /** * Real `nativeImage` on a macOS host, driving the live `NSBitmapImageRep`/`NSData` * FFI. The headline assertion is that `getSize()` returns the EXACT known @@ -58,6 +62,12 @@ if (currentPlatform() === 'macos') { expect(png[3]).toBe(0x47); }); + test('toPNG encodes a gray+alpha source (PNG color type 4)', () => { + const image = nativeImage.createFromDataURL(`data:image/png;base64,${GRAY_ALPHA_1X1_PNG}`); + expect(image.isEmpty()).toBe(false); + expect(image.toPNG()[0]).toBe(0x89); + }); + test('toJPEG returns non-empty bytes starting with the JPEG SOI marker', () => { const jpeg = nativeImage.createFromPath(fixture).toJPEG(80); expect(jpeg.length > 0).toBe(true); From deb274c6960bb6c9962526ec6be654f480841f1c Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:50:40 -0700 Subject: [PATCH 052/586] fix: start the Windows pump before running ready callbacks --- src/main/platform/windows/windows-backend.ts | 9 +++-- .../windows/windows-backend.test.ts | 33 +++++++++++++++++++ 2 files changed, 37 insertions(+), 5 deletions(-) create mode 100644 tests/integration/windows/windows-backend.test.ts diff --git a/src/main/platform/windows/windows-backend.ts b/src/main/platform/windows/windows-backend.ts index b05a9a46..2f23b68d 100644 --- a/src/main/platform/windows/windows-backend.ts +++ b/src/main/platform/windows/windows-backend.ts @@ -393,11 +393,6 @@ export class WindowsApplication implements NativeApplication { } ensureOleInitialized(); this.#started = true; - this.#ready = true; - for (const callback of this.#readyCallbacks) { - callback(); - } - this.#readyCallbacks.length = 0; // WM_HOTKEY is a thread message with no window proc, so only the drain sees it. const drainMessages = createWindowsDrain((_hwnd, message, wParam) => windowsGlobalShortcutBackend.dispatchHotkeyMessage(message, wParam), @@ -407,6 +402,10 @@ export class WindowsApplication implements NativeApplication { pollWindows(); }); this.#pump.start(); + this.#ready = true; + for (const callback of this.#readyCallbacks.splice(0)) { + callback(); + } } onReady(callback: () => void): void { diff --git a/tests/integration/windows/windows-backend.test.ts b/tests/integration/windows/windows-backend.test.ts new file mode 100644 index 00000000..c26edef0 --- /dev/null +++ b/tests/integration/windows/windows-backend.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, test } from 'bun:test'; +import { currentPlatform } from '../../../src/common/platform'; +import { loadUser32 } from '../../../src/main/platform/windows/win32-ffi'; +import { WindowsApplication } from '../../../src/main/platform/windows/windows-backend'; +import { NativeWin32Window } from '../../../src/main/platform/windows/windows-native-window'; + +const WM_CLOSE = 0x0010; + +describe.skipIf(currentPlatform() !== 'windows')('WindowsApplication', () => { + test('keeps pumping messages when a ready listener throws', async () => { + const app = new WindowsApplication(); + app.onReady(() => { + throw new Error('ready listener'); + }); + expect(() => app.start()).toThrow('ready listener'); + const win = new NativeWin32Window({ title: 'Pump', width: 320, height: 240, show: false }); + let closed = 0; + win.onClosed(() => { + closed += 1; + }); + try { + loadUser32().symbols.PostMessageW(win.hwnd(), WM_CLOSE, 0n, 0n); + const deadline = Date.now() + 2000; + while (closed === 0 && Date.now() < deadline) { + await Bun.sleep(16); + } + expect(closed).toBe(1); + } finally { + win.destroy(); + app.quit(); + } + }); +}); From 1277e3af4ec26d01c3949b0949aa2fbc43b37b4f Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:50:41 -0700 Subject: [PATCH 053/586] fix: make Linux window and web contents calls after close inert --- src/main/platform/linux/linux-backend.ts | 167 +++++++++--------- tests/integration/linux/window-events.test.ts | 23 +++ 2 files changed, 103 insertions(+), 87 deletions(-) diff --git a/src/main/platform/linux/linux-backend.ts b/src/main/platform/linux/linux-backend.ts index 13d9b790..606fda9a 100644 --- a/src/main/platform/linux/linux-backend.ts +++ b/src/main/platform/linux/linux-backend.ts @@ -64,6 +64,7 @@ class LinuxWebContents implements NativeWebContents { readonly #view: Pointer; readonly #registry: SignalRegistry; readonly #exec = new ExecResultChannel((source) => evalInPageWorld(this.#view, source)); + #destroyed = false; #didFinishLoad = false; readonly #pendingEnvelopes: string[] = []; readonly #navigationCallbacks: Array<(event: NativeNavigationEvent) => void> = []; @@ -139,79 +140,78 @@ class LinuxWebContents implements NativeWebContents { return this.#view; } - /** The signal registry to disconnect when the owning window closes. */ - registry(): SignalRegistry { - return this.#registry; + /** WebKit symbols while the view lives; `undefined` once the window closed and freed it. */ + #live(): ReturnType['symbols'] | undefined { + return this.#destroyed ? undefined : loadWebKitGtkFFI().symbols; + } + + /** @internal Tear down on window close; every later call is a no-op on the freed view. */ + teardown(): void { + this.#destroyed = true; + this.#exec.destroy(); + this.#registry.disconnectAll(); } loadURL(url: string): void { - const webkit = loadWebKitGtkFFI(); - webkit.symbols.webkit_web_view_load_uri(this.#view, cstr(url)); + this.#live()?.webkit_web_view_load_uri(this.#view, cstr(url)); } loadHTML(html: string, baseUrl?: string): void { - const webkit = loadWebKitGtkFFI(); // base_uri is nullable; cstring cannot encode NULL, so pass a pinned // NUL-terminated buffer for a real base or null for NULL. const baseUri = baseUrl === undefined ? null : cstr(baseUrl); - webkit.symbols.webkit_web_view_load_html(this.#view, cstr(html), baseUri); + this.#live()?.webkit_web_view_load_html(this.#view, cstr(html), baseUri); } getURL(): string { - const webkit = loadWebKitGtkFFI(); - return readGetUriResult(webkit.symbols.webkit_web_view_get_uri(this.#view)); + const webkit = this.#live(); + return webkit === undefined ? '' : readGetUriResult(webkit.webkit_web_view_get_uri(this.#view)); } getTitle(): string { - const webkit = loadWebKitGtkFFI(); - return readGetUriResult(webkit.symbols.webkit_web_view_get_title(this.#view)); + const webkit = this.#live(); + return webkit === undefined + ? '' + : readGetUriResult(webkit.webkit_web_view_get_title(this.#view)); } reload(): void { - const webkit = loadWebKitGtkFFI(); - webkit.symbols.webkit_web_view_reload(this.#view); + this.#live()?.webkit_web_view_reload(this.#view); } reloadIgnoringCache(): void { - const webkit = loadWebKitGtkFFI(); - webkit.symbols.webkit_web_view_reload_bypass_cache(this.#view); + this.#live()?.webkit_web_view_reload_bypass_cache(this.#view); } stop(): void { - const webkit = loadWebKitGtkFFI(); - webkit.symbols.webkit_web_view_stop_loading(this.#view); + this.#live()?.webkit_web_view_stop_loading(this.#view); } goBack(): void { - const webkit = loadWebKitGtkFFI(); - webkit.symbols.webkit_web_view_go_back(this.#view); + this.#live()?.webkit_web_view_go_back(this.#view); } goForward(): void { - const webkit = loadWebKitGtkFFI(); - webkit.symbols.webkit_web_view_go_forward(this.#view); + this.#live()?.webkit_web_view_go_forward(this.#view); } canGoBack(): boolean { - const webkit = loadWebKitGtkFFI(); - return webkit.symbols.webkit_web_view_can_go_back(this.#view) !== 0; + return (this.#live()?.webkit_web_view_can_go_back(this.#view) ?? 0) !== 0; } canGoForward(): boolean { - const webkit = loadWebKitGtkFFI(); - return webkit.symbols.webkit_web_view_can_go_forward(this.#view) !== 0; + return (this.#live()?.webkit_web_view_can_go_forward(this.#view) ?? 0) !== 0; } setZoomFactor(factor: number): void { - const webkit = loadWebKitGtkFFI(); - webkit.symbols.webkit_web_view_set_zoom_level(this.#view, factor); + this.#live()?.webkit_web_view_set_zoom_level(this.#view, factor); } setUserAgent(userAgent: string): void { - const webkit = loadWebKitGtkFFI(); + const webkit = this.#live(); // Set on the view's WebKitSettings; takes effect on the next navigation. - webkit.symbols.webkit_settings_set_user_agent( - webkit.symbols.webkit_web_view_get_settings(this.#view), + webkit?.webkit_settings_set_user_agent( + webkit.webkit_web_view_get_settings(this.#view), cstr(userAgent), ); } @@ -235,6 +235,9 @@ class LinuxWebContents implements NativeWebContents { } capturePage(): Promise { + if (this.#destroyed) { + return Promise.reject(new Error('capturePage failed: web contents destroyed')); + } return webkitCapturePage(this.#view); } @@ -242,30 +245,26 @@ class LinuxWebContents implements NativeWebContents { throw new UnsupportedPlatformError('webContents.sendInputEvent is not yet supported on Linux'); } - /** @internal Reject every still-pending exec; called on window close. */ - rejectPendingExecs(): void { - this.#exec.destroy(); - } - openDevTools(): void { - const webkit = loadWebKitGtkFFI(); - const inspector = webkit.symbols.webkit_web_view_get_inspector(this.#view); - if (inspector === null) { - return; + const webkit = this.#live(); + const inspector = webkit?.webkit_web_view_get_inspector(this.#view) ?? null; + if (inspector !== null) { + webkit?.webkit_web_inspector_show(inspector); } - webkit.symbols.webkit_web_inspector_show(inspector); } closeDevTools(): void { - const webkit = loadWebKitGtkFFI(); - const inspector = webkit.symbols.webkit_web_view_get_inspector(this.#view); - if (inspector === null) { - return; + const webkit = this.#live(); + const inspector = webkit?.webkit_web_view_get_inspector(this.#view) ?? null; + if (inspector !== null) { + webkit?.webkit_web_inspector_close(inspector); } - webkit.symbols.webkit_web_inspector_close(inspector); } sendEnvelopeToRenderer(envelopeJson: string): void { + if (this.#destroyed) { + return; // an invoke reply or send() after close: the view is freed. + } if (!this.#didFinishLoad) { this.#pendingEnvelopes.push(envelopeJson); return; @@ -517,18 +516,18 @@ class LinuxWindow implements NativeWindow { } } this.#releaseAppMenu?.(); - // Reject any executeJavaScript Promise still awaiting a `bunmaskaExec` result - // it can no longer receive, THEN disconnect signals + close the retained - // JSCallbacks (including the shared exec handler) — never per-call. - this.#webContents.rejectPendingExecs(); - this.#webContents.registry().disconnectAll(); + this.#webContents.teardown(); this.#registry.disconnectAll(); } + /** GTK symbols while the window lives; `undefined` once it is destroyed (freed). */ + #gtk(): ReturnType['symbols'] | undefined { + return this.#closed ? undefined : loadGtkFFI().symbols; + } + setTitle(title: string): void { - const gtk = loadGtkFFI(); this.#title = title; - gtk.symbols.gtk_window_set_title(this.#window, cstr(title)); + this.#gtk()?.gtk_window_set_title(this.#window, cstr(title)); } getTitle(): string { @@ -536,8 +535,7 @@ class LinuxWindow implements NativeWindow { } setSize(width: number, height: number): void { - const gtk = loadGtkFFI(); - gtk.symbols.gtk_window_set_default_size(this.#window, width, height); + this.#gtk()?.gtk_window_set_default_size(this.#window, width, height); } setPosition(_x: number, _y: number): void { @@ -551,18 +549,15 @@ class LinuxWindow implements NativeWindow { } setResizable(resizable: boolean): void { - const gtk = loadGtkFFI(); - gtk.symbols.gtk_window_set_resizable(this.#window, resizable ? GTK_TRUE : GTK_FALSE); + this.#gtk()?.gtk_window_set_resizable(this.#window, resizable ? GTK_TRUE : GTK_FALSE); } setOpacity(opacity: number): void { - const gtk = loadGtkFFI(); - gtk.symbols.gtk_widget_set_opacity(this.#window, opacity); + this.#gtk()?.gtk_widget_set_opacity(this.#window, opacity); } setMinimumSize(width: number, height: number): void { - const gtk = loadGtkFFI(); - gtk.symbols.gtk_widget_set_size_request(this.#window, width, height); + this.#gtk()?.gtk_widget_set_size_request(this.#window, width, height); } center(): void { @@ -571,9 +566,9 @@ class LinuxWindow implements NativeWindow { } getBounds(): Rect { - const gtk = loadGtkFFI(); - const width = gtk.symbols.gtk_widget_get_width(this.#window); - const height = gtk.symbols.gtk_widget_get_height(this.#window); + const gtk = this.#gtk(); + const width = gtk?.gtk_widget_get_width(this.#window) ?? 0; + const height = gtk?.gtk_widget_get_height(this.#window) ?? 0; return { x: 0, y: 0, @@ -583,11 +578,14 @@ class LinuxWindow implements NativeWindow { } show(): void { - const gtk = loadGtkFFI(); - gtk.symbols.gtk_widget_set_visible(this.#window, GTK_TRUE); + const gtk = this.#gtk(); + if (gtk === undefined) { + return; + } + gtk.gtk_widget_set_visible(this.#window, GTK_TRUE); // `present` requests focus; a dev respawn leaves the editor focused. if (!isDevRestart()) { - gtk.symbols.gtk_window_present(this.#window); + gtk.gtk_window_present(this.#window); } this.#visible = true; this.#minimized = false; @@ -595,8 +593,11 @@ class LinuxWindow implements NativeWindow { } hide(): void { - const gtk = loadGtkFFI(); - gtk.symbols.gtk_widget_set_visible(this.#window, GTK_FALSE); + const gtk = this.#gtk(); + if (gtk === undefined) { + return; + } + gtk.gtk_widget_set_visible(this.#window, GTK_FALSE); this.#visible = false; this.#emitEvent('hide'); } @@ -606,29 +607,24 @@ class LinuxWindow implements NativeWindow { } focus(): void { - const gtk = loadGtkFFI(); - gtk.symbols.gtk_window_present(this.#window); + this.#gtk()?.gtk_window_present(this.#window); } minimize(): void { - const gtk = loadGtkFFI(); - gtk.symbols.gtk_window_minimize(this.#window); + this.#gtk()?.gtk_window_minimize(this.#window); this.#minimized = true; } maximize(): void { - const gtk = loadGtkFFI(); - gtk.symbols.gtk_window_maximize(this.#window); + this.#gtk()?.gtk_window_maximize(this.#window); } unmaximize(): void { - const gtk = loadGtkFFI(); - gtk.symbols.gtk_window_unmaximize(this.#window); + this.#gtk()?.gtk_window_unmaximize(this.#window); } isMaximized(): boolean { - const gtk = loadGtkFFI(); - return gtk.symbols.gtk_window_is_maximized(this.#window) !== 0; + return (this.#gtk()?.gtk_window_is_maximized(this.#window) ?? 0) !== 0; } isMinimized(): boolean { @@ -636,28 +632,25 @@ class LinuxWindow implements NativeWindow { } restore(): void { - const gtk = loadGtkFFI(); - gtk.symbols.gtk_window_unminimize(this.#window); + this.#gtk()?.gtk_window_unminimize(this.#window); this.#minimized = false; } isFocused(): boolean { - const gtk = loadGtkFFI(); - return gtk.symbols.gtk_window_is_active(this.#window) !== 0; + return (this.#gtk()?.gtk_window_is_active(this.#window) ?? 0) !== 0; } setFullScreen(flag: boolean): void { - const gtk = loadGtkFFI(); + const gtk = this.#gtk(); if (flag) { - gtk.symbols.gtk_window_fullscreen(this.#window); + gtk?.gtk_window_fullscreen(this.#window); } else { - gtk.symbols.gtk_window_unfullscreen(this.#window); + gtk?.gtk_window_unfullscreen(this.#window); } } isFullScreen(): boolean { - const gtk = loadGtkFFI(); - return gtk.symbols.gtk_window_is_fullscreen(this.#window) !== 0; + return (this.#gtk()?.gtk_window_is_fullscreen(this.#window) ?? 0) !== 0; } setAlwaysOnTop(_flag: boolean): void { diff --git a/tests/integration/linux/window-events.test.ts b/tests/integration/linux/window-events.test.ts index ad356165..354b1363 100644 --- a/tests/integration/linux/window-events.test.ts +++ b/tests/integration/linux/window-events.test.ts @@ -120,6 +120,29 @@ describe.skipIf(!isLinux)('Linux window lifecycle events end-to-end', () => { app.quit(); }); + test('calls after close never touch the freed window or view', () => { + if (loadGtkFFI().symbols.gtk_init_check() === 0) { + return; + } + const app = createLinuxApplication(); + app.start(); + const window = app.createWindow({ width: 200, height: 120, title: 'After Close', show: true }); + window.webContents.loadHTML('

x

'); + window.close(); + + window.setTitle('ignored'); + window.show(); + window.webContents.loadURL('about:blank'); + window.webContents.sendEnvelopeToRenderer('{"kind":"send","channel":"late","args":[]}'); + + expect(window.isVisible()).toBe(false); + expect(window.isFocused()).toBe(false); + expect(window.getBounds()).toEqual({ x: 0, y: 0, width: 200, height: 120 }); + expect(window.webContents.getURL()).toBe(''); + expect(window.webContents.canGoBack()).toBe(false); + app.quit(); + }); + test('a close listener that destroys the window does not destroy it twice', () => { if (loadGtkFFI().symbols.gtk_init_check() === 0) { return; From 84eb522f3fc67fd49f712ef178e656561a357992 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:50:49 -0700 Subject: [PATCH 054/586] chore: delete the dead cocoa-rect module --- src/main/platform/macos/cocoa-rect.ts | 51 ---------- .../main/platform/macos/cocoa-rect.test.ts | 93 ------------------- 2 files changed, 144 deletions(-) delete mode 100644 src/main/platform/macos/cocoa-rect.ts delete mode 100644 tests/unit/main/platform/macos/cocoa-rect.test.ts diff --git a/src/main/platform/macos/cocoa-rect.ts b/src/main/platform/macos/cocoa-rect.ts deleted file mode 100644 index 2c8d4007..00000000 --- a/src/main/platform/macos/cocoa-rect.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { BunmaskaError } from '../../../common/errors'; - -/** - * A Cocoa rectangle in user-space coordinates. - * - * Mirrors the C struct `CGRect = { CGPoint origin; CGSize size; }` where each - * field is a `double`. - */ -export type CGRect = { - readonly x: number; - readonly y: number; - readonly width: number; - readonly height: number; -}; - -/** Size of a `CGRect` in bytes on macOS (4 × `double` = 32). */ -export const CG_RECT_SIZE = 32; - -/** - * Pack a `CGRect` into a 32-byte `ArrayBuffer` with the layout Cocoa expects: - * `[x, y, width, height]` as four contiguous little-endian f64s. macOS is - * little-endian on both Intel and Apple Silicon, so endianness is hard-coded. - */ -export const packCGRect = (rect: CGRect): ArrayBuffer => { - const buf = new ArrayBuffer(CG_RECT_SIZE); - const view = new DataView(buf); - view.setFloat64(0, rect.x, true); - view.setFloat64(8, rect.y, true); - view.setFloat64(16, rect.width, true); - view.setFloat64(24, rect.height, true); - return buf; -}; - -/** - * Read a `CGRect` from a buffer laid out as `[x, y, width, height]` little-endian f64s. - * Throws {@link BunmaskaError} when the buffer is shorter than {@link CG_RECT_SIZE}. - */ -export const unpackCGRect = (buffer: ArrayBufferLike): CGRect => { - if (buffer.byteLength < CG_RECT_SIZE) { - throw new BunmaskaError( - `CGRect buffer must be at least ${CG_RECT_SIZE} bytes, got ${buffer.byteLength}`, - ); - } - const view = new DataView(buffer); - return { - x: view.getFloat64(0, true), - y: view.getFloat64(8, true), - width: view.getFloat64(16, true), - height: view.getFloat64(24, true), - }; -}; diff --git a/tests/unit/main/platform/macos/cocoa-rect.test.ts b/tests/unit/main/platform/macos/cocoa-rect.test.ts deleted file mode 100644 index 1a8d505e..00000000 --- a/tests/unit/main/platform/macos/cocoa-rect.test.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { BunmaskaError } from '../../../../../src/common/errors'; -import { - CG_RECT_SIZE, - type CGRect, - packCGRect, - unpackCGRect, -} from '../../../../../src/main/platform/macos/cocoa-rect'; - -describe('CG_RECT_SIZE', () => { - test('is 32 bytes (4 × f64)', () => { - expect(CG_RECT_SIZE).toBe(32); - }); -}); - -describe('packCGRect', () => { - test('returns an ArrayBuffer of CG_RECT_SIZE', () => { - const buf = packCGRect({ x: 0, y: 0, width: 0, height: 0 }); - expect(buf).toBeInstanceOf(ArrayBuffer); - expect(buf.byteLength).toBe(CG_RECT_SIZE); - }); - - test('lays out fields as [x, y, width, height] in little-endian f64', () => { - const buf = packCGRect({ x: 1, y: 2, width: 3, height: 4 }); - const view = new DataView(buf); - expect(view.getFloat64(0, true)).toBe(1); - expect(view.getFloat64(8, true)).toBe(2); - expect(view.getFloat64(16, true)).toBe(3); - expect(view.getFloat64(24, true)).toBe(4); - }); - - test('preserves fractional values', () => { - const r: CGRect = { x: 0.5, y: 1.25, width: 100.75, height: 200.125 }; - const view = new DataView(packCGRect(r)); - expect(view.getFloat64(0, true)).toBe(0.5); - expect(view.getFloat64(8, true)).toBe(1.25); - expect(view.getFloat64(16, true)).toBe(100.75); - expect(view.getFloat64(24, true)).toBe(200.125); - }); - - test('preserves negative coordinates (multi-monitor case)', () => { - const view = new DataView(packCGRect({ x: -100, y: -50, width: 800, height: 600 })); - expect(view.getFloat64(0, true)).toBe(-100); - expect(view.getFloat64(8, true)).toBe(-50); - }); - - test('preserves large values within f64 range', () => { - const big = 1e15; - const view = new DataView(packCGRect({ x: big, y: big, width: big, height: big })); - expect(view.getFloat64(0, true)).toBe(big); - expect(view.getFloat64(24, true)).toBe(big); - }); -}); - -describe('unpackCGRect', () => { - test('reads back a packed buffer correctly', () => { - const r: CGRect = { x: 10, y: 20, width: 800, height: 600 }; - expect(unpackCGRect(packCGRect(r))).toEqual(r); - }); - - test('throws BunmaskaError when buffer is smaller than CG_RECT_SIZE', () => { - const small = new ArrayBuffer(16); - expect(() => unpackCGRect(small)).toThrow(BunmaskaError); - expect(() => unpackCGRect(small)).toThrow(/CGRect buffer must be at least 32 bytes/); - }); - - test('accepts a buffer larger than CG_RECT_SIZE and reads only the first 32 bytes', () => { - const big = new ArrayBuffer(64); - const view = new DataView(big); - view.setFloat64(0, 7, true); - view.setFloat64(8, 8, true); - view.setFloat64(16, 9, true); - view.setFloat64(24, 10, true); - expect(unpackCGRect(big)).toEqual({ x: 7, y: 8, width: 9, height: 10 }); - }); -}); - -describe('pack/unpack round-trip', () => { - const cases: ReadonlyArray = [ - { x: 0, y: 0, width: 0, height: 0 }, - { x: 1, y: 1, width: 1, height: 1 }, - { x: -1, y: -1, width: 1, height: 1 }, - { x: 100, y: 200, width: 1920, height: 1080 }, - { x: 0.5, y: 0.5, width: 0.5, height: 0.5 }, - { x: 1e10, y: -1e10, width: 1e9, height: 1e9 }, - ]; - - for (const r of cases) { - test(`round-trips ${JSON.stringify(r)}`, () => { - expect(unpackCGRect(packCGRect(r))).toEqual(r); - }); - } -}); From 4b97d619a8e64c717448db9ff54f2be26372320f Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:51:16 -0700 Subject: [PATCH 055/586] fix: release each Linux window's user content manager on close --- src/main/platform/linux/linux-backend.ts | 6 ++++++ src/main/platform/linux/webkit-ipc.ts | 10 +++------- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/src/main/platform/linux/linux-backend.ts b/src/main/platform/linux/linux-backend.ts index 606fda9a..85fc7d26 100644 --- a/src/main/platform/linux/linux-backend.ts +++ b/src/main/platform/linux/linux-backend.ts @@ -23,6 +23,7 @@ import type { } from '../native'; import { windowControlsScript } from '../window-controls'; import { ExecResultChannel } from './eval-js'; +import { loadGObjectFFI } from './gobject-ffi'; import { loadGtkFFI } from './gtk-ffi'; import { getCurrentAppMenu, getMenuEntry, realizeForWindow, onAppMenuCleared } from './gtk-menu'; import { loadGtkMenuFFI } from './gtk-menu-ffi'; @@ -62,6 +63,7 @@ const GTK_ORIENTATION_VERTICAL = 1; */ class LinuxWebContents implements NativeWebContents { readonly #view: Pointer; + readonly #ucm: Pointer; readonly #registry: SignalRegistry; readonly #exec = new ExecResultChannel((source) => evalInPageWorld(this.#view, source)); #destroyed = false; @@ -96,6 +98,7 @@ class LinuxWebContents implements NativeWebContents { }, }); this.#view = wired.view; + this.#ucm = wired.ucm; this.#registry = wired.registry; // Wire every custom scheme registered via `protocol.handle` onto THIS view's // WebKitWebContext before any load, so `app://…` loads are served. Each @@ -150,6 +153,9 @@ class LinuxWebContents implements NativeWebContents { this.#destroyed = true; this.#exec.destroy(); this.#registry.disconnectAll(); + // Deferred: close() can run inside this manager's own script-message emission. + const ucm = this.#ucm; + setTimeout(() => loadGObjectFFI().symbols.g_object_unref(ucm), 0); } loadURL(url: string): void { diff --git a/src/main/platform/linux/webkit-ipc.ts b/src/main/platform/linux/webkit-ipc.ts index fb51cf2c..8a80da86 100644 --- a/src/main/platform/linux/webkit-ipc.ts +++ b/src/main/platform/linux/webkit-ipc.ts @@ -68,11 +68,7 @@ const requirePointer = (ptr: Pointer | null, what: string): Pointer => { return ptr; }; -/** - * Build a `WebKitUserScript` from `source` for the named isolated world and add - * it to the manager at document-start in all frames. The manager takes its own - * ref on the script, so it need not be retained here. - */ +/** Add `source` to the isolated `BunmaskaPreload` world at document-start. */ const addUserScript = (ucm: Pointer, source: string): void => { const webkit = loadWebKitGtkFFI(); const script = webkit.symbols.webkit_user_script_new_for_world( @@ -83,7 +79,7 @@ const addUserScript = (ucm: Pointer, source: string): void => { null, null, ); - webkit.symbols.webkit_user_content_manager_add_script(ucm, requirePointer(script, 'user_script')); + webkit.symbols.webkit_user_content_manager_add_script(ucm, requirePointer(script, 'user_script')); // ponytail: our script ref leaks; unref needs webkit_user_script_unref in webkitgtk-ffi }; const addPageWorldScript = (ucm: Pointer, source: string): void => { @@ -95,7 +91,7 @@ const addPageWorldScript = (ucm: Pointer, source: string): void => { null, null, ); - webkit.symbols.webkit_user_content_manager_add_script(ucm, requirePointer(script, 'user_script')); + webkit.symbols.webkit_user_content_manager_add_script(ucm, requirePointer(script, 'user_script')); // ponytail: our script ref leaks; unref needs webkit_user_script_unref in webkitgtk-ffi }; /** From 30a149fe8fb444097e0ed5587e47d26df121b3a1 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:51:17 -0700 Subject: [PATCH 056/586] fix: type ipcMain event senders and add event.reply --- src/main/api/ipc-main.ts | 11 ++++++----- src/main/api/web-contents.ts | 5 ++++- tests/integration/macos/ipc-e2e.test.ts | 4 +++- tests/unit/main/api/web-contents.test.ts | 11 +++++++++++ tests/unit/main/ipc/ipc-main.test.ts | 5 +++-- 5 files changed, 27 insertions(+), 9 deletions(-) diff --git a/src/main/api/ipc-main.ts b/src/main/api/ipc-main.ts index 6afb74fa..e7c8fd35 100644 --- a/src/main/api/ipc-main.ts +++ b/src/main/api/ipc-main.ts @@ -1,5 +1,6 @@ import { createLogger } from '../../common/logger'; import type { InvokeEnvelope, ReplyEnvelope, SendEnvelope } from '../ipc/ipc-protocol'; +import type { WebContents } from './web-contents'; /** * Main-process IPC — the drop-in equivalent of Electron's `ipcMain`. At most one @@ -7,13 +8,13 @@ import type { InvokeEnvelope, ReplyEnvelope, SendEnvelope } from '../ipc/ipc-pro * {@link IpcMainImpl.dispatch}. */ -/** `sender` is the originating `WebContents`. */ -export type IpcMainEvent = { - readonly sender: unknown; +export type IpcMainInvokeEvent = { + readonly sender: WebContents; }; -export type IpcMainInvokeEvent = { - readonly sender: unknown; +export type IpcMainEvent = IpcMainInvokeEvent & { + /** Sends to the renderer the message came from. */ + reply(channel: string, ...args: readonly unknown[]): void; }; const log = createLogger('ipc-main'); diff --git a/src/main/api/web-contents.ts b/src/main/api/web-contents.ts index b98d5711..882b8418 100644 --- a/src/main/api/web-contents.ts +++ b/src/main/api/web-contents.ts @@ -347,7 +347,10 @@ export class WebContents extends EventEmitter { if ((envelope.kind !== 'send' && envelope.kind !== 'invoke') || this.#destroyed) { return; } - const reply = await ipcMain.dispatch(envelope, { sender: this }); + const reply = await ipcMain.dispatch(envelope, { + sender: this, + reply: (channel, ...args) => this.send(channel, ...args), + }); if (reply !== undefined && !this.#destroyed) { this.#view.sendEnvelopeToRenderer(encodeReply(reply)); } diff --git a/tests/integration/macos/ipc-e2e.test.ts b/tests/integration/macos/ipc-e2e.test.ts index 063def5a..4f746132 100644 --- a/tests/integration/macos/ipc-e2e.test.ts +++ b/tests/integration/macos/ipc-e2e.test.ts @@ -1,6 +1,7 @@ import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; import { currentPlatform } from '../../../src/common/platform'; import { IpcMainImpl } from '../../../src/main/api/ipc-main'; +import type { WebContents } from '../../../src/main/api/web-contents'; import { decodeEnvelope, encodeEnvelope } from '../../../src/main/ipc/ipc-protocol'; import { createMacOSApplication } from '../../../src/main/platform/macos/cocoa-backend'; import type { NativeApplication, NativeWindow } from '../../../src/main/platform/native'; @@ -113,7 +114,8 @@ if (currentPlatform() === 'macos') { received.push(json); const env = decodeEnvelope(json); if (env.kind === 'send' || env.kind === 'invoke') { - const reply = await ipc.dispatch(env, { sender: win.webContents }); + const event = { sender: {} as WebContents, reply: () => undefined }; + const reply = await ipc.dispatch(env, event); if (reply !== undefined) { win.webContents.sendEnvelopeToRenderer(encodeEnvelope(reply)); } diff --git a/tests/unit/main/api/web-contents.test.ts b/tests/unit/main/api/web-contents.test.ts index db7844ba..db20e5f9 100644 --- a/tests/unit/main/api/web-contents.test.ts +++ b/tests/unit/main/api/web-contents.test.ts @@ -376,6 +376,17 @@ describe('WebContents <-> ipcMain auto-wiring', () => { expect(calls[0]?.sender).toBe(wc); }); + test('event.reply sends to the renderer the message came from', async () => { + const { native, sent, fireRenderer } = makeFakeNative(); + new WebContents(native); + ipcMain.on('ping', (event) => event.reply('pong', 1)); + + fireRenderer(encodeEnvelope({ kind: 'send', channel: 'ping', args: [] })); + await flush(); + + expect(decodeEnvelope(sent[0] ?? '')).toEqual({ kind: 'send', channel: 'pong', args: [1] }); + }); + test('a renderer invoke is handled and a reply is sent back', async () => { const { native, sent, fireRenderer } = makeFakeNative(); new WebContents(native); diff --git a/tests/unit/main/ipc/ipc-main.test.ts b/tests/unit/main/ipc/ipc-main.test.ts index d4ec862a..006330cf 100644 --- a/tests/unit/main/ipc/ipc-main.test.ts +++ b/tests/unit/main/ipc/ipc-main.test.ts @@ -1,5 +1,6 @@ import { beforeEach, describe, expect, test } from 'bun:test'; -import { IpcMainImpl } from '../../../../src/main/api/ipc-main'; +import { type IpcMainEvent, IpcMainImpl } from '../../../../src/main/api/ipc-main'; +import type { WebContents } from '../../../../src/main/api/web-contents'; import type { InvokeEnvelope, SendEnvelope } from '../../../../src/main/ipc/ipc-protocol'; const send = (channel: string, ...args: unknown[]): SendEnvelope => ({ @@ -13,7 +14,7 @@ const invoke = (id: number, channel: string, ...args: unknown[]): InvokeEnvelope channel, args, }); -const event = { sender: undefined }; +const event: IpcMainEvent = { sender: {} as WebContents, reply: () => undefined }; let ipc: IpcMainImpl; beforeEach(() => { From 24d850f6f05f9497f7960b40152a712c2c0a5d2b Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:51:19 -0700 Subject: [PATCH 057/586] fix: read Linux user folders from xdg-user-dirs --- src/main/api/app-environment.ts | 19 +++++++++++++++++-- tests/unit/main/api/app.test.ts | 12 ++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/main/api/app-environment.ts b/src/main/api/app-environment.ts index e75a2070..67f2b560 100644 --- a/src/main/api/app-environment.ts +++ b/src/main/api/app-environment.ts @@ -1,6 +1,6 @@ import { readFileSync } from 'node:fs'; import { homedir, tmpdir } from 'node:os'; -import { dirname } from 'node:path'; +import { dirname, posix } from 'node:path'; import { currentPlatform, type Platform } from '../../common/platform'; import { findManifest, type Manifest, type ManifestReader, readManifest } from './app-metadata'; import { normalizeLocale, parsePreferredLanguages } from './app-locale'; @@ -70,6 +70,20 @@ const locateApp = (deps: EnvironmentDeps): { dir: string; manifest: Manifest | u return { dir: found?.dir ?? deps.cwd, manifest: found?.manifest }; }; +/** The absolute `XDG__DIR` entries of xdg-user-dirs' `user-dirs.dirs`, `$HOME` expanded. */ +const readUserDirs = (deps: EnvironmentDeps): Record => { + const configHome = deps.env['XDG_CONFIG_HOME'] || posix.join(deps.home, '.config'); + const text = deps.readFile(posix.join(configHome, 'user-dirs.dirs')) ?? ''; + const dirs: Record = {}; + for (const [, key = '', value = ''] of text.matchAll(/^[ \t]*(XDG_\w+_DIR)="([^"]*)"/gm)) { + const dir = value.replace(/^\$HOME(?=\/|$)/, deps.home); + if (dir.startsWith('/')) { + dirs[key] = dir; + } + } + return dirs; +}; + export const buildAppEnvironment = (deps: EnvironmentDeps): AppEnvironment => { const app = locateApp(deps); const locale = normalizeLocale(deps.locale); @@ -79,7 +93,8 @@ export const buildAppEnvironment = (deps: EnvironmentDeps): AppEnvironment => { temp: deps.temp, execPath: deps.execPath, appPath: app.dir, - env: deps.env, + // Desktop sessions keep the localized user folders in the file, not the environment. + env: deps.platform === 'linux' ? { ...readUserDirs(deps), ...deps.env } : deps.env, manifest: app.manifest, locale, preferredLanguages: computePreferredLanguages(deps.env, locale), diff --git a/tests/unit/main/api/app.test.ts b/tests/unit/main/api/app.test.ts index 1199c34d..56f74777 100644 --- a/tests/unit/main/api/app.test.ts +++ b/tests/unit/main/api/app.test.ts @@ -313,6 +313,18 @@ describe('App paths', () => { expect(() => appWith().setPath('userData', 'data')).toThrow(InvalidArgumentError); }); + test('Linux user folders come from xdg-user-dirs', () => { + const userDirs = + '# written by xdg-user-dirs-update\nXDG_DOWNLOAD_DIR="$HOME/Téléchargements"\n'; + const a = appWith({ + platform: 'linux', + home: '/home/ada', + readFile: (path) => + slash(path) === '/home/ada/.config/user-dirs.dirs' ? userDirs : undefined, + }); + expect(a.getPath('downloads')).toBe('/home/ada/Téléchargements'); + }); + test('setAppLogsPath without a path restores the platform default', () => { const a = appWith(); a.setAppLogsPath('/var/log/custom'); From b36ecff8581e39f1de6b7745ccf2ce17808886dd Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:51:31 -0700 Subject: [PATCH 058/586] fix: honour the fullscreen option on Windows --- src/main/platform/windows/windows-backend.ts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/main/platform/windows/windows-backend.ts b/src/main/platform/windows/windows-backend.ts index 2f23b68d..e4869498 100644 --- a/src/main/platform/windows/windows-backend.ts +++ b/src/main/platform/windows/windows-backend.ts @@ -40,6 +40,7 @@ const WS_EX_LAYERED = 0x00080000n; const LWA_ALPHA = 0x02; const WS_POPUP = 0x80000000; const WS_VISIBLE = 0x10000000; +const WS_CLIPCHILDREN = 0x02000000; const STYLE_RESIZABLE = 0x00050000n; // WS_THICKFRAME | WS_MAXIMIZEBOX const SM_CXSCREEN = 0; const SM_CYSCREEN = 1; @@ -49,6 +50,10 @@ const SM_CYSCREEN = 1; const TPM_RETURNCMD = 0x0100; const TPM_RIGHTBUTTON = 0x0002; +/** `style` with the `WS_VISIBLE` bit of `current`: a style swap must never show or hide. */ +const keepVisibility = (style: bigint, current: bigint): bigint => + (style & ~BigInt(WS_VISIBLE)) | (current & BigInt(WS_VISIBLE)); + /** Windows {@link NativeWindow}: a top-level window hosting a WinCairo `WKView`. */ class WindowsWindow implements NativeWindow { readonly #native: NativeWin32Window; @@ -111,6 +116,9 @@ class WindowsWindow implements NativeWindow { this.#native.emit('ready-to-show'); } }); + if (options.fullscreen === true) { + this.setFullScreen(true); + } if (options.show) { this.show(); } @@ -264,13 +272,15 @@ class WindowsWindow implements NativeWindow { this.#fullscreen = true; this.#savedStyle = user32.GetWindowLongPtrW(hwnd, GWL_STYLE); this.#savedBounds = this.getBounds(); - user32.SetWindowLongPtrW(hwnd, GWL_STYLE, BigInt((WS_POPUP | WS_VISIBLE | 0x02000000) >>> 0)); + const fullscreenStyle = BigInt((WS_POPUP | WS_CLIPCHILDREN) >>> 0); + user32.SetWindowLongPtrW(hwnd, GWL_STYLE, keepVisibility(fullscreenStyle, this.#savedStyle)); const width = user32.GetSystemMetrics(SM_CXSCREEN); const height = user32.GetSystemMetrics(SM_CYSCREEN); user32.SetWindowPos(hwnd, 0n, 0, 0, width, height, SWP_NOZORDER | SWP_FRAMECHANGED); } else if (!flag && this.#fullscreen) { this.#fullscreen = false; - user32.SetWindowLongPtrW(hwnd, GWL_STYLE, this.#savedStyle); + const current = user32.GetWindowLongPtrW(hwnd, GWL_STYLE); + user32.SetWindowLongPtrW(hwnd, GWL_STYLE, keepVisibility(this.#savedStyle, current)); const b = this.#savedBounds; user32.SetWindowPos(hwnd, 0n, b.x, b.y, b.width, b.height, SWP_NOZORDER | SWP_FRAMECHANGED); } From e65f5accf5951df12b60d51717048b01717c6c58 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:51:31 -0700 Subject: [PATCH 059/586] test: make the macOS FFI tests able to fail --- tests/integration/macos/carbon-ffi.test.ts | 14 ------ tests/integration/macos/cocoa-ffi.test.ts | 17 ++----- .../macos/cocoa-msgsend-returns-u8.test.ts | 10 ---- .../macos/cocoa-msgsend-u8.test.ts | 4 +- .../macos/cocoa-runtime-class.test.ts | 4 ++ tests/integration/macos/cocoa-runtime.test.ts | 7 --- .../macos/cocoa-runtime-class.test.ts | 11 ----- tests/unit/main/platform/macos/objc.test.ts | 49 ++++++++----------- 8 files changed, 32 insertions(+), 84 deletions(-) delete mode 100644 tests/unit/main/platform/macos/cocoa-runtime-class.test.ts diff --git a/tests/integration/macos/carbon-ffi.test.ts b/tests/integration/macos/carbon-ffi.test.ts index 35e9ef01..cbe54fcd 100644 --- a/tests/integration/macos/carbon-ffi.test.ts +++ b/tests/integration/macos/carbon-ffi.test.ts @@ -3,23 +3,9 @@ import { describe, expect, test } from 'bun:test'; import { currentPlatform } from '../../../src/common/platform'; import { loadCarbonFFI } from '../../../src/main/platform/macos/carbon-ffi'; -/** - * macOS-only. Verifies the Carbon framework opens and the six hot-key/event - * symbols resolve. We do NOT register a real hot key here (that is the backend's - * integration test); this asserts the FFI surface is present and shaped. - */ const isMac = currentPlatform() === 'macos'; describe.skipIf(!isMac)('Carbon FFI on macOS', () => { - test('loadCarbonFFI resolves the hot-key + event symbols', () => { - const carbon = loadCarbonFFI(); - expect(typeof carbon.symbols.RegisterEventHotKey).toBe('function'); - expect(typeof carbon.symbols.UnregisterEventHotKey).toBe('function'); - expect(typeof carbon.symbols.GetApplicationEventTarget).toBe('function'); - expect(typeof carbon.symbols.InstallEventHandler).toBe('function'); - expect(typeof carbon.symbols.GetEventParameter).toBe('function'); - }); - test('GetApplicationEventTarget returns a non-null event target', () => { const carbon = loadCarbonFFI(); const target = carbon.symbols.GetApplicationEventTarget(); diff --git a/tests/integration/macos/cocoa-ffi.test.ts b/tests/integration/macos/cocoa-ffi.test.ts index 8379c73a..b3e64b0d 100644 --- a/tests/integration/macos/cocoa-ffi.test.ts +++ b/tests/integration/macos/cocoa-ffi.test.ts @@ -5,17 +5,10 @@ import { cstr } from '../../../src/main/platform/cstr'; if (currentPlatform() === 'macos') { describe('Cocoa FFI on macOS', () => { - test('loadCocoaFFI returns a library handle with the three foundational symbols', () => { - const lib = loadCocoaFFI(); - expect(typeof lib.symbols.sel_registerName).toBe('function'); - expect(typeof lib.symbols.objc_getClass).toBe('function'); - expect(typeof lib.symbols.objc_msgSend).toBe('function'); - }); - test('sel_registerName returns a non-null selector for "alloc"', () => { const lib = loadCocoaFFI(); const sel = lib.symbols.sel_registerName(cstr('alloc')); - expect(sel).not.toBeNull(); + expect(sel).not.toBe(0n); }); test('sel_registerName is idempotent — same name yields the same selector pointer', () => { @@ -28,13 +21,13 @@ if (currentPlatform() === 'macos') { test('objc_getClass resolves NSObject after Foundation is loaded', () => { const lib = loadCocoaFFI(); const cls = lib.symbols.objc_getClass(cstr('NSObject')); - expect(cls).not.toBeNull(); + expect(cls).not.toBe(0n); }); test('objc_getClass resolves NSString after Foundation is loaded', () => { const lib = loadCocoaFFI(); const cls = lib.symbols.objc_getClass(cstr('NSString')); - expect(cls).not.toBeNull(); + expect(cls).not.toBe(0n); }); test('objc_getClass returns 0n for an unknown class name', () => { @@ -46,13 +39,13 @@ if (currentPlatform() === 'macos') { test('objc_getClass resolves NSWindow after AppKit is loaded', () => { const lib = loadCocoaFFI(); const cls = lib.symbols.objc_getClass(cstr('NSWindow')); - expect(cls).not.toBeNull(); + expect(cls).not.toBe(0n); }); test('objc_getClass resolves NSApplication after AppKit is loaded', () => { const lib = loadCocoaFFI(); const cls = lib.symbols.objc_getClass(cstr('NSApplication')); - expect(cls).not.toBeNull(); + expect(cls).not.toBe(0n); }); }); } diff --git a/tests/integration/macos/cocoa-msgsend-returns-u8.test.ts b/tests/integration/macos/cocoa-msgsend-returns-u8.test.ts index 98b07da9..a9b4b6d0 100644 --- a/tests/integration/macos/cocoa-msgsend-returns-u8.test.ts +++ b/tests/integration/macos/cocoa-msgsend-returns-u8.test.ts @@ -22,15 +22,5 @@ if (currentPlatform() === 'macos') { rt.msgSend(initialized, releaseSel); }); - - test('return value is a JS number (not bigint)', () => { - const rt = cocoa(); - const nsObject = rt.classes.get('NSObject'); - const allocSel = rt.selectors.get('alloc'); - const isProxySel = rt.selectors.get('isProxy'); - - const instance = rt.msgSend(nsObject, allocSel); - expect(typeof msgSendReturnsU8(instance, isProxySel)).toBe('number'); - }); }); } diff --git a/tests/integration/macos/cocoa-msgsend-u8.test.ts b/tests/integration/macos/cocoa-msgsend-u8.test.ts index bc06088c..542a9e9d 100644 --- a/tests/integration/macos/cocoa-msgsend-u8.test.ts +++ b/tests/integration/macos/cocoa-msgsend-u8.test.ts @@ -16,7 +16,7 @@ if (currentPlatform() === 'macos') { expect(result).not.toBe(nsNumber); }); - test('[NSNumber numberWithBool:0] and [NSNumber numberWithBool:1] both return non-zero', () => { + test('the BOOL arg reaches the callee: YES and NO give distinct NSNumbers', () => { const rt = cocoa(); const nsNumber = rt.classes.get('NSNumber'); const sel = rt.selectors.get('numberWithBool:'); @@ -24,8 +24,8 @@ if (currentPlatform() === 'macos') { const yes = msgSendU8(nsNumber, sel, 1); const no = msgSendU8(nsNumber, sel, 0); - expect(yes).not.toBe(0n); expect(no).not.toBe(0n); + expect(yes).not.toBe(no); }); }); } diff --git a/tests/integration/macos/cocoa-runtime-class.test.ts b/tests/integration/macos/cocoa-runtime-class.test.ts index 16b7e1f2..0637b3ad 100644 --- a/tests/integration/macos/cocoa-runtime-class.test.ts +++ b/tests/integration/macos/cocoa-runtime-class.test.ts @@ -9,6 +9,10 @@ import { defineObjcClass } from '../../../src/main/platform/macos/cocoa-runtime- if (currentPlatform() === 'macos') { describe('defineObjcClass', () => { + test('throws for an already-registered class name', () => { + expect(() => defineObjcClass('NSObject', 'NSObject', [])).toThrow(/already registered/); + }); + test('creates a registered subclass of NSObject', () => { expect(defineObjcClass('BunmaskaTestClassA', 'NSObject', [])).not.toBe(0n); }); diff --git a/tests/integration/macos/cocoa-runtime.test.ts b/tests/integration/macos/cocoa-runtime.test.ts index 4ce89f80..f3c365aa 100644 --- a/tests/integration/macos/cocoa-runtime.test.ts +++ b/tests/integration/macos/cocoa-runtime.test.ts @@ -5,13 +5,6 @@ import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; if (currentPlatform() === 'macos') { describe('cocoa() runtime on macOS', () => { - test('returns a runtime object exposing selectors, classes, and msgSend', () => { - const rt = cocoa(); - expect(rt.selectors).toBeDefined(); - expect(rt.classes).toBeDefined(); - expect(typeof rt.msgSend).toBe('function'); - }); - test('returns the same runtime object across calls (singleton)', () => { expect(cocoa()).toBe(cocoa()); }); diff --git a/tests/unit/main/platform/macos/cocoa-runtime-class.test.ts b/tests/unit/main/platform/macos/cocoa-runtime-class.test.ts deleted file mode 100644 index bbdde3b1..00000000 --- a/tests/unit/main/platform/macos/cocoa-runtime-class.test.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { currentPlatform } from '../../../../../src/common/platform'; -import { defineObjcClass } from '../../../../../src/main/platform/macos/cocoa-runtime-class'; - -describe('defineObjcClass duplicate names', () => { - test.skipIf(currentPlatform() !== 'macos')('throws for an already-registered class name', () => { - // NSObject is always registered, so objc_allocateClassPair returns nil for - // it; the guard turns that into an error instead of silent corruption. - expect(() => defineObjcClass('NSObject', 'NSObject', [])).toThrow(/already registered/); - }); -}); diff --git a/tests/unit/main/platform/macos/objc.test.ts b/tests/unit/main/platform/macos/objc.test.ts index 1f27139d..30f6ea12 100644 --- a/tests/unit/main/platform/macos/objc.test.ts +++ b/tests/unit/main/platform/macos/objc.test.ts @@ -4,17 +4,10 @@ import { currentPlatform } from '../../../../../src/common/platform'; import { bigIntOut, type Handle, - LIBOBJC_PATH, macOSLibraryAccessor, ptrIn, } from '../../../../../src/main/platform/macos/objc'; -describe('LIBOBJC_PATH', () => { - test('is the dynamic library name for the Objective-C runtime', () => { - expect(LIBOBJC_PATH).toBe('libobjc.A.dylib'); - }); -}); - describe('ptrIn', () => { test('converts a bigint handle to a numeric pointer', () => { expect(Number(ptrIn(4636917472n))).toBe(4636917472); @@ -46,26 +39,26 @@ describe('bigIntOut', () => { }); describe('macOSLibraryAccessor', () => { - test('returns a memoising accessor that calls open at most once', () => { - if (currentPlatform() !== 'macos') { - return; - } - let opens = 0; - const get = macOSLibraryAccessor('test', () => { - opens += 1; - return { value: opens }; - }); - const a = get(); - const b = get(); - expect(a).toBe(b); - expect(opens).toBe(1); - }); + test.skipIf(currentPlatform() !== 'macos')( + 'returns a memoising accessor that calls open at most once', + () => { + let opens = 0; + const get = macOSLibraryAccessor('test', () => { + opens += 1; + return { value: opens }; + }); + const a = get(); + const b = get(); + expect(a).toBe(b); + expect(opens).toBe(1); + }, + ); - test('throws UnsupportedPlatformError on non-macOS hosts', () => { - if (currentPlatform() === 'macos') { - return; - } - const get = macOSLibraryAccessor('test', () => ({})); - expect(() => get()).toThrow(UnsupportedPlatformError); - }); + test.skipIf(currentPlatform() === 'macos')( + 'throws UnsupportedPlatformError on non-macOS hosts', + () => { + const get = macOSLibraryAccessor('test', () => ({})); + expect(() => get()).toThrow(UnsupportedPlatformError); + }, + ); }); From 14ea2c00151023fb895ec74314827d5f91229731 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:51:36 -0700 Subject: [PATCH 060/586] fix: keep render completion blocks alive after a macOS timeout --- src/main/platform/macos/cocoa-backend.ts | 5 +-- tests/integration/macos/cocoa-backend.test.ts | 37 ++++++++++++++++++- 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/src/main/platform/macos/cocoa-backend.ts b/src/main/platform/macos/cocoa-backend.ts index 1de25b87..ee7afc26 100644 --- a/src/main/platform/macos/cocoa-backend.ts +++ b/src/main/platform/macos/cocoa-backend.ts @@ -26,7 +26,7 @@ import type { import { windowControlsScript } from '../window-controls'; import * as cocoaApp from './cocoa-app'; import { createAppDelegate } from './cocoa-app-delegate'; -import { cancelOneShotBlock, makeOneShotBlock } from './cocoa-block'; +import { makeOneShotBlock } from './cocoa-block'; import { getContentWorld, pageWorld } from './cocoa-content-world'; import { nsString, nsStringToString } from './cocoa-foundation'; import { cancelMenuTracking, popUpMenu } from './cocoa-menu'; @@ -382,8 +382,8 @@ class MacOSWebContents implements NativeWebContents { return Promise.reject(new Error('printToPDF failed: web contents destroyed')); } return new Promise((resolve, reject) => { + // WebKit still calls the block later (nil on close), so a timeout only rejects. const timer = setTimeout(() => { - cancelOneShotBlock(block); reject(new Error(`printToPDF timed out after ${RENDER_TIMEOUT_MS}ms`)); }, RENDER_TIMEOUT_MS); const block = makeOneShotBlock( @@ -418,7 +418,6 @@ class MacOSWebContents implements NativeWebContents { } return new Promise((resolve, reject) => { const timer = setTimeout(() => { - cancelOneShotBlock(block); reject(new Error(`capturePage timed out after ${RENDER_TIMEOUT_MS}ms`)); }, RENDER_TIMEOUT_MS); const block = makeOneShotBlock( diff --git a/tests/integration/macos/cocoa-backend.test.ts b/tests/integration/macos/cocoa-backend.test.ts index 15d1edab..9b95a2f0 100644 --- a/tests/integration/macos/cocoa-backend.test.ts +++ b/tests/integration/macos/cocoa-backend.test.ts @@ -1,6 +1,7 @@ -import { describe, expect, test } from 'bun:test'; +import { describe, expect, jest, test } from 'bun:test'; import { currentPlatform } from '../../../src/common/platform'; import { createMacOSApplication } from '../../../src/main/platform/macos/cocoa-backend'; +import { retainedBlockCount } from '../../../src/main/platform/macos/cocoa-block'; const delay = (ms: number): Promise => new Promise((resolve) => setTimeout(resolve, ms)); @@ -149,6 +150,40 @@ if (currentPlatform() === 'macos') { } }); + test('a timed-out render keeps its completion block alive until WebKit calls it', async () => { + const app = createMacOSApplication(); + app.start(); + const win = app.createWindow({ width: 320, height: 240, title: 't', show: true }); + win.webContents.loadHTML('

render

', 'about:blank'); + await waitFor(() => win.webContents.getURL() === 'about:blank'); + // Let earlier tests' fired blocks finish their deferred cleanup before counting. + await delay(50); + // No pump while timers are faked, so WebKit cannot complete the render first. + app.quit(); + const pump = createMacOSApplication(); + const baseline = retainedBlockCount(); + jest.useFakeTimers(); + try { + const pdf = win.webContents.printToPDF(); + const png = win.webContents.capturePage(); + jest.advanceTimersByTime(30_001); + await expect(pdf).rejects.toThrow(/timed out/); + await expect(png).rejects.toThrow(/timed out/); + jest.advanceTimersByTime(10); + expect(retainedBlockCount()).toBe(baseline + 2); + } finally { + jest.useRealTimers(); + } + pump.start(); + try { + win.destroy(); + await waitFor(() => retainedBlockCount() === baseline); + expect(retainedBlockCount()).toBe(baseline); + } finally { + pump.quit(); + } + }); + test('openDevTools exists and does not throw', async () => { const app = createMacOSApplication(); app.start(); From cfc5f22a6f54c218375e9fe31cd23e4ae5f5e807 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:51:44 -0700 Subject: [PATCH 061/586] fix: fire ready-to-show on the first did-finish-load on Windows --- src/main/platform/windows/windows-backend.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/platform/windows/windows-backend.ts b/src/main/platform/windows/windows-backend.ts index e4869498..a48c3fc7 100644 --- a/src/main/platform/windows/windows-backend.ts +++ b/src/main/platform/windows/windows-backend.ts @@ -109,9 +109,9 @@ class WindowsWindow implements NativeWindow { } } }); - // `ready-to-show` fires once, when the page first reaches dom-ready. + // `ready-to-show` fires once, on the first finished load (as on macOS and Linux). this.#webContents.onNavigation((event) => { - if (event.type === 'dom-ready' && !this.#readyToShown) { + if (event.type === 'did-finish-load' && !this.#readyToShown) { this.#readyToShown = true; this.#native.emit('ready-to-show'); } @@ -349,7 +349,7 @@ class WindowsWindow implements NativeWindow { onWindowEvent(type: WindowEventType, callback: () => void): void { // focus/blur/move/resize/maximize/minimize/restore are surfaced by the pump poll // (pollWindows); show/hide fire from the window directly; ready-to-show fires - // on the first dom-ready. The close/closed pair flows through onClose/onClosed. + // on the first did-finish-load. The close/closed pair flows through onClose/onClosed. this.#native.onWindowEvent(type, callback); } From 713e01c4c012e70ca8884bb787a90e10b9e6b1d3 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:51:44 -0700 Subject: [PATCH 062/586] fix: add BrowserWindow.fromWebContents and getFocusedWindow --- src/main/api/browser-window.ts | 16 ++++++++++------ tests/unit/main/api/browser-window.test.ts | 16 ++++++++++++++++ 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/src/main/api/browser-window.ts b/src/main/api/browser-window.ts index a5eb1f01..954a939c 100644 --- a/src/main/api/browser-window.ts +++ b/src/main/api/browser-window.ts @@ -376,18 +376,22 @@ export class BrowserWindow extends EventEmitter { static fromId(id: number): BrowserWindow | undefined { return registry.get(id); } + + static fromWebContents(webContents: WebContents): BrowserWindow | null { + return BrowserWindow.getAllWindows().find((w) => w.webContents === webContents) ?? null; + } + + static getFocusedWindow(): BrowserWindow | null { + return BrowserWindow.getAllWindows().find((w) => w.isFocused()) ?? null; + } } // Let Menu.popup resolve a target window (focused → most-recent) without importing // BrowserWindow into menu.ts (which would cycle). The registry is creation-ordered. installWindowResolver({ focused: () => { - for (const window of registry.values()) { - if (window.isFocused()) { - return popupTargets.get(window); - } - } - return undefined; + const window = BrowserWindow.getFocusedWindow(); + return window === null ? undefined : popupTargets.get(window); }, mostRecent: () => { const windows = [...registry.values()]; diff --git a/tests/unit/main/api/browser-window.test.ts b/tests/unit/main/api/browser-window.test.ts index 38be3d1b..3d841f7c 100644 --- a/tests/unit/main/api/browser-window.test.ts +++ b/tests/unit/main/api/browser-window.test.ts @@ -419,6 +419,22 @@ describe('BrowserWindow registry', () => { test('fromId returns undefined for an unknown id', () => { expect(BrowserWindow.fromId(9999)).toBeUndefined(); }); + + test('fromWebContents returns the owning open window, else null', () => { + const a = new BrowserWindow(); + const b = new BrowserWindow(); + expect(BrowserWindow.fromWebContents(b.webContents)).toBe(b); + a.close(); + expect(BrowserWindow.fromWebContents(a.webContents)).toBeNull(); + }); + + test('getFocusedWindow returns the focused window, else null', () => { + new BrowserWindow(); + const b = new BrowserWindow(); + expect(BrowserWindow.getFocusedWindow()).toBeNull(); + b.focus(); + expect(BrowserWindow.getFocusedWindow()).toBe(b); + }); }); describe('BrowserWindow lifecycle', () => { From 052a1011272d7cef10166c6a9688694ae1fb5292 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:51:45 -0700 Subject: [PATCH 063/586] fix: read TIFF-only clipboard images as PNG on macOS --- src/main/platform/macos/cocoa-clipboard.ts | 29 +++++++++----- tests/integration/macos/clipboard.test.ts | 45 ++++++++++++++++++++++ 2 files changed, 65 insertions(+), 9 deletions(-) diff --git a/src/main/platform/macos/cocoa-clipboard.ts b/src/main/platform/macos/cocoa-clipboard.ts index f96636d2..0b3f44a6 100644 --- a/src/main/platform/macos/cocoa-clipboard.ts +++ b/src/main/platform/macos/cocoa-clipboard.ts @@ -1,6 +1,6 @@ import { nsString, nsStringToString } from './cocoa-foundation'; import { msgSendI64, msgSendPtr, msgSendPtrPtr, msgSendReturnsI64 } from './cocoa-msgsend-variants'; -import { nsDataFromBytes, nsDataToBytes } from './cocoa-native-image'; +import { cocoaNativeImageBackend, nsDataFromBytes, nsDataToBytes } from './cocoa-native-image'; import { cocoa } from './cocoa-runtime'; /** @@ -15,6 +15,7 @@ import { cocoa } from './cocoa-runtime'; const NS_PASTEBOARD_TYPE_STRING = 'public.utf8-plain-text'; const NS_PASTEBOARD_TYPE_HTML = 'public.html'; const NS_PASTEBOARD_TYPE_PNG = 'public.png'; +const NS_PASTEBOARD_TYPE_TIFF = 'public.tiff'; /** Map common pasteboard UTIs to Electron-style format names; pass others through. */ const UTI_TO_FORMAT: Readonly> = { @@ -78,15 +79,25 @@ export const writeHTML = (markup: string): void => { ); }; -/** Read the clipboard's image as PNG bytes, or an empty array if it holds none. */ -export const readImage = (): Uint8Array => { - const rt = cocoa(); - const data = msgSendPtr( - generalPasteboard(), - rt.selectors.get('dataForType:'), - nsString(NS_PASTEBOARD_TYPE_PNG), +const readData = (uti: string): Uint8Array => + nsDataToBytes( + msgSendPtr(generalPasteboard(), cocoa().selectors.get('dataForType:'), nsString(uti)), ); - return nsDataToBytes(data); + +/** Read the clipboard's image as PNG bytes (TIFF-only images are transcoded), or empty if none. */ +export const readImage = (): Uint8Array => { + const png = readData(NS_PASTEBOARD_TYPE_PNG); + if (png.length > 0) { + return png; + } + const tiff = readData(NS_PASTEBOARD_TYPE_TIFF); + if (tiff.length === 0) { + return tiff; + } + const { handle } = cocoaNativeImageBackend.decode(tiff); + const encoded = cocoaNativeImageBackend.encodePng(handle); + cocoa().msgSend(handle, cocoa().selectors.get('release')); // a nil receiver is a no-op + return encoded; }; /** Replace the clipboard's contents with `png` (PNG-encoded image bytes). */ diff --git a/tests/integration/macos/clipboard.test.ts b/tests/integration/macos/clipboard.test.ts index a09a4948..8fc2481e 100644 --- a/tests/integration/macos/clipboard.test.ts +++ b/tests/integration/macos/clipboard.test.ts @@ -1,7 +1,19 @@ import { describe, expect, test } from 'bun:test'; import { clipboard } from '../../../src/main/api/clipboard'; import * as macosClipboard from '../../../src/main/platform/macos/cocoa-clipboard'; +import { nsString } from '../../../src/main/platform/macos/cocoa-foundation'; +import { + msgSendI64Ptr, + msgSendPtrPtr, +} from '../../../src/main/platform/macos/cocoa-msgsend-variants'; +import { + cocoaNativeImageBackend, + nsDataFromBytes, + nsDataToBytes, +} from '../../../src/main/platform/macos/cocoa-native-image'; +import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; import { currentPlatform } from '../../../src/common/platform'; +import { makeTinyPng, TINY_PNG_WIDTH } from '../../fixtures/tiny-png'; // A valid 1x1 PNG; NSPasteboard stores public.png data verbatim, so it // round-trips byte-for-byte without going through NativeImage's PNG encoder. @@ -12,6 +24,32 @@ const PNG_1x1 = new Uint8Array( ), ); +/** Put `png` on the pasteboard as TIFF only, the way some apps copy images. */ +const writeTiffOnly = (png: Uint8Array): void => { + const rt = cocoa(); + const rep = cocoaNativeImageBackend.decode(png).handle; + const NS_BITMAP_IMAGE_FILE_TYPE_TIFF = 0n; + const tiff = nsDataToBytes( + msgSendI64Ptr( + rep, + rt.selectors.get('representationUsingType:properties:'), + NS_BITMAP_IMAGE_FILE_TYPE_TIFF, + 0n, + ), + ); + const pasteboard = rt.msgSend( + rt.classes.get('NSPasteboard'), + rt.selectors.get('generalPasteboard'), + ); + rt.msgSend(pasteboard, rt.selectors.get('clearContents')); + msgSendPtrPtr( + pasteboard, + rt.selectors.get('setData:forType:'), + nsDataFromBytes(tiff), + nsString('public.tiff'), + ); +}; + if (currentPlatform() === 'macos') { describe('clipboard on macOS', () => { test('writeText then readText round-trips plain text', async () => { @@ -57,6 +95,13 @@ if (currentPlatform() === 'macos') { expect(macosClipboard.readImage()).toEqual(PNG_1x1); }); + test('readImage transcodes a TIFF-only clipboard image to PNG', () => { + writeTiffOnly(makeTinyPng()); + const png = macosClipboard.readImage(); + expect(png[0]).toBe(0x89); + expect(cocoaNativeImageBackend.decode(png).width).toBe(TINY_PNG_WIDTH); + }); + test('availableFormats reports image/png after writing an image', () => { macosClipboard.writeImage(PNG_1x1); expect(macosClipboard.availableFormats()).toContain('image/png'); From 8035bd0808466d5bb7e438afc9213ec38fe34308 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:51:48 -0700 Subject: [PATCH 064/586] fix: deliver queued Linux IPC at dom-ready, not after full load --- src/main/platform/linux/linux-backend.ts | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/src/main/platform/linux/linux-backend.ts b/src/main/platform/linux/linux-backend.ts index 85fc7d26..d394c77b 100644 --- a/src/main/platform/linux/linux-backend.ts +++ b/src/main/platform/linux/linux-backend.ts @@ -67,7 +67,7 @@ class LinuxWebContents implements NativeWebContents { readonly #registry: SignalRegistry; readonly #exec = new ExecResultChannel((source) => evalInPageWorld(this.#view, source)); #destroyed = false; - #didFinishLoad = false; + #bridgeReady = false; readonly #pendingEnvelopes: string[] = []; readonly #navigationCallbacks: Array<(event: NativeNavigationEvent) => void> = []; readonly #rendererEnvelopeCallbacks: Array<(json: string) => void> = []; @@ -86,6 +86,7 @@ class LinuxWebContents implements NativeWebContents { pageWorldSource: `${generatePageWorldStub(channelId)}\n${windowControlsScript()}`, ...(userPreloadSource !== undefined ? { userPreloadSource } : {}), onMessage: (json: string) => { + this.#markBridgeReady(); for (const callback of this.#rendererEnvelopeCallbacks) { callback(json); } @@ -94,6 +95,7 @@ class LinuxWebContents implements NativeWebContents { this.#exec.deliverExecResult(json); }, onDomReady: () => { + this.#markBridgeReady(); this.#dispatchNavigation({ type: 'dom-ready' }); }, }); @@ -114,12 +116,7 @@ class LinuxWebContents implements NativeWebContents { ); const load = makeLoadCallbacks((event) => { if (event.type === 'did-finish-load') { - this.#didFinishLoad = true; - const queued = [...this.#pendingEnvelopes]; - this.#pendingEnvelopes.length = 0; - for (const json of queued) { - sendToRenderer(this.#view, json); - } + this.#markBridgeReady(); } this.#dispatchNavigation(event); }); @@ -132,6 +129,17 @@ class LinuxWebContents implements NativeWebContents { ); } + /** Flush queued envelopes once the first page's isolated-world bridge is running. */ + #markBridgeReady(): void { + if (this.#bridgeReady) { + return; + } + this.#bridgeReady = true; + for (const json of this.#pendingEnvelopes.splice(0)) { + this.sendEnvelopeToRenderer(json); + } + } + #dispatchNavigation(event: NativeNavigationEvent): void { for (const callback of this.#navigationCallbacks) { callback(event); @@ -271,7 +279,7 @@ class LinuxWebContents implements NativeWebContents { if (this.#destroyed) { return; // an invoke reply or send() after close: the view is freed. } - if (!this.#didFinishLoad) { + if (!this.#bridgeReady) { this.#pendingEnvelopes.push(envelopeJson); return; } From ae470017bc0605ba8df8de5e9b26220d7a486a30 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:51:52 -0700 Subject: [PATCH 065/586] fix: take preferred languages from LANGUAGE/LANG only on Linux --- src/main/api/app-environment.ts | 10 ++++------ tests/unit/main/api/app-environment.test.ts | 13 ++++++++----- tests/unit/main/api/app.test.ts | 10 ++++++---- 3 files changed, 18 insertions(+), 15 deletions(-) diff --git a/src/main/api/app-environment.ts b/src/main/api/app-environment.ts index 67f2b560..f8ac17f7 100644 --- a/src/main/api/app-environment.ts +++ b/src/main/api/app-environment.ts @@ -47,11 +47,9 @@ export type AppEnvironment = { /** A `bun build --compile` binary runs its entry from Bun's embedded filesystem. */ const COMPILED_ENTRY = /^(?:\/\$bunfs\/|[A-Za-z]:[\\/]~BUN[\\/])/; -const computePreferredLanguages = ( - env: EnvironmentDeps['env'], - normalizedLocale: string, -): string[] => { - const fromEnv = parsePreferredLanguages(env); +/** `$LANGUAGE`/`$LANG` only on Linux: macOS and Windows `Intl` follow the system, not the env. */ +const computePreferredLanguages = (deps: EnvironmentDeps, normalizedLocale: string): string[] => { + const fromEnv = deps.platform === 'linux' ? parsePreferredLanguages(deps.env) : []; if (fromEnv.length > 0) { return fromEnv; } @@ -97,7 +95,7 @@ export const buildAppEnvironment = (deps: EnvironmentDeps): AppEnvironment => { env: deps.platform === 'linux' ? { ...readUserDirs(deps), ...deps.env } : deps.env, manifest: app.manifest, locale, - preferredLanguages: computePreferredLanguages(deps.env, locale), + preferredLanguages: computePreferredLanguages(deps, locale), isPackaged: COMPILED_ENTRY.test(deps.mainScript), exit: deps.exit, relaunch: deps.relaunch, diff --git a/tests/unit/main/api/app-environment.test.ts b/tests/unit/main/api/app-environment.test.ts index bdfb73c3..da0f81ca 100644 --- a/tests/unit/main/api/app-environment.test.ts +++ b/tests/unit/main/api/app-environment.test.ts @@ -86,11 +86,14 @@ describe('buildAppEnvironment — locale & languages', () => { expect(build({ locale: 'en_US.UTF-8' }).locale).toBe('en-US'); }); - test('derives preferred languages from the environment', () => { - expect(build({ env: { LANGUAGE: 'fr_FR:en_US' } }).preferredLanguages).toEqual([ - 'fr-FR', - 'en-US', - ]); + test('derives preferred languages from the Linux environment', () => { + const env = build({ platform: 'linux', env: { LANGUAGE: 'fr_FR:en_US' } }); + expect(env.preferredLanguages).toEqual(['fr-FR', 'en-US']); + }); + + test('ignores LANG off Linux, where the system locale is authoritative', () => { + const env = build({ platform: 'macos', locale: 'fr-FR', env: { LANG: 'en_US.UTF-8' } }); + expect(env.preferredLanguages).toEqual(['fr-FR']); }); test('falls back to the normalized locale when no language env is set', () => { diff --git a/tests/unit/main/api/app.test.ts b/tests/unit/main/api/app.test.ts index 56f74777..fb0f2f1b 100644 --- a/tests/unit/main/api/app.test.ts +++ b/tests/unit/main/api/app.test.ts @@ -348,10 +348,12 @@ describe('App locale', () => { }); test('getPreferredSystemLanguages reflects the environment', () => { - expect(appWith({ env: { LANGUAGE: 'fr_FR:en_US' } }).getPreferredSystemLanguages()).toEqual([ - 'fr-FR', - 'en-US', - ]); + expect( + appWith({ + platform: 'linux', + env: { LANGUAGE: 'fr_FR:en_US' }, + }).getPreferredSystemLanguages(), + ).toEqual(['fr-FR', 'en-US']); }); }); From 76da318be765e8e25c0f5d07de80cccc8160b2ed Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:51:54 -0700 Subject: [PATCH 066/586] fix: fail loudly when OleInitialize fails --- src/main/platform/windows/windows-native-window.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/platform/windows/windows-native-window.ts b/src/main/platform/windows/windows-native-window.ts index 8d8e00e6..20766bd2 100644 --- a/src/main/platform/windows/windows-native-window.ts +++ b/src/main/platform/windows/windows-native-window.ts @@ -58,7 +58,11 @@ export const ensureOleInitialized = (): void => { if (oleInitialized) { return; } - loadOle32().symbols.OleInitialize(null); + // S_FALSE (already initialised) is fine; RPC_E_CHANGED_MODE (an MTA thread) is not. + const hr = loadOle32().symbols.OleInitialize(null); + if (hr < 0) { + throw new FFIError(`OleInitialize failed: 0x${(hr >>> 0).toString(16)}`); + } oleInitialized = true; }; From 69eb791a9a3070fef3f93f294a87652f90572d46 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:51:58 -0700 Subject: [PATCH 067/586] fix: start the Linux pump before running ready callbacks --- src/main/platform/linux/linux-backend.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/platform/linux/linux-backend.ts b/src/main/platform/linux/linux-backend.ts index d394c77b..a71b2e1f 100644 --- a/src/main/platform/linux/linux-backend.ts +++ b/src/main/platform/linux/linux-backend.ts @@ -764,12 +764,12 @@ export class LinuxApplication implements NativeApplication { } this.#started = true; this.#ready = true; - for (const callback of this.#readyCallbacks) { - callback(); - } - this.#readyCallbacks.length = 0; + // Pump first: a throwing 'ready' listener must not leave GTK unpumped. this.#pump = new CooperativePump(createLinuxDrain()); this.#pump.start(); + for (const callback of this.#readyCallbacks.splice(0)) { + callback(); + } } onReady(callback: () => void): void { From ac3aad2630c07e95a0530a15de4fe82c820ef84a Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:52:00 -0700 Subject: [PATCH 068/586] refactor: reuse makeCancelableEvent for the window close event --- src/main/api/browser-window.ts | 20 +------------------- 1 file changed, 1 insertion(+), 19 deletions(-) diff --git a/src/main/api/browser-window.ts b/src/main/api/browser-window.ts index 954a939c..5757221a 100644 --- a/src/main/api/browser-window.ts +++ b/src/main/api/browser-window.ts @@ -68,24 +68,6 @@ const WINDOW_EVENT_TYPES: readonly WindowEventType[] = [ 'ready-to-show', ]; -/** Passed to `close` listeners; {@link preventDefault} vetoes the close. */ -export type WindowCloseEvent = { - preventDefault(): void; - readonly defaultPrevented: boolean; -}; - -const makeCloseEvent = (): WindowCloseEvent => { - let prevented = false; - return { - preventDefault(): void { - prevented = true; - }, - get defaultPrevented(): boolean { - return prevented; - }, - }; -}; - const registry = new Map(); /** So `Menu.popup` can anchor to a window without a menu→window import cycle. */ const popupTargets = new WeakMap(); @@ -169,7 +151,7 @@ export class BrowserWindow extends EventEmitter { }); // Returning true tells the backend to stay open. this.#native.onClose(() => { - const event = makeCloseEvent(); + const event = makeCancelableEvent(); this.emit('close', event); return event.defaultPrevented; }); From b8d219f4ae514da7b3430b55a2a724994f74d7f8 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:52:23 -0700 Subject: [PATCH 069/586] fix: type the bunmaska/electron default export as the barrel --- src/electron.ts | 2 +- tests/unit/electron-shim.test.ts | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/electron.ts b/src/electron.ts index 444ca6c6..b08797ea 100644 --- a/src/electron.ts +++ b/src/electron.ts @@ -30,5 +30,5 @@ export const createElectronShim = ( */ export * from './index'; -const electron = createElectronShim(); +const electron = createElectronShim() as typeof bunmaska; export default electron; diff --git a/tests/unit/electron-shim.test.ts b/tests/unit/electron-shim.test.ts index 1165e29a..a43592f6 100644 --- a/tests/unit/electron-shim.test.ts +++ b/tests/unit/electron-shim.test.ts @@ -38,8 +38,9 @@ describe('bunmaska/electron named exports', () => { }); test('still ships the Proxy default whose property access is actionable', () => { - const surface = electronShim.default as Record; - expect(surface['app']).toBe(electronShim.app); - expect(() => surface['netLog']).toThrow(/not yet implemented/); + expect(electronShim.default.app).toBe(electronShim.app); + expect(() => (electronShim.default as Record)['netLog']).toThrow( + /not yet implemented/, + ); }); }); From 58e0e5984383543611fb2bdd868ccad014332115 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:52:28 -0700 Subject: [PATCH 070/586] fix: harden the Windows message window against WM_CLOSE and failures --- .../windows/windows-message-window.ts | 16 +++++++++++-- .../windows/windows-message-window.test.ts | 24 +++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) create mode 100644 tests/integration/windows/windows-message-window.test.ts diff --git a/src/main/platform/windows/windows-message-window.ts b/src/main/platform/windows/windows-message-window.ts index b50aee44..ada1f241 100644 --- a/src/main/platform/windows/windows-message-window.ts +++ b/src/main/platform/windows/windows-message-window.ts @@ -14,6 +14,7 @@ const CLASS_NAME = 'BunmaskaMessageWindow'; /** `WS_EX_TOOLWINDOW` — keep the (never-shown) window out of the taskbar/alt-tab. */ const WS_EX_TOOLWINDOW = 0x00000080; const WS_OVERLAPPED = 0x00000000; +const WM_CLOSE = 0x0010; /** A per-window message observer: a posted/sent message and its parameters. */ export type MessageHandler = (message: number, wParam: bigint, lParam: bigint) => void; @@ -45,7 +46,8 @@ const ensureClassRegistered = (): void => { // A throwing JS handler must never propagate into the native WndProc. } } - return user32.DefWindowProcW(hwnd, message, wParam, lParam); + // An external WM_CLOSE must not destroy it; only destroy() does. + return message === WM_CLOSE ? 0n : user32.DefWindowProcW(hwnd, message, wParam, lParam); }, { args: [FFIType.u64, FFIType.u32, FFIType.u64, FFIType.i64], returns: FFIType.i64 }, ); @@ -62,7 +64,9 @@ const ensureClassRegistered = (): void => { view.setBigUint64(8, BigInt(wndProcPtr), true); // lpfnWndProc view.setBigUint64(24, hInstance, true); // hInstance view.setBigUint64(64, BigInt(ptr(className)), true); // lpszClassName - user32.RegisterClassExW(ptr(wc)); + if (user32.RegisterClassExW(ptr(wc)) === 0) { + throw new FFIError('RegisterClassExW failed for the Bunmaska message window class'); + } // Retain the JSCallback for the whole process (the class references it forever). registered = { wndProc }; }; @@ -92,10 +96,18 @@ export const createMessageWindow = (handler: MessageHandler): MessageWindow => { hInstance, null, ); + if (hwnd === 0n) { + throw new FFIError('CreateWindowExW returned NULL for the message window'); + } handlersByHwnd.set(hwnd, handler); + let destroyed = false; return { hwnd, destroy: (): void => { + if (destroyed) { + return; + } + destroyed = true; handlersByHwnd.delete(hwnd); user32.DestroyWindow(hwnd); }, diff --git a/tests/integration/windows/windows-message-window.test.ts b/tests/integration/windows/windows-message-window.test.ts new file mode 100644 index 00000000..c5474581 --- /dev/null +++ b/tests/integration/windows/windows-message-window.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, test } from 'bun:test'; +import { currentPlatform } from '../../../src/common/platform'; +import { loadUser32 } from '../../../src/main/platform/windows/win32-ffi'; +import { createMessageWindow } from '../../../src/main/platform/windows/windows-message-window'; + +const WM_CLOSE = 0x0010; +const WM_USER = 0x0400; + +describe.skipIf(currentPlatform() !== 'windows')('createMessageWindow', () => { + test('survives WM_CLOSE and keeps delivering messages', () => { + const seen: number[] = []; + const win = createMessageWindow((message) => { + seen.push(message); + }); + const user32 = loadUser32().symbols; + try { + user32.SendMessageW(win.hwnd, WM_CLOSE, 0n, 0n); + user32.SendMessageW(win.hwnd, WM_USER, 0n, 0n); + expect(seen).toContain(WM_USER); + } finally { + win.destroy(); + } + }); +}); From 44671067d77871eb7d4e848c616460e19a564c3b Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:52:28 -0700 Subject: [PATCH 071/586] refactor: drop the unused protocol.handlerFor and clearForTesting --- src/main/api/protocol.ts | 13 +------------ tests/unit/main/api/protocol.test.ts | 16 +++++++++------- 2 files changed, 10 insertions(+), 19 deletions(-) diff --git a/src/main/api/protocol.ts b/src/main/api/protocol.ts index 2754ef2f..399ca5f1 100644 --- a/src/main/api/protocol.ts +++ b/src/main/api/protocol.ts @@ -55,7 +55,7 @@ const toBytes = (data: string | Uint8Array): Uint8Array => /** Returns `undefined` when the handler declines (backend serves a 404-ish empty response). */ export const buildProtocolResponse = ( handler: ProtocolHandler, - request: ProtocolRequest = { url: '' }, + request: ProtocolRequest, ): BuiltProtocolResponse | undefined => { const response = handler(request); if (response === undefined) { @@ -115,10 +115,6 @@ const isProtocolHandled = (scheme: string): boolean => registry.has(normalizeSch /** Every currently registered scheme, normalized. */ const getRegisteredSchemes = (): string[] => [...registry.keys()]; -/** The handler registered for `scheme`, or `undefined`. */ -const handlerFor = (scheme: string): ProtocolHandler | undefined => - registry.get(normalizeScheme(scheme)); - /** * Serve `url`. Returns `undefined` for an unregistered scheme, an unparseable * URL, or a handler that declined. @@ -135,18 +131,11 @@ const dispatch = (url: string): BuiltProtocolResponse | undefined => { return buildProtocolResponse(handler, { url }); }; -/** Clear every registered scheme. Test-only. */ -const clearForTesting = (): void => { - registry.clear(); -}; - /** The `protocol` module — Electron-compatible custom URL-scheme registration. */ export const protocol = { handle, unhandle, isProtocolHandled, getRegisteredSchemes, - handlerFor, dispatch, - clearForTesting, }; diff --git a/tests/unit/main/api/protocol.test.ts b/tests/unit/main/api/protocol.test.ts index e8050c93..0dfaa986 100644 --- a/tests/unit/main/api/protocol.test.ts +++ b/tests/unit/main/api/protocol.test.ts @@ -46,8 +46,10 @@ describe('schemeOfUrl', () => { }); describe('buildProtocolResponse', () => { + const request = { url: 'app://host/' }; + test('utf8-encodes a string body and defaults the mimeType to text/html', () => { - const built = buildProtocolResponse(() => ({ data: 'hi' })); + const built = buildProtocolResponse(() => ({ data: 'hi' }), request); expect(built).not.toBeUndefined(); if (built === undefined) { throw new Error('expected a built response'); @@ -58,10 +60,10 @@ describe('buildProtocolResponse', () => { test('passes Uint8Array bytes through unchanged and honours an explicit mimeType', () => { const raw = new Uint8Array([1, 2, 3]); - const built = buildProtocolResponse(() => ({ - data: raw, - mimeType: 'application/octet-stream', - })); + const built = buildProtocolResponse( + () => ({ data: raw, mimeType: 'application/octet-stream' }), + request, + ); if (built === undefined) { throw new Error('expected a built response'); } @@ -70,11 +72,11 @@ describe('buildProtocolResponse', () => { }); test('returns undefined when the handler returns undefined', () => { - expect(buildProtocolResponse(() => undefined)).toBeUndefined(); + expect(buildProtocolResponse(() => undefined, request)).toBeUndefined(); }); test('utf8-encodes multibyte characters by length, not character count', () => { - const built = buildProtocolResponse(() => ({ data: '€' })); + const built = buildProtocolResponse(() => ({ data: '€' }), request); if (built === undefined) { throw new Error('expected a built response'); } From 63db656ddc2038648cd9b815c3e35c0d22961244 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:52:31 -0700 Subject: [PATCH 072/586] fix: inject the Linux bridge and preload into the top frame only --- src/main/platform/linux/webkit-ipc.ts | 13 ++-- .../linux/top-frame-injection.test.ts | 61 +++++++++++++++++++ 2 files changed, 67 insertions(+), 7 deletions(-) create mode 100644 tests/integration/linux/top-frame-injection.test.ts diff --git a/src/main/platform/linux/webkit-ipc.ts b/src/main/platform/linux/webkit-ipc.ts index 8a80da86..15ea5abe 100644 --- a/src/main/platform/linux/webkit-ipc.ts +++ b/src/main/platform/linux/webkit-ipc.ts @@ -3,11 +3,10 @@ import { cstr } from '../cstr'; import { DOM_READY_HANDLER_NAME, generateDomReadyScript } from '../dom-ready'; import { loadGObjectFFI } from './gobject-ffi'; import { makeScriptMessageCallback, SignalRegistry } from './gtk-signals'; -import { - loadWebKitGtkFFI, - WEBKIT_USER_CONTENT_INJECT_ALL_FRAMES, - WEBKIT_USER_SCRIPT_INJECT_AT_DOCUMENT_START, -} from './webkitgtk-ffi'; +import { loadWebKitGtkFFI, WEBKIT_USER_SCRIPT_INJECT_AT_DOCUMENT_START } from './webkitgtk-ffi'; + +/** `WebKitUserContentInjectedFrames`: never inject into subframes, or a third-party iframe gets the bridge and every exposed API. */ +const WEBKIT_USER_CONTENT_INJECT_TOP_FRAME = 1; /** * Name of the isolated JS world the bridge + user preload run in (Electron @@ -73,7 +72,7 @@ const addUserScript = (ucm: Pointer, source: string): void => { const webkit = loadWebKitGtkFFI(); const script = webkit.symbols.webkit_user_script_new_for_world( cstr(source), - WEBKIT_USER_CONTENT_INJECT_ALL_FRAMES, + WEBKIT_USER_CONTENT_INJECT_TOP_FRAME, WEBKIT_USER_SCRIPT_INJECT_AT_DOCUMENT_START, cstr(PRELOAD_WORLD_NAME), null, @@ -86,7 +85,7 @@ const addPageWorldScript = (ucm: Pointer, source: string): void => { const webkit = loadWebKitGtkFFI(); const script = webkit.symbols.webkit_user_script_new( cstr(source), - WEBKIT_USER_CONTENT_INJECT_ALL_FRAMES, + WEBKIT_USER_CONTENT_INJECT_TOP_FRAME, WEBKIT_USER_SCRIPT_INJECT_AT_DOCUMENT_START, null, null, diff --git a/tests/integration/linux/top-frame-injection.test.ts b/tests/integration/linux/top-frame-injection.test.ts new file mode 100644 index 00000000..4ae51d86 --- /dev/null +++ b/tests/integration/linux/top-frame-injection.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, test } from 'bun:test'; +import { loadGtkFFI } from '../../../src/main/platform/linux/gtk-ffi'; +import { createLinuxApplication } from '../../../src/main/platform/linux/linux-backend'; + +/** Electron runs preloads and dom-ready in the main frame only (nodeIntegrationInSubFrames off). */ + +const isLinux = process.platform === 'linux'; + +const pumpUntil = async (predicate: () => boolean, budgetMs: number): Promise => { + for (let waited = 0; waited < budgetMs && !predicate(); waited += 20) { + await new Promise((resolve) => setTimeout(resolve, 20)); + } +}; + +describe.skipIf(!isLinux)('Linux injection is top-frame only', () => { + test('an iframe gets no preload, no exposed API and no dom-ready', async () => { + if (loadGtkFFI().symbols.gtk_init_check() === 0) { + return; + } + const app = createLinuxApplication(); + app.start(); + const window = app.createWindow({ + width: 320, + height: 240, + title: 'Top Frame Only', + show: true, + preloadScript: + "window.__bunmaska.exposeInMainWorld('api', { ok: 1 });\n" + + "window.__bunmaska.send('preload-ran', location.href);", + }); + const contents = window.webContents; + const preloadRuns: string[] = []; + contents.onRendererEnvelope((json) => { + const env = JSON.parse(json) as { channel?: string }; + if (env.channel === 'preload-ran') { + preloadRuns.push(json); + } + }); + let domReady = 0; + let didFinish = false; + contents.onNavigation((event) => { + if (event.type === 'dom-ready') { + domReady += 1; + } else if (event.type === 'did-finish-load') { + didFinish = true; + } + }); + + contents.loadHTML(''); + await pumpUntil(() => didFinish, 5000); + const childApi = await contents.executeJavaScript('typeof frames[0].api'); + + expect(didFinish).toBe(true); + expect(childApi).toBe('undefined'); + expect(preloadRuns).toHaveLength(1); + expect(domReady).toBe(1); + + window.close(); + app.quit(); + }); +}); From 23fba118bf249443760d8236125f1dcd71fb3e75 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:52:44 -0700 Subject: [PATCH 073/586] chore: drop unused user32 symbols --- src/main/platform/windows/win32-ffi.ts | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/main/platform/windows/win32-ffi.ts b/src/main/platform/windows/win32-ffi.ts index 930fe1db..e6e07c84 100644 --- a/src/main/platform/windows/win32-ffi.ts +++ b/src/main/platform/windows/win32-ffi.ts @@ -13,8 +13,6 @@ import { winLibraryAccessor } from './win32'; const USER32_SYMBOLS = { // (const WNDCLASSEXW *) -> ATOM RegisterClassExW: { args: [FFIType.ptr], returns: FFIType.u16 }, - // (LPCWSTR className, HINSTANCE) -> BOOL - UnregisterClassW: { args: [FFIType.ptr, FFIType.u64], returns: FFIType.i32 }, // (DWORD exStyle, LPCWSTR className, LPCWSTR windowName, DWORD style, // int x, int y, int w, int h, HWND parent, HMENU menu, HINSTANCE, LPVOID param) -> HWND CreateWindowExW: { @@ -63,8 +61,6 @@ const USER32_SYMBOLS = { TranslateMessage: { args: [FFIType.ptr], returns: FFIType.i32 }, // (const MSG *) -> LRESULT DispatchMessageW: { args: [FFIType.ptr], returns: FFIType.i64 }, - // (int exitCode) -> void - PostQuitMessage: { args: [FFIType.i32], returns: FFIType.void }, // (HINSTANCE, LPCWSTR lpCursorName) -> HCURSOR LoadCursorW: { args: [FFIType.u64, FFIType.u64], returns: FFIType.u64 }, // (HWND, UINT msg, WPARAM, LPARAM) -> LRESULT (synchronous dispatch to the WndProc) From 49a2bacd11c6b8f0b00f2df2e6f068f625b9e191 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:52:57 -0700 Subject: [PATCH 074/586] fix: release Cocoa objects once AppKit holds its own reference --- src/main/platform/macos/cocoa-clipboard.ts | 4 +++- src/main/platform/macos/cocoa-dialog.ts | 1 + src/main/platform/macos/cocoa-native-image.ts | 8 ++++++-- src/main/platform/macos/cocoa-safe-storage.ts | 4 +++- src/main/platform/macos/cocoa-tray.ts | 1 + 5 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/main/platform/macos/cocoa-clipboard.ts b/src/main/platform/macos/cocoa-clipboard.ts index 0b3f44a6..467347c5 100644 --- a/src/main/platform/macos/cocoa-clipboard.ts +++ b/src/main/platform/macos/cocoa-clipboard.ts @@ -105,12 +105,14 @@ export const writeImage = (png: Uint8Array): void => { const rt = cocoa(); const pasteboard = generalPasteboard(); rt.msgSend(pasteboard, rt.selectors.get('clearContents')); + const data = nsDataFromBytes(png); msgSendPtrPtr( pasteboard, rt.selectors.get('setData:forType:'), - nsDataFromBytes(png), + data, nsString(NS_PASTEBOARD_TYPE_PNG), ); + rt.msgSend(data, rt.selectors.get('release')); // the pasteboard keeps its own reference }; /** The format names currently on the clipboard (Electron's `availableFormats`). */ diff --git a/src/main/platform/macos/cocoa-dialog.ts b/src/main/platform/macos/cocoa-dialog.ts index 7be22eb4..d4882a14 100644 --- a/src/main/platform/macos/cocoa-dialog.ts +++ b/src/main/platform/macos/cocoa-dialog.ts @@ -99,6 +99,7 @@ export const buildAlert = (spec: MessageBoxSpec): Handle => { export const showMessageBox = (spec: MessageBoxSpec): number => { const alert = buildAlert(spec); const response = msgSendReturnsI64(alert, cocoa().selectors.get('runModal')); + cocoa().msgSend(alert, cocoa().selectors.get('release')); return Number(response - NS_ALERT_FIRST_BUTTON_RETURN); }; diff --git a/src/main/platform/macos/cocoa-native-image.ts b/src/main/platform/macos/cocoa-native-image.ts index f582619d..71982549 100644 --- a/src/main/platform/macos/cocoa-native-image.ts +++ b/src/main/platform/macos/cocoa-native-image.ts @@ -106,8 +106,12 @@ const decodePath = (path: string): DecodedImage => { return decodeFromRep(bitmapRepFromData(data)); }; -const decodeBuffer = (bytes: Uint8Array): DecodedImage => - decodeFromRep(bitmapRepFromData(nsDataFromBytes(bytes))); +const decodeBuffer = (bytes: Uint8Array): DecodedImage => { + const data = nsDataFromBytes(bytes); + const rep = bitmapRepFromData(data); + cocoa().msgSend(data, cocoa().selectors.get('release')); // the rep keeps what it needs + return decodeFromRep(rep); +}; /** * Redraw a rep's `CGImage` into a NEW `width`×`height` offscreen bitmap, placing the source diff --git a/src/main/platform/macos/cocoa-safe-storage.ts b/src/main/platform/macos/cocoa-safe-storage.ts index 3d78696a..2c109a9d 100644 --- a/src/main/platform/macos/cocoa-safe-storage.ts +++ b/src/main/platform/macos/cocoa-safe-storage.ts @@ -70,7 +70,9 @@ export const makeMacosKeychainBackend = (service: string, account: string): Keyr const sec = loadSecurityFFI(); const k = secConstants(); const query = baseQuery(); - dictSet(query, nsDataFromBytes(key), k.kSecValueData); + const data = nsDataFromBytes(key); + dictSet(query, data, k.kSecValueData); + cocoa().msgSend(data, cocoa().selectors.get('release')); // the dictionary retains it // Device-bound, non-syncing accessibility. dictSet(query, k.kSecAttrAccessibleWhenUnlockedThisDeviceOnly, k.kSecAttrAccessible); const status = sec.symbols.SecItemAdd(query, null); diff --git a/src/main/platform/macos/cocoa-tray.ts b/src/main/platform/macos/cocoa-tray.ts index eac63139..ef65dac5 100644 --- a/src/main/platform/macos/cocoa-tray.ts +++ b/src/main/platform/macos/cocoa-tray.ts @@ -94,6 +94,7 @@ const create = (image: string, options?: TrayImageOptions): TrayInstance => { // A template image lets the menu bar recolor it for light/dark. msgSendU8(img, rt.selectors.get('setTemplate:'), template ? 1 : 0); msgSendPtr(btn, rt.selectors.get('setImage:'), img); + rt.msgSend(img, rt.selectors.get('release')); // the button retains it } }; applyImage(image, options?.template === true); From 122439ff9c252b2804143907147922386b0b762c Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:53:01 -0700 Subject: [PATCH 075/586] fix: export every entry under the default condition for require() --- package.json | 10 +++++----- tests/unit/package-exports.test.ts | 13 +++++++++++++ 2 files changed, 18 insertions(+), 5 deletions(-) create mode 100644 tests/unit/package-exports.test.ts diff --git a/package.json b/package.json index f6769143..4013973a 100644 --- a/package.json +++ b/package.json @@ -43,23 +43,23 @@ "exports": { ".": { "types": "./src/index.ts", - "import": "./src/index.ts" + "default": "./src/index.ts" }, "./main": { "types": "./src/main/index.ts", - "import": "./src/main/index.ts" + "default": "./src/main/index.ts" }, "./renderer": { "types": "./src/renderer/index.ts", - "import": "./src/renderer/index.ts" + "default": "./src/renderer/index.ts" }, "./config": { "types": "./src/config.ts", - "import": "./src/config.ts" + "default": "./src/config.ts" }, "./electron": { "types": "./src/electron.ts", - "import": "./src/electron.ts" + "default": "./src/electron.ts" } }, "files": [ diff --git a/tests/unit/package-exports.test.ts b/tests/unit/package-exports.test.ts new file mode 100644 index 00000000..75a3316a --- /dev/null +++ b/tests/unit/package-exports.test.ts @@ -0,0 +1,13 @@ +import { describe, expect, test } from 'bun:test'; + +describe('package exports', () => { + test.each([ + 'bunmaska', + 'bunmaska/main', + 'bunmaska/renderer', + 'bunmaska/config', + 'bunmaska/electron', + ])('%s resolves for require(), not only import', (specifier) => { + expect(require.resolve(specifier)).toEndWith('.ts'); + }); +}); From e80be59f313701aa76fda2fb5bfdc7e936dfa858 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:53:03 -0700 Subject: [PATCH 076/586] fix: report the last set size for hidden Linux windows --- src/main/platform/linux/linux-backend.ts | 6 ++++-- tests/integration/linux/window-events.test.ts | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/main/platform/linux/linux-backend.ts b/src/main/platform/linux/linux-backend.ts index a71b2e1f..77ea04b6 100644 --- a/src/main/platform/linux/linux-backend.ts +++ b/src/main/platform/linux/linux-backend.ts @@ -322,8 +322,8 @@ class LinuxWindow implements NativeWindow { #minimized = false; #active = false; #maximized = false; - readonly #defaultWidth: number; - readonly #defaultHeight: number; + #defaultWidth: number; + #defaultHeight: number; #closed = false; #activePopover: Pointer | null = null; readonly #closedCallbacks: Array<() => void> = []; @@ -549,6 +549,8 @@ class LinuxWindow implements NativeWindow { } setSize(width: number, height: number): void { + this.#defaultWidth = width; + this.#defaultHeight = height; this.#gtk()?.gtk_window_set_default_size(this.#window, width, height); } diff --git a/tests/integration/linux/window-events.test.ts b/tests/integration/linux/window-events.test.ts index 354b1363..cf3b862b 100644 --- a/tests/integration/linux/window-events.test.ts +++ b/tests/integration/linux/window-events.test.ts @@ -120,6 +120,21 @@ describe.skipIf(!isLinux)('Linux window lifecycle events end-to-end', () => { app.quit(); }); + test('getBounds of a hidden window reports the size last set', () => { + if (loadGtkFFI().symbols.gtk_init_check() === 0) { + return; + } + const app = createLinuxApplication(); + app.start(); + const window = app.createWindow({ width: 800, height: 600, title: 'Hidden', show: false }); + + window.setSize(1024, 768); + + expect(window.getBounds()).toEqual({ x: 0, y: 0, width: 1024, height: 768 }); + window.close(); + app.quit(); + }); + test('calls after close never touch the freed window or view', () => { if (loadGtkFFI().symbols.gtk_init_check() === 0) { return; From a987ac84838846edc77e749fe6f650ad47fe64c6 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:53:09 -0700 Subject: [PATCH 077/586] fix: let frameless macOS windows become key, minimize, resize and close --- src/main/platform/macos/cocoa-backend.ts | 59 ++++++++++++-- src/main/platform/macos/cocoa-style-mask.ts | 2 - tests/integration/macos/cocoa-backend.test.ts | 76 +++++++++++++++++++ .../platform/macos/cocoa-style-mask.test.ts | 7 -- 4 files changed, 128 insertions(+), 16 deletions(-) diff --git a/src/main/platform/macos/cocoa-backend.ts b/src/main/platform/macos/cocoa-backend.ts index ee7afc26..219f65b4 100644 --- a/src/main/platform/macos/cocoa-backend.ts +++ b/src/main/platform/macos/cocoa-backend.ts @@ -41,6 +41,7 @@ import { msgSendPtr4, msgSendPtrI64U8Ptr, msgSendPtrPtr, + msgSendPtrReturnsU8, msgSendReturnsI64, msgSendReturnsU8, msgSendSize, @@ -52,10 +53,10 @@ import { createMacOSDrain } from './cocoa-run-loop'; import { primaryDisplayHeight } from './cocoa-screen'; import { msgSendRectU8 } from './cocoa-msgsend-variants'; import { readWindowBounds } from './cocoa-window-bounds'; -import { cocoa } from './cocoa-runtime'; import { createScriptMessageHandler } from './cocoa-script-message-handler'; +import { cocoa } from './cocoa-runtime'; +import { defineObjcClass } from './cocoa-runtime-class'; import { - BORDERLESS_WINDOW_STYLE, type CocoaWindowStyle, computeWindowStyleMask, STANDARD_WINDOW_STYLE, @@ -187,10 +188,52 @@ const registerCustomSchemes = (configuration: Handle): void => { } }; -const styleFromOptions = (options: NativeWindowOptions): CocoaWindowStyle => - options.frame === false - ? BORDERLESS_WINDOW_STYLE - : { ...STANDARD_WINDOW_STYLE, resizable: options.resizable !== false }; +const styleFromOptions = (options: NativeWindowOptions): CocoaWindowStyle => ({ + ...STANDARD_WINDOW_STYLE, + titled: options.frame !== false, + resizable: options.resizable !== false, +}); + +let framelessWindowClass: Handle | undefined; + +/** + * An NSWindow for frame: false. Without a title bar AppKit answers NO to becoming + * key or main, and -performClose: only beeps, so both are overridden. + */ +const ensureFramelessWindowClass = (): Handle => { + framelessWindowClass ??= defineObjcClass('BunmaskaFramelessWindow', 'NSWindow', [ + { + selector: 'canBecomeKeyWindow', + typeEncoding: 'c@:', + args: [], + returns: 'bool', + impl: () => 1, + }, + { + selector: 'canBecomeMainWindow', + typeEncoding: 'c@:', + args: [], + returns: 'bool', + impl: () => 1, + }, + { + selector: 'performClose:', + typeEncoding: 'v@:@', + args: ['object'], + impl: (self) => { + const rt = cocoa(); + const delegate = rt.msgSend(self, rt.selectors.get('delegate')); + const allowed = + delegate === 0n || + msgSendPtrReturnsU8(delegate, rt.selectors.get('windowShouldClose:'), self) === 1; + if (allowed) { + rt.msgSend(self, rt.selectors.get('close')); + } + }, + }, + ]); + return framelessWindowClass; +}; class MacOSWebContents implements NativeWebContents { #webview: Handle; @@ -969,8 +1012,10 @@ class MacOSApplication implements NativeApplication { 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(rt.classes.get('NSWindow'), rt.selectors.get('alloc')), + rt.msgSend(windowClass, rt.selectors.get('alloc')), rt.selectors.get('initWithContentRect:styleMask:backing:defer:'), frame, BigInt(computeWindowStyleMask(styleFromOptions(options))), diff --git a/src/main/platform/macos/cocoa-style-mask.ts b/src/main/platform/macos/cocoa-style-mask.ts index 47889d65..a72c8295 100644 --- a/src/main/platform/macos/cocoa-style-mask.ts +++ b/src/main/platform/macos/cocoa-style-mask.ts @@ -28,8 +28,6 @@ export const STANDARD_WINDOW_STYLE: CocoaWindowStyle = Object.freeze({ resizable: true, }); -export const BORDERLESS_WINDOW_STYLE: CocoaWindowStyle = Object.freeze({}); - export const computeWindowStyleMask = (style: CocoaWindowStyle): number => { let mask = 0; if (style.titled === true) { diff --git a/tests/integration/macos/cocoa-backend.test.ts b/tests/integration/macos/cocoa-backend.test.ts index 9b95a2f0..a86db300 100644 --- a/tests/integration/macos/cocoa-backend.test.ts +++ b/tests/integration/macos/cocoa-backend.test.ts @@ -2,9 +2,31 @@ import { describe, expect, jest, test } from 'bun:test'; import { currentPlatform } from '../../../src/common/platform'; import { createMacOSApplication } from '../../../src/main/platform/macos/cocoa-backend'; import { retainedBlockCount } from '../../../src/main/platform/macos/cocoa-block'; +import { nsStringToString } from '../../../src/main/platform/macos/cocoa-foundation'; +import { + msgSendI64, + msgSendReturnsI64, + msgSendReturnsU8, +} from '../../../src/main/platform/macos/cocoa-msgsend-variants'; +import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; const delay = (ms: number): Promise => new Promise((resolve) => setTimeout(resolve, ms)); +/** The NSWindow in NSApp's window list with this title, or 0n. */ +const nsWindowTitled = (title: string): bigint => { + const rt = cocoa(); + const app = rt.msgSend(rt.classes.get('NSApplication'), rt.selectors.get('sharedApplication')); + const windows = rt.msgSend(app, rt.selectors.get('windows')); + const count = rt.msgSend(windows, rt.selectors.get('count')); + for (let i = 0n; i < count; i += 1n) { + const window = msgSendI64(windows, rt.selectors.get('objectAtIndex:'), i); + if (nsStringToString(rt.msgSend(window, rt.selectors.get('title'))) === title) { + return window; + } + } + return 0n; +}; + const waitFor = async (predicate: () => boolean, ms = 3_000): Promise => { const deadline = performance.now() + ms; while (!predicate() && performance.now() < deadline) { @@ -278,6 +300,60 @@ if (currentPlatform() === 'macos') { } }); + test('a frameless window can become key, minimizes, resizes and closes', async () => { + const app = createMacOSApplication(); + app.start(); + try { + const win = app.createWindow({ + width: 320, + height: 240, + title: 'frameless', + show: true, + frame: false, + }); + const window = nsWindowTitled('frameless'); + const sel = cocoa().selectors; + expect(msgSendReturnsU8(window, sel.get('canBecomeKeyWindow'))).toBe(1); + expect(msgSendReturnsU8(window, sel.get('canBecomeMainWindow'))).toBe(1); + expect(msgSendReturnsI64(window, sel.get('styleMask')) & 8n).toBe(8n); + win.minimize(); + await waitFor(() => win.isMinimized()); + expect(win.isMinimized()).toBe(true); + let closed = 0; + win.onClose(() => closed === 0); + win.onClosed(() => { + closed += 1; + }); + win.close(); + expect(closed).toBe(0); + win.onClose(() => false); + win.close(); + expect(closed).toBe(1); + } finally { + app.quit(); + } + }); + + test('a frameless window honours resizable: false', () => { + const app = createMacOSApplication(); + app.start(); + try { + const win = app.createWindow({ + width: 320, + height: 240, + title: 'frameless-fixed', + show: false, + frame: false, + resizable: false, + }); + const window = nsWindowTitled('frameless-fixed'); + expect(msgSendReturnsI64(window, cocoa().selectors.get('styleMask')) & 8n).toBe(0n); + win.destroy(); + } finally { + app.quit(); + } + }); + test('close fires the onClosed callback once', () => { const app = createMacOSApplication(); app.start(); diff --git a/tests/unit/main/platform/macos/cocoa-style-mask.test.ts b/tests/unit/main/platform/macos/cocoa-style-mask.test.ts index c5b2e00a..243a2f81 100644 --- a/tests/unit/main/platform/macos/cocoa-style-mask.test.ts +++ b/tests/unit/main/platform/macos/cocoa-style-mask.test.ts @@ -1,6 +1,5 @@ import { describe, expect, test } from 'bun:test'; import { - BORDERLESS_WINDOW_STYLE, computeWindowStyleMask, STANDARD_WINDOW_STYLE, } from '../../../../../src/main/platform/macos/cocoa-style-mask'; @@ -67,9 +66,3 @@ describe('STANDARD_WINDOW_STYLE', () => { ); }); }); - -describe('BORDERLESS_WINDOW_STYLE', () => { - test('composes to mask 0', () => { - expect(computeWindowStyleMask(BORDERLESS_WINDOW_STYLE)).toBe(0); - }); -}); From 96bd9ddac1ca48a38ba377d4c2604295ca353f70 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:53:10 -0700 Subject: [PATCH 078/586] test: gate win32 accessor tests with skipIf, drop a type test --- .../unit/main/platform/windows/win32.test.ts | 23 +++++++------------ 1 file changed, 8 insertions(+), 15 deletions(-) diff --git a/tests/unit/main/platform/windows/win32.test.ts b/tests/unit/main/platform/windows/win32.test.ts index d1ee3a64..063a014e 100644 --- a/tests/unit/main/platform/windows/win32.test.ts +++ b/tests/unit/main/platform/windows/win32.test.ts @@ -11,10 +11,6 @@ import { } from '../../../../../src/main/platform/windows/win32'; describe('wstr', () => { - test('returns a Uint8Array', () => { - expect(wstr('x')).toBeInstanceOf(Uint8Array); - }); - test('null-terminates with a UTF-16 (two-byte) NUL', () => { const bytes = wstr('hello'); expect(bytes[bytes.length - 2]).toBe(0); @@ -59,10 +55,7 @@ describe('NULL_HANDLE', () => { }); describe('winLibraryAccessor', () => { - test('returns a memoising accessor that calls open at most once', () => { - if (currentPlatform() !== 'windows') { - return; - } + test.skipIf(currentPlatform() !== 'windows')('memoises: open runs at most once', () => { let opens = 0; const get = winLibraryAccessor('test', () => { opens += 1; @@ -74,11 +67,11 @@ describe('winLibraryAccessor', () => { expect(opens).toBe(1); }); - test('throws UnsupportedPlatformError on non-Windows hosts', () => { - if (currentPlatform() === 'windows') { - return; - } - const get = winLibraryAccessor('test', () => ({})); - expect(() => get()).toThrow(UnsupportedPlatformError); - }); + test.skipIf(currentPlatform() === 'windows')( + 'throws UnsupportedPlatformError off Windows', + () => { + const get = winLibraryAccessor('test', () => ({})); + expect(() => get()).toThrow(UnsupportedPlatformError); + }, + ); }); From f9b61865e4dce8aa93d8b8b1ab287ba81ad20318 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:53:18 -0700 Subject: [PATCH 079/586] fix: show a new window after its event handlers are wired --- src/main/api/browser-window.ts | 6 +++++- tests/unit/main/api/browser-window.test.ts | 20 +++++++++++++++++--- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/src/main/api/browser-window.ts b/src/main/api/browser-window.ts index 5757221a..23c973e9 100644 --- a/src/main/api/browser-window.ts +++ b/src/main/api/browser-window.ts @@ -122,7 +122,7 @@ export class BrowserWindow extends EventEmitter { width: options.width ?? DEFAULT_WIDTH, height: options.height ?? DEFAULT_HEIGHT, title: options.title ?? DEFAULT_TITLE, - show: options.show ?? true, + show: false, ...(preloadScript !== undefined ? { preloadScript } : {}), ...(options.resizable !== undefined ? { resizable: options.resizable } : {}), ...(options.frame !== undefined ? { frame: options.frame } : {}), @@ -178,6 +178,10 @@ export class BrowserWindow extends EventEmitter { } registry.set(this.id, this); app.emit('browser-window-created', makeCancelableEvent(), this); + // Shown last so the initial `show`/`focus` reach the handlers wired above. + if (options.show ?? true) { + this.#native.show(); + } } get #native(): NativeWindow { diff --git a/tests/unit/main/api/browser-window.test.ts b/tests/unit/main/api/browser-window.test.ts index 3d841f7c..ce9bbd84 100644 --- a/tests/unit/main/api/browser-window.test.ts +++ b/tests/unit/main/api/browser-window.test.ts @@ -128,6 +128,7 @@ const makeFakeWindow = (options: NativeWindowOptions): FakeWindow => { }, show: () => { visible = true; + eventCallbacks.get('show')?.(); }, hide: () => { visible = false; @@ -316,13 +317,26 @@ describe('BrowserWindow runtime setters', () => { describe('BrowserWindow construction', () => { test('applies default options when none are given', () => { - new BrowserWindow(); - expect(created[0]).toEqual({ width: 800, height: 600, title: 'Bunmaska', show: true }); + const win = new BrowserWindow(); + expect(created[0]).toEqual({ width: 800, height: 600, title: 'Bunmaska', show: false }); + expect(win.isVisible()).toBe(true); }); test('passes through provided options', () => { - new BrowserWindow({ width: 1024, height: 768, title: 'My App', show: false }); + const win = new BrowserWindow({ width: 1024, height: 768, title: 'My App', show: false }); expect(created[0]).toEqual({ width: 1024, height: 768, title: 'My App', show: false }); + expect(win.isVisible()).toBe(false); + }); + + test('the initial show is emitted after the window is wired and announced', () => { + let shown = 0; + app.on('browser-window-created', (_event: unknown, win: BrowserWindow) => { + win.on('show', () => { + shown += 1; + }); + }); + new BrowserWindow(); + expect(shown).toBe(1); }); test('forwards resizable, frame, and fullscreen when provided', () => { From c1ac18a8b35cddf3a4dec7589d0f93e30ddf2e4a Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:53:19 -0700 Subject: [PATCH 080/586] chore: drop the unused NULL_HANDLE and WinHandle exports --- src/main/platform/windows/win32.ts | 5 ----- tests/unit/main/platform/windows/win32.test.ts | 15 +-------------- 2 files changed, 1 insertion(+), 19 deletions(-) diff --git a/src/main/platform/windows/win32.ts b/src/main/platform/windows/win32.ts index 9c358243..94ede694 100644 --- a/src/main/platform/windows/win32.ts +++ b/src/main/platform/windows/win32.ts @@ -12,11 +12,6 @@ import { UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; import type { Rect } from '../native'; -/** Opaque pointer-width Win32 handle (`HWND`/`HMENU`/`HINSTANCE`/...). */ -export type WinHandle = bigint; - -export const NULL_HANDLE: WinHandle = 0n; - /** * Encode a JS string as a null-terminated UTF-16LE byte sequence suitable for a * Win32 wide-character (`LPCWSTR`) argument — the `wstr` sibling of {@link cstr}. diff --git a/tests/unit/main/platform/windows/win32.test.ts b/tests/unit/main/platform/windows/win32.test.ts index 063a014e..1d8cf7c5 100644 --- a/tests/unit/main/platform/windows/win32.test.ts +++ b/tests/unit/main/platform/windows/win32.test.ts @@ -2,13 +2,7 @@ import { describe, expect, test } from 'bun:test'; import { ptr } from 'bun:ffi'; import { UnsupportedPlatformError } from '../../../../../src/common/errors'; import { currentPlatform } from '../../../../../src/common/platform'; -import { - NULL_HANDLE, - readRect, - type WinHandle, - winLibraryAccessor, - wstr, -} from '../../../../../src/main/platform/windows/win32'; +import { readRect, winLibraryAccessor, wstr } from '../../../../../src/main/platform/windows/win32'; describe('wstr', () => { test('null-terminates with a UTF-16 (two-byte) NUL', () => { @@ -47,13 +41,6 @@ describe('readRect', () => { }); }); -describe('NULL_HANDLE', () => { - test('is the zero bigint handle', () => { - const handle: WinHandle = NULL_HANDLE; - expect(handle).toBe(0n); - }); -}); - describe('winLibraryAccessor', () => { test.skipIf(currentPlatform() !== 'windows')('memoises: open runs at most once', () => { let opens = 0; From be2ecdb14c23e80b19e8d7dcebc6dcadacc7d408 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:53:24 -0700 Subject: [PATCH 081/586] fix: emit resize when a Linux window maximizes or goes fullscreen --- src/main/platform/linux/linux-backend.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/main/platform/linux/linux-backend.ts b/src/main/platform/linux/linux-backend.ts index 77ea04b6..f38cd3d3 100644 --- a/src/main/platform/linux/linux-backend.ts +++ b/src/main/platform/linux/linux-backend.ts @@ -451,9 +451,15 @@ class LinuxWindow implements NativeWindow { return; } this.#maximized = maximized; + this.#emitEvent('resize'); this.#emitEvent(maximized ? 'maximize' : 'unmaximize'); }), ); + this.#registry.connect( + this.#window, + 'notify::fullscreened', + makeNotifyCallback(() => this.#emitEvent('resize')), + ); // Resize: the default-size props change when the window is resized. Two // distinct callbacks so the registry closes each exactly once on teardown. From 96b4cffdda8060141fa6ef8570629970de6f38df Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:53:33 -0700 Subject: [PATCH 082/586] fix: list Electron's view, share and service-worker modules as known --- src/main/module-list.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/main/module-list.ts b/src/main/module-list.ts index c069881b..951a17f9 100644 --- a/src/main/module-list.ts +++ b/src/main/module-list.ts @@ -21,6 +21,7 @@ export const KNOWN_ELECTRON_MODULES = [ 'dialog', 'globalShortcut', 'ipcMain', + 'ImageView', 'inAppPurchase', 'Menu', 'MenuItem', @@ -36,14 +37,19 @@ export const KNOWN_ELECTRON_MODULES = [ 'pushNotifications', 'safeStorage', 'screen', + 'ServiceWorkerMain', 'session', + 'sharedTexture', + 'ShareMenu', 'shell', 'systemPreferences', 'TouchBar', 'Tray', 'utilityProcess', + 'View', 'webContents', 'WebContents', + 'WebContentsView', 'webFrameMain', ] as const; From 1c8e094cd8f756c521f16a8a5b6e3ae40d861cde Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:53:59 -0700 Subject: [PATCH 083/586] fix: inject the macOS preload and bridge into the main frame only --- src/main/platform/macos/cocoa-backend.ts | 4 +- tests/integration/macos/cocoa-backend.test.ts | 38 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/src/main/platform/macos/cocoa-backend.ts b/src/main/platform/macos/cocoa-backend.ts index 219f65b4..e972b654 100644 --- a/src/main/platform/macos/cocoa-backend.ts +++ b/src/main/platform/macos/cocoa-backend.ts @@ -118,6 +118,8 @@ const nsImageToPng = (image: Handle): Uint8Array => { /** `NSFloatingWindowLevel` — above normal windows. */ const NS_FLOATING_WINDOW_LEVEL = 3n; const WK_INJECTION_TIME_AT_DOCUMENT_START = 0n; +/** Electron runs preloads in the main frame only; an iframe must never get the bridge. */ +const FOR_MAIN_FRAME_ONLY = 1; const SCRIPT_MESSAGE_HANDLER_NAME = 'bunmaska'; /** Page-world handler name `executeJavaScript` posts its result to (D022). */ const EXEC_RESULT_HANDLER_NAME = 'bunmaskaExec'; @@ -1104,7 +1106,7 @@ class MacOSApplication implements NativeApplication { rt.selectors.get('initWithSource:injectionTime:forMainFrameOnly:inContentWorld:'), nsString(source), WK_INJECTION_TIME_AT_DOCUMENT_START, - 0, + FOR_MAIN_FRAME_ONLY, world, ); msgSendPtr(userContentController, rt.selectors.get('addUserScript:'), userScript); diff --git a/tests/integration/macos/cocoa-backend.test.ts b/tests/integration/macos/cocoa-backend.test.ts index a86db300..d23d65d2 100644 --- a/tests/integration/macos/cocoa-backend.test.ts +++ b/tests/integration/macos/cocoa-backend.test.ts @@ -354,6 +354,44 @@ if (currentPlatform() === 'macos') { } }); + test('the preload, bridge and dom-ready run in the main frame only', async () => { + const app = createMacOSApplication(); + app.start(); + try { + const win = app.createWindow({ + width: 320, + height: 240, + title: 't', + show: true, + preloadScript: "window.__bunmaska.exposeInMainWorld('myApi', { v: 1 });", + }); + let domReady = 0; + win.webContents.onNavigation((event) => { + if (event.type === 'dom-ready') { + domReady += 1; + } + }); + win.webContents.loadHTML('', 'about:blank'); + const probe = `(() => { + const frame = document.querySelector('iframe'); + if (!frame || !frame.contentDocument || frame.contentDocument.readyState !== 'complete') { + return null; + } + return [typeof window.myApi, typeof frame.contentWindow.myApi]; + })()`; + let seen: unknown = null; + const deadline = performance.now() + 5_000; + while (seen === null && performance.now() < deadline) { + await Bun.sleep(20); + seen = await win.webContents.executeJavaScript(probe); + } + expect(seen).toEqual(['object', 'undefined']); + expect(domReady).toBe(1); + } finally { + app.quit(); + } + }); + test('close fires the onClosed callback once', () => { const app = createMacOSApplication(); app.start(); From 72deb53f119cda5da407f9a5aaf1faf3c7dab3bb Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:54:11 -0700 Subject: [PATCH 084/586] test: gate the socket-file assertion with skipIf and drop fixed sleeps --- .../single-instance-backend.test.ts | 29 ++++++++----------- 1 file changed, 12 insertions(+), 17 deletions(-) diff --git a/tests/integration/single-instance-backend.test.ts b/tests/integration/single-instance-backend.test.ts index 713eafac..37a63de4 100644 --- a/tests/integration/single-instance-backend.test.ts +++ b/tests/integration/single-instance-backend.test.ts @@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; import { existsSync, mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import { currentPlatform } from '../../src/common/platform'; import { encodePayload, type SecondInstancePayload, @@ -9,13 +10,7 @@ import { } from '../../src/main/api/single-instance'; import { createLockBackend } from '../../src/main/api/single-instance-backend'; -/** - * Exercises the REAL filesystem pidfile + Bun unix-socket backend (pure Bun, so - * it runs on macOS, Linux AND Windows — Bun's AF_UNIX works on Win10+). The - * decision logic itself is unit-tested with a fake backend in - * single-instance.test.ts. NOTE: on Windows an AF_UNIX bind is not a visible - * filesystem file, so the socket-file assertion below is guarded accordingly. - */ +// The real pidfile + unix-socket backend; pure Bun, so it runs on every OS (AF_UNIX needs Win10+). const delay = (ms: number): Promise => new Promise((resolve) => setTimeout(resolve, ms)); @@ -111,7 +106,6 @@ describe('createLockBackend — socket hand-off', () => { const backend = createLockBackend(); const received: string[] = []; backend.startServer(socketPath, (json) => received.push(json)); - await delay(50); const message = encodePayload({ argv: ['x', 'y'], cwd: '/work', additionalData: { n: 7 } }); backend.notify(socketPath, message); @@ -123,21 +117,22 @@ describe('createLockBackend — socket hand-off', () => { expect(received).toEqual([message]); }); - test('stop() removes the socket + lock files', async () => { + test('stop() removes the lock file', () => { const backend = createLockBackend(); backend.tryCreateLock(lockPath, process.pid); backend.startServer(socketPath, () => undefined); - await delay(50); - // macOS/Linux expose the AF_UNIX bind as a visible socket file; Bun's Windows - // AF_UNIX binding is not a filesystem entry, so only assert the socket-file - // lifecycle where it is observable. The lock file exists on every platform. - const socketIsVisibleFile = existsSync(socketPath); backend.stop(lockPath, socketPath); - if (socketIsVisibleFile) { - expect(existsSync(socketPath)).toBe(false); - } expect(existsSync(lockPath)).toBe(false); }); + + // Bun's Windows AF_UNIX bind is not a filesystem entry. + test.skipIf(currentPlatform() === 'windows')('stop() removes the socket file', () => { + const backend = createLockBackend(); + backend.startServer(socketPath, () => undefined); + expect(existsSync(socketPath)).toBe(true); + backend.stop(lockPath, socketPath); + expect(existsSync(socketPath)).toBe(false); + }); }); describe('SingleInstanceManager over the real backend (end-to-end)', () => { From 23cda063b23212a2cf1ad8eaec5c9cdc95f826ba Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:54:18 -0700 Subject: [PATCH 085/586] fix: clear a stale mirrored app region when --app-region changes --- src/main/platform/window-controls.ts | 18 +++++- .../main/platform/window-controls.test.ts | 63 +++++++++++++++++++ 2 files changed, 78 insertions(+), 3 deletions(-) diff --git a/src/main/platform/window-controls.ts b/src/main/platform/window-controls.ts index bd366d9a..dd3358bc 100644 --- a/src/main/platform/window-controls.ts +++ b/src/main/platform/window-controls.ts @@ -50,12 +50,19 @@ export function windowControlsScript(options: { nativeOpChannel?: boolean } = {} ` : ''; return `(function(){ -${ops} var mirror = function(){ +${ops} var mirrored = new WeakSet(); + var mirror = function(){ try { var els = document.querySelectorAll('*'); for (var i = 0; i < els.length; i++) { var v = getComputedStyle(els[i]).getPropertyValue('--app-region').trim(); - if (v === 'drag' || v === 'no-drag') els[i].style.setProperty('-webkit-app-region', v); + if (v === 'drag' || v === 'no-drag') { + els[i].style.setProperty('-webkit-app-region', v); + mirrored.add(els[i]); + } else if (mirrored.has(els[i])) { + els[i].style.removeProperty('-webkit-app-region'); + mirrored.delete(els[i]); + } } } catch (e) {} }; @@ -68,7 +75,12 @@ ${ops} var mirror = function(){ if (document.readyState !== 'loading') schedule(); document.addEventListener('DOMContentLoaded', schedule); try { - new MutationObserver(schedule).observe(document.documentElement, { childList: true, subtree: true }); + new MutationObserver(schedule).observe(document.documentElement, { + childList: true, + subtree: true, + attributes: true, + attributeFilter: ['class'] + }); } catch (e) {} })();`; } diff --git a/tests/unit/main/platform/window-controls.test.ts b/tests/unit/main/platform/window-controls.test.ts index beaf5ac6..f3389b7c 100644 --- a/tests/unit/main/platform/window-controls.test.ts +++ b/tests/unit/main/platform/window-controls.test.ts @@ -40,3 +40,66 @@ describe('windowControlsScript', () => { expect(windowControlsScript({ nativeOpChannel: false })).toBe(windowControlsScript()); }); }); + +type FakeElement = { appRegion: string; style: Map }; + +/** Run the mirror against fake elements; `mutate()` fires the MutationObserver. */ +const runMirror = (elements: FakeElement[]) => { + let onMutation: () => void = () => undefined; + let observed: unknown; + const style = (el: FakeElement) => ({ + setProperty: (name: string, value: string) => el.style.set(name, value), + removeProperty: (name: string) => el.style.delete(name), + }); + const nodes = elements.map((el) => ({ el, style: style(el) })); + const document = { + readyState: 'complete', + documentElement: {}, + addEventListener: () => undefined, + querySelectorAll: () => nodes, + }; + const getComputedStyle = ({ el }: { el: FakeElement }) => ({ + getPropertyValue: () => el.appRegion, + }); + class MutationObserver { + constructor(callback: () => void) { + onMutation = callback; + } + observe(_target: unknown, options: unknown): void { + observed = options; + } + } + const raf = (callback: () => void) => callback(); + new Function( + 'document', + 'getComputedStyle', + 'requestAnimationFrame', + 'MutationObserver', + windowControlsScript(), + )(document, getComputedStyle, raf, MutationObserver); + return { mutate: () => onMutation(), observed: () => observed }; +}; + +describe('the --app-region mirror', () => { + test('clears the region it mirrored once --app-region no longer applies', () => { + const bar: FakeElement = { appRegion: 'drag', style: new Map() }; + const page = runMirror([bar]); + expect(bar.style.get('-webkit-app-region')).toBe('drag'); + bar.appRegion = ''; + page.mutate(); + expect(bar.style.has('-webkit-app-region')).toBe(false); + }); + + test('leaves an author-set -webkit-app-region alone', () => { + const bar: FakeElement = { appRegion: '', style: new Map([['-webkit-app-region', 'drag']]) }; + runMirror([bar]).mutate(); + expect(bar.style.get('-webkit-app-region')).toBe('drag'); + }); + + test('re-runs on class changes but never on the style attribute it writes', () => { + expect(runMirror([]).observed()).toMatchObject({ + attributes: true, + attributeFilter: ['class'], + }); + }); +}); From ba5367dd35140c97c8349da36ea052931c5624d9 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:54:23 -0700 Subject: [PATCH 086/586] test: replace cannot-fail notification checks with a bundle-id check --- .../macos/cocoa-notification.test.ts | 49 +++++-------------- 1 file changed, 11 insertions(+), 38 deletions(-) diff --git a/tests/integration/macos/cocoa-notification.test.ts b/tests/integration/macos/cocoa-notification.test.ts index a0a48813..4230a98c 100644 --- a/tests/integration/macos/cocoa-notification.test.ts +++ b/tests/integration/macos/cocoa-notification.test.ts @@ -1,54 +1,27 @@ import { describe, expect, test } from 'bun:test'; import { currentPlatform } from '../../../src/common/platform'; import { macosNotificationBackend } from '../../../src/main/platform/macos/cocoa-notification'; +import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; -/** - * macOS-only. Exercises the REAL NSUserNotification FFI path on the host. - * - * EMPIRICAL REALITY (measured un-bundled, `bun test`): the `NSUserNotification` - * class resolves and the setters run cleanly, but - * `[NSUserNotificationCenter defaultUserNotificationCenter]` returns NIL without - * an app bundle, so nothing is actually delivered — and `deliverNotification:` - * to a nil center is a safe no-op (no SIGSEGV). This test therefore asserts the - * path runs WITHOUT THROWING and that `isSupported()` honestly reflects the - * nil-center reality; it CANNOT assert a banner appeared. - */ const isMac = currentPlatform() === 'macos'; -describe.skipIf(!isMac)('cocoa-notification (macOS, un-bundled)', () => { - test('present() builds and best-effort delivers without throwing', () => { - expect(() => - macosNotificationBackend.present({ - title: 'Bunmaska test', - body: 'Integration body', - subtitle: 'Integration subtitle', - silent: false, - }), - ).not.toThrow(); - }); - - test('the returned handle close()/onClosed() do not throw', () => { +describe.skipIf(!isMac)('cocoa-notification', () => { + // Un-bundled (bun test) the default center is nil, so nothing is delivered. + test('present() and its handle run without throwing', () => { const handle = macosNotificationBackend.present({ title: 'Bunmaska test', body: 'body', - subtitle: '', - silent: true, + subtitle: 'subtitle', + silent: false, }); expect(() => handle.onClosed(() => undefined)).not.toThrow(); expect(() => handle.close()).not.toThrow(); }); - test('isSupported() returns a boolean reflecting the default center', () => { - // Honest: un-bundled the default center is nil so this is `false`. We assert - // the type (not a fixed value) so a future bundled build that flips it to - // `true` does not break this test. - expect(typeof macosNotificationBackend.isSupported()).toBe('boolean'); - }); - - test('present() does not throw even when delivery cannot happen un-bundled', () => { - // The whole point: a clean no-throw run on a host whose center is nil. - expect(() => - macosNotificationBackend.present({ title: 'x', body: '', subtitle: '', silent: false }), - ).not.toThrow(); + test('isSupported() is true exactly when the process has a bundle identifier', () => { + const rt = cocoa(); + const bundle = rt.msgSend(rt.classes.get('NSBundle'), rt.selectors.get('mainBundle')); + const bundled = rt.msgSend(bundle, rt.selectors.get('bundleIdentifier')) !== 0n; + expect(macosNotificationBackend.isSupported()).toBe(bundled); }); }); From 8386205d23f12ef0a4c8e9109d6a67d76f476c17 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:54:32 -0700 Subject: [PATCH 087/586] test: make the Windows window tests able to fail --- tests/integration/windows/app-menu.test.ts | 206 +++++++++--------- tests/integration/windows/win32-ffi.test.ts | 22 +- .../windows/windows-native-window.test.ts | 18 +- 3 files changed, 117 insertions(+), 129 deletions(-) diff --git a/tests/integration/windows/app-menu.test.ts b/tests/integration/windows/app-menu.test.ts index a1becccf..80951efb 100644 --- a/tests/integration/windows/app-menu.test.ts +++ b/tests/integration/windows/app-menu.test.ts @@ -30,115 +30,115 @@ const wireWindow = (realizer: ReturnType) => { return native; }; -if (currentPlatform() === 'windows') { - describe('Windows application menu bar', () => { - test('installs a real menu bar and dispatches a click through the frame proc', () => { - const realizer = createWindowsMenuRealizer(); - let clicked = 0; - const native = wireWindow(realizer); - try { - const template: NativeMenuItemSpec[] = [ - { - type: 'normal', - label: 'Quit', - enabled: true, - keyEquivalent: '', - onClick: () => (clicked += 1), - }, - { - type: 'submenu', - label: 'Help', - enabled: true, - keyEquivalent: '', - submenu: [{ type: 'normal', label: 'About', enabled: true, keyEquivalent: '' }], - }, - ]; - // Mirror menu.ts: realize, then setApplicationMenu(handle). - realizer.setApplicationMenu(realizer.realize(template)); +const isWindows = currentPlatform() === 'windows'; - const user32 = loadUser32().symbols; - const bar = user32.GetMenu(native.hwnd()); - expect(bar).not.toBe(0n); - expect(user32.GetMenuItemCount(bar)).toBe(2); // Quit + Help +describe.skipIf(!isWindows)('Windows application menu bar', () => { + test('installs a real menu bar and dispatches a click through the frame proc', () => { + const realizer = createWindowsMenuRealizer(); + let clicked = 0; + const native = wireWindow(realizer); + try { + const template: NativeMenuItemSpec[] = [ + { + type: 'normal', + label: 'Quit', + enabled: true, + keyEquivalent: '', + onClick: () => (clicked += 1), + }, + { + type: 'submenu', + label: 'Help', + enabled: true, + keyEquivalent: '', + submenu: [{ type: 'normal', label: 'About', enabled: true, keyEquivalent: '' }], + }, + ]; + // Mirror menu.ts: realize, then setApplicationMenu(handle). + realizer.setApplicationMenu(realizer.realize(template)); - // Position 0 is the clickable "Quit"; deliver its real WM_COMMAND. - const quitId = user32.GetMenuItemID(bar, 0); - expect(quitId).toBeGreaterThan(0); - user32.SendMessageW(native.hwnd(), WM_COMMAND, BigInt(quitId), 0n); - expect(clicked).toBe(1); + const user32 = loadUser32().symbols; + const bar = user32.GetMenu(native.hwnd()); + expect(bar).not.toBe(0n); + expect(user32.GetMenuItemCount(bar)).toBe(2); // Quit + Help - // Position 1 is the "Help" submenu — popups have no command id. - expect(user32.GetMenuItemID(bar, 1) >>> 0).toBe(0xffffffff); - } finally { - native.destroy(); - } - }); + // Position 0 is the clickable "Quit"; deliver its real WM_COMMAND. + const quitId = user32.GetMenuItemID(bar, 0); + expect(quitId).toBeGreaterThan(0); + user32.SendMessageW(native.hwnd(), WM_COMMAND, BigInt(quitId), 0n); + expect(clicked).toBe(1); - test('mirrors the menu onto every registered window (one HMENU each)', () => { - const realizer = createWindowsMenuRealizer(); - const a = wireWindow(realizer); - const b = wireWindow(realizer); - try { - const template: NativeMenuItemSpec[] = [ - { - type: 'submenu', - label: 'File', - enabled: true, - keyEquivalent: '', - submenu: [{ type: 'normal', label: 'New', enabled: true, keyEquivalent: '' }], - }, - ]; - realizer.setApplicationMenu(realizer.realize(template)); + // Position 1 is the "Help" submenu — popups have no command id. + expect(user32.GetMenuItemID(bar, 1) >>> 0).toBe(0xffffffff); + } finally { + native.destroy(); + } + }); - const user32 = loadUser32().symbols; - const barA = user32.GetMenu(a.hwnd()); - const barB = user32.GetMenu(b.hwnd()); - expect(barA).not.toBe(0n); - expect(barB).not.toBe(0n); - expect(barA).not.toBe(barB); // a distinct HMENU per window - expect(user32.GetMenuItemCount(barA)).toBe(1); - expect(user32.GetMenuItemCount(barB)).toBe(1); - } finally { - a.destroy(); - b.destroy(); - } - }); + test('mirrors the menu onto every registered window (one HMENU each)', () => { + const realizer = createWindowsMenuRealizer(); + const a = wireWindow(realizer); + const b = wireWindow(realizer); + try { + const template: NativeMenuItemSpec[] = [ + { + type: 'submenu', + label: 'File', + enabled: true, + keyEquivalent: '', + submenu: [{ type: 'normal', label: 'New', enabled: true, keyEquivalent: '' }], + }, + ]; + realizer.setApplicationMenu(realizer.realize(template)); - test('a window registered AFTER the menu is set still receives the bar', () => { - const realizer = createWindowsMenuRealizer(); - realizer.setApplicationMenu( - realizer.realize([ - { type: 'submenu', label: 'Edit', enabled: true, keyEquivalent: '', submenu: [] }, - ]), - ); - const late = wireWindow(realizer); - try { - const user32 = loadUser32().symbols; - const bar = user32.GetMenu(late.hwnd()); - expect(bar).not.toBe(0n); - expect(user32.GetMenuItemCount(bar)).toBe(1); - } finally { - late.destroy(); - } - }); + const user32 = loadUser32().symbols; + const barA = user32.GetMenu(a.hwnd()); + const barB = user32.GetMenu(b.hwnd()); + expect(barA).not.toBe(0n); + expect(barB).not.toBe(0n); + expect(barA).not.toBe(barB); // a distinct HMENU per window + expect(user32.GetMenuItemCount(barA)).toBe(1); + expect(user32.GetMenuItemCount(barB)).toBe(1); + } finally { + a.destroy(); + b.destroy(); + } }); - // Engine-gated: the menu bar coexisting with a LIVE WebKit view (the JSCallback - // frame proc must keep driving the runtime; the menu-bar client-area shrink must - // not disturb the hosted WKView). Spawned in a subprocess like the other engine - // probes — WebKit's multi-process IPC does not coexist with the bun:test host. - const hasEngine = resolveWindowsEngineDir() !== undefined; - describe.skipIf(!hasEngine)('application menu bar with a live engine', () => { - test('executeJavaScript still works with an application menu attached', async () => { - const fixture = `${import.meta.dir}/fixtures/app-menu-engine-probe.ts`; - const proc = Bun.spawn([process.execPath, 'run', fixture], { - env: { ...process.env }, - stdout: 'pipe', - stderr: 'pipe', - }); - const stdout = await new Response(proc.stdout).text(); - await proc.exited; - expect(stdout).toContain('MENU_ENGINE_OK 5'); - }, 40000); + test('a window registered AFTER the menu is set still receives the bar', () => { + const realizer = createWindowsMenuRealizer(); + realizer.setApplicationMenu( + realizer.realize([ + { type: 'submenu', label: 'Edit', enabled: true, keyEquivalent: '', submenu: [] }, + ]), + ); + const late = wireWindow(realizer); + try { + const user32 = loadUser32().symbols; + const bar = user32.GetMenu(late.hwnd()); + expect(bar).not.toBe(0n); + expect(user32.GetMenuItemCount(bar)).toBe(1); + } finally { + late.destroy(); + } }); -} +}); + +// Engine-gated: the menu bar coexisting with a LIVE WebKit view (the JSCallback +// frame proc must keep driving the runtime; the menu-bar client-area shrink must +// not disturb the hosted WKView). Spawned in a subprocess like the other engine +// probes — WebKit's multi-process IPC does not coexist with the bun:test host. +const hasEngine = isWindows && resolveWindowsEngineDir() !== undefined; +describe.skipIf(!hasEngine)('application menu bar with a live engine', () => { + test('executeJavaScript still works with an application menu attached', async () => { + const fixture = `${import.meta.dir}/fixtures/app-menu-engine-probe.ts`; + const proc = Bun.spawn([process.execPath, 'run', fixture], { + env: { ...process.env }, + stdout: 'pipe', + stderr: 'pipe', + }); + const stdout = await new Response(proc.stdout).text(); + await proc.exited; + expect(stdout).toContain('MENU_ENGINE_OK 5'); + }, 40000); +}); diff --git a/tests/integration/windows/win32-ffi.test.ts b/tests/integration/windows/win32-ffi.test.ts index 59af739b..ba50e26c 100644 --- a/tests/integration/windows/win32-ffi.test.ts +++ b/tests/integration/windows/win32-ffi.test.ts @@ -2,30 +2,10 @@ import { describe, expect, test } from 'bun:test'; import { currentPlatform } from '../../../src/common/platform'; import { loadKernel32, loadUser32 } from '../../../src/main/platform/windows/win32-ffi'; -/** - * Windows-only. Verifies user32.dll and kernel32.dll open and the windowing + - * message-pump symbols resolve. We do NOT create a real window here (that is the - * windows-native-window integration test); this asserts the FFI surface is present. - */ +/** Windows-only: the DLLs open (dlopen throws on any missing symbol) and stay memoised. */ const isWindows = currentPlatform() === 'windows'; describe.skipIf(!isWindows)('Win32 FFI on Windows', () => { - test('loadUser32 resolves the window + message-pump symbols', () => { - const user32 = loadUser32(); - expect(typeof user32.symbols.RegisterClassExW).toBe('function'); - expect(typeof user32.symbols.CreateWindowExW).toBe('function'); - expect(typeof user32.symbols.DefWindowProcW).toBe('function'); - expect(typeof user32.symbols.DestroyWindow).toBe('function'); - expect(typeof user32.symbols.PeekMessageW).toBe('function'); - expect(typeof user32.symbols.TranslateMessage).toBe('function'); - expect(typeof user32.symbols.DispatchMessageW).toBe('function'); - }); - - test('loadKernel32 resolves GetModuleHandleW', () => { - const kernel32 = loadKernel32(); - expect(typeof kernel32.symbols.GetModuleHandleW).toBe('function'); - }); - test('GetModuleHandleW(NULL) returns a non-null module handle', () => { const kernel32 = loadKernel32(); // NULL module name returns the base address of the running executable. diff --git a/tests/integration/windows/windows-native-window.test.ts b/tests/integration/windows/windows-native-window.test.ts index 6d093f37..b33779b1 100644 --- a/tests/integration/windows/windows-native-window.test.ts +++ b/tests/integration/windows/windows-native-window.test.ts @@ -23,6 +23,11 @@ const SWP_NOSIZE_NOZORDER_NOACTIVATE = 0x0001 | 0x0004 | 0x0010; */ const isWindows = currentPlatform() === 'windows'; const WM_CLOSE = 0x0010; +const GWL_STYLE = -16; +const WS_POPUP = 0x80000000n; +const WS_CAPTION = 0x00c00000n; +const WS_THICKFRAME = 0x00040000n; +const WS_MAXIMIZEBOX = 0x00010000n; const WM_SYSCOMMAND = 0x0112; const SC_CLOSE = 0xf060; @@ -36,7 +41,7 @@ describe.skipIf(!isWindows)('NativeWin32Window on Windows', () => { } }); - test('show()/hide() toggle visibility; setTitle and client size work', () => { + test('show()/hide() toggle visibility and the client size is positive', () => { const win = new NativeWin32Window({ title: 'Vis', width: 320, height: 240, show: false }); try { expect(win.isVisible()).toBe(false); @@ -44,7 +49,6 @@ describe.skipIf(!isWindows)('NativeWin32Window on Windows', () => { expect(win.isVisible()).toBe(true); win.hide(); expect(win.isVisible()).toBe(false); - expect(() => win.setTitle('Renamed')).not.toThrow(); const size = win.getClientSize(); expect(size.width).toBeGreaterThan(0); expect(size.height).toBeGreaterThan(0); @@ -53,7 +57,7 @@ describe.skipIf(!isWindows)('NativeWin32Window on Windows', () => { } }); - test('creates frameless and non-resizable windows (the style branches)', () => { + test('frame:false is a captionless popup; resizable:false drops the sizing frame', () => { const a = new NativeWin32Window({ title: 'F', width: 400, @@ -68,9 +72,13 @@ describe.skipIf(!isWindows)('NativeWin32Window on Windows', () => { show: false, resizable: false, }); + const style = (win: NativeWin32Window): bigint => + loadUser32().symbols.GetWindowLongPtrW(win.hwnd(), GWL_STYLE); try { - expect(a.hwnd()).not.toBe(0n); - expect(b.hwnd()).not.toBe(0n); + expect(style(a) & WS_POPUP).toBe(WS_POPUP); + expect(style(a) & WS_CAPTION).toBe(0n); + expect(style(b) & WS_CAPTION).toBe(WS_CAPTION); + expect(style(b) & (WS_THICKFRAME | WS_MAXIMIZEBOX)).toBe(0n); } finally { a.destroy(); b.destroy(); From bd3ceca66df4cd70ec111ba40ca4d4db9401707b Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:54:35 -0700 Subject: [PATCH 088/586] fix: show macOS notification banners while the app is frontmost --- src/main/platform/macos/cocoa-notification.ts | 24 +++++++++++++++++++ .../macos/cocoa-notification.test.ts | 16 ++++++++++++- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/src/main/platform/macos/cocoa-notification.ts b/src/main/platform/macos/cocoa-notification.ts index 50ebd910..b20d71e6 100644 --- a/src/main/platform/macos/cocoa-notification.ts +++ b/src/main/platform/macos/cocoa-notification.ts @@ -6,6 +6,7 @@ import type { import { nsString } from './cocoa-foundation'; import { msgSendPtr } from './cocoa-msgsend-variants'; import { cocoa } from './cocoa-runtime'; +import { defineObjcClass } from './cocoa-runtime-class'; import type { Handle } from './objc'; /** @@ -41,6 +42,28 @@ const defaultCenter = (): Handle => { ); }; +let delegate: Handle | undefined; + +/** The center holds its delegate weakly, so this one lives for the process. */ +export const notificationDelegate = (): Handle => { + if (delegate !== undefined) { + return delegate; + } + const rt = cocoa(); + const cls = defineObjcClass('BunmaskaNotificationDelegate', 'NSObject', [ + { + // Without a YES here AppKit skips the banner while the app is frontmost. + selector: 'userNotificationCenter:shouldPresentNotification:', + typeEncoding: 'c@:@@', + args: ['object', 'object'], + returns: 'bool', + impl: () => 1, + }, + ]); + delegate = rt.msgSend(rt.msgSend(cls, rt.selectors.get('alloc')), rt.selectors.get('init')); + return delegate; +}; + const buildNotification = (spec: NotificationSpec): Handle => { const rt = cocoa(); const notification = rt.msgSend( @@ -74,6 +97,7 @@ const present = (spec: NotificationSpec): NotificationHandle => { const notification = buildNotification(spec); const center = defaultCenter(); if (center !== 0n) { + msgSendPtr(center, rt.selectors.get('setDelegate:'), notificationDelegate()); msgSendPtr(center, rt.selectors.get('deliverNotification:'), notification); } return { diff --git a/tests/integration/macos/cocoa-notification.test.ts b/tests/integration/macos/cocoa-notification.test.ts index 4230a98c..9518c9a2 100644 --- a/tests/integration/macos/cocoa-notification.test.ts +++ b/tests/integration/macos/cocoa-notification.test.ts @@ -1,6 +1,10 @@ import { describe, expect, test } from 'bun:test'; import { currentPlatform } from '../../../src/common/platform'; -import { macosNotificationBackend } from '../../../src/main/platform/macos/cocoa-notification'; +import { msgSendPtrPtr } from '../../../src/main/platform/macos/cocoa-msgsend-variants'; +import { + macosNotificationBackend, + notificationDelegate, +} from '../../../src/main/platform/macos/cocoa-notification'; import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; const isMac = currentPlatform() === 'macos'; @@ -24,4 +28,14 @@ describe.skipIf(!isMac)('cocoa-notification', () => { const bundled = rt.msgSend(bundle, rt.selectors.get('bundleIdentifier')) !== 0n; expect(macosNotificationBackend.isSupported()).toBe(bundled); }); + + test('the center delegate asks AppKit to show banners while the app is frontmost', () => { + const shouldPresent = msgSendPtrPtr( + notificationDelegate(), + cocoa().selectors.get('userNotificationCenter:shouldPresentNotification:'), + 0n, + 0n, + ); + expect(shouldPresent & 0xffn).toBe(1n); + }); }); From 63a09117c7a7c69201a7467a9c178640ee85b641 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:54:50 -0700 Subject: [PATCH 089/586] fix: skip WebKit-native and malformed schemes instead of aborting --- src/main/platform/macos/cocoa-backend.ts | 25 ++++++++++++++----- tests/integration/macos/cocoa-backend.test.ts | 18 +++++++++++++ 2 files changed, 37 insertions(+), 6 deletions(-) diff --git a/src/main/platform/macos/cocoa-backend.ts b/src/main/platform/macos/cocoa-backend.ts index e972b654..654bc499 100644 --- a/src/main/platform/macos/cocoa-backend.ts +++ b/src/main/platform/macos/cocoa-backend.ts @@ -161,13 +161,15 @@ const enableDeveloperExtras = (preferences: Handle): void => { } }; +/** RFC 3986 scheme syntax. */ +const VALID_SCHEME = /^[a-z][a-z0-9+.-]*$/; + /** - * Register every scheme currently registered with the `protocol` module onto a - * `WKWebViewConfiguration` via `setURLSchemeHandler:forURLScheme:`. Must run - * BEFORE the web view is created from this config (WebKit forbids adding a - * scheme handler afterwards). One shared handler serves all schemes; a failure - * to register one scheme (e.g. a forbidden/built-in scheme) is logged and - * skipped so it cannot abort window creation. + * Put every `protocol.handle` scheme on `configuration`; WebKit only accepts + * scheme handlers before the web view exists. `setURLSchemeHandler:` raises an + * NSException for a scheme WebKit handles itself (https, file, ...) or a + * malformed one, and an NSException aborts Bun past any JS catch, so those are + * skipped up front. */ const registerCustomSchemes = (configuration: Handle): void => { const schemes = protocol.getRegisteredSchemes(); @@ -177,6 +179,17 @@ const registerCustomSchemes = (configuration: Handle): void => { const rt = cocoa(); const handler = createUrlSchemeHandler(); for (const scheme of schemes) { + const unsupported = + !VALID_SCHEME.test(scheme) || + msgSendPtrReturnsU8( + rt.classes.get('WKWebView'), + rt.selectors.get('handlesURLScheme:'), + nsString(scheme), + ) === 1; + if (unsupported) { + log.warn(`protocol.handle('${scheme}') is ignored on macOS: WebKit cannot intercept it`); + continue; + } try { msgSendPtrPtr( configuration, diff --git a/tests/integration/macos/cocoa-backend.test.ts b/tests/integration/macos/cocoa-backend.test.ts index d23d65d2..8e326dd8 100644 --- a/tests/integration/macos/cocoa-backend.test.ts +++ b/tests/integration/macos/cocoa-backend.test.ts @@ -1,5 +1,6 @@ import { describe, expect, jest, test } from 'bun:test'; import { currentPlatform } from '../../../src/common/platform'; +import { protocol } from '../../../src/main/api/protocol'; import { createMacOSApplication } from '../../../src/main/platform/macos/cocoa-backend'; import { retainedBlockCount } from '../../../src/main/platform/macos/cocoa-block'; import { nsStringToString } from '../../../src/main/platform/macos/cocoa-foundation'; @@ -392,6 +393,23 @@ if (currentPlatform() === 'macos') { } }); + test('a WebKit-native or malformed protocol.handle scheme does not abort window creation', () => { + const app = createMacOSApplication(); + app.start(); + const serve = () => ({ data: 'x' }); + protocol.handle('https', serve); + protocol.handle('my_app', serve); + try { + const win = app.createWindow({ width: 320, height: 240, title: 't', show: false }); + expect(win.getTitle()).toBe('t'); + win.destroy(); + } finally { + protocol.unhandle('https'); + protocol.unhandle('my_app'); + app.quit(); + } + }); + test('close fires the onClosed callback once', () => { const app = createMacOSApplication(); app.start(); From d161c47251570eda3403eb5b7ece0d33d85c02cf Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:55:01 -0700 Subject: [PATCH 090/586] refactor: declare each msgSend variant in one line --- .../platform/macos/cocoa-msgsend-variants.ts | 319 ++++-------------- 1 file changed, 63 insertions(+), 256 deletions(-) diff --git a/src/main/platform/macos/cocoa-msgsend-variants.ts b/src/main/platform/macos/cocoa-msgsend-variants.ts index 467e65d7..2329d594 100644 --- a/src/main/platform/macos/cocoa-msgsend-variants.ts +++ b/src/main/platform/macos/cocoa-msgsend-variants.ts @@ -3,6 +3,8 @@ import { dlopen } from '../dlopen'; import { cstr } from '../cstr'; import { type Handle, LIBOBJC_PATH, macOSLibraryAccessor } from './objc'; +const { u64, u8, i64, f64, cstring } = FFIType; + /** * Typed `objc_msgSend` variants for selectors whose signatures don't match * the zero-extra-arg form exposed on {@link CocoaRuntime}. @@ -39,155 +41,48 @@ export const RECT_F64: readonly FFIType.f64[] = new Array( rectPadding(process.arch) + 4, ).fill(FFIType.f64); -const INIT_WITH_CONTENT_RECT_VARIANT = { - objc_msgSend: { - args: [FFIType.u64, FFIType.u64, ...RECT_F64, FFIType.u64, FFIType.u64, FFIType.u8], - returns: FFIType.u64, - }, -} as const; - -const PTR_VARIANT = { - objc_msgSend: { - args: [FFIType.u64, FFIType.u64, FFIType.u64], - returns: FFIType.u64, - }, -} as const; - -const U8_VARIANT = { - objc_msgSend: { - args: [FFIType.u64, FFIType.u64, FFIType.u8], - returns: FFIType.u64, - }, -} as const; - -const F64_VARIANT = { - objc_msgSend: { - args: [FFIType.u64, FFIType.u64, FFIType.f64], - returns: FFIType.u64, - }, -} as const; - -const I64_VARIANT = { - objc_msgSend: { - args: [FFIType.u64, FFIType.u64, FFIType.i64], - returns: FFIType.u64, - }, -} as const; - -const RETURNS_U8_VARIANT = { - objc_msgSend: { - args: [FFIType.u64, FFIType.u64], - returns: FFIType.u8, - }, -} as const; - -const CSTR_VARIANT = { - objc_msgSend: { - args: [FFIType.u64, FFIType.u64, FFIType.cstring], - returns: FFIType.u64, - }, -} as const; - -const PTR_PTR_VARIANT = { - objc_msgSend: { - args: [FFIType.u64, FFIType.u64, FFIType.u64, FFIType.u64], - returns: FFIType.u64, - }, -} as const; - -const PTR3_VARIANT = { - objc_msgSend: { - args: [FFIType.u64, FFIType.u64, FFIType.u64, FFIType.u64, FFIType.u64], - returns: FFIType.u64, - }, -} as const; - -const RETURNS_I64_VARIANT = { - objc_msgSend: { - args: [FFIType.u64, FFIType.u64], - returns: FFIType.i64, - }, -} as const; - -const PTR_RETURNS_U8_VARIANT = { - objc_msgSend: { - args: [FFIType.u64, FFIType.u64, FFIType.u64], - returns: FFIType.u8, - }, -} as const; - -const FRAME_CONFIG_VARIANT = { - objc_msgSend: { - args: [FFIType.u64, FFIType.u64, ...RECT_F64, FFIType.u64], - returns: FFIType.u64, - }, -} as const; - -// (receiver, selector, NSRect by value (D018), BOOL) -> void. -const RECT_U8_VARIANT = { - objc_msgSend: { - args: [FFIType.u64, FFIType.u64, ...RECT_F64, FFIType.u8], - returns: FFIType.void, - }, -} as const; - -const SIZE_VARIANT = { - objc_msgSend: { - args: [FFIType.u64, FFIType.u64, FFIType.f64, FFIType.f64], - returns: FFIType.u64, - }, -} as const; - -// (receiver, selector, ptr, NSPoint{x,y} as two doubles (D018), ptr) -> BOOL. -// For -[NSMenu popUpMenuPositioningItem:atLocation:inView:]. -const PTR_POINT_PTR_RETURNS_U8_VARIANT = { - objc_msgSend: { - args: [FFIType.u64, FFIType.u64, FFIType.u64, FFIType.f64, FFIType.f64, FFIType.u64], - returns: FFIType.u8, - }, -} as const; - -const getInitWithContentRectLib = macOSLibraryAccessor('msgSendInitWithContentRect', () => - dlopen(LIBOBJC_PATH, INIT_WITH_CONTENT_RECT_VARIANT), -); - -const getRectU8Lib = macOSLibraryAccessor('msgSendRectU8', () => - dlopen(LIBOBJC_PATH, RECT_U8_VARIANT), -); - -const getPtrLib = macOSLibraryAccessor('msgSendPtr', () => dlopen(LIBOBJC_PATH, PTR_VARIANT)); - -const getU8Lib = macOSLibraryAccessor('msgSendU8', () => dlopen(LIBOBJC_PATH, U8_VARIANT)); - -const getF64Lib = macOSLibraryAccessor('msgSendF64', () => dlopen(LIBOBJC_PATH, F64_VARIANT)); - -const getI64Lib = macOSLibraryAccessor('msgSendI64', () => dlopen(LIBOBJC_PATH, I64_VARIANT)); - -const getReturnsU8Lib = macOSLibraryAccessor('msgSendReturnsU8', () => - dlopen(LIBOBJC_PATH, RETURNS_U8_VARIANT), -); - -const getCStrLib = macOSLibraryAccessor('msgSendCStr', () => dlopen(LIBOBJC_PATH, CSTR_VARIANT)); - -const getPtrPtrLib = macOSLibraryAccessor('msgSendPtrPtr', () => - dlopen(LIBOBJC_PATH, PTR_PTR_VARIANT), -); - -const getFrameConfigLib = macOSLibraryAccessor('msgSendInitWithFrameConfig', () => - dlopen(LIBOBJC_PATH, FRAME_CONFIG_VARIANT), -); - -const getPtr3Lib = macOSLibraryAccessor('msgSendPtr3', () => dlopen(LIBOBJC_PATH, PTR3_VARIANT)); +/** One lazily opened `objc_msgSend` binding with its own signature. */ +const variant = ( + name: string, + args: Args, + returns: Returns, +) => { + const library = macOSLibraryAccessor(name, () => + dlopen(LIBOBJC_PATH, { objc_msgSend: { args, returns } }), + ); + return () => library().symbols.objc_msgSend; +}; -const getReturnsI64Lib = macOSLibraryAccessor('msgSendReturnsI64', () => - dlopen(LIBOBJC_PATH, RETURNS_I64_VARIANT), +const initWithContentRect = variant( + 'msgSendInitWithContentRect', + [u64, u64, ...RECT_F64, u64, u64, u8], + u64, ); - -const getPtrReturnsU8Lib = macOSLibraryAccessor('msgSendPtrReturnsU8', () => - dlopen(LIBOBJC_PATH, PTR_RETURNS_U8_VARIANT), +const rectU8 = variant('msgSendRectU8', [u64, u64, ...RECT_F64, u8], FFIType.void); +const ptr1 = variant('msgSendPtr', [u64, u64, u64], u64); +const u8Arg = variant('msgSendU8', [u64, u64, u8], u64); +const f64Arg = variant('msgSendF64', [u64, u64, f64], u64); +const i64Arg = variant('msgSendI64', [u64, u64, i64], u64); +const returnsU8 = variant('msgSendReturnsU8', [u64, u64], u8); +const cstrArg = variant('msgSendCStr', [u64, u64, cstring], u64); +const ptr2 = variant('msgSendPtrPtr', [u64, u64, u64, u64], u64); +const frameConfig = variant('msgSendInitWithFrameConfig', [u64, u64, ...RECT_F64, u64], u64); +const ptr3 = variant('msgSendPtr3', [u64, u64, u64, u64, u64], u64); +const returnsI64 = variant('msgSendReturnsI64', [u64, u64], i64); +const ptrReturnsU8 = variant('msgSendPtrReturnsU8', [u64, u64, u64], u8); +const size = variant('msgSendSize', [u64, u64, f64, f64], u64); +const ptrPointPtrReturnsU8 = variant( + 'msgSendPtrPointPtrReturnsU8', + [u64, u64, u64, f64, f64, u64], + u8, ); - -const getSizeLib = macOSLibraryAccessor('msgSendSize', () => dlopen(LIBOBJC_PATH, SIZE_VARIANT)); +const ptr4 = variant('msgSendPtr4', [u64, u64, u64, u64, u64, u64], u64); +const ptrI64U8Ptr = variant('msgSendPtrI64U8Ptr', [u64, u64, u64, i64, u8, u64], u64); +const ptrI64 = variant('msgSendPtrI64', [u64, u64, u64, i64], u64); +const i64Ptr = variant('msgSendI64Ptr', [u64, u64, i64, u64], u64); +const returnsF64 = variant('msgSendReturnsF64', [u64, u64], f64); +const ptrI64Ptr = variant('msgSendPtrI64Ptr', [u64, u64, u64, i64, u64], u64); +const ptrPtrI64Ptr = variant('msgSendPtrPtrI64Ptr', [u64, u64, u64, u64, i64, u64], u64); /** Send `initWithContentRect:styleMask:backing:defer:`; the rect goes by value (D018). */ export const msgSendInitWithContentRect = ( @@ -198,14 +93,7 @@ export const msgSendInitWithContentRect = ( backing: Handle, defer: boolean, ): Handle => - getInitWithContentRectLib().symbols.objc_msgSend( - receiver, - selector, - ...cgRectArgs(rect), - styleMask, - backing, - defer ? 1 : 0, - ); + initWithContentRect()(receiver, selector, ...cgRectArgs(rect), styleMask, backing, defer ? 1 : 0); /** Send a message with an NSRect by value (D018) plus a trailing BOOL. */ export const msgSendRectU8 = ( @@ -214,36 +102,36 @@ export const msgSendRectU8 = ( rect: CGRectArgs, flag: boolean, ): void => { - getRectU8Lib().symbols.objc_msgSend(receiver, selector, ...cgRectArgs(rect), flag ? 1 : 0); + rectU8()(receiver, selector, ...cgRectArgs(rect), flag ? 1 : 0); }; export const msgSendPtr = (receiver: Handle, selector: Handle, arg: Handle): Handle => - getPtrLib().symbols.objc_msgSend(receiver, selector, arg); + ptr1()(receiver, selector, arg); /** Send a message with one extra `BOOL` arg: pass `0` (NO) or `1` (YES). */ export const msgSendU8 = (receiver: Handle, selector: Handle, arg: number): Handle => - getU8Lib().symbols.objc_msgSend(receiver, selector, arg); + u8Arg()(receiver, selector, arg); export const msgSendF64 = (receiver: Handle, selector: Handle, arg: number): Handle => - getF64Lib().symbols.objc_msgSend(receiver, selector, arg); + f64Arg()(receiver, selector, arg); export const msgSendI64 = (receiver: Handle, selector: Handle, arg: bigint): Handle => - getI64Lib().symbols.objc_msgSend(receiver, selector, arg); + i64Arg()(receiver, selector, arg); /** Send a zero-extra-arg message returning `BOOL`: 0 (NO) or 1 (YES). */ export const msgSendReturnsU8 = (receiver: Handle, selector: Handle): number => - getReturnsU8Lib().symbols.objc_msgSend(receiver, selector); + returnsU8()(receiver, selector); /** Send a message with one extra C-string arg; the text is encoded null-terminated. */ export const msgSendCStr = (receiver: Handle, selector: Handle, text: string): Handle => - getCStrLib().symbols.objc_msgSend(receiver, selector, cstr(text)); + cstrArg()(receiver, selector, cstr(text)); export const msgSendPtrPtr = ( receiver: Handle, selector: Handle, arg0: Handle, arg1: Handle, -): Handle => getPtrPtrLib().symbols.objc_msgSend(receiver, selector, arg0, arg1); +): Handle => ptr2()(receiver, selector, arg0, arg1); /** Send `initWithFrame:configuration:`; the rect goes by value (D018). */ export const msgSendInitWithFrameConfig = ( @@ -251,8 +139,7 @@ export const msgSendInitWithFrameConfig = ( selector: Handle, frame: CGRectArgs, configuration: Handle, -): Handle => - getFrameConfigLib().symbols.objc_msgSend(receiver, selector, ...cgRectArgs(frame), configuration); +): Handle => frameConfig()(receiver, selector, ...cgRectArgs(frame), configuration); export const msgSendPtr3 = ( receiver: Handle, @@ -260,14 +147,14 @@ export const msgSendPtr3 = ( arg0: Handle, arg1: Handle, arg2: Handle, -): Handle => getPtr3Lib().symbols.objc_msgSend(receiver, selector, arg0, arg1, arg2); +): Handle => ptr3()(receiver, selector, arg0, arg1, arg2); export const msgSendReturnsI64 = (receiver: Handle, selector: Handle): bigint => - getReturnsI64Lib().symbols.objc_msgSend(receiver, selector); + returnsI64()(receiver, selector); /** Send a message with one extra pointer arg, returning `BOOL`: 0 (NO) or 1 (YES). */ export const msgSendPtrReturnsU8 = (receiver: Handle, selector: Handle, arg: Handle): number => - getPtrReturnsU8Lib().symbols.objc_msgSend(receiver, selector, arg); + ptrReturnsU8()(receiver, selector, arg); /** * Send a message with an `NSSize`/`CGSize` arg (two `double`s by value), e.g. @@ -278,11 +165,7 @@ export const msgSendSize = ( selector: Handle, width: number, height: number, -): Handle => getSizeLib().symbols.objc_msgSend(receiver, selector, width, height); - -const getPtrPointPtrReturnsU8Lib = macOSLibraryAccessor('msgSendPtrPointPtrReturnsU8', () => - dlopen(LIBOBJC_PATH, PTR_POINT_PTR_RETURNS_U8_VARIANT), -); +): Handle => size()(receiver, selector, width, height); /** * Send a message taking a pointer, an `NSPoint` (two `double`s BY VALUE — the @@ -297,17 +180,7 @@ export const msgSendPtrPointPtrReturnsU8 = ( x: number, y: number, view: Handle, -): number => - getPtrPointPtrReturnsU8Lib().symbols.objc_msgSend(receiver, selector, item, x, y, view); - -const PTR4_VARIANT = { - objc_msgSend: { - args: [FFIType.u64, FFIType.u64, FFIType.u64, FFIType.u64, FFIType.u64, FFIType.u64], - returns: FFIType.u64, - }, -} as const; - -const getPtr4Lib = macOSLibraryAccessor('msgSendPtr4', () => dlopen(LIBOBJC_PATH, PTR4_VARIANT)); +): number => ptrPointPtrReturnsU8()(receiver, selector, item, x, y, view); /** * Send a message with four extra pointer-sized args — specifically @@ -322,18 +195,7 @@ export const msgSendPtr4 = ( arg1: Handle, arg2: Handle, arg3: Handle, -): Handle => getPtr4Lib().symbols.objc_msgSend(receiver, selector, arg0, arg1, arg2, arg3); - -const PTR_I64_U8_PTR_VARIANT = { - objc_msgSend: { - args: [FFIType.u64, FFIType.u64, FFIType.u64, FFIType.i64, FFIType.u8, FFIType.u64], - returns: FFIType.u64, - }, -} as const; - -const getPtrI64U8PtrLib = macOSLibraryAccessor('msgSendPtrI64U8Ptr', () => - dlopen(LIBOBJC_PATH, PTR_I64_U8_PTR_VARIANT), -); +): Handle => ptr4()(receiver, selector, arg0, arg1, arg2, arg3); /** * Send a message with a pointer arg, an `NSInteger` arg, a `BOOL` arg, and a @@ -348,18 +210,7 @@ export const msgSendPtrI64U8Ptr = ( arg1: bigint, arg2: number, arg3: Handle, -): Handle => getPtrI64U8PtrLib().symbols.objc_msgSend(receiver, selector, arg0, arg1, arg2, arg3); - -const PTR_I64_VARIANT = { - objc_msgSend: { - args: [FFIType.u64, FFIType.u64, FFIType.u64, FFIType.i64], - returns: FFIType.u64, - }, -} as const; - -const getPtrI64Lib = macOSLibraryAccessor('msgSendPtrI64', () => - dlopen(LIBOBJC_PATH, PTR_I64_VARIANT), -); +): Handle => ptrI64U8Ptr()(receiver, selector, arg0, arg1, arg2, arg3); /** * Send a message with a pointer arg and an `NSInteger`/`NSUInteger` arg — @@ -371,18 +222,7 @@ export const msgSendPtrI64 = ( selector: Handle, arg0: Handle, arg1: bigint, -): Handle => getPtrI64Lib().symbols.objc_msgSend(receiver, selector, arg0, arg1); - -const I64_PTR_VARIANT = { - objc_msgSend: { - args: [FFIType.u64, FFIType.u64, FFIType.i64, FFIType.u64], - returns: FFIType.u64, - }, -} as const; - -const getI64PtrLib = macOSLibraryAccessor('msgSendI64Ptr', () => - dlopen(LIBOBJC_PATH, I64_PTR_VARIANT), -); +): Handle => ptrI64()(receiver, selector, arg0, arg1); /** * Send a message with an `NSInteger` arg followed by a trailing pointer arg — @@ -395,18 +235,7 @@ export const msgSendI64Ptr = ( selector: Handle, arg0: bigint, arg1: Handle, -): Handle => getI64PtrLib().symbols.objc_msgSend(receiver, selector, arg0, arg1); - -const RETURNS_F64_VARIANT = { - objc_msgSend: { - args: [FFIType.u64, FFIType.u64], - returns: FFIType.f64, - }, -} as const; - -const getReturnsF64Lib = macOSLibraryAccessor('msgSendReturnsF64', () => - dlopen(LIBOBJC_PATH, RETURNS_F64_VARIANT), -); +): Handle => i64Ptr()(receiver, selector, arg0, arg1); /** * Send a zero-extra-arg message returning a C `double` — e.g. `-[NSDate @@ -415,18 +244,7 @@ const getReturnsF64Lib = macOSLibraryAccessor('msgSendReturnsF64', () => * for `long double` there) - no fpret variant needed. */ export const msgSendReturnsF64 = (receiver: Handle, selector: Handle): number => - getReturnsF64Lib().symbols.objc_msgSend(receiver, selector); - -const PTR_I64_PTR_VARIANT = { - objc_msgSend: { - args: [FFIType.u64, FFIType.u64, FFIType.u64, FFIType.i64, FFIType.u64], - returns: FFIType.u64, - }, -} as const; - -const getPtrI64PtrLib = macOSLibraryAccessor('msgSendPtrI64Ptr', () => - dlopen(LIBOBJC_PATH, PTR_I64_PTR_VARIANT), -); + returnsF64()(receiver, selector); /** * Send a message with a pointer arg, an `NSInteger` arg, and a trailing pointer @@ -439,18 +257,7 @@ export const msgSendPtrI64Ptr = ( arg0: Handle, arg1: bigint, arg2: Handle, -): Handle => getPtrI64PtrLib().symbols.objc_msgSend(receiver, selector, arg0, arg1, arg2); - -const PTR_PTR_I64_PTR_VARIANT = { - objc_msgSend: { - args: [FFIType.u64, FFIType.u64, FFIType.u64, FFIType.u64, FFIType.i64, FFIType.u64], - returns: FFIType.u64, - }, -} as const; - -const getPtrPtrI64PtrLib = macOSLibraryAccessor('msgSendPtrPtrI64Ptr', () => - dlopen(LIBOBJC_PATH, PTR_PTR_I64_PTR_VARIANT), -); +): Handle => ptrI64Ptr()(receiver, selector, arg0, arg1, arg2); /** * Send a message with two pointer args, an `NSInteger` arg, and a trailing @@ -465,4 +272,4 @@ export const msgSendPtrPtrI64Ptr = ( arg1: Handle, arg2: bigint, arg3: Handle, -): Handle => getPtrPtrI64PtrLib().symbols.objc_msgSend(receiver, selector, arg0, arg1, arg2, arg3); +): Handle => ptrPtrI64Ptr()(receiver, selector, arg0, arg1, arg2, arg3); From 57d884a35e63d5649cce8e588c80cc6283fff5c3 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:55:04 -0700 Subject: [PATCH 091/586] refactor: remove dead Linux signal exports and URI-scheme test seams --- src/main/platform/linux/gtk-signals.ts | 16 ---- src/main/platform/linux/webkit-ipc.ts | 61 ++++++-------- src/main/platform/linux/webkit-uri-scheme.ts | 24 +----- .../main/platform/linux/gtk-signals.test.ts | 79 +++---------------- .../platform/linux/webkit-uri-scheme.test.ts | 53 ++----------- 5 files changed, 40 insertions(+), 193 deletions(-) diff --git a/src/main/platform/linux/gtk-signals.ts b/src/main/platform/linux/gtk-signals.ts index 840ae3ac..955f43b4 100644 --- a/src/main/platform/linux/gtk-signals.ts +++ b/src/main/platform/linux/gtk-signals.ts @@ -47,8 +47,6 @@ export const guarded = /** ABI shape for `GtkWindow::close-request`: `(self, user_data) -> gboolean`. */ export const CLOSE_REQUEST_CB_DEF = { args: ['ptr', 'ptr'], returns: 'i32' } as const; -/** ABI shape for `GtkWidget::destroy`: `(self, user_data) -> void`. */ -export const DESTROY_CB_DEF = { args: ['ptr', 'ptr'], returns: 'void' } as const; /** ABI shape for `WebKitWebView::load-changed`: `(self, load_event, user_data) -> void`. */ export const LOAD_CHANGED_CB_DEF = { args: ['ptr', 'i32', 'ptr'], returns: 'void' } as const; /** ABI shape for `WebKitWebView::load-failed`: `(self, load_event, uri, error, user_data) -> gboolean`. */ @@ -104,15 +102,6 @@ export const makeNotifyCallback = (onNotify: () => void): JSCallback => NOTIFY_CB_DEF, ); -/** - * `GtkWidget::destroy` handler. Fires `onClosed` bookkeeping + drops retained - * refs; performs no further GTK calls on self. - */ -export const makeDestroyCallback = (onClosed: () => void): JSCallback => - new JSCallback((_self: Pointer, _userData: Pointer): void => { - onClosed(); - }, DESTROY_CB_DEF); - /** * `load-changed` + `load-failed` handlers sharing one failed flag: WebKitGTK always * emits `load-changed` FINISHED right after `load-failed`, and that FINISHED must @@ -282,11 +271,6 @@ export class SignalRegistry { return connection; } - /** The number of retained connections (for tests + teardown bookkeeping). */ - get size(): number { - return this.#connections.length; - } - /** * Disconnect every handler synchronously (no more signals fire), then close * the callback thunks on a LATER tick via {@link deferCallbackClose} — safe to diff --git a/src/main/platform/linux/webkit-ipc.ts b/src/main/platform/linux/webkit-ipc.ts index 15ea5abe..eed35c34 100644 --- a/src/main/platform/linux/webkit-ipc.ts +++ b/src/main/platform/linux/webkit-ipc.ts @@ -46,18 +46,18 @@ export type WebViewIpcOptions = { /** The preload bridge source injected at document-start in the isolated world. */ readonly preloadSource: string; readonly userPreloadSource?: string; - readonly isolatedSetupSource?: string; - readonly isolatedHostSource?: string; - readonly pageWorldSource?: string; + readonly isolatedSetupSource: string; + readonly isolatedHostSource: string; + readonly pageWorldSource: string; /** Called with each JSON envelope the renderer posts. */ readonly onMessage: (json: string) => void; /** * Called with each JSON `{ execId, ok, result?, error? }` the page-world * `executeJavaScript` wrapper posts to the `bunmaskaExec` handler. Optional. */ - readonly onExecMessage?: (json: string) => void; + readonly onExecMessage: (json: string) => void; /** Called when the page-world dom-ready script fires (DOMContentLoaded). Optional. */ - readonly onDomReady?: () => void; + readonly onDomReady: () => void; }; const requirePointer = (ptr: Pointer | null, what: string): Pointer => { @@ -125,50 +125,39 @@ export const createWebViewWithIpc = (options: WebViewIpcOptions): WiredWebView = // JSCallback is retained in the SAME registry so it is closed on window // teardown — NEVER per-call (closing a JSCallback mid-invocation frees its // native trampoline). Connect the detailed signal BEFORE registering (race). - if (options.onExecMessage !== undefined) { - const execCallback = makeScriptMessageCallback(options.onExecMessage); - registry.connect(ucm, EXEC_SIGNAL, execCallback); - webkit.symbols.webkit_user_content_manager_register_script_message_handler( - ucm, - cstr(EXEC_HANDLER_NAME), - null, - ); - } + registry.connect(ucm, EXEC_SIGNAL, makeScriptMessageCallback(options.onExecMessage)); + webkit.symbols.webkit_user_content_manager_register_script_message_handler( + ucm, + cstr(EXEC_HANDLER_NAME), + null, + ); // Page-world dom-ready handler: the injected script posts here on // DOMContentLoaded. Same retain/connect-before-register discipline as exec. - if (options.onDomReady !== undefined) { - const onDomReady = options.onDomReady; - const domReadyCallback = makeScriptMessageCallback(() => onDomReady()); - registry.connect(ucm, `script-message-received::${DOM_READY_HANDLER_NAME}`, domReadyCallback); - webkit.symbols.webkit_user_content_manager_register_script_message_handler( - ucm, - cstr(DOM_READY_HANDLER_NAME), - null, - ); - } + registry.connect( + ucm, + `script-message-received::${DOM_READY_HANDLER_NAME}`, + makeScriptMessageCallback(() => options.onDomReady()), + ); + webkit.symbols.webkit_user_content_manager_register_script_message_handler( + ucm, + cstr(DOM_READY_HANDLER_NAME), + null, + ); // Isolated world: channel-id setup (if any) BEFORE the bridge, then the // bridge, then the contextBridge host (installs exposeInMainWorld), then the // user preload (so it can call exposeInMainWorld). - if (options.isolatedSetupSource !== undefined) { - addUserScript(ucm, options.isolatedSetupSource); - } + addUserScript(ucm, options.isolatedSetupSource); addUserScript(ucm, options.preloadSource); - if (options.isolatedHostSource !== undefined) { - addUserScript(ucm, options.isolatedHostSource); - } + addUserScript(ucm, options.isolatedHostSource); if (options.userPreloadSource !== undefined) { addUserScript(ucm, options.userPreloadSource); } // Page/main world: the cross-world contextBridge stub (Phase B). - if (options.pageWorldSource !== undefined) { - addPageWorldScript(ucm, options.pageWorldSource); - } + addPageWorldScript(ucm, options.pageWorldSource); // Page/main world: the dom-ready notifier (posts on DOMContentLoaded). - if (options.onDomReady !== undefined) { - addPageWorldScript(ucm, generateDomReadyScript()); - } + addPageWorldScript(ucm, generateDomReadyScript()); const view = requirePointer( gobject.symbols.g_object_new( diff --git a/src/main/platform/linux/webkit-uri-scheme.ts b/src/main/platform/linux/webkit-uri-scheme.ts index af32e54c..314a3976 100644 --- a/src/main/platform/linux/webkit-uri-scheme.ts +++ b/src/main/platform/linux/webkit-uri-scheme.ts @@ -30,28 +30,6 @@ const retainedCallbacks = new Set(); /** Schemes already registered on the (single, default) context — dedup guard. */ const registeredSchemes = new Set(); -/** - * The dispatcher the callback uses to serve a URI. Defaults to the live - * {@link protocol.dispatch}; overridable for unit tests. - */ -let dispatcher: (url: string) => BuiltProtocolResponse | undefined = protocol.dispatch; - -/** Override the URI dispatcher. Test-only. */ -export const setUriSchemeDispatcherForTesting = ( - fake: ((url: string) => BuiltProtocolResponse | undefined) | undefined, -): void => { - dispatcher = fake ?? protocol.dispatch; -}; - -/** Reset the registration guard + drop retained callbacks. Test-only. */ -export const resetUriSchemeRegistryForTesting = (): void => { - for (const callback of retainedCallbacks) { - callback.close(); - } - retainedCallbacks.clear(); - registeredSchemes.clear(); -}; - /** Read the (transfer-none) request URI as a JS string. */ const requestUri = (request: Pointer): string => { const webkit = loadWebKitGtkFFI(); @@ -127,7 +105,7 @@ const finishWithBytes = (request: Pointer, built: BuiltProtocolResponse): void = export const handleUriSchemeRequest = (request: Pointer): void => { try { const url = requestUri(request); - const built = dispatcher(url); + const built = protocol.dispatch(url); if (built === undefined) { finishError(request); return; diff --git a/tests/unit/main/platform/linux/gtk-signals.test.ts b/tests/unit/main/platform/linux/gtk-signals.test.ts index 5f081d30..11e5b146 100644 --- a/tests/unit/main/platform/linux/gtk-signals.test.ts +++ b/tests/unit/main/platform/linux/gtk-signals.test.ts @@ -1,21 +1,17 @@ import { CFunction, type FFITypeOrString, type JSCallback, type Pointer, ptr } from 'bun:ffi'; -import { describe, expect, it, test } from 'bun:test'; +import { describe, expect, test } from 'bun:test'; import { type LogRecord, resetLogger, setLogSink } from '../../../../../src/common/logger'; import type { NativeNavigationEvent } from '../../../../../src/main/platform/native'; import { CLOSE_REQUEST_CB_DEF, closeRequestDecision, - CREATE_CB_DEF, deferCallbackClose, - DESTROY_CB_DEF, LOAD_CHANGED_CB_DEF, LOAD_FAILED_CB_DEF, makeCloseRequestCallback, makeLoadCallbacks, makeNotifyCallback, NOTIFY_CB_DEF, - SCRIPT_MESSAGE_CB_DEF, - SignalRegistry, } from '../../../../../src/main/platform/linux/gtk-signals'; import { WEBKIT_LOAD_COMMITTED, @@ -23,8 +19,6 @@ import { WEBKIT_LOAD_STARTED, } from '../../../../../src/main/platform/linux/webkitgtk-ffi'; -const noop = (): void => undefined; - /** Invoke a JSCallback through its native thunk, as GLib would. */ const nativeCall = ( cb: JSCallback, @@ -36,68 +30,22 @@ const nativeCall = ( return CFunction({ ptr: cb.ptr, args: [...def.args], returns: def.returns }); }; -describe('gtk-signals callback ABI definitions (shape-only)', () => { - it('close-request returns i32 (inverted gboolean) with two pointer args', () => { - expect(CLOSE_REQUEST_CB_DEF.args).toEqual(['ptr', 'ptr']); +describe('signal ABI gotchas', () => { + test('gboolean returns are i32, not bool (close-request, load-failed)', () => { expect(CLOSE_REQUEST_CB_DEF.returns).toBe('i32'); - }); - - it('destroy is (ptr, ptr) -> void', () => { - expect(DESTROY_CB_DEF.args).toEqual(['ptr', 'ptr']); - expect(DESTROY_CB_DEF.returns).toBe('void'); - }); - - it('load-changed second arg is i32 (the WebKitLoadEvent)', () => { - expect(LOAD_CHANGED_CB_DEF.args).toEqual(['ptr', 'i32', 'ptr']); - expect(LOAD_CHANGED_CB_DEF.args[1]).toBe('i32'); - expect(LOAD_CHANGED_CB_DEF.returns).toBe('void'); - }); - - it('load-failed is (self, load_event, uri, error, user_data) -> i32', () => { - expect(LOAD_FAILED_CB_DEF.args).toEqual(['ptr', 'i32', 'ptr', 'ptr', 'ptr']); expect(LOAD_FAILED_CB_DEF.returns).toBe('i32'); }); - it('create is (self, navigation_action, user_data) -> ptr (the new view or NULL)', () => { - expect(CREATE_CB_DEF.args).toEqual(['ptr', 'ptr', 'ptr']); - expect(CREATE_CB_DEF.returns).toBe('ptr'); - }); - - it('script-message takes three pointers (WK6.0 JSCValue* direct)', () => { - expect(SCRIPT_MESSAGE_CB_DEF.args).toEqual(['ptr', 'ptr', 'ptr']); - expect(SCRIPT_MESSAGE_CB_DEF.returns).toBe('void'); - }); - - it('notify is (gobject, pspec, user_data) -> void: three pointers', () => { - expect(NOTIFY_CB_DEF.args).toEqual(['ptr', 'ptr', 'ptr']); - expect(NOTIFY_CB_DEF.returns).toBe('void'); + test('load-changed passes the WebKitLoadEvent enum as an i32, not a pointer', () => { + expect(LOAD_CHANGED_CB_DEF.args[1]).toBe('i32'); }); -}); -describe('closeRequestDecision (preventable close, GTK semantics)', () => { - it('returns 1 (veto, stay open) when the close request is vetoed', () => { + test('close-request returns 1 to veto (window stays) and 0 to let GTK destroy', () => { expect(closeRequestDecision(() => true)).toBe(1); - }); - - it('returns 0 (allow GTK to destroy) when not vetoed', () => { expect(closeRequestDecision(() => false)).toBe(0); }); }); -describe('gtk-signals JSCallback factories (constructible + closable)', () => { - it('builds a close-request callback exposing a native ptr', () => { - const cb = makeCloseRequestCallback(() => false); - expect(typeof cb.ptr).toBe('number'); - cb.close(); - }); - - it('builds a notify callback exposing a native ptr', () => { - const cb = makeNotifyCallback(noop); - expect(typeof cb.ptr).toBe('number'); - cb.close(); - }); -}); - describe('a throwing handler never unwinds into GLib', () => { const boom = (): never => { throw new Error('boom'); @@ -206,17 +154,8 @@ describe('makeLoadCallbacks', () => { }); }); -describe('SignalRegistry', () => { - it('starts empty and disconnectAll is a no-op when empty', () => { - const registry = new SignalRegistry(); - expect(registry.size).toBe(0); - expect(() => registry.disconnectAll()).not.toThrow(); - expect(registry.size).toBe(0); - }); -}); - describe('deferCallbackClose (never close a thunk inside its own invocation)', () => { - it('does not close synchronously; closes only when the scheduled task runs', () => { + test('does not close synchronously; closes only when the scheduled task runs', () => { let closed = 0; const cb = { close: () => (closed += 1) }; let scheduled: (() => void) | undefined; @@ -228,7 +167,7 @@ describe('deferCallbackClose (never close a thunk inside its own invocation)', ( expect(closed).toBe(1); }); - it('is a no-op (does not schedule) for an empty list', () => { + test('is a no-op (does not schedule) for an empty list', () => { let scheduledCount = 0; deferCallbackClose([], () => { scheduledCount += 1; @@ -236,7 +175,7 @@ describe('deferCallbackClose (never close a thunk inside its own invocation)', ( expect(scheduledCount).toBe(0); }); - it('closes every callback in the batch on the deferred tick', () => { + test('closes every callback in the batch on the deferred tick', () => { const closes: number[] = []; const cbs = [0, 1, 2].map((i) => ({ close: () => closes.push(i) })); let scheduled: (() => void) | undefined; diff --git a/tests/unit/main/platform/linux/webkit-uri-scheme.test.ts b/tests/unit/main/platform/linux/webkit-uri-scheme.test.ts index af78574d..94ca9709 100644 --- a/tests/unit/main/platform/linux/webkit-uri-scheme.test.ts +++ b/tests/unit/main/platform/linux/webkit-uri-scheme.test.ts @@ -1,53 +1,10 @@ -import { describe, expect, it } from 'bun:test'; +import { describe, expect, test } from 'bun:test'; import { UnsupportedPlatformError } from '../../../../../src/common/errors'; import { currentPlatform } from '../../../../../src/common/platform'; -import { - registerAllSchemes, - registerUriScheme, - resetUriSchemeRegistryForTesting, - setUriSchemeDispatcherForTesting, - URI_SCHEME_CB_DEF, -} from '../../../../../src/main/platform/linux/webkit-uri-scheme'; +import { registerUriScheme } from '../../../../../src/main/platform/linux/webkit-uri-scheme'; -/** - * Host-safe unit tests for the Linux URI-scheme module. - * - * The native serve path needs a real WebKitGTK process, so the round-trip is - * proven by the CI-gated Linux integration test. Here we assert the module's - * exported seam, the callback ABI shape (pure JS), and that registration refuses - * to run off Linux (every FFI entry throws {@link UnsupportedPlatformError}). - */ - -describe('URI_SCHEME_CB_DEF', () => { - it('declares the WebKitURISchemeRequestCallback shape (request, user_data) -> void', () => { - expect(URI_SCHEME_CB_DEF.args).toEqual(['ptr', 'ptr']); - expect(URI_SCHEME_CB_DEF.returns).toBe('void'); +describe.skipIf(currentPlatform() === 'linux')('registerUriScheme off Linux', () => { + test('throws UnsupportedPlatformError instead of touching a missing WebKitGTK', () => { + expect(() => registerUriScheme('app', null)).toThrow(UnsupportedPlatformError); }); }); - -describe('exports', () => { - it('exposes the registration + test seam functions', () => { - expect(typeof registerUriScheme).toBe('function'); - expect(typeof registerAllSchemes).toBe('function'); - expect(typeof setUriSchemeDispatcherForTesting).toBe('function'); - expect(typeof resetUriSchemeRegistryForTesting).toBe('function'); - }); - - it('setUriSchemeDispatcherForTesting accepts a fake and a reset', () => { - expect(() => setUriSchemeDispatcherForTesting(() => undefined)).not.toThrow(); - expect(() => setUriSchemeDispatcherForTesting(undefined)).not.toThrow(); - }); -}); - -if (currentPlatform() !== 'linux') { - describe('registerUriScheme off Linux', () => { - it('throws UnsupportedPlatformError (FFI is Linux-only)', () => { - expect(() => registerUriScheme('app', null)).toThrow(UnsupportedPlatformError); - }); - - it('registerAllSchemes is a no-op when no schemes are registered', () => { - // protocol has no schemes here; the loop body never runs, so no FFI. - expect(() => registerAllSchemes(null)).not.toThrow(); - }); - }); -} From cda744a9bde228018930cfe5b4c5c463851ea750 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:55:05 -0700 Subject: [PATCH 092/586] test: run buildDispatchScript instead of transcribing IPC constants --- .../main/platform/linux/webkit-ipc.test.ts | 58 +++++-------------- 1 file changed, 15 insertions(+), 43 deletions(-) diff --git a/tests/unit/main/platform/linux/webkit-ipc.test.ts b/tests/unit/main/platform/linux/webkit-ipc.test.ts index 48f9d88e..8515bb7e 100644 --- a/tests/unit/main/platform/linux/webkit-ipc.test.ts +++ b/tests/unit/main/platform/linux/webkit-ipc.test.ts @@ -1,50 +1,22 @@ -import { describe, expect, it } from 'bun:test'; -import { - buildDispatchScript, - EXEC_HANDLER_NAME, - EXEC_SIGNAL, - HANDLER_NAME, - PRELOAD_WORLD_NAME, - SIGNAL, -} from '../../../../../src/main/platform/linux/webkit-ipc'; +import { describe, expect, test } from 'bun:test'; +import { buildDispatchScript } from '../../../../../src/main/platform/linux/webkit-ipc'; -describe('webkit-ipc constants', () => { - it('posts to and registers the "bunmaska" handler name', () => { - expect(HANDLER_NAME).toBe('bunmaska'); - }); - - it('connects the detailed script-message-received::bunmaska signal', () => { - expect(SIGNAL).toBe('script-message-received::bunmaska'); - }); - - it('uses the BunmaskaPreload isolated world name (matches the macOS backend)', () => { - expect(PRELOAD_WORLD_NAME).toBe('BunmaskaPreload'); - }); - - it('uses the page-world "bunmaskaExec" exec return-channel handler (matches macOS)', () => { - expect(EXEC_HANDLER_NAME).toBe('bunmaskaExec'); - }); - - it('connects the detailed script-message-received::bunmaskaExec signal', () => { - expect(EXEC_SIGNAL).toBe('script-message-received::bunmaskaExec'); - }); -}); +/** Run a dispatch script against a fake `window`, as `evaluate_javascript` would. */ +const run = (script: string, window: unknown): void => { + new Function('window', script)(window); +}; describe('buildDispatchScript', () => { - it('calls __bunmaska._dispatch with a JS-string-escaped JSON envelope', () => { - const script = buildDispatchScript('{"a":1}'); - expect(script).toContain('window.__bunmaska._dispatch('); - expect(script).toContain(JSON.stringify('{"a":1}')); - }); - - it('escapes quotes and backslashes so the literal is valid JS', () => { - const envelope = '{"msg":"he said \\"hi\\""}'; - const script = buildDispatchScript(envelope); - expect(script).toContain(JSON.stringify(envelope)); - expect(() => new Function(`return ${JSON.stringify(envelope)};`)).not.toThrow(); + test('hands the exact envelope string to the isolated-world bridge', () => { + const envelope = '{"msg":"he said \\"hi\\"\\n\\u2028"}'; + const received: string[] = []; + run(buildDispatchScript(envelope), { + __bunmaska: { _dispatch: (json: string) => received.push(json) }, + }); + expect(received).toEqual([envelope]); }); - it('guards on window.__bunmaska before dispatching', () => { - expect(buildDispatchScript('{}')).toContain('window.__bunmaska &&'); + test('is a no-op before the bridge exists', () => { + expect(() => run(buildDispatchScript('{}'), {})).not.toThrow(); }); }); From 7b91d816742dea90078e7eae29da42552b501368 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:55:36 -0700 Subject: [PATCH 093/586] fix: register Plus and F16-F20 global shortcuts on macOS --- src/main/platform/macos/carbon-keymap.ts | 9 ++++++- .../macos/carbon-global-shortcut.test.ts | 6 ++++- .../main/platform/macos/carbon-keymap.test.ts | 27 ++++++++++++------- 3 files changed, 30 insertions(+), 12 deletions(-) diff --git a/src/main/platform/macos/carbon-keymap.ts b/src/main/platform/macos/carbon-keymap.ts index 398e1cc0..a69cd127 100644 --- a/src/main/platform/macos/carbon-keymap.ts +++ b/src/main/platform/macos/carbon-keymap.ts @@ -42,6 +42,7 @@ const VIRTUAL_KEY_CODES: ReadonlyMap = new Map([ ['6', 22], ['5', 23], ['=', 24], + ['PLUS', 24], ['9', 25], ['7', 26], ['-', 27], @@ -94,6 +95,11 @@ const VIRTUAL_KEY_CODES: ReadonlyMap = new Map([ ['F13', 105], ['F14', 107], ['F15', 113], + ['F16', 106], + ['F17', 64], + ['F18', 79], + ['F19', 80], + ['F20', 90], ]); /** @@ -111,7 +117,8 @@ export const carbonModifierMask = (parsed: ParsedAccelerator): number => { if (parsed.meta || parsed.super) { mask |= CMD_KEY; } - if (parsed.shift) { + // Plus is the shifted =/+ key; Electron adds Shift for it too. + if (parsed.shift || parsed.key.toUpperCase() === 'PLUS') { mask |= SHIFT_KEY; } if (parsed.alt) { diff --git a/tests/integration/macos/carbon-global-shortcut.test.ts b/tests/integration/macos/carbon-global-shortcut.test.ts index a5f405ae..1b4c4c92 100644 --- a/tests/integration/macos/carbon-global-shortcut.test.ts +++ b/tests/integration/macos/carbon-global-shortcut.test.ts @@ -28,7 +28,11 @@ describe.skipIf(!isMac)('carbon-global-shortcut (macOS)', () => { }); test('register() returns false for a key with no virtual-key mapping', () => { - expect(macosGlobalShortcutBackend.register('CmdOrCtrl+Plus', () => undefined)).toBe(false); + expect(macosGlobalShortcutBackend.register('CmdOrCtrl+F21', () => undefined)).toBe(false); + }); + + test('register() accepts Plus', () => { + expect(macosGlobalShortcutBackend.register('CmdOrCtrl+Plus', () => undefined)).toBe(true); }); test('unregister() of a live shortcut runs clean', () => { diff --git a/tests/unit/main/platform/macos/carbon-keymap.test.ts b/tests/unit/main/platform/macos/carbon-keymap.test.ts index 264811a1..eb04de8e 100644 --- a/tests/unit/main/platform/macos/carbon-keymap.test.ts +++ b/tests/unit/main/platform/macos/carbon-keymap.test.ts @@ -34,10 +34,16 @@ describe('macVirtualKeyCode', () => { expect(macVirtualKeyCode('0')).toBe(29); }); - test('maps function keys', () => { + test('maps function keys through F20', () => { expect(macVirtualKeyCode('F1')).toBe(122); expect(macVirtualKeyCode('F5')).toBe(96); expect(macVirtualKeyCode('F12')).toBe(111); + expect(macVirtualKeyCode('F16')).toBe(106); + expect(macVirtualKeyCode('F20')).toBe(90); + }); + + test('maps Plus to the =/+ key', () => { + expect(macVirtualKeyCode('Plus')).toBe(macVirtualKeyCode('=')); }); test('maps common named keys', () => { @@ -47,8 +53,8 @@ describe('macVirtualKeyCode', () => { expect(macVirtualKeyCode('Tab')).toBe(48); }); - test('returns undefined for an unmappable key', () => { - expect(macVirtualKeyCode('Plus')).toBeUndefined(); + test('returns undefined for a key macOS has no code for', () => { + expect(macVirtualKeyCode('F21')).toBeUndefined(); }); test('is case-insensitive on the key label', () => { @@ -57,13 +63,6 @@ describe('macVirtualKeyCode', () => { }); describe('carbonModifierMask', () => { - test('exposes the Carbon mask constants', () => { - expect(CMD_KEY).toBe(0x100); - expect(SHIFT_KEY).toBe(0x200); - expect(OPTION_KEY).toBe(0x800); - expect(CONTROL_KEY).toBe(0x1000); - }); - test('Cmd accelerator on macOS yields the cmdKey mask', () => { const parsed = parseAccelerator('CmdOrCtrl+K', 'macos'); expect(parsed).toBeDefined(); @@ -81,6 +80,14 @@ describe('carbonModifierMask', () => { expect(carbonModifierMask(parsed)).toBe(CMD_KEY | CONTROL_KEY | OPTION_KEY | SHIFT_KEY); }); + test('Plus implies Shift, as Electron registers it', () => { + const parsed = parseAccelerator('CmdOrCtrl+Plus', 'macos'); + if (parsed === undefined) { + throw new Error('unreachable'); + } + expect(carbonModifierMask(parsed)).toBe(CMD_KEY | SHIFT_KEY); + }); + test('a bare key yields a zero mask', () => { const parsed = parseAccelerator('K', 'macos'); if (parsed === undefined) { From 62322e590a4eacfc8848747d3c507da5bf73c311 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:55:40 -0700 Subject: [PATCH 094/586] fix: release a closed macOS window even when a closed listener throws --- src/main/platform/macos/cocoa-backend.ts | 14 ++++--------- .../integration/macos/window-release.test.ts | 21 +++++++++++++++++++ 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/src/main/platform/macos/cocoa-backend.ts b/src/main/platform/macos/cocoa-backend.ts index 654bc499..224f471f 100644 --- a/src/main/platform/macos/cocoa-backend.ts +++ b/src/main/platform/macos/cocoa-backend.ts @@ -599,7 +599,6 @@ class MacOSWindow implements NativeWindow { #bounds: Rect; #frameKnown = false; #tornDown = false; - #released = false; #onClosed: (() => void) | undefined; #onClose: (() => boolean) | undefined; #activePopupMenu: Handle = 0n; @@ -645,18 +644,13 @@ class MacOSWindow implements NativeWindow { this.#tornDown = true; // Messaging nil is a no-op, so every later call is safe once the window is released. this.#window = 0n; - this.#teardown(); - this.#onClosed?.(); // Balance our alloc of the NSWindow + WKWebView (both kept alive by // setReleasedWhenClosed:NO) on a LATER tick — AppKit's -close is still on the // stack here, so releasing now would risk the use-after-free that flag avoids. - setTimeout(() => { - if (this.#released) { - return; - } - this.#released = true; - this.#releaseNative(); - }, 0); + // Scheduled before any listener runs, so a throwing one cannot skip it. + setTimeout(this.#releaseNative, 0); + this.#teardown(); + this.#onClosed?.(); } /** @internal Surface a non-preventable lifecycle event. Called by the delegate. */ diff --git a/tests/integration/macos/window-release.test.ts b/tests/integration/macos/window-release.test.ts index 0a17152b..eac44c76 100644 --- a/tests/integration/macos/window-release.test.ts +++ b/tests/integration/macos/window-release.test.ts @@ -29,4 +29,25 @@ describe.skipIf(currentPlatform() !== 'macos')('closed windows are freed', () => app.quit(); } }, 10_000); + + test('a throwing closed listener still releases the window', async () => { + const app = createMacOSApplication(); + app.start(); + try { + await Bun.sleep(100); + const before = liveWindowCount(); + const win = app.createWindow({ width: 320, height: 240, title: 'throws', show: true }); + win.onClosed(() => { + throw new Error('closed listener bug'); + }); + expect(() => win.close()).toThrow('closed listener bug'); + const deadline = performance.now() + 3_000; + while (liveWindowCount() > before && performance.now() < deadline) { + await Bun.sleep(50); + } + expect(liveWindowCount()).toBe(before); + } finally { + app.quit(); + } + }, 10_000); }); From c66936a64093d5a2e5de8c8d7230486cfe0b8a3b Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:55:55 -0700 Subject: [PATCH 095/586] test: drop cannot-fail app tests and make applicationMenu able to fail --- tests/unit/main/api/app.test.ts | 171 ++++++-------------------------- 1 file changed, 29 insertions(+), 142 deletions(-) diff --git a/tests/unit/main/api/app.test.ts b/tests/unit/main/api/app.test.ts index fb0f2f1b..d058c540 100644 --- a/tests/unit/main/api/app.test.ts +++ b/tests/unit/main/api/app.test.ts @@ -1,6 +1,5 @@ -import { EventEmitter } from 'node:events'; import { afterEach, describe, expect, test } from 'bun:test'; -import { App, app } from '../../../../src/main/api/app'; +import { App } from '../../../../src/main/api/app'; import { setNativeAppForTesting } from '../../../../src/main/native-app'; import type { NativeAppKit, NativeApplication } from '../../../../src/main/platform/native'; import { @@ -13,7 +12,11 @@ import { type LockBackend, SingleInstanceManager, } from '../../../../src/main/api/single-instance'; -import { Menu, resetApplicationMenuForTesting } from '../../../../src/main/api/menu'; +import { + Menu, + resetApplicationMenuForTesting, + setMenuRealizerForTesting, +} from '../../../../src/main/api/menu'; import type { AppPathName } from '../../../../src/main/api/app-paths'; import { InvalidArgumentError } from '../../../../src/common/errors'; @@ -46,21 +49,9 @@ const appWith = (overrides: Partial = {}): App => { return a; }; -describe('App singleton', () => { - test('is an instance of App', () => { - expect(app).toBeInstanceOf(App); - }); - - test('is a Node EventEmitter for Electron compatibility', () => { - expect(app).toBeInstanceOf(EventEmitter); - }); -}); - describe('App.isReady', () => { - test('is a method (Electron parity), false on a fresh instance', () => { - const a = new App(); - expect(typeof a.isReady).toBe('function'); - expect(a.isReady()).toBe(false); + test('is false on a fresh instance', () => { + expect(new App().isReady()).toBe(false); }); test('is true after markReady', () => { @@ -158,29 +149,6 @@ describe('App.whenReady', () => { }); }); -describe('App event surface', () => { - test('before-quit handlers can be registered', () => { - const a = new App(); - a.on('before-quit', () => undefined); - expect(a.listenerCount('before-quit')).toBe(1); - }); - - test('window-all-closed handlers can be registered', () => { - const a = new App(); - a.on('window-all-closed', () => undefined); - expect(a.listenerCount('window-all-closed')).toBe(1); - }); - - test('supports the Electron addListener/removeListener alias surface', () => { - const a = new App(); - const handler = (): void => undefined; - a.addListener('will-quit', handler); - expect(a.listenerCount('will-quit')).toBe(1); - a.removeListener('will-quit', handler); - expect(a.listenerCount('will-quit')).toBe(0); - }); -}); - describe('App.quit', () => { /** An app whose env records exit codes instead of killing the process. */ const quittableApp = (): { app: App; exits: number[] } => { @@ -414,59 +382,32 @@ describe('App.relaunch', () => { }); describe('App single-instance lock', () => { - /** A real manager over a fake backend; exposes the captured server callback. */ - const managerWith = ( - opts: { acquire?: boolean[]; existingPid?: number; alive?: boolean } = {}, - ): { manager: SingleInstanceManager; deliver: (json: string) => void; stops: () => number } => { - const acquireQueue = [...(opts.acquire ?? [true])]; + /** A primary manager over a fake backend; `deliver` plays a peer's message. */ + const primary = (): { manager: SingleInstanceManager; deliver: (json: string) => void } => { let onMessage: ((json: string) => void) | undefined; - let stops = 0; const backend: LockBackend = { - tryCreateLock: () => acquireQueue.shift() ?? false, - readLockPid: () => opts.existingPid, - isAlive: () => opts.alive ?? false, + tryCreateLock: () => true, + readLockPid: () => undefined, + isAlive: () => false, clearLock: () => undefined, startServer: (_path, cb) => { onMessage = cb; }, notify: () => undefined, - stop: () => { - stops += 1; - }, + stop: () => undefined, }; return { - manager: new SingleInstanceManager(backend, { - lockPath: '/l', - socketPath: '/s', - pid: 1, - }), + manager: new SingleInstanceManager(backend, { lockPath: '/l', socketPath: '/s', pid: 1 }), deliver: (json) => onMessage?.(json), - stops: () => stops, }; }; - test('requestSingleInstanceLock returns true for the primary', () => { - const a = new App(); - a.setSingleInstanceForTesting(managerWith({ acquire: [true] }).manager); - expect(a.requestSingleInstanceLock()).toBe(true); - expect(a.hasSingleInstanceLock()).toBe(true); - }); - - test('requestSingleInstanceLock returns false for a secondary', () => { - const a = new App(); - a.setSingleInstanceForTesting( - managerWith({ acquire: [false], existingPid: 999, alive: true }).manager, - ); - expect(a.requestSingleInstanceLock()).toBe(false); - expect(a.hasSingleInstanceLock()).toBe(false); - }); - const flush = (): Promise => new Promise((resolve) => setTimeout(resolve, 0)); test('emits second-instance with argv/cwd/data when a peer connects', async () => { const a = new App(); a.markReady(); - const fixture = managerWith({ acquire: [true] }); + const fixture = primary(); a.setSingleInstanceForTesting(fixture.manager); let captured: { argv: string[]; cwd: string; data: unknown } | undefined; a.on('second-instance', (_event: unknown, argv: string[], cwd: string, data: unknown) => { @@ -481,7 +422,7 @@ describe('App single-instance lock', () => { test('holds second-instance until after ready', async () => { const a = new App(); - const fixture = managerWith({ acquire: [true] }); + const fixture = primary(); a.setSingleInstanceForTesting(fixture.manager); const order: string[] = []; a.on('ready', () => order.push('ready')); @@ -493,47 +434,19 @@ describe('App single-instance lock', () => { await flush(); expect(order).toEqual(['ready', 'second-instance']); }); - - test('releaseSingleInstanceLock releases the lock', () => { - const a = new App(); - const fixture = managerWith({ acquire: [true] }); - a.setSingleInstanceForTesting(fixture.manager); - a.requestSingleInstanceLock(); - a.releaseSingleInstanceLock(); - expect(fixture.stops()).toBe(1); - expect(a.hasSingleInstanceLock()).toBe(false); - }); }); describe('App macOS desktop integration', () => { - type DesktopCalls = { - policy: string[]; - hidden: number; - shown: number; - badges: string[]; - bounces: boolean[]; - about: number; - }; + type DesktopCalls = { badges: string[]; bounces: boolean[] }; /** Install a fake native app (optionally with macOS appKit) and record calls. */ const install = (withAppKit: boolean): DesktopCalls => { - const calls: DesktopCalls = { - policy: [], - hidden: 0, - shown: 0, - badges: [], - bounces: [], - about: 0, - }; + const calls: DesktopCalls = { badges: [], bounces: [] }; let dockBadge = ''; const appKit: NativeAppKit = { - setActivationPolicy: (p) => calls.policy.push(p), - hide: () => { - calls.hidden += 1; - }, - show: () => { - calls.shown += 1; - }, + setActivationPolicy: () => undefined, + hide: () => undefined, + show: () => undefined, isHidden: () => true, isActive: () => true, setDockBadge: (label) => { @@ -550,9 +463,6 @@ describe('App macOS desktop integration', () => { throw new Error('createWindow unused in desktop tests'); }, quit: () => undefined, - showAboutPanel: () => { - calls.about += 1; - }, ...(withAppKit ? { appKit } : {}), }; setNativeAppForTesting(native); @@ -561,20 +471,6 @@ describe('App macOS desktop integration', () => { afterEach(() => setNativeAppForTesting(undefined)); - test('setActivationPolicy delegates to appKit', () => { - const calls = install(true); - new App().setActivationPolicy('accessory'); - expect(calls.policy).toEqual(['accessory']); - }); - - test('hide/show delegate to appKit', () => { - const calls = install(true); - const a = new App(); - a.hide(); - a.show(); - expect([calls.hidden, calls.shown]).toEqual([1, 1]); - }); - test('isHidden/isActive reflect appKit', () => { install(true); const a = new App(); @@ -582,12 +478,6 @@ describe('App macOS desktop integration', () => { expect(a.isActive()).toBe(true); }); - test('showAboutPanel delegates', () => { - const calls = install(true); - new App().showAboutPanel(); - expect(calls.about).toBe(1); - }); - test('dock proxies setBadge/getBadge/bounce', () => { const calls = install(true); const dock = new App().dock; @@ -620,22 +510,19 @@ describe('App macOS desktop integration', () => { }); describe('App.applicationMenu', () => { - test('is null by default', () => { - resetApplicationMenuForTesting(); - expect(new App().applicationMenu).toBeNull(); - }); - - test('the getter delegates to Menu.getApplicationMenu', () => { + afterEach(() => { + setMenuRealizerForTesting(undefined); resetApplicationMenuForTesting(); - expect(new App().applicationMenu).toBe(Menu.getApplicationMenu()); }); - test('assigning null clears the application menu', () => { - resetApplicationMenuForTesting(); + test('reads back the menu it was assigned, then null once cleared', () => { + setMenuRealizerForTesting({ realize: () => 1n, setApplicationMenu: () => undefined }); const a = new App(); + const menu = new Menu(); + a.applicationMenu = menu; + expect(a.applicationMenu).toBe(menu); a.applicationMenu = null; expect(a.applicationMenu).toBeNull(); - expect(Menu.getApplicationMenu()).toBeNull(); }); }); From c0dbfd523ecec3cdcd8c66648b349e2f02fcbcac Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:56:07 -0700 Subject: [PATCH 096/586] refactor: memoise loadCocoaFFI through the shared macOS accessor --- src/main/platform/macos/cocoa-ffi.ts | 31 +++++------------------ tests/integration/macos/cocoa-ffi.test.ts | 4 +++ 2 files changed, 11 insertions(+), 24 deletions(-) diff --git a/src/main/platform/macos/cocoa-ffi.ts b/src/main/platform/macos/cocoa-ffi.ts index b22c378d..ec171fc7 100644 --- a/src/main/platform/macos/cocoa-ffi.ts +++ b/src/main/platform/macos/cocoa-ffi.ts @@ -1,8 +1,6 @@ import { FFIType } from 'bun:ffi'; import { dlopen } from '../dlopen'; -import { UnsupportedPlatformError } from '../../../common/errors'; -import { currentPlatform } from '../../../common/platform'; -import { LIBOBJC_PATH } from './objc'; +import { LIBOBJC_PATH, macOSLibraryAccessor } from './objc'; const FOUNDATION_PATH = '/System/Library/Frameworks/Foundation.framework/Foundation'; const APPKIT_PATH = '/System/Library/Frameworks/AppKit.framework/AppKit'; @@ -21,9 +19,6 @@ const APPKIT_SYMBOLS = { }, }; -let foundationLib: unknown; -let appKitLib: unknown; - /** * Open `libobjc.A.dylib` plus `Foundation.framework` and `AppKit.framework`. * @@ -35,27 +30,15 @@ let appKitLib: unknown; * classes (`NSString`, `NSWindow`, `NSApplication`, etc.) with the Objective-C * runtime so subsequent `objc_getClass(...)` calls resolve them. Bun requires * at least one symbol per `dlopen`, so we declare anchor symbols - * (`NSGetSizeAndAlignment`, `NSApplicationMain`) without invoking them. The - * handles are kept at module scope to prevent GC from closing the libraries. + * (`NSGetSizeAndAlignment`, `NSApplicationMain`) without invoking them. Both + * live in the dyld shared cache, which never unloads, so the handles are dropped. * * Throws {@link BunmaskaError} on non-macOS at call time, not at module load, so * this module stays safely *importable* on Linux/Windows. */ -export const loadCocoaFFI = () => { - const platform = currentPlatform(); - if (platform !== 'macos') { - throw new UnsupportedPlatformError( - `loadCocoaFFI() is only supported on macOS; current platform is ${platform}`, - ); - } - - if (foundationLib === undefined) { - foundationLib = dlopen(FOUNDATION_PATH, FOUNDATION_SYMBOLS); - } - - if (appKitLib === undefined) { - appKitLib = dlopen(APPKIT_PATH, APPKIT_SYMBOLS); - } +export const loadCocoaFFI = macOSLibraryAccessor('loadCocoaFFI()', () => { + dlopen(FOUNDATION_PATH, FOUNDATION_SYMBOLS); + dlopen(APPKIT_PATH, APPKIT_SYMBOLS); // ObjC handles (id/SEL/Class) are declared u64, not pointer: tagged-pointer // objects (short NSString/NSNumber/NSDate) set high bits that exceed 2^53, @@ -75,4 +58,4 @@ export const loadCocoaFFI = () => { returns: FFIType.u64, }, }); -}; +}); diff --git a/tests/integration/macos/cocoa-ffi.test.ts b/tests/integration/macos/cocoa-ffi.test.ts index b3e64b0d..4aa9afaa 100644 --- a/tests/integration/macos/cocoa-ffi.test.ts +++ b/tests/integration/macos/cocoa-ffi.test.ts @@ -5,6 +5,10 @@ import { cstr } from '../../../src/main/platform/cstr'; if (currentPlatform() === 'macos') { describe('Cocoa FFI on macOS', () => { + test('loadCocoaFFI opens the libraries once', () => { + expect(loadCocoaFFI()).toBe(loadCocoaFFI()); + }); + test('sel_registerName returns a non-null selector for "alloc"', () => { const lib = loadCocoaFFI(); const sel = lib.symbols.sel_registerName(cstr('alloc')); From 8324f5d5d9c44b0d2a1fcd541e8a8012219115fb Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:56:08 -0700 Subject: [PATCH 097/586] fix: keep one tick chain when the adaptive pump restarts --- src/main/run-loop.ts | 11 +++++++---- tests/unit/main/run-loop.test.ts | 22 ++++++++++++++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/src/main/run-loop.ts b/src/main/run-loop.ts index 1772e583..393595e5 100644 --- a/src/main/run-loop.ts +++ b/src/main/run-loop.ts @@ -109,6 +109,8 @@ export class AdaptiveBlockingPump { readonly #schedule: TickScheduler; #timeoutMs: number; #running = false; + /** Bumped by stop(), so a tick scheduled before a stop()/start() pair dies. */ + #generation = 0; constructor(drain: (timeoutMs: number) => boolean, options?: AdaptiveBlockingPumpOptions) { this.#drain = drain; @@ -133,16 +135,17 @@ export class AdaptiveBlockingPump { return; } this.#running = true; - this.#tick(); + this.#tick(this.#generation); } /** Stop pumping. Idempotent — safe to call when not running. */ stop(): void { this.#running = false; + this.#generation += 1; } - #tick(): void { - if (!this.#running) { + #tick(generation: number): void { + if (generation !== this.#generation) { return; } let active = false; @@ -155,6 +158,6 @@ export class AdaptiveBlockingPump { this.#timeoutMs = active ? this.#minTimeoutMs : Math.min(this.#timeoutMs * 2, this.#maxTimeoutMs); - this.#schedule(() => this.#tick()); + this.#schedule(() => this.#tick(generation)); } } diff --git a/tests/unit/main/run-loop.test.ts b/tests/unit/main/run-loop.test.ts index 186b53f0..ddcfa41b 100644 --- a/tests/unit/main/run-loop.test.ts +++ b/tests/unit/main/run-loop.test.ts @@ -191,6 +191,28 @@ describe('AdaptiveBlockingPump start / stop', () => { }); }); +describe('AdaptiveBlockingPump restart', () => { + test('stop then start in the same turn keeps a single tick chain', () => { + const queue: Array<() => void> = []; + let drains = 0; + const pump = new AdaptiveBlockingPump( + () => { + drains += 1; + return false; + }, + { schedule: (tick) => queue.push(tick) }, + ); + pump.start(); + pump.stop(); + pump.start(); + drains = 0; + for (const tick of queue.splice(0)) { + tick(); + } + expect(drains).toBe(1); + }); +}); + describe('AdaptiveBlockingPump adaptive timeout', () => { test('starts at the minimum and drives the drain with the current timeout', () => { const s = manualScheduler(); From 88d5e60259d34725f6be17bb65d8dd6f00229be4 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:56:12 -0700 Subject: [PATCH 098/586] refactor: share one window-class registration helper --- src/main/platform/windows/win32.ts | 27 +++++++++- .../windows/windows-message-window.ts | 17 ++---- .../platform/windows/windows-native-window.ts | 52 +++++-------------- .../unit/main/platform/windows/win32.test.ts | 50 ++++++++++++++++-- 4 files changed, 88 insertions(+), 58 deletions(-) diff --git a/src/main/platform/windows/win32.ts b/src/main/platform/windows/win32.ts index 94ede694..abc9708a 100644 --- a/src/main/platform/windows/win32.ts +++ b/src/main/platform/windows/win32.ts @@ -7,8 +7,8 @@ * pointers (struct buffers, wide strings) are passed with `ptr()` as usual. */ -import { type Pointer, read } from 'bun:ffi'; -import { UnsupportedPlatformError } from '../../../common/errors'; +import { type Pointer, ptr, read } from 'bun:ffi'; +import { FFIError, UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; import type { Rect } from '../native'; @@ -44,6 +44,29 @@ export const readRect = (pointer: Pointer, offset: number): Rect => { }; }; +const WNDCLASSEXW_SIZE = 80; + +/** Register a window class, throwing `FFIError` on failure; the name is copied into an atom. */ +export const registerWindowClass = ( + user32: { readonly RegisterClassExW: (wc: Pointer) => number }, + name: string, + wndProc: bigint, + hInstance: bigint, + hCursor = 0n, +): void => { + const wc = new Uint8Array(WNDCLASSEXW_SIZE); + const dv = new DataView(wc.buffer); + dv.setUint32(0, WNDCLASSEXW_SIZE, true); // cbSize + dv.setBigUint64(8, wndProc, true); // lpfnWndProc + dv.setBigUint64(24, hInstance, true); // hInstance + dv.setBigUint64(40, hCursor, true); // hCursor + const className = wstr(name); + dv.setBigUint64(64, BigInt(ptr(className)), true); // lpszClassName + if (user32.RegisterClassExW(ptr(wc)) === 0) { + throw new FFIError(`RegisterClassExW failed for ${name}`); + } +}; + /** * Build a memoising accessor for a Windows-only resource. The accessor opens the * resource on first call and caches it; it throws {@link UnsupportedPlatformError} diff --git a/src/main/platform/windows/windows-message-window.ts b/src/main/platform/windows/windows-message-window.ts index ada1f241..ac633bf5 100644 --- a/src/main/platform/windows/windows-message-window.ts +++ b/src/main/platform/windows/windows-message-window.ts @@ -1,6 +1,6 @@ import { FFIType, JSCallback, ptr } from 'bun:ffi'; import { FFIError } from '../../../common/errors'; -import { wstr } from './win32'; +import { registerWindowClass, wstr } from './win32'; import { loadKernel32, loadUser32 } from './win32-ffi'; /** @@ -9,7 +9,6 @@ import { loadKernel32, loadUser32 } from './win32-ffi'; * WebKit, so a JSCallback WndProc is safe here (unlike `windows-native-window.ts`). */ -const WNDCLASSEXW_SIZE = 80; const CLASS_NAME = 'BunmaskaMessageWindow'; /** `WS_EX_TOOLWINDOW` — keep the (never-shown) window out of the taskbar/alt-tab. */ const WS_EX_TOOLWINDOW = 0x00000080; @@ -57,16 +56,7 @@ const ensureClassRegistered = (): void => { } const hInstance = loadKernel32().symbols.GetModuleHandleW(null); - const className = wstr(CLASS_NAME); - const wc = new Uint8Array(WNDCLASSEXW_SIZE); - const view = new DataView(wc.buffer); - view.setUint32(0, WNDCLASSEXW_SIZE, true); // cbSize - view.setBigUint64(8, BigInt(wndProcPtr), true); // lpfnWndProc - view.setBigUint64(24, hInstance, true); // hInstance - view.setBigUint64(64, BigInt(ptr(className)), true); // lpszClassName - if (user32.RegisterClassExW(ptr(wc)) === 0) { - throw new FFIError('RegisterClassExW failed for the Bunmaska message window class'); - } + registerWindowClass(user32, CLASS_NAME, BigInt(wndProcPtr), hInstance); // Retain the JSCallback for the whole process (the class references it forever). registered = { wndProc }; }; @@ -81,10 +71,9 @@ export const createMessageWindow = (handler: MessageHandler): MessageWindow => { ensureClassRegistered(); const user32 = loadUser32().symbols; const hInstance = loadKernel32().symbols.GetModuleHandleW(null); - const className = wstr(CLASS_NAME); const hwnd = user32.CreateWindowExW( WS_EX_TOOLWINDOW, - ptr(className), + ptr(wstr(CLASS_NAME)), null, WS_OVERLAPPED, 0, diff --git a/src/main/platform/windows/windows-native-window.ts b/src/main/platform/windows/windows-native-window.ts index 20766bd2..34b1b99a 100644 --- a/src/main/platform/windows/windows-native-window.ts +++ b/src/main/platform/windows/windows-native-window.ts @@ -3,7 +3,7 @@ import { isDevRestart } from '../../dev-reload'; import { FFIError } from '../../../common/errors'; import { cstr } from '../cstr'; import type { Rect, WindowEventType } from '../native'; -import { readRect, wstr } from './win32'; +import { readRect, registerWindowClass, wstr } from './win32'; import { loadKernel32, loadOle32, loadUser32 } from './win32-ffi'; /** @@ -17,7 +17,6 @@ import { loadKernel32, loadOle32, loadUser32 } from './win32-ffi'; const NATIVE_WINDOW_CLASS_NAME = 'BunmaskaNativeWindow'; const FRAME_WINDOW_CLASS_NAME = 'BunmaskaFrameWindow'; -const WNDCLASSEXW_SIZE = 80; const RECT_SIZE = 16; /** `sizeof(WINDOWPLACEMENT)`: length, flags, showCmd, two POINTs, then rcNormalPosition@28. */ const WINDOWPLACEMENT_SIZE = 44; @@ -50,8 +49,6 @@ const HTCAPTION = 2; let oleInitialized = false; let classRegistered = false; -// Pinned for the process lifetime: the window class references the name buffer. -let classNameBuffer: Uint8Array | undefined; /** Initialise COM on this thread once — WinCairo WebKit requires it. */ export const ensureOleInitialized = (): void => { @@ -78,19 +75,9 @@ const ensureNativeWindowClass = (): bigint => { if (defWindowProc === 0n) { throw new FFIError('GetProcAddress(DefWindowProcW) failed'); } - classNameBuffer = wstr(NATIVE_WINDOW_CLASS_NAME); - const user32 = loadUser32(); - const hCursor = user32.symbols.LoadCursorW(0n, BigInt(IDC_ARROW)); - const wc = new Uint8Array(WNDCLASSEXW_SIZE); - const dv = new DataView(wc.buffer); - dv.setUint32(0, WNDCLASSEXW_SIZE, true); // cbSize - dv.setBigUint64(8, defWindowProc, true); // lpfnWndProc = native DefWindowProcW - dv.setBigUint64(24, hInstance, true); // hInstance - dv.setBigUint64(40, hCursor, true); // hCursor - dv.setBigUint64(64, BigInt(ptr(classNameBuffer)), true); // lpszClassName - if (user32.symbols.RegisterClassExW(ptr(wc)) === 0) { - throw new FFIError('RegisterClassExW failed for the Bunmaska window class'); - } + const user32 = loadUser32().symbols; + const hCursor = user32.LoadCursorW(0n, BigInt(IDC_ARROW)); + registerWindowClass(user32, NATIVE_WINDOW_CLASS_NAME, defWindowProc, hInstance, hCursor); classRegistered = true; return hInstance; }; @@ -98,7 +85,6 @@ const ensureNativeWindowClass = (): bigint => { // Frame-class shared state: the registered class + its retained JSCallback proc. let frameClassRegistered = false; let frameWndProc: JSCallback | undefined; -let frameClassNameBuffer: Uint8Array | undefined; /** * Register the top-level FRAME window class once, wiring a shared JSCallback @@ -131,18 +117,14 @@ const ensureFrameWindowClass = (): bigint => { if (frameWndProcPtr === null) { throw new FFIError('frame window: failed to allocate the WndProc trampoline'); } - frameClassNameBuffer = wstr(FRAME_WINDOW_CLASS_NAME); const hCursor = user32.symbols.LoadCursorW(0n, BigInt(IDC_ARROW)); - const wc = new Uint8Array(WNDCLASSEXW_SIZE); - const dv = new DataView(wc.buffer); - dv.setUint32(0, WNDCLASSEXW_SIZE, true); // cbSize - dv.setBigUint64(8, BigInt(frameWndProcPtr), true); // lpfnWndProc = JSCallback frame proc - dv.setBigUint64(24, hInstance, true); // hInstance - dv.setBigUint64(40, hCursor, true); // hCursor - dv.setBigUint64(64, BigInt(ptr(frameClassNameBuffer)), true); // lpszClassName - if (user32.symbols.RegisterClassExW(ptr(wc)) === 0) { - throw new FFIError('RegisterClassExW failed for the Bunmaska frame class'); - } + registerWindowClass( + user32.symbols, + FRAME_WINDOW_CLASS_NAME, + BigInt(frameWndProcPtr), + hInstance, + hCursor, + ); frameClassRegistered = true; return hInstance; }; @@ -153,13 +135,9 @@ export const createNativeChildHost = ( height: number, ): bigint => { const hInstance = ensureNativeWindowClass(); - const className = classNameBuffer; - if (className === undefined) { - throw new FFIError('native window class buffer was not initialised'); - } const hwnd = loadUser32().symbols.CreateWindowExW( 0, - ptr(className), + ptr(wstr(NATIVE_WINDOW_CLASS_NAME)), ptr(wstr('')), (WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN) >>> 0, 0, @@ -392,13 +370,9 @@ export class NativeWin32Window { // The TOP-LEVEL frame uses the JSCallback frame class (so a menu bar's // WM_COMMAND is dispatchable); the WebKit view lives in a native child. const hInstance = ensureFrameWindowClass(); - const className = frameClassNameBuffer; - if (className === undefined) { - throw new FFIError('frame window class buffer was not initialised'); - } const hwnd = loadUser32().symbols.CreateWindowExW( 0, - ptr(className), + ptr(wstr(FRAME_WINDOW_CLASS_NAME)), ptr(wstr(options.title)), computeStyle(options.frame, options.resizable), CW_USEDEFAULT, diff --git a/tests/unit/main/platform/windows/win32.test.ts b/tests/unit/main/platform/windows/win32.test.ts index 1d8cf7c5..4a506fa3 100644 --- a/tests/unit/main/platform/windows/win32.test.ts +++ b/tests/unit/main/platform/windows/win32.test.ts @@ -1,8 +1,13 @@ import { describe, expect, test } from 'bun:test'; -import { ptr } from 'bun:ffi'; -import { UnsupportedPlatformError } from '../../../../../src/common/errors'; +import { type Pointer, ptr, read } from 'bun:ffi'; +import { FFIError, UnsupportedPlatformError } from '../../../../../src/common/errors'; import { currentPlatform } from '../../../../../src/common/platform'; -import { readRect, winLibraryAccessor, wstr } from '../../../../../src/main/platform/windows/win32'; +import { + readRect, + registerWindowClass, + winLibraryAccessor, + wstr, +} from '../../../../../src/main/platform/windows/win32'; describe('wstr', () => { test('null-terminates with a UTF-16 (two-byte) NUL', () => { @@ -41,6 +46,45 @@ describe('readRect', () => { }); }); +describe('registerWindowClass', () => { + const readWide = (pointer: Pointer): string => { + let text = ''; + for (let offset = 0; read.u16(pointer, offset) !== 0; offset += 2) { + text += String.fromCharCode(read.u16(pointer, offset)); + } + return text; + }; + + test('packs WNDCLASSEXW: cbSize, then proc@8, instance@24, cursor@40, name@64', () => { + let packed: unknown[] = []; + registerWindowClass( + { + RegisterClassExW: (wc: Pointer) => { + packed = [ + read.u32(wc, 0), + read.u64(wc, 8), + read.u64(wc, 24), + read.u64(wc, 40), + readWide(read.ptr(wc, 64) as Pointer), + ]; + return 1; + }, + }, + 'BunmaskaTest', + 0x1111n, + 0x2222n, + 0x3333n, + ); + expect(packed).toEqual([80, 0x1111n, 0x2222n, 0x3333n, 'BunmaskaTest']); + }); + + test('throws FFIError when RegisterClassExW returns 0', () => { + expect(() => registerWindowClass({ RegisterClassExW: () => 0 }, 'Bad', 1n, 2n)).toThrow( + FFIError, + ); + }); +}); + describe('winLibraryAccessor', () => { test.skipIf(currentPlatform() !== 'windows')('memoises: open runs at most once', () => { let opens = 0; From 8d4eaf54b1ef4d3b9590f726ec16fc29a0b4a7c2 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:56:25 -0700 Subject: [PATCH 099/586] refactor: drop native-image and tray backend contracts from the barrel --- src/main/index.ts | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/src/main/index.ts b/src/main/index.ts index 2b57f5d6..e97ff967 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -34,13 +34,7 @@ export { type MenuItemType, type MenuPopupOptions, } from './api/menu'; -export { - type DecodedImage, - NativeImage, - type NativeImageBackend, - type NativeImageHandle, - nativeImage, -} from './api/native-image'; +export { NativeImage, nativeImage } from './api/native-image'; export { nativeTheme, type NativeTheme } from './api/native-theme'; export { Notification, type NotificationOptions } from './api/notification'; export { type PowerMonitor, powerMonitor } from './api/power-monitor'; @@ -57,7 +51,7 @@ export { type Display, type Point, screen, type Size } from './api/screen'; export type { Cookie, CookieFilter, CookieSetDetails } from './api/cookie-util'; export { Cookies, Session, session } from './api/session'; export { shell, type Shell } from './api/shell'; -export { Tray, type TrayBackend, type TrayImageOptions, type TrayInstance } from './api/tray'; +export { Tray, type TrayImageOptions } from './api/tray'; export type { KeyboardInputEvent, MouseInputEvent, NativeInputEvent } from './platform/native'; export { FFIError, From 83e67812d8218ba93edc81d86d0229c23b83be79 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:56:41 -0700 Subject: [PATCH 100/586] refactor: encode wstr with Buffer utf16le --- src/main/platform/windows/win32.ts | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/src/main/platform/windows/win32.ts b/src/main/platform/windows/win32.ts index abc9708a..48e3a8b4 100644 --- a/src/main/platform/windows/win32.ts +++ b/src/main/platform/windows/win32.ts @@ -21,16 +21,7 @@ import type { Rect } from '../native'; * little-endian bytes (surrogate pairs become their two units) followed by a * 16-bit NUL. The caller pins the buffer (e.g. `ptr(wstr(s))`) for the call. */ -export const wstr = (input: string): Uint8Array => { - const terminated = `${input}\0`; - const out = new Uint8Array(terminated.length * 2); - for (let i = 0; i < terminated.length; i += 1) { - const unit = terminated.charCodeAt(i); - out[i * 2] = unit & 0xff; - out[i * 2 + 1] = (unit >> 8) & 0xff; - } - return out; -}; +export const wstr = (input: string): Uint8Array => Buffer.from(`${input}\0`, 'utf16le'); /** Read a native `RECT` (left, top, right, bottom as LONGs) at `offset` as a {@link Rect}. */ export const readRect = (pointer: Pointer, offset: number): Rect => { From 90a26fadb0aec40cb001027eae37866f2640f7d9 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:56:53 -0700 Subject: [PATCH 101/586] fix: leave foreign Carbon hot-key events alone and report install failure --- .../platform/macos/carbon-global-shortcut.ts | 55 ++++++++++------- .../macos/carbon-global-shortcut.test.ts | 59 ++++++++++++++++++- 2 files changed, 93 insertions(+), 21 deletions(-) diff --git a/src/main/platform/macos/carbon-global-shortcut.ts b/src/main/platform/macos/carbon-global-shortcut.ts index 60901a94..4e566253 100644 --- a/src/main/platform/macos/carbon-global-shortcut.ts +++ b/src/main/platform/macos/carbon-global-shortcut.ts @@ -28,6 +28,7 @@ const K_EVENT_HOT_KEY_PRESSED = 6; const K_EVENT_PARAM_HOT_KEY_ID = 0x686b6964; // 'hkid' const TYPE_EVENT_HOT_KEY_ID = 0x686b6964; // 'hkid' const NO_ERR = 0; +const EVENT_NOT_HANDLED_ERR = -9874; type Registration = { readonly id: number; @@ -45,7 +46,7 @@ let nextId = 1; let handlerCallback: JSCallback | undefined; let handlerInstalled = false; -/** Read the fired hot key's id from the event's kEventParamHotKeyID parameter. */ +/** The fired hot key's id, or undefined when the event is not one of ours. */ const readFiredId = (event: Pointer | null): number | undefined => { const carbon = loadCarbonFFI(); const out = new Uint8Array(8); @@ -61,21 +62,31 @@ const readFiredId = (event: Pointer | null): number | undefined => { if (rc !== NO_ERR) { return undefined; } - // EventHotKeyID { OSType signature; UInt32 id } — id is the high 4 bytes. - return new DataView(out.buffer).getUint32(4, true); + // EventHotKeyID { OSType signature; UInt32 id }: signature is the low 4 bytes, id the high 4. + const view = new DataView(out.buffer); + return view.getUint32(0, true) === SIGNATURE ? view.getUint32(4, true) : undefined; }; -/** Install the one shared Carbon event handler. Idempotent. */ -const ensureHandler = (): void => { +/** Install the one shared Carbon event handler. Idempotent; false if Carbon refused it. */ +const ensureHandler = (): boolean => { if (handlerInstalled) { - return; + return true; } const carbon = loadCarbonFFI(); - handlerCallback = new JSCallback( + handlerCallback ??= new JSCallback( (_callRef: Pointer | null, event: Pointer | null): number => { const id = readFiredId(event); - if (id !== undefined) { - byId.get(id)?.(); + const callback = id === undefined ? undefined : byId.get(id); + if (callback === undefined) { + return EVENT_NOT_HANDLED_ERR; // leave other hot-key users' events alone + } + try { + callback(); + } catch (error) { + // A throw must not unwind into Carbon; surface it as an ordinary uncaught error. + queueMicrotask(() => { + throw error; + }); } return NO_ERR; }, @@ -85,15 +96,16 @@ const ensureHandler = (): void => { // EventTypeSpec { UInt32 eventClass; UInt32 eventKind } passed by reference. const typeList = new Uint32Array([KEYBOARD_EVENT_CLASS, K_EVENT_HOT_KEY_PRESSED]); const handlerRefOut = new BigInt64Array(1); - carbon.symbols.InstallEventHandler( - carbon.symbols.GetApplicationEventTarget(), - handlerCallback.ptr, - 1, - ptr(typeList), - null, - ptr(handlerRefOut), - ); - handlerInstalled = true; + handlerInstalled = + carbon.symbols.InstallEventHandler( + carbon.symbols.GetApplicationEventTarget(), + handlerCallback.ptr, + 1, + ptr(typeList), + null, + ptr(handlerRefOut), + ) === NO_ERR; + return handlerInstalled; }; const register = (accelerator: string, callback: () => void): boolean => { @@ -102,10 +114,9 @@ const register = (accelerator: string, callback: () => void): boolean => { return false; } const keyCode = macVirtualKeyCode(parsed.key); - if (keyCode === undefined) { + if (keyCode === undefined || !ensureHandler()) { return false; } - ensureHandler(); const carbon = loadCarbonFFI(); const id = nextId; @@ -139,6 +150,10 @@ const unregister = (accelerator: string): void => { loadCarbonFFI().symbols.UnregisterEventHotKey(Number(registration.hotKeyRef) as Pointer); }; +/** @internal */ +export const registeredHotKeyId = (accelerator: string): number | undefined => + byAccelerator.get(accelerator)?.id; + const unregisterAll = (): void => { for (const accelerator of [...byAccelerator.keys()]) { unregister(accelerator); diff --git a/tests/integration/macos/carbon-global-shortcut.test.ts b/tests/integration/macos/carbon-global-shortcut.test.ts index 1b4c4c92..df8a303f 100644 --- a/tests/integration/macos/carbon-global-shortcut.test.ts +++ b/tests/integration/macos/carbon-global-shortcut.test.ts @@ -1,6 +1,44 @@ import { afterEach, describe, expect, test } from 'bun:test'; +import { dlopen, FFIType, ptr } from 'bun:ffi'; import { currentPlatform } from '../../../src/common/platform'; -import { macosGlobalShortcutBackend } from '../../../src/main/platform/macos/carbon-global-shortcut'; +import { + macosGlobalShortcutBackend, + registeredHotKeyId, +} from '../../../src/main/platform/macos/carbon-global-shortcut'; +import { loadCarbonFFI } from '../../../src/main/platform/macos/carbon-ffi'; + +const SIGNATURE = 0x53414d42; // 'SAMB' +const HOT_KEY_ID = 0x686b6964; // 'hkid': both the parameter name and its type + +/** Synthesize a kEventHotKeyPressed carrying `{signature, id}` and send it to the app target. */ +const pressHotKey = (signature: number, id: number): number => { + const carbon = dlopen('/System/Library/Frameworks/Carbon.framework/Carbon', { + CreateEvent: { + args: [FFIType.ptr, FFIType.u32, FFIType.u32, FFIType.f64, FFIType.u32, FFIType.ptr], + returns: FFIType.i32, + }, + SetEventParameter: { + args: [FFIType.ptr, FFIType.u32, FFIType.u32, FFIType.u64, FFIType.ptr], + returns: FFIType.i32, + }, + SendEventToEventTarget: { args: [FFIType.ptr, FFIType.ptr], returns: FFIType.i32 }, + ReleaseEvent: { args: [FFIType.ptr], returns: FFIType.void }, + }); + const KEYBOARD_EVENT_CLASS = 0x6b657962; // 'keyb' + const K_EVENT_HOT_KEY_PRESSED = 6; + const out = new BigUint64Array(1); + carbon.symbols.CreateEvent(null, KEYBOARD_EVENT_CLASS, K_EVENT_HOT_KEY_PRESSED, 0, 0, ptr(out)); + const event = out[0] ?? 0n; + const hotKeyId = new Uint32Array([signature, id]); + carbon.symbols.SetEventParameter(event, HOT_KEY_ID, HOT_KEY_ID, 8n, ptr(hotKeyId)); + const status = carbon.symbols.SendEventToEventTarget( + event, + loadCarbonFFI().symbols.GetApplicationEventTarget(), + ); + carbon.symbols.ReleaseEvent(event); + carbon.close(); + return status; +}; /** * macOS-only. Exercises the REAL Carbon `RegisterEventHotKey` path on the host. @@ -19,6 +57,25 @@ describe.skipIf(!isMac)('carbon-global-shortcut (macOS)', () => { macosGlobalShortcutBackend.unregisterAll(); }); + test('a hot-key press with our signature fires only that shortcut', () => { + const fired: string[] = []; + macosGlobalShortcutBackend.register('CmdOrCtrl+Shift+K', () => fired.push('K')); + macosGlobalShortcutBackend.register('CmdOrCtrl+Shift+L', () => fired.push('L')); + pressHotKey(SIGNATURE, registeredHotKeyId('CmdOrCtrl+Shift+L') ?? 0); + expect(fired).toEqual(['L']); + }); + + test('a hot-key press with a foreign signature is left to other handlers', () => { + let fired = false; + macosGlobalShortcutBackend.register('CmdOrCtrl+Shift+K', () => { + fired = true; + }); + const EVENT_NOT_HANDLED_ERR = -9874; + const status = pressHotKey(0x4f544852, registeredHotKeyId('CmdOrCtrl+Shift+K') ?? 0); // 'OTHR' + expect(fired).toBe(false); + expect(status).toBe(EVENT_NOT_HANDLED_ERR); + }); + test('isSupported() is true on macOS', () => { expect(macosGlobalShortcutBackend.isSupported()).toBe(true); }); From 7dfd6392c2048971874abc1fcad6c5ee55fc71be Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:57:06 -0700 Subject: [PATCH 102/586] refactor: inline app-desktop pass-throughs and export the Dock type --- src/main/api/app-desktop.ts | 30 +----------------------------- src/main/api/app.ts | 37 ++++++++++++++++++------------------- src/main/index.ts | 1 + 3 files changed, 20 insertions(+), 48 deletions(-) diff --git a/src/main/api/app-desktop.ts b/src/main/api/app-desktop.ts index af4edcf5..8465711c 100644 --- a/src/main/api/app-desktop.ts +++ b/src/main/api/app-desktop.ts @@ -1,12 +1,6 @@ import { nativeApp } from '../native-app'; -/** - * macOS desktop-integration operations behind Electron's `app`. Each delegates - * to the native backend's optional `appKit`, present only on macOS; off macOS - * they no-op / return falsy, matching Electron. - */ - -/** macOS dock object (Electron's `app.dock`); `undefined` on other platforms. */ +/** Electron's `app.dock`; `undefined` off macOS. */ export type Dock = { /** An empty string clears the badge. */ setBadge(text: string): void; @@ -15,28 +9,6 @@ export type Dock = { bounce(type?: 'critical' | 'informational'): void; }; -export const setActivationPolicy = (policy: 'regular' | 'accessory' | 'prohibited'): void => { - nativeApp().appKit?.setActivationPolicy(policy); -}; - -export const hideApp = (): void => { - nativeApp().appKit?.hide(); -}; - -export const showApp = (): void => { - nativeApp().appKit?.show(); -}; - -/** Whether the application is hidden (macOS); `false` off macOS. */ -export const isAppHidden = (): boolean => nativeApp().appKit?.isHidden() ?? false; - -/** Whether the application is the active app (macOS); `false` off macOS. */ -export const isAppActive = (): boolean => nativeApp().appKit?.isActive() ?? false; - -export const showAboutPanel = (): void => { - nativeApp().showAboutPanel?.(); -}; - export const getDock = (): Dock | undefined => { const appKit = nativeApp().appKit; if (appKit === undefined) { diff --git a/src/main/api/app.ts b/src/main/api/app.ts index c74c207c..0d4cbf58 100644 --- a/src/main/api/app.ts +++ b/src/main/api/app.ts @@ -6,13 +6,12 @@ import { type AppEnvironment, defaultAppEnvironment } from './app-environment'; import { localeCountryCode } from './app-locale'; import { resolveAppName, resolveAppVersion } from './app-metadata'; import { type AppPathName, isAppPathName, resolveAppPath } from './app-paths'; -import * as desktop from './app-desktop'; +import { type Dock, displayBadgeCount, getDock } from './app-desktop'; import { Menu } from './menu'; +import { nativeApp } from '../native-app'; import { createLockBackend } from './single-instance-backend'; import { SingleInstanceManager } from './single-instance'; -export type { Dock } from './app-desktop'; - /** * Application lifecycle controller — the drop-in equivalent of Electron's `app`. * @@ -218,39 +217,39 @@ export class App extends EventEmitter { Menu.setApplicationMenu(menu); } - /** Set the macOS activation policy (no-op off macOS). */ + /** No-op off macOS. */ setActivationPolicy(policy: 'regular' | 'accessory' | 'prohibited'): void { - desktop.setActivationPolicy(policy); + nativeApp().appKit?.setActivationPolicy(policy); } - /** Hide all application windows — macOS (no-op off macOS). */ + /** No-op off macOS. */ hide(): void { - desktop.hideApp(); + nativeApp().appKit?.hide(); } - /** Show application windows after {@link hide} — macOS (no-op off macOS). */ + /** No-op off macOS. */ show(): void { - desktop.showApp(); + nativeApp().appKit?.show(); } - /** Whether the application is hidden (macOS); `false` off macOS. */ + /** `false` off macOS. */ isHidden(): boolean { - return desktop.isAppHidden(); + return nativeApp().appKit?.isHidden() ?? false; } - /** Whether the application is the active app (macOS); `false` off macOS. */ + /** `false` off macOS. */ isActive(): boolean { - return desktop.isAppActive(); + return nativeApp().appKit?.isActive() ?? false; } - /** Show the platform's standard about panel (no-op where unsupported). */ + /** No-op where the platform has no standard about panel. */ showAboutPanel(): void { - desktop.showAboutPanel(); + nativeApp().showAboutPanel?.(); } - /** The macOS dock object, or `undefined` on other platforms. */ - get dock(): desktop.Dock | undefined { - return desktop.getDock(); + /** `undefined` off macOS. */ + get dock(): Dock | undefined { + return getDock(); } /** @@ -259,7 +258,7 @@ export class App extends EventEmitter { */ setBadgeCount(count = 0): boolean { this.#badgeCount = count; - return desktop.displayBadgeCount(count); + return displayBadgeCount(count); } getBadgeCount(): number { diff --git a/src/main/index.ts b/src/main/index.ts index e97ff967..083deb64 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -1,6 +1,7 @@ import './bootstrap'; export { App, app } from './api/app'; +export type { Dock } from './api/app-desktop'; export { type AutoUpdater, type AutoUpdaterDeps, From e2030571656965eb02660a1f8ea3a28ec97fccdb Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:57:09 -0700 Subject: [PATCH 103/586] fix: match Electron focus on macOS: skip hidden windows, activate app --- src/main/platform/macos/cocoa-backend.ts | 9 ++++++++- tests/integration/macos/cocoa-backend.test.ts | 13 +++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/main/platform/macos/cocoa-backend.ts b/src/main/platform/macos/cocoa-backend.ts index 224f471f..990dbaeb 100644 --- a/src/main/platform/macos/cocoa-backend.ts +++ b/src/main/platform/macos/cocoa-backend.ts @@ -794,7 +794,14 @@ class MacOSWindow implements NativeWindow { } focus(): void { - msgSendPtr(this.#window, cocoa().selectors.get('makeKeyAndOrderFront:'), 0n); + // Electron: a no-op while hidden, and activates the app only when none is active. + if (!this.isVisible()) { + return; + } + const rt = cocoa(); + const app = rt.msgSend(rt.classes.get('NSApplication'), rt.selectors.get('sharedApplication')); + msgSendU8(app, rt.selectors.get('activateIgnoringOtherApps:'), 0); + msgSendPtr(this.#window, rt.selectors.get('makeKeyAndOrderFront:'), 0n); } minimize(): void { diff --git a/tests/integration/macos/cocoa-backend.test.ts b/tests/integration/macos/cocoa-backend.test.ts index 8e326dd8..ace3febb 100644 --- a/tests/integration/macos/cocoa-backend.test.ts +++ b/tests/integration/macos/cocoa-backend.test.ts @@ -222,6 +222,19 @@ if (currentPlatform() === 'macos') { } }); + test('focus leaves a hidden window hidden, like Electron', () => { + const app = createMacOSApplication(); + app.start(); + try { + const win = app.createWindow({ width: 320, height: 240, title: 't', show: false }); + win.focus(); + expect(win.isVisible()).toBe(false); + win.destroy(); + } finally { + app.quit(); + } + }); + test('hide makes the window not visible', () => { const app = createMacOSApplication(); app.start(); From 16def9f1180532a5c38fe41ab4ed6e76d1a35f74 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:57:24 -0700 Subject: [PATCH 104/586] fix: correct the inverted destroyOnClose doc and init handlers once --- src/main/platform/windows/windows-native-window.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/platform/windows/windows-native-window.ts b/src/main/platform/windows/windows-native-window.ts index 34b1b99a..2eb3fcfb 100644 --- a/src/main/platform/windows/windows-native-window.ts +++ b/src/main/platform/windows/windows-native-window.ts @@ -355,17 +355,17 @@ export interface NativeWin32WindowOptions { readonly show: boolean; readonly resizable?: boolean; readonly frame?: boolean; - /** Hide instead of destroy on close (for WebKit-hosting windows). Default true. */ + /** `false` hides on close instead of DestroyWindow (required for a WebKit host, D043). Default true. */ readonly destroyOnClose?: boolean; } /** A live top-level native-WndProc window that can host a WebKit view. */ export class NativeWin32Window { readonly #hwnd: bigint; - readonly #handlers: NativeWindowHandlers = newHandlers(true); + readonly #handlers: NativeWindowHandlers; constructor(options: NativeWin32WindowOptions) { - this.#handlers.destroyOnClose = options.destroyOnClose ?? true; + this.#handlers = newHandlers(options.destroyOnClose ?? true); ensureOleInitialized(); // The TOP-LEVEL frame uses the JSCallback frame class (so a menu bar's // WM_COMMAND is dispatchable); the WebKit view lives in a native child. From b01c7f2ee34a885994c648f7914bd0b8d8efedf4 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:57:46 -0700 Subject: [PATCH 105/586] refactor: resolve getPath from one name list and a user-folder table --- src/main/api/app-paths.ts | 199 ++++++++++---------------------------- 1 file changed, 51 insertions(+), 148 deletions(-) diff --git a/src/main/api/app-paths.ts b/src/main/api/app-paths.ts index 2969bef0..fb3b619b 100644 --- a/src/main/api/app-paths.ts +++ b/src/main/api/app-paths.ts @@ -2,47 +2,7 @@ import { posix, win32 } from 'node:path'; import { InvalidArgumentError } from '../../common/errors'; import type { Platform } from '../../common/platform'; -/** - * Pure resolution of Electron's `app.getPath(name)` special directories. - * - * Each resolver joins with its TARGET platform's separator (`path.posix` for - * macOS/Linux, `path.win32` for Windows) rather than the host's `path.join`, so - * a macOS path resolves with `/` even when this runs on a Windows CI host, and - * vice versa. - */ - -export type AppPathName = - | 'home' - | 'appData' - | 'userData' - | 'sessionData' - | 'temp' - | 'exe' - | 'module' - | 'desktop' - | 'documents' - | 'downloads' - | 'music' - | 'pictures' - | 'videos' - | 'logs' - | 'crashDumps'; - -export type PathEnvironment = { - readonly platform: Platform; - /** `os.homedir()`. */ - readonly home: string; - /** `os.tmpdir()`. */ - readonly temp: string; - /** Names the per-app `userData` subdirectory. */ - readonly appName: string; - /** `process.execPath`. */ - readonly execPath: string; - /** Consulted for the Linux XDG overrides. */ - readonly env: Readonly>; -}; - -const KNOWN_NAMES: ReadonlySet = new Set([ +const APP_PATH_NAMES = [ 'home', 'appData', 'userData', @@ -58,94 +18,53 @@ const KNOWN_NAMES: ReadonlySet = new Set([ 'videos', 'logs', 'crashDumps', -]); +] as const; + +export type AppPathName = (typeof APP_PATH_NAMES)[number]; + +export type PathEnvironment = { + readonly platform: Platform; + readonly home: string; + readonly temp: string; + /** Names the per-app `userData` subdirectory. */ + readonly appName: string; + readonly execPath: string; + /** Linux `XDG_*` values (from the environment or `user-dirs.dirs`) and Windows `APPDATA`. */ + readonly env: Readonly>; +}; + +const KNOWN_NAMES: ReadonlySet = new Set(APP_PATH_NAMES); export const isAppPathName = (name: string): name is AppPathName => KNOWN_NAMES.has(name); +/** Home-relative user folders; Linux consults `xdg` first. */ +const USER_FOLDERS = { + desktop: { dir: 'Desktop', xdg: 'XDG_DESKTOP_DIR' }, + documents: { dir: 'Documents', xdg: 'XDG_DOCUMENTS_DIR' }, + downloads: { dir: 'Downloads', xdg: 'XDG_DOWNLOAD_DIR' }, + music: { dir: 'Music', xdg: 'XDG_MUSIC_DIR' }, + pictures: { dir: 'Pictures', xdg: 'XDG_PICTURES_DIR' }, + videos: { dir: 'Videos', xdg: 'XDG_VIDEOS_DIR' }, +} as const; + const envDir = (env: PathEnvironment['env'], variable: string, fallback: string): string => { const value = env[variable]; return value !== undefined && value.length > 0 ? value : fallback; }; -/** Linux XDG user-dir lookup: `$VAR` if set and non-empty, else `home/fallback`. */ -const xdgDir = (env: PathEnvironment['env'], variable: string, home: string, fallback: string) => - envDir(env, variable, posix.join(home, fallback)); - -const resolveMacOS = (name: AppPathName, e: PathEnvironment): string => { - const { join } = posix; - const appSupport = join(e.home, 'Library', 'Application Support'); - const userData = join(appSupport, e.appName); - switch (name) { - case 'home': - return e.home; - case 'appData': - return appSupport; - case 'userData': - case 'sessionData': - return userData; - case 'temp': - return e.temp; - case 'exe': - case 'module': - return e.execPath; - case 'desktop': - return join(e.home, 'Desktop'); - case 'documents': - return join(e.home, 'Documents'); - case 'downloads': - return join(e.home, 'Downloads'); - case 'music': - return join(e.home, 'Music'); - case 'pictures': - return join(e.home, 'Pictures'); - case 'videos': - return join(e.home, 'Movies'); - case 'logs': - return join(e.home, 'Library', 'Logs', e.appName); - case 'crashDumps': - return join(userData, 'Crashpad'); - } -}; - -const resolveLinux = (name: AppPathName, e: PathEnvironment): string => { - const { join } = posix; - const appData = xdgDir(e.env, 'XDG_CONFIG_HOME', e.home, '.config'); - const userData = join(appData, e.appName); - switch (name) { - case 'home': - return e.home; - case 'appData': - return appData; - case 'userData': - case 'sessionData': - return userData; - case 'temp': - return e.temp; - case 'exe': - case 'module': - return e.execPath; - case 'desktop': - return xdgDir(e.env, 'XDG_DESKTOP_DIR', e.home, 'Desktop'); - case 'documents': - return xdgDir(e.env, 'XDG_DOCUMENTS_DIR', e.home, 'Documents'); - case 'downloads': - return xdgDir(e.env, 'XDG_DOWNLOAD_DIR', e.home, 'Downloads'); - case 'music': - return xdgDir(e.env, 'XDG_MUSIC_DIR', e.home, 'Music'); - case 'pictures': - return xdgDir(e.env, 'XDG_PICTURES_DIR', e.home, 'Pictures'); - case 'videos': - return xdgDir(e.env, 'XDG_VIDEOS_DIR', e.home, 'Videos'); - case 'logs': - return join(userData, 'logs'); - case 'crashDumps': - return join(userData, 'Crashpad'); +/** Throws {@link InvalidArgumentError} on an unrecognized name, matching Electron. */ +export const resolveAppPath = (name: AppPathName, e: PathEnvironment): string => { + if (!isAppPathName(name)) { + throw new InvalidArgumentError(`Failed to get '${name}' path: unknown path name`); } -}; - -const resolveWindows = (name: AppPathName, e: PathEnvironment): string => { - const { join } = win32; - const appData = envDir(e.env, 'APPDATA', join(e.home, 'AppData', 'Roaming')); + // The TARGET platform's separator, not the host's, so every platform resolves on any CI host. + const { join } = e.platform === 'windows' ? win32 : posix; + const appData = + e.platform === 'macos' + ? join(e.home, 'Library', 'Application Support') + : e.platform === 'windows' + ? envDir(e.env, 'APPDATA', join(e.home, 'AppData', 'Roaming')) + : envDir(e.env, 'XDG_CONFIG_HOME', join(e.home, '.config')); const userData = join(appData, e.appName); switch (name) { case 'home': @@ -160,36 +79,20 @@ const resolveWindows = (name: AppPathName, e: PathEnvironment): string => { case 'exe': case 'module': return e.execPath; - case 'desktop': - return join(e.home, 'Desktop'); - case 'documents': - return join(e.home, 'Documents'); - case 'downloads': - return join(e.home, 'Downloads'); - case 'music': - return join(e.home, 'Music'); - case 'pictures': - return join(e.home, 'Pictures'); - case 'videos': - return join(e.home, 'Videos'); case 'logs': - return join(userData, 'logs'); + return e.platform === 'macos' + ? join(e.home, 'Library', 'Logs', e.appName) + : join(userData, 'logs'); case 'crashDumps': return join(userData, 'Crashpad'); - } -}; - -/** Throws {@link InvalidArgumentError} on an unrecognized name, matching Electron. */ -export const resolveAppPath = (name: AppPathName, environment: PathEnvironment): string => { - if (!isAppPathName(name)) { - throw new InvalidArgumentError(`Failed to get '${name}' path: unknown path name`); - } - switch (environment.platform) { - case 'macos': - return resolveMacOS(name, environment); - case 'windows': - return resolveWindows(name, environment); - default: - return resolveLinux(name, environment); + default: { + const folder = USER_FOLDERS[name]; + if (e.platform === 'macos') { + return join(e.home, name === 'videos' ? 'Movies' : folder.dir); + } + // ponytail: Windows ignores Known Folder redirection (OneDrive); SHGetKnownFolderPath if it bites. + const fallback = join(e.home, folder.dir); + return e.platform === 'linux' ? envDir(e.env, folder.xdg, fallback) : fallback; + } } }; From 51297770d6be59583b091d6844d7622510e2e3ed Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:58:36 -0700 Subject: [PATCH 106/586] chore: trim Linux core comments to the comment rules --- src/main/platform/linux/gasync.ts | 22 +--- src/main/platform/linux/gtk-run-loop.ts | 24 +--- src/main/platform/linux/gtk-signals.ts | 95 ++++----------- src/main/platform/linux/linux-backend.ts | 115 ++++--------------- src/main/platform/linux/webkit-ipc.ts | 76 +++--------- src/main/platform/linux/webkit-uri-scheme.ts | 59 ++-------- 6 files changed, 80 insertions(+), 311 deletions(-) diff --git a/src/main/platform/linux/gasync.ts b/src/main/platform/linux/gasync.ts index 1d28aebc..2b53f3ee 100644 --- a/src/main/platform/linux/gasync.ts +++ b/src/main/platform/linux/gasync.ts @@ -1,27 +1,17 @@ import { JSCallback, type Pointer } from 'bun:ffi'; -/** - * Shared one-shot `GAsyncReadyCallback` runner (dialogs, cookies, snapshots). - * - * JSCallback lifecycle safety (a past SIGSEGV regression): the thunk MUST stay - * reachable until GLib fires it, and MUST NOT be `close()`d synchronously inside - * its own invocation (that frees the native trampoline the caller is about to - * return into). Each in-flight callback is retained in {@link inFlight} and its - * `close()` is deferred to a later tick. - */ - /** ABI shape for `GAsyncReadyCallback`: `(source, result, user_data) -> void`. */ export const GASYNC_READY_CB_DEF = { args: ['ptr', 'ptr', 'ptr'], returns: 'void' } as const; -/** Every JSCallback awaiting a GLib async settle. Retained so Bun can't GC it. */ +/** Retained so Bun cannot GC a thunk GLib still holds. */ const inFlight = new Set(); /** - * Kick off one async GLib operation and settle a Promise from its - * `GAsyncReadyCallback`. `settle` runs inside the callback (call the matching - * `*_finish` there); a thrown `settle` rejects. The thunk is closed on a - * deferred tick after it fires; if the operation never completes the thunk - * stays retained (never close a callback native code may still invoke). + * Start one async GLib operation and settle a Promise from its `GAsyncReadyCallback`. + * `settle` runs inside the callback (call the matching `*_finish` there); a throw + * rejects. The thunk closes on a later tick, never inside its own invocation + * (D022b); if the operation never completes it stays retained, because native + * code may still invoke it. */ export const runAsyncReady = ( start: (callbackPtr: Pointer) => void, diff --git a/src/main/platform/linux/gtk-run-loop.ts b/src/main/platform/linux/gtk-run-loop.ts index 00dd6040..999d5c14 100644 --- a/src/main/platform/linux/gtk-run-loop.ts +++ b/src/main/platform/linux/gtk-run-loop.ts @@ -1,31 +1,14 @@ import { loadGlibFFI } from './glib-ffi'; import { pollX11ShortcutsOnce } from './x11-global-shortcut'; -/** - * Linux native run-loop drain. - * - * The Linux analogue of the macOS CF drain (D020): the {@link CooperativePump} - * calls this each tick to service GTK/GLib events without blocking Bun's thread. - * We iterate the default main context while it reports pending sources, never - * blocking (`may_block = FALSE`), bounded by a per-tick budget so a busy loop - * cannot starve Bun's own event loop. - * - * The drain ALSO polls the dedicated X11 global-shortcut connection - * ({@link pollX11ShortcutsOnce}) each tick: `XGrabKey` events arrive on their own - * display connection, not GLib's main context, so they need their own poll. The - * poll is a no-op until a global shortcut is registered. - */ - const NULL_CONTEXT = null; +// Never block: the pump shares Bun's only thread (D020). const MAY_BLOCK_FALSE = 0; -/** Upper bound on inner iterations per tick. */ +/** Upper bound on inner iterations per tick, so a busy GLib loop cannot starve Bun's event loop. */ const DRAIN_BUDGET = 256; -/** - * Create the Linux drain function. Throws {@link UnsupportedPlatformError} off - * Linux (via the loader). Cheap to call repeatedly; never blocks. - */ +/** The {@link CooperativePump} drain for GTK/GLib; throws off Linux (via the loader). */ export const createLinuxDrain = (): (() => void) => { const glib = loadGlibFFI(); return () => { @@ -35,6 +18,7 @@ export const createLinuxDrain = (): (() => void) => { } glib.symbols.g_main_context_iteration(NULL_CONTEXT, MAY_BLOCK_FALSE); } + // XGrabKey events arrive on their own X display connection, not GLib's context. pollX11ShortcutsOnce(); }; }; diff --git a/src/main/platform/linux/gtk-signals.ts b/src/main/platform/linux/gtk-signals.ts index 955f43b4..03d2af1e 100644 --- a/src/main/platform/linux/gtk-signals.ts +++ b/src/main/platform/linux/gtk-signals.ts @@ -12,21 +12,6 @@ import { WEBKIT_LOAD_STARTED, } from './webkitgtk-ffi'; -/** - * GObject signal wiring for the Linux backend. - * - * Wraps `g_signal_connect_data` with {@link JSCallback} creation and lifetime - * management. Every {@link JSCallback} handed to `g_signal_connect_data` MUST - * stay reachable from JS for the life of the connection — if Bun GCs the native - * thunk while GObject still holds the function pointer, the next signal emission - * jumps into freed memory. The {@link SignalRegistry}, owned by each long-lived - * `NativeWindow`/`NativeWebContents`, retains every callback to prevent that. - * - * Bun's {@link JSCallback} does not expose its `{ args, returns }` definition at - * runtime, so each handler's ABI shape is declared as an exported `*_CB_DEF` - * constant (unit-testable in pure JS) and reused by the factory below. - */ - const log = createLogger('gtk-signals'); /** @@ -45,41 +30,31 @@ export const guarded = } }; -/** ABI shape for `GtkWindow::close-request`: `(self, user_data) -> gboolean`. */ +/** `GtkWindow::close-request`: `(self, user_data) -> gboolean`. */ export const CLOSE_REQUEST_CB_DEF = { args: ['ptr', 'ptr'], returns: 'i32' } as const; -/** ABI shape for `WebKitWebView::load-changed`: `(self, load_event, user_data) -> void`. */ +/** `WebKitWebView::load-changed`: `(self, WebKitLoadEvent, user_data) -> void`. */ export const LOAD_CHANGED_CB_DEF = { args: ['ptr', 'i32', 'ptr'], returns: 'void' } as const; -/** ABI shape for `WebKitWebView::load-failed`: `(self, load_event, uri, error, user_data) -> gboolean`. */ +/** `WebKitWebView::load-failed`: `(self, load_event, uri, GError*, user_data) -> gboolean`. */ export const LOAD_FAILED_CB_DEF = { args: ['ptr', 'i32', 'ptr', 'ptr', 'ptr'], returns: 'i32', } as const; -/** ABI shape for `WebKitWebView::create`: `(self, navigation_action, user_data) -> GtkWidget*`. */ +/** `WebKitWebView::create`: `(self, navigation_action, user_data) -> GtkWidget*`. */ export const CREATE_CB_DEF = { args: ['ptr', 'ptr', 'ptr'], returns: 'ptr' } as const; -/** ABI shape for `script-message-received` (WK6.0): `(manager, value, user_data) -> void`. */ +/** `script-message-received` (WK6.0): `(manager, JSCValue*, user_data) -> void`. */ export const SCRIPT_MESSAGE_CB_DEF = { args: ['ptr', 'ptr', 'ptr'], returns: 'void' } as const; -/** ABI shape for a `GObject::notify` signal: `(gobject, pspec, user_data) -> void`. */ +/** `GObject::notify`: `(gobject, pspec, user_data) -> void`. */ export const NOTIFY_CB_DEF = { args: ['ptr', 'ptr', 'ptr'], returns: 'void' } as const; /** - * Decide a `GtkWindow::close-request` return value from a JS close handler. - * - * INVERTED GTK semantics: return 1 (TRUE) to VETO (stop the default handler, so - * the window stays open); return 0 (FALSE) to ALLOW GTK's default handler to - * destroy the window. `onCloseRequest` returns `true` to veto. + * `close-request` returns an INVERTED gboolean: 1 (TRUE) vetoes (GTK's default + * handler does not run, the window stays), 0 lets GTK destroy the window. + * `onCloseRequest` returns `true` to veto. */ export const closeRequestDecision = (onCloseRequest: () => boolean): number => onCloseRequest() ? 1 : 0; -/** - * `GtkWindow::close-request` handler (preventable). - * - * `onCloseRequest` is consulted on every close attempt (title-bar button or the - * programmatic `gtk_window_close`). It returns `true` to VETO — the window stays - * open and {@link closeRequestDecision} returns 1; otherwise it runs the close - * bookkeeping/teardown itself and returns `false`, so this returns 0 and GTK - * destroys the window. - */ +/** Native (title-bar) close; `onCloseRequest` runs teardown itself when it does not veto. */ export const makeCloseRequestCallback = (onCloseRequest: () => boolean): JSCallback => new JSCallback( guarded( @@ -89,11 +64,7 @@ export const makeCloseRequestCallback = (onCloseRequest: () => boolean): JSCallb CLOSE_REQUEST_CB_DEF, ); -/** - * A generic `GObject::notify::` handler. Runs `onNotify` on each property - * change; the caller reads the new value (e.g. via `g_object_get`) or toggles a - * tracked flag. The `GParamSpec*` second arg is ignored. - */ +/** `notify::` handler; `onNotify` reads the new value through the widget's getter. */ export const makeNotifyCallback = (onNotify: () => void): JSCallback => new JSCallback( guarded((_gobject: Pointer, _pspec: Pointer, _userData: Pointer): void => { @@ -152,11 +123,7 @@ export const makeLoadCallbacks = ( return { changed, failed: failedCallback }; }; -/** - * `WebKitWebView::create` handler (`window.open` / `target=_blank`). Reads the - * target URI from the navigation action, hands it to `onWindowOpen`, and returns - * NULL so no child web view is created (v1 deny path). - */ +/** `window.open` / `target=_blank`: report the URL and return NULL, so no child view is created. */ export const makeCreateCallback = (onWindowOpen: (url: string) => void): JSCallback => { const webkit = loadWebKitGtkFFI(); return new JSCallback( @@ -175,13 +142,9 @@ export const makeCreateCallback = (onWindowOpen: (url: string) => void): JSCallb }; /** - * `WebKitUserContentManager::script-message-received` handler (WK6.0). - * - * In WK6.0 the second arg is a `JSCValue*` DIRECTLY (NOT a - * `WebKitJavascriptResult*` — calling `webkit_javascript_result_get_js_value` - * on it is the stale 4.x path and crashes). Convert via `jsc_value_to_string` - * (transfer-full `char*`), read it, then `g_free` it to avoid leaking on every - * message. + * WK6.0 passes a `JSCValue*` directly; never call the 4.x + * `webkit_javascript_result_get_js_value` on it (crashes). `jsc_value_to_string` + * is transfer-full, so every message must `g_free` it. */ export const makeScriptMessageCallback = (onMessage: (json: string) => void): JSCallback => { const jsc = loadJscFFI(); @@ -205,11 +168,10 @@ export const makeScriptMessageCallback = (onMessage: (json: string) => void): JS type Closable = { close: () => void }; /** - * Close each callback's native trampoline on a LATER tick, never synchronously. - * A signal handler runs on GTK's stack; closing its own {@link JSCallback} while - * that stack is live frees the trampoline GTK is about to return into (SIGSEGV, - * the D022b discipline). Disconnecting the handler is safe synchronously; only - * the `.close()` is deferred. Empty batches schedule nothing. + * Close native trampolines on a LATER tick, never synchronously. This is the one + * statement of the rule (D022b): closing a {@link JSCallback} while native code is + * still inside its invocation frees the trampoline it returns into (SIGSEGV). + * Disconnecting a handler is safe synchronously; only `.close()` is deferred. */ export const deferCallbackClose = ( callbacks: readonly Closable[], @@ -235,8 +197,8 @@ export type SignalConnection = { }; /** - * Connect a {@link JSCallback} to a GObject signal via `g_signal_connect_data`. - * The caller MUST retain the returned `callback` (see {@link SignalRegistry}). + * Connect via `g_signal_connect_data`. The caller MUST keep `callback` reachable + * while connected: a GC'd thunk turns the next emission into a jump into freed memory. */ export const connectSignal = ( instance: Pointer, @@ -255,28 +217,17 @@ export const connectSignal = ( return { handlerId, callback }; }; -/** - * Retains every {@link JSCallback} connected to a long-lived GObject so Bun does - * not GC the native thunk while the connection is live. Owned by each - * `NativeWindow`/`NativeWebContents`. {@link disconnectAll} disconnects each - * handler then closes its callback. - */ +/** Retains every thunk connected to one window's or web view's GObjects until teardown. */ export class SignalRegistry { readonly #connections: Array<{ instance: Pointer; connection: SignalConnection }> = []; - /** Connect and retain in one step. */ connect(instance: Pointer, detailedSignal: string, callback: JSCallback): SignalConnection { const connection = connectSignal(instance, detailedSignal, callback); this.#connections.push({ instance, connection }); return connection; } - /** - * Disconnect every handler synchronously (no more signals fire), then close - * the callback thunks on a LATER tick via {@link deferCallbackClose} — safe to - * call from inside a signal handler's own invocation (e.g. close-request). - * Idempotent. - */ + /** Idempotent, and safe inside a handler's own invocation (closes via {@link deferCallbackClose}). */ disconnectAll(): void { if (this.#connections.length === 0) { return; diff --git a/src/main/platform/linux/linux-backend.ts b/src/main/platform/linux/linux-backend.ts index f38cd3d3..ae614c9a 100644 --- a/src/main/platform/linux/linux-backend.ts +++ b/src/main/platform/linux/linux-backend.ts @@ -40,15 +40,7 @@ import { capturePage as webkitCapturePage } from './webkit-snapshot'; import { registerAllSchemes } from './webkit-uri-scheme'; import { loadWebKitGtkFFI, readGetUriResult } from './webkitgtk-ffi'; -/** - * Linux {@link NativeApplication} backend on GTK 4 + WebKitGTK 6.0, pure - * `bun:ffi`. Mirrors `cocoa-backend.ts` structurally (D024): a thin lifecycle - * shell over a cooperative GLib pump plus a window factory. - * - * The pump reuses the shared {@link CooperativePump} driven by the Linux drain - * (`g_main_context_iteration` with `may_block = FALSE`) — NO `GtkApplication` - * or `g_main_loop_run`, which would block Bun's thread (D020). - */ +// Never GtkApplication or g_main_loop_run: both block Bun's only thread (D020). const log = createLogger('linux-backend'); @@ -57,10 +49,6 @@ const GTK_FALSE = 0; /** `GtkOrientation`: stack the menu bar above the webview vertically. */ const GTK_ORIENTATION_VERTICAL = 1; -/** - * Linux {@link NativeWebContents}: a `WebKitWebView` wired for navigation, JS - * evaluation, and the IPC round-trip. - */ class LinuxWebContents implements NativeWebContents { readonly #view: Pointer; readonly #ucm: Pointer; @@ -79,11 +67,8 @@ class LinuxWebContents implements NativeWebContents { preloadSource: generatePreloadBootstrap(), isolatedSetupSource: generateIsolatedChannelSetup(channelId), isolatedHostSource: generateIsolatedHostSource(channelId), - // Page world: the cross-world stub + the custom-title-bar script. The page world - // stays free of any `__bunmaska` handle (context isolation), so it only mirrors - // `--app-region`; the window-op controls + native GTK handler are a follow-up on - // the isolated-world bridge. - pageWorldSource: `${generatePageWorldStub(channelId)}\n${windowControlsScript()}`, + // No `__bunmaska` in the page world (context isolation): it only mirrors `--app-region`. + pageWorldSource: `${generatePageWorldStub(channelId)}\n${windowControlsScript()}`, // ponytail: frameless window-op buttons wait on the isolated-world bridge (D045) ...(userPreloadSource !== undefined ? { userPreloadSource } : {}), onMessage: (json: string) => { this.#markBridgeReady(); @@ -102,13 +87,7 @@ class LinuxWebContents implements NativeWebContents { this.#view = wired.view; this.#ucm = wired.ucm; this.#registry = wired.registry; - // Wire every custom scheme registered via `protocol.handle` onto THIS view's - // WebKitWebContext before any load, so `app://…` loads are served. Each - // scheme registers once per process (the dedup guard inside); the request - // callback's JSCallback is retained there for the process lifetime. registerAllSchemes(this.#view); - // Enable developer extras so the inspector is available (right-click → - // Inspect Element, and openDevTools()). Stable WebKitGTK 6.0 API. const webkit = loadWebKitGtkFFI(); webkit.symbols.webkit_settings_set_enable_developer_extras( webkit.symbols.webkit_web_view_get_settings(this.#view), @@ -161,7 +140,7 @@ class LinuxWebContents implements NativeWebContents { this.#destroyed = true; this.#exec.destroy(); this.#registry.disconnectAll(); - // Deferred: close() can run inside this manager's own script-message emission. + // Unref on a later tick: close() may run inside this manager's own script-message emission. const ucm = this.#ucm; setTimeout(() => loadGObjectFFI().symbols.g_object_unref(ucm), 0); } @@ -171,8 +150,7 @@ class LinuxWebContents implements NativeWebContents { } loadHTML(html: string, baseUrl?: string): void { - // base_uri is nullable; cstring cannot encode NULL, so pass a pinned - // NUL-terminated buffer for a real base or null for NULL. + // base_uri is nullable and FFI cstring cannot encode NULL. const baseUri = baseUrl === undefined ? null : cstr(baseUrl); this.#live()?.webkit_web_view_load_html(this.#view, cstr(html), baseUri); } @@ -223,26 +201,19 @@ class LinuxWebContents implements NativeWebContents { setUserAgent(userAgent: string): void { const webkit = this.#live(); - // Set on the view's WebKitSettings; takes effect on the next navigation. + // Takes effect on the next navigation. webkit?.webkit_settings_set_user_agent( webkit.webkit_web_view_get_settings(this.#view), cstr(userAgent), ); } - /** - * Evaluate `code` in the PAGE world (world_name = NULL) and resolve to its - * completion value. The result returns out-of-band through the page-world - * `bunmaskaExec` handler (mirrors macOS, D022) — NO per-call native callback, so - * nothing is freed mid-invocation. - */ executeJavaScript(code: string): Promise { return this.#exec.executeJavaScript(code); } printToPDF(): Promise { - // WebKitGTK exposes only a printer/file print operation, not a page→PDF-bytes - // API like WKWebView's createPDFWithConfiguration. Deferred (see PARITY.md). + // WebKitGTK prints only to a printer or file; it has no page-to-PDF-bytes API. return Promise.reject( new UnsupportedPlatformError('webContents.printToPDF is not yet supported on Linux'), ); @@ -299,20 +270,7 @@ class LinuxWebContents implements NativeWebContents { } } -/** - * Linux {@link NativeWindow}: a `GtkWindow` hosting a `WebKitWebView` as its - * single child. Title / visibility / minimized state are tracked in JS because - * GTK 4 exposes no reliable getters for them. - * - * Lifecycle events: `focus`/`blur` (notify::is-active), `resize` - * (notify::default-width/height), `maximize`/`unmaximize` (notify::maximized), - * `show`/`hide` (emitted from show()/hide()), `ready-to-show` (first finished - * load), and a preventable `close` (close-request veto). DEFERRED on Linux: - * `minimize`/`restore` — GTK 4 has no public, notifiable minimized property nor - * a `gtk_window_is_minimized` getter, so the window-manager-driven iconify state - * cannot be observed reliably. `minimize()` still iconifies and `isMinimized()` - * reports the JS-tracked flag; only the EVENT is unavailable. - */ +/** Title, visibility and minimized state are tracked in JS: GTK 4 has no reliable getters for them. */ class LinuxWindow implements NativeWindow { readonly #window: Pointer; readonly #webContents: LinuxWebContents; @@ -331,7 +289,6 @@ class LinuxWindow implements NativeWindow { #releaseAppMenu: (() => void) | undefined; readonly #eventHandlers = new Map void>(); - /** Surface a non-preventable lifecycle event to its registered handler. */ #emitEvent(type: WindowEventType): void { this.#eventHandlers.get(type)?.(); } @@ -361,18 +318,15 @@ class LinuxWindow implements NativeWindow { this.#webContents = new LinuxWebContents(options.preloadScript); const appMenu = getCurrentAppMenu(); if (appMenu === undefined) { - // Default path — unchanged: the webview is the window's sole child. gtk.symbols.gtk_window_set_child(this.#window, this.#webContents.view()); } else { - // App-menu path: realize a PER-WINDOW model + action group from the app-menu spec tree, - // so role items (Copy/Paste/minimize/…) dispatch onto THIS window's own web view/window. - // Then stack a GtkPopoverMenuBar above the webview and insert this window's group. + // Per-window model + group, so role items act on THIS window's own view (D039). const menu = loadGtkMenuFFI(); const view = this.#webContents.view(); const win = this.#window; const dispatchRole = (spec: NativeMenuItemSpec): void => { if (this.#closed) { - return; // window torn down — its view/window pointers may be freed (use-after-free guard). + return; // the view and window may be freed (use-after-free guard, D039). } if (spec.editingCommand !== undefined) { loadWebKitGtkFFI().symbols.webkit_web_view_execute_editing_command( @@ -398,8 +352,7 @@ class LinuxWindow implements NativeWindow { gtk.symbols.gtk_window_fullscreen(win); } } - // appAction roles (quit/about) are deferred on Linux v1 — a no-op here. - }; + }; // ponytail: appAction roles (quit/about) are inert on a Linux click; their shortcuts work (D039) const entry = realizeForWindow(appMenu.specs, dispatchRole); const model = Number(entry.model) as unknown as Pointer; const group = Number(entry.group) as unknown as Pointer; @@ -416,18 +369,12 @@ class LinuxWindow implements NativeWindow { gtk.symbols.gtk_window_set_child(this.#window, box); } - // Preventable close-request: consult the JS `close` listener first. If it - // vetoes, return true (1) so GTK's default handler does NOT destroy the - // window. Otherwise run teardown + fire `closed`, then return false (0) so - // GTK destroys it. Returning the veto is the Linux half of preventable close. this.#registry.connect( this.#window, 'close-request', makeCloseRequestCallback(() => this.#requestClose()), ); - // Focus/blur: `notify::is-active` fires when the active state flips; read the - // dedicated getter (no g_object_get varargs) and emit the matching edge. this.#registry.connect( this.#window, 'notify::is-active', @@ -441,7 +388,7 @@ class LinuxWindow implements NativeWindow { }), ); - // Maximize/unmaximize: `notify::maximized` on the GtkWindow:maximized prop. + // GTK 4 leaves default-width/height untouched while maximized or fullscreen. this.#registry.connect( this.#window, 'notify::maximized', @@ -461,8 +408,7 @@ class LinuxWindow implements NativeWindow { makeNotifyCallback(() => this.#emitEvent('resize')), ); - // Resize: the default-size props change when the window is resized. Two - // distinct callbacks so the registry closes each exactly once on teardown. + // One thunk per signal, so the registry closes each exactly once. this.#registry.connect( this.#window, 'notify::default-width', @@ -474,8 +420,6 @@ class LinuxWindow implements NativeWindow { makeNotifyCallback(() => this.#emitEvent('resize')), ); - // ready-to-show: emit once on the first finished load (reuses the web - // contents' load-changed FINISHED signal). let readyToShowEmitted = false; this.#webContents.onNavigation((event) => { if (event.type === 'did-finish-load' && !readyToShowEmitted) { @@ -493,15 +437,9 @@ class LinuxWindow implements NativeWindow { return this.#webContents; } - /** - * Consult the JS `close` listener for a native `close-request`. Returns true - * to VETO (the window stays open); on a non-veto runs the close bookkeeping + - * teardown and returns false so GTK destroys the window. - */ + /** Native close: true vetoes; otherwise tear down and let GTK destroy the window. */ #requestClose(): boolean { if (this.#closed) { - // Already torn down (e.g. programmatic close races the native request): - // allow GTK to finish destroying. return false; } if (this.#vetoed()) { @@ -561,12 +499,10 @@ class LinuxWindow implements NativeWindow { } setPosition(_x: number, _y: number): void { - // GTK4 removed programmatic positioning; the compositor places the window - // (Wayland forbids clients moving themselves). No-op by design, like center(). + // No-op: GTK 4 has no client positioning; the compositor places windows (Wayland forbids it). } setBounds(bounds: Rect): void { - // Only the size is honourable on GTK4; position is compositor-controlled. this.setSize(bounds.width, bounds.height); } @@ -583,8 +519,7 @@ class LinuxWindow implements NativeWindow { } center(): void { - // GTK4 removed programmatic window positioning; the compositor places the - // window (and Wayland forbids clients moving themselves). No-op by design. + // No-op: see setPosition. } getBounds(): Rect { @@ -650,7 +585,7 @@ class LinuxWindow implements NativeWindow { } isMinimized(): boolean { - return this.#minimized; + return this.#minimized; // ponytail: misses WM iconify and never emits minimize/restore; X11 reports it via GdkToplevel notify::state } restore(): void { @@ -676,7 +611,7 @@ class LinuxWindow implements NativeWindow { } setAlwaysOnTop(_flag: boolean): void { - // GTK4 dropped keep-above; no portable client API. No-op (best-effort). + // No-op: GTK 4 dropped keep-above and has no portable replacement. } close(): void { @@ -690,7 +625,6 @@ class LinuxWindow implements NativeWindow { if (this.#closed) { return; } - // Force-close: run teardown then destroy WITHOUT consulting the veto. this.#handleClosed(); loadGtkFFI().symbols.gtk_window_destroy(this.#window); } @@ -713,7 +647,7 @@ class LinuxWindow implements NativeWindow { } const entry = getMenuEntry(menuHandle); if (entry === undefined) { - return; // unknown handle — nothing to show. + return; // unknown handle } const menu = loadGtkMenuFFI(); this.#closeActivePopover(); // replace any open popover. @@ -724,13 +658,13 @@ class LinuxWindow implements NativeWindow { return; } menu.symbols.gtk_widget_set_parent(popover, this.#window); - // Insert the menu's action group so its items are live (mirrors the menu-bar path). + // Without its action group the items render but stay inert. menu.symbols.gtk_widget_insert_action_group( popover, cstr('bunmaska'), Number(entry.group) as unknown as Pointer, ); - // GdkRectangle { x, y, width:1, height:1 } — a 1×1 rect is a point (window-relative coords). + // A 1x1 GdkRectangle { x, y, width, height } is a point, window-relative. menu.symbols.gtk_popover_set_pointing_to(popover, ptr(new Int32Array([x, y, 1, 1]))); menu.symbols.gtk_popover_popup(popover); // non-blocking; item activation fires via the pump. this.#activePopover = popover; @@ -751,10 +685,6 @@ class LinuxWindow implements NativeWindow { } } -/** - * Linux {@link NativeApplication}: initializes GTK, drives the cooperative pump, - * and owns the set of live windows. - */ export class LinuxApplication implements NativeApplication { #pump: CooperativePump | undefined; #started = false; @@ -788,10 +718,9 @@ export class LinuxApplication implements NativeApplication { this.#readyCallbacks.push(callback); } - /** Show a GTK about dialog (Electron's `showAboutPanel`). */ showAboutPanel(): void { const gtk = loadGtkFFI(); - const dialog = gtk.symbols.gtk_about_dialog_new(); + const dialog = gtk.symbols.gtk_about_dialog_new(); // ponytail: no name, version or parent; needs gtk_about_dialog_set_* in gtk-ffi if (dialog !== null) { gtk.symbols.gtk_window_present(dialog); } diff --git a/src/main/platform/linux/webkit-ipc.ts b/src/main/platform/linux/webkit-ipc.ts index eed35c34..4b0dddbf 100644 --- a/src/main/platform/linux/webkit-ipc.ts +++ b/src/main/platform/linux/webkit-ipc.ts @@ -5,34 +5,18 @@ import { loadGObjectFFI } from './gobject-ffi'; import { makeScriptMessageCallback, SignalRegistry } from './gtk-signals'; import { loadWebKitGtkFFI, WEBKIT_USER_SCRIPT_INJECT_AT_DOCUMENT_START } from './webkitgtk-ffi'; -/** `WebKitUserContentInjectedFrames`: never inject into subframes, or a third-party iframe gets the bridge and every exposed API. */ +/** `WebKitUserContentInjectedFrames`: never subframes, or a third-party iframe gets every exposed API. */ const WEBKIT_USER_CONTENT_INJECT_TOP_FRAME = 1; -/** - * Name of the isolated JS world the bridge + user preload run in (Electron - * `contextIsolation: true`). The page/main world is `NULL`. Must match the - * macOS `PRELOAD_WORLD_NAME`. - */ +/** The isolated world (Electron `contextIsolation`) the bridge and preloads run in. */ export const PRELOAD_WORLD_NAME = 'BunmaskaPreload'; -/** - * WebKitGTK 6.0 IPC bridge. The `WebKitUserContentManager` must be fully wired - * BEFORE the view is constructed (it is a construct-only property); envelopes go - * back to the renderer fire-and-forget via `evaluate_javascript` (D022). - */ - -/** The script-message handler name the preload bridge posts to. */ +/** The isolated-world handler the preload bridge posts envelopes to. */ export const HANDLER_NAME = 'bunmaska'; -/** The detailed signal connected before registering the handler (documented race). */ export const SIGNAL = `script-message-received::${HANDLER_NAME}`; -/** - * Page-world handler name `executeJavaScript` posts its result to. Mirrors the - * macOS `EXEC_RESULT_HANDLER_NAME` — the return channel for the public - * `executeJavaScript`, registered in the PAGE world (world_name = NULL). - */ +/** The page-world handler the `executeJavaScript` wrapper posts its result to. */ export const EXEC_HANDLER_NAME = 'bunmaskaExec'; -/** The detailed signal connected before registering the exec handler. */ export const EXEC_SIGNAL = `script-message-received::${EXEC_HANDLER_NAME}`; /** A web view wired for IPC, plus the manager and the signal registry to retain. */ @@ -43,20 +27,14 @@ export type WiredWebView = { }; export type WebViewIpcOptions = { - /** The preload bridge source injected at document-start in the isolated world. */ readonly preloadSource: string; readonly userPreloadSource?: string; readonly isolatedSetupSource: string; readonly isolatedHostSource: string; readonly pageWorldSource: string; - /** Called with each JSON envelope the renderer posts. */ readonly onMessage: (json: string) => void; - /** - * Called with each JSON `{ execId, ok, result?, error? }` the page-world - * `executeJavaScript` wrapper posts to the `bunmaskaExec` handler. Optional. - */ + /** Receives each `{ execId, ok, result?, error? }` JSON the exec wrapper posts. */ readonly onExecMessage: (json: string) => void; - /** Called when the page-world dom-ready script fires (DOMContentLoaded). Optional. */ readonly onDomReady: () => void; }; @@ -94,10 +72,10 @@ const addPageWorldScript = (ucm: Pointer, source: string): void => { }; /** - * Create a `WebKitWebView` with a pre-wired user-content-manager. Connect each - * `script-message-received::` signal BEFORE registering its handler (documented - * race), then pass the manager to `g_object_new` as a construct-only property — - * its trailing arg MUST be a true null terminator (0). + * The user-content-manager is construct-only, so it is fully wired before + * `g_object_new`, whose varargs MUST end in a real NULL. Each + * `script-message-received::` signal is connected BEFORE its handler is + * registered (documented race). */ export const createWebViewWithIpc = (options: WebViewIpcOptions): WiredWebView => { const webkit = loadWebKitGtkFFI(); @@ -112,19 +90,13 @@ export const createWebViewWithIpc = (options: WebViewIpcOptions): WiredWebView = const callback = makeScriptMessageCallback(options.onMessage); registry.connect(ucm, SIGNAL, callback); - // Register the handler IN the isolated world so its `webkit.messageHandlers` - // binding is reachable only from there (matches the user-script world below). + // Isolated world only: page scripts must never reach the `bunmaska` handler. webkit.symbols.webkit_user_content_manager_register_script_message_handler( ucm, cstr(HANDLER_NAME), cstr(PRELOAD_WORLD_NAME), ); - // Second handler in the PAGE world (world_name = NULL): the return channel for - // the public `executeJavaScript`, whose wrapper posts its result here. Its - // JSCallback is retained in the SAME registry so it is closed on window - // teardown — NEVER per-call (closing a JSCallback mid-invocation frees its - // native trampoline). Connect the detailed signal BEFORE registering (race). registry.connect(ucm, EXEC_SIGNAL, makeScriptMessageCallback(options.onExecMessage)); webkit.symbols.webkit_user_content_manager_register_script_message_handler( ucm, @@ -132,8 +104,6 @@ export const createWebViewWithIpc = (options: WebViewIpcOptions): WiredWebView = null, ); - // Page-world dom-ready handler: the injected script posts here on - // DOMContentLoaded. Same retain/connect-before-register discipline as exec. registry.connect( ucm, `script-message-received::${DOM_READY_HANDLER_NAME}`, @@ -145,18 +115,15 @@ export const createWebViewWithIpc = (options: WebViewIpcOptions): WiredWebView = null, ); - // Isolated world: channel-id setup (if any) BEFORE the bridge, then the - // bridge, then the contextBridge host (installs exposeInMainWorld), then the - // user preload (so it can call exposeInMainWorld). + // Order matters: channel setup, bridge, contextBridge host (installs + // exposeInMainWorld), then the user preload that calls it. addUserScript(ucm, options.isolatedSetupSource); addUserScript(ucm, options.preloadSource); addUserScript(ucm, options.isolatedHostSource); if (options.userPreloadSource !== undefined) { addUserScript(ucm, options.userPreloadSource); } - // Page/main world: the cross-world contextBridge stub (Phase B). addPageWorldScript(ucm, options.pageWorldSource); - // Page/main world: the dom-ready notifier (posts on DOMContentLoaded). addPageWorldScript(ucm, generateDomReadyScript()); const view = requirePointer( @@ -172,19 +139,11 @@ export const createWebViewWithIpc = (options: WebViewIpcOptions): WiredWebView = return { view, ucm, registry }; }; -/** - * Escape a JSON envelope string as a JS string literal so it can be embedded in - * the `window.__bunmaska._dispatch(...)` call passed to `evaluate_javascript`. - */ +/** A no-op until the isolated-world bridge exists. */ export const buildDispatchScript = (envelopeJson: string): string => `window.__bunmaska && window.__bunmaska._dispatch(${JSON.stringify(envelopeJson)});`; -/** - * Push a JSON envelope to the renderer's preload bridge via fire-and-forget - * `evaluate_javascript` (length = -1 for NUL-terminated; cancellable/callback/ - * user_data are NULL). `world_name` targets the ISOLATED `BunmaskaPreload` world, - * where `__bunmaska._dispatch` lives — NOT the page world. - */ +/** Fire-and-forget into the ISOLATED world, where `__bunmaska._dispatch` lives (not the page world). */ export const sendToRenderer = (view: Pointer, envelopeJson: string): void => { const webkit = loadWebKitGtkFFI(); webkit.symbols.webkit_web_view_evaluate_javascript( @@ -199,12 +158,7 @@ export const sendToRenderer = (view: Pointer, envelopeJson: string): void => { ); }; -/** - * Evaluate `source` in the PAGE/main world (world_name = NULL) fire-and-forget — - * NO `GAsyncReadyCallback` (length = -1 for NUL-terminated; cancellable/callback/ - * user_data are NULL). Used to inject the `executeJavaScript` wrapper, whose - * result returns out-of-band via the `bunmaskaExec` page-world handler. - */ +/** Fire-and-forget into the page world (world_name NULL); used for the exec wrapper. */ export const evalInPageWorld = (view: Pointer, source: string): void => { const webkit = loadWebKitGtkFFI(); webkit.symbols.webkit_web_view_evaluate_javascript( diff --git a/src/main/platform/linux/webkit-uri-scheme.ts b/src/main/platform/linux/webkit-uri-scheme.ts index 314a3976..07d5505f 100644 --- a/src/main/platform/linux/webkit-uri-scheme.ts +++ b/src/main/platform/linux/webkit-uri-scheme.ts @@ -7,40 +7,24 @@ import { loadGlibFFI } from './glib-ffi'; import { loadGObjectFFI } from './gobject-ffi'; import { loadWebKitGtkFFI } from './webkitgtk-ffi'; -/** - * Bridges WebKitGTK custom URI-scheme requests to the `protocol` module. - * - * JSCallback lifecycle: each scheme's callback is a {@link JSCallback} retained - * in a module-level Set for the process lifetime. It is NEVER closed inside its - * own invocation — closing the thunk mid-callback frees the native trampoline - * GObject still points at (SIGSEGV). Schemes are registered once per process on - * the default context; a second registration of the same scheme is a guarded - * no-op (WebKit aborts on a duplicate registration). - */ - const log = createLogger('linux-uri-scheme'); -/** The Bunmaska error domain for a failed custom-scheme request. */ const ERROR_DOMAIN = 'BunmaskaProtocol'; -/** Error code for an unhandled/declined request. */ const ERROR_CODE_NO_HANDLER = 1; -/** Retains every URI-scheme {@link JSCallback} for the process lifetime. */ +/** Scheme thunks live for the process: WebKit keeps calling them and has no unregister. */ const retainedCallbacks = new Set(); -/** Schemes already registered on the (single, default) context — dedup guard. */ +/** WebKit aborts on a duplicate registration, so each scheme registers once per process. */ const registeredSchemes = new Set(); -/** Read the (transfer-none) request URI as a JS string. */ +/** The request URI is transfer-none: read it, never free it. */ const requestUri = (request: Pointer): string => { const webkit = loadWebKitGtkFFI(); const uriPtr = webkit.symbols.webkit_uri_scheme_request_get_uri(request); return uriPtr === null ? '' : new CString(uriPtr).toString(); }; -/** - * Complete `request` with an error (no handler / declined). Best-effort: builds - * a GError, finishes the request with it, then frees the GError. - */ +/** Fail `request`: no handler matched, or the handler threw. */ const finishError = (request: Pointer): void => { const webkit = loadWebKitGtkFFI(); const glib = loadGlibFFI(); @@ -56,12 +40,7 @@ const finishError = (request: Pointer): void => { } }; -/** - * Serve `built` to `request`: copy the bytes into a `GBytes`, wrap it in a - * `GMemoryInputStream`, then complete via `webkit_uri_scheme_request_finish`. - * The stream is owned by `finish` (it takes its own ref); the local `GBytes` - * (and the stream ref we hold) are dropped after the call. - */ +/** Ownership: `finish` refs the stream and the stream refs the GBytes, so both of our refs drop here. */ const finishWithBytes = (request: Pointer, built: BuiltProtocolResponse): void => { const webkit = loadWebKitGtkFFI(); const glib = loadGlibFFI(); @@ -93,15 +72,11 @@ const finishWithBytes = (request: Pointer, built: BuiltProtocolResponse): void = BigInt(bytes.length), cstr(built.mimeType), ); - // finish() took its own ref on the stream; drop the one g_memory_input_stream - // handed us (transfer-full) so the stream is freed once WebKit is done. + // Drop our transfer-full stream ref; WebKit frees the stream when done. loadGObjectFFI().symbols.g_object_unref(stream); }; -/** - * @internal The body of the URI-scheme callback. Never throws out into the - * callback — any error completes the request with an error instead. - */ +/** @internal Completes the request with an error rather than throwing into the native callback. */ export const handleUriSchemeRequest = (request: Pointer): void => { try { const url = requestUri(request); @@ -117,16 +92,14 @@ export const handleUriSchemeRequest = (request: Pointer): void => { } }; -/** ABI shape for `WebKitURISchemeRequestCallback`: `(request, user_data) -> void`. */ +/** `WebKitURISchemeRequestCallback`: `(request, user_data) -> void`. */ export const URI_SCHEME_CB_DEF = { args: ['ptr', 'ptr'], returns: 'void' } as const; -/** Build the retained URI-scheme {@link JSCallback}. */ const makeUriSchemeCallback = (): JSCallback => new JSCallback((request: Pointer, _userData: Pointer): void => { handleUriSchemeRequest(request); }, URI_SCHEME_CB_DEF); -/** Get the WebKit context for `view` (or the process-wide default if `view` is null). */ const contextFor = (view: Pointer | null): Pointer | null => { const webkit = loadWebKitGtkFFI(); if (view === null) { @@ -135,15 +108,7 @@ const contextFor = (view: Pointer | null): Pointer | null => { return webkit.symbols.webkit_web_view_get_context(view); }; -/** - * Register a custom URI scheme on `view`'s WebKit context (or the default - * context when `view` is null). Idempotent per scheme name: registering an - * already-registered scheme is a no-op (WebKit aborts on a duplicate - * registration on the same context). - * - * The callback {@link JSCallback} is retained for the process lifetime — never - * closed inside its own invocation. - */ +/** Register `scheme` on `view`'s context (the default one when null); idempotent per scheme. */ export const registerUriScheme = (scheme: string, view: Pointer | null): void => { if (registeredSchemes.has(scheme)) { return; @@ -170,11 +135,7 @@ export const registerUriScheme = (scheme: string, view: Pointer | null): void => registeredSchemes.add(scheme); }; -/** - * Register every scheme currently registered with the `protocol` module on - * `view`'s context. Called at web-view creation so custom schemes are wired - * before any load. Each scheme is registered once per process (the dedup guard). - */ +/** Wire every `protocol.handle` scheme; call before the view's first load. */ export const registerAllSchemes = (view: Pointer | null): void => { for (const scheme of protocol.getRegisteredSchemes()) { registerUriScheme(scheme, view); From f169d29dea611e0087ea91a8dfff47dd82f8e24a Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:58:36 -0700 Subject: [PATCH 107/586] fix: free per-window WebKit config and scripts, share scheme handler --- src/main/platform/macos/cocoa-backend.ts | 10 ++- tests/integration/macos/cocoa-backend.test.ts | 88 ++++++++++++++++++- 2 files changed, 95 insertions(+), 3 deletions(-) diff --git a/src/main/platform/macos/cocoa-backend.ts b/src/main/platform/macos/cocoa-backend.ts index 990dbaeb..496552d3 100644 --- a/src/main/platform/macos/cocoa-backend.ts +++ b/src/main/platform/macos/cocoa-backend.ts @@ -161,6 +161,9 @@ const enableDeveloperExtras = (preferences: Handle): void => { } }; +/** One stateless handler serves every scheme of every window. */ +let schemeHandler: Handle | undefined; + /** RFC 3986 scheme syntax. */ const VALID_SCHEME = /^[a-z][a-z0-9+.-]*$/; @@ -177,7 +180,7 @@ const registerCustomSchemes = (configuration: Handle): void => { return; } const rt = cocoa(); - const handler = createUrlSchemeHandler(); + schemeHandler ??= createUrlSchemeHandler().handle; for (const scheme of schemes) { const unsupported = !VALID_SCHEME.test(scheme) || @@ -194,7 +197,7 @@ const registerCustomSchemes = (configuration: Handle): void => { msgSendPtrPtr( configuration, rt.selectors.get('setURLSchemeHandler:forURLScheme:'), - handler.handle, + schemeHandler, nsString(scheme), ); } catch (error) { @@ -1124,6 +1127,7 @@ class MacOSApplication implements NativeApplication { world, ); msgSendPtr(userContentController, rt.selectors.get('addUserScript:'), userScript); + rt.msgSend(userScript, rt.selectors.get('release')); }; // Per-window cross-world channel id for contextBridge (Phase B). The page @@ -1156,6 +1160,8 @@ class MacOSApplication implements NativeApplication { 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); // Forward-declared so the navigation + window delegate closures can reference diff --git a/tests/integration/macos/cocoa-backend.test.ts b/tests/integration/macos/cocoa-backend.test.ts index ace3febb..b895a668 100644 --- a/tests/integration/macos/cocoa-backend.test.ts +++ b/tests/integration/macos/cocoa-backend.test.ts @@ -1,15 +1,18 @@ import { describe, expect, jest, test } from 'bun:test'; +import { dlopen, FFIType, ptr } from 'bun:ffi'; import { currentPlatform } from '../../../src/common/platform'; import { protocol } from '../../../src/main/api/protocol'; import { createMacOSApplication } from '../../../src/main/platform/macos/cocoa-backend'; import { retainedBlockCount } from '../../../src/main/platform/macos/cocoa-block'; -import { nsStringToString } from '../../../src/main/platform/macos/cocoa-foundation'; +import { nsString, nsStringToString } from '../../../src/main/platform/macos/cocoa-foundation'; import { msgSendI64, + msgSendPtr, msgSendReturnsI64, msgSendReturnsU8, } from '../../../src/main/platform/macos/cocoa-msgsend-variants'; import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; +import { LIBOBJC_PATH } from '../../../src/main/platform/macos/objc'; const delay = (ms: number): Promise => new Promise((resolve) => setTimeout(resolve, ms)); @@ -28,6 +31,33 @@ const nsWindowTitled = (title: string): bigint => { return 0n; }; +const weakRefs = (): { + readonly observe: (object: bigint) => BigUint64Array; + readonly isAlive: (slot: BigUint64Array) => boolean; + readonly forget: (slot: BigUint64Array) => void; +} => { + const objc = dlopen(LIBOBJC_PATH, { + objc_initWeak: { args: [FFIType.ptr, FFIType.u64], returns: FFIType.u64 }, + objc_loadWeakRetained: { args: [FFIType.ptr], returns: FFIType.u64 }, + objc_destroyWeak: { args: [FFIType.ptr], returns: FFIType.void }, + }).symbols; + return { + observe: (object) => { + const slot = new BigUint64Array(1); + objc.objc_initWeak(ptr(slot), object); + return slot; + }, + isAlive: (slot) => { + const object = objc.objc_loadWeakRetained(ptr(slot)); + if (object !== 0n) { + cocoa().msgSend(object, cocoa().selectors.get('release')); + } + return object !== 0n; + }, + forget: (slot) => objc.objc_destroyWeak(ptr(slot)), + }; +}; + const waitFor = async (predicate: () => boolean, ms = 3_000): Promise => { const deadline = performance.now() + ms; while (!predicate() && performance.now() < deadline) { @@ -423,6 +453,62 @@ if (currentPlatform() === 'macos') { } }); + test('a closed window releases its configuration and user scripts', async () => { + const app = createMacOSApplication(); + app.start(); + const weak = weakRefs(); + try { + const win = app.createWindow({ width: 320, height: 240, title: 'scripts', show: true }); + const rt = cocoa(); + const webview = rt.msgSend(nsWindowTitled('scripts'), rt.selectors.get('contentView')); + const configuration = rt.msgSend(webview, rt.selectors.get('configuration')); + const controller = rt.msgSend(configuration, rt.selectors.get('userContentController')); + const scripts = rt.msgSend(controller, rt.selectors.get('userScripts')); + const slot = weak.observe(msgSendI64(scripts, rt.selectors.get('objectAtIndex:'), 0n)); + try { + win.close(); + await waitFor(() => !weak.isAlive(slot)); + expect(weak.isAlive(slot)).toBe(false); + } finally { + weak.forget(slot); + } + } finally { + app.quit(); + } + }); + + test('windows share one URL scheme handler', () => { + const app = createMacOSApplication(); + app.start(); + protocol.handle('bmshared', () => ({ data: 'x' })); + try { + const rt = cocoa(); + const handlerOf = (title: string): bigint => { + const webview = rt.msgSend(nsWindowTitled(title), rt.selectors.get('contentView')); + const configuration = rt.msgSend(webview, rt.selectors.get('configuration')); + return msgSendPtr( + configuration, + rt.selectors.get('urlSchemeHandlerForURLScheme:'), + nsString('bmshared'), + ); + }; + const first = app.createWindow({ width: 200, height: 100, title: 'scheme-a', show: false }); + const second = app.createWindow({ + width: 200, + height: 100, + title: 'scheme-b', + show: false, + }); + expect(handlerOf('scheme-a')).not.toBe(0n); + expect(handlerOf('scheme-a')).toBe(handlerOf('scheme-b')); + first.destroy(); + second.destroy(); + } finally { + protocol.unhandle('bmshared'); + app.quit(); + } + }); + test('close fires the onClosed callback once', () => { const app = createMacOSApplication(); app.start(); From ed6979978589bb44e85017594db0544879a6878e Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:58:48 -0700 Subject: [PATCH 108/586] fix: report real macOS display origins, work areas and cursor --- src/main/platform/macos/cocoa-screen.ts | 180 +++++++++++-------- tests/integration/macos/cocoa-screen.test.ts | 67 +++---- 2 files changed, 131 insertions(+), 116 deletions(-) diff --git a/src/main/platform/macos/cocoa-screen.ts b/src/main/platform/macos/cocoa-screen.ts index 0adee227..9a6f2d3a 100644 --- a/src/main/platform/macos/cocoa-screen.ts +++ b/src/main/platform/macos/cocoa-screen.ts @@ -1,31 +1,21 @@ import { FFIType, ptr } from 'bun:ffi'; import { dlopen } from '../dlopen'; -import { UnsupportedPlatformError } from '../../../common/errors'; -import { currentPlatform } from '../../../common/platform'; import type { Point, RawDisplay, ScreenBackend } from '../../api/screen'; +import type { Rect } from '../native'; +import { nsString } from './cocoa-foundation'; +import { + msgSendI64, + msgSendPtr, + msgSendPtrI64, + msgSendReturnsF64, + msgSendReturnsI64, +} from './cocoa-msgsend-variants'; +import { cocoa } from './cocoa-runtime'; +import { type Handle, macOSLibraryAccessor } from './objc'; /** - * macOS display enumeration via CoreGraphics scalar getters. - * - * WHY NOT NSScreen.frame / CGDisplayBounds (the struct-return path): bun:ffi - * 1.3.14 has no struct return type — `FFIType` exposes no `struct` member and - * `dlopen` rejects both an array layout (`[f64,f64,f64,f64]`) and an object - * layout as a `returns` type ("Unknown return type"). On arm64 a CGRect/NSRect - * is a homogeneous-float aggregate returned in v0..v3; declaring the call as - * `returns: f64` recovers ONLY the first field (origin.x). The remaining three - * doubles (y/width/height) are unreachable without struct support, and the - * inline C compiler (`cc`) is off-limits (zero-compiled-native-code rule). So - * the geometry comes entirely from CoreGraphics scalar getters, which were - * empirically verified on a real arm64 host to return sane values. - * - * v1 LIMITATION — display ORIGIN (bounds.x/y): CoreGraphics has no scalar - * getter for a display's global origin; only the struct-return CGDisplayBounds - * exposes it. The primary display's origin is (0,0) by definition, so single- - * display and primary geometry are exact. For SECONDARY displays the origin is - * reported as (0,0) too (documented), which makes multi-monitor bounds.x/y and - * cross-display nearest-point placement approximate until struct return lands. - * workArea == bounds on macOS v1 (the menu-bar/dock inset needs NSScreen - * visibleFrame, another struct return), documented. + * macOS displays. bun:ffi cannot return an NSRect/NSPoint struct, so geometry is read + * through KVC (`valueForKey:` boxes it in an NSValue) and copied out with `getValue:size:`. */ const CG_PATH = '/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics'; @@ -47,35 +37,16 @@ const CG_SYMBOLS = { CGDisplayModeRelease: { args: [FFIType.pointer], returns: FFIType.void }, } as const; -const cache: { ffi: ReturnType> | undefined } = { ffi: undefined }; +export const loadCoreGraphicsFFI = macOSLibraryAccessor('CoreGraphics screen', () => + dlopen(CG_PATH, CG_SYMBOLS), +); -/** - * Open CoreGraphics and expose the display scalar getters. Only callable on - * macOS — throws {@link UnsupportedPlatformError} elsewhere so the module stays - * importable on Linux for unit testing. - */ -export const loadCoreGraphicsFFI = () => { - const platform = currentPlatform(); - if (platform !== 'macos') { - throw new UnsupportedPlatformError( - `loadCoreGraphicsFFI() is only supported on macOS; current platform is ${platform}`, - ); - } - if (cache.ffi) { - return cache.ffi; - } - const ffi = dlopen(CG_PATH, CG_SYMBOLS); - cache.ffi = ffi; - return ffi; -}; +type CGSymbols = ReturnType['symbols']; const MAX_DISPLAYS = 32; /** scaleFactor = physical / logical width of the display's current mode (>= 1). */ -const scaleFactorFor = ( - symbols: ReturnType['symbols'], - id: number, -): number => { +const scaleFactorFor = (symbols: CGSymbols, id: number): number => { const mode = symbols.CGDisplayCopyDisplayMode(id); if (mode === null) { return 1; @@ -86,15 +57,14 @@ const scaleFactorFor = ( return logical > 0 ? physical / logical : 1; }; -const rawDisplayFor = ( - symbols: ReturnType['symbols'], - id: number, -): RawDisplay => { - const width = Number(symbols.CGDisplayPixelsWide(id)); - const height = Number(symbols.CGDisplayPixelsHigh(id)); - // Origin x/y has no scalar getter; (0,0) is exact for the primary display and - // a documented v1 approximation for secondary displays. See module header. - const bounds = { x: 0, y: 0, width, height }; +/** CoreGraphics-only fallback for when AppKit lists no screens: origin (0,0), workArea = bounds. */ +const cgDisplayFor = (symbols: CGSymbols, id: number): RawDisplay => { + const bounds = { + x: 0, + y: 0, + width: Number(symbols.CGDisplayPixelsWide(id)), + height: Number(symbols.CGDisplayPixelsHigh(id)), + }; return { id, bounds, @@ -106,37 +76,95 @@ const rawDisplayFor = ( }; }; -/** Enumerate the active displays via CoreGraphics scalar getters. */ +const cgDisplays = (symbols: CGSymbols): RawDisplay[] => { + const ids = new Uint32Array(MAX_DISPLAYS); + const count = new Uint32Array(1); + const err = symbols.CGGetActiveDisplayList(MAX_DISPLAYS, ptr(ids), ptr(count)); + const found = count[0] ?? 0; + if (err !== 0 || found === 0) { + return [cgDisplayFor(symbols, symbols.CGMainDisplayID())]; + } + return Array.from(ids.subarray(0, found), (id) => cgDisplayFor(symbols, id)); +}; + +/** Copy `count` doubles out of the NSValue that `[object valueForKey:key]` boxes. */ +const readBoxed = (object: Handle, key: string, count: number): Float64Array => { + const rt = cocoa(); + const value = msgSendPtr(object, rt.selectors.get('valueForKey:'), nsString(key)); + const out = new Float64Array(count); + msgSendPtrI64(value, rt.selectors.get('getValue:size:'), BigInt(ptr(out)), BigInt(count * 8)); + return out; +}; + +/** A Cocoa bottom-left rect as top-left global coordinates; `primaryHeight` is the flip pivot. */ +const flipRect = ( + [x = 0, y = 0, width = 0, height = 0]: Float64Array, + primaryHeight: number, +): Rect => ({ + x, + y: primaryHeight - (y + height), + width, + height, +}); + +const screens = (): Handle[] => { + const rt = cocoa(); + const list = rt.msgSend(rt.classes.get('NSScreen'), rt.selectors.get('screens')); + const count = Number(msgSendReturnsI64(list, rt.selectors.get('count'))); + return Array.from({ length: count }, (_, i) => + msgSendI64(list, rt.selectors.get('objectAtIndex:'), BigInt(i)), + ); +}; + +/** Height of the menu-bar screen, which AppKit always lists first at the global origin. */ +const primaryHeightOf = (all: readonly Handle[]): number => { + const [primary] = all; + return primary === undefined ? 0 : (readBoxed(primary, 'frame', 4)[3] ?? 0); +}; + +const screenNumber = (screen: Handle): number => { + const rt = cocoa(); + const description = rt.msgSend(screen, rt.selectors.get('deviceDescription')); + const number = msgSendPtr( + description, + rt.selectors.get('objectForKey:'), + nsString('NSScreenNumber'), + ); + return Number(msgSendReturnsI64(number, rt.selectors.get('unsignedIntValue')) & 0xffffffffn); +}; + /** Primary display height (pt) - the top-left <-> bottom-left flip pivot. */ export const primaryDisplayHeight = (): number => { const symbols = loadCoreGraphicsFFI().symbols; return Number(symbols.CGDisplayPixelsHigh(symbols.CGMainDisplayID())); }; +/** The active displays in top-left global coordinates. */ export const getDisplays = (): readonly RawDisplay[] => { const { symbols } = loadCoreGraphicsFFI(); - const ids = new Uint32Array(MAX_DISPLAYS); - const count = new Uint32Array(1); - const err = symbols.CGGetActiveDisplayList(MAX_DISPLAYS, ptr(ids), ptr(count)); - const found = count[0] ?? 0; - if (err !== 0 || found === 0) { - // Fall back to the main display so callers always get at least one entry. - return [rawDisplayFor(symbols, symbols.CGMainDisplayID())]; + const all = screens(); + if (all.length === 0) { + return cgDisplays(symbols); } - const displays: RawDisplay[] = []; - for (let i = 0; i < found; i++) { - displays.push(rawDisplayFor(symbols, ids[i] ?? 0)); - } - return displays; + const primaryHeight = primaryHeightOf(all); + return all.map((screen) => { + const id = screenNumber(screen); + return { + id, + bounds: flipRect(readBoxed(screen, 'frame', 4), primaryHeight), + workArea: flipRect(readBoxed(screen, 'visibleFrame', 4), primaryHeight), + scaleFactor: msgSendReturnsF64(screen, cocoa().selectors.get('backingScaleFactor')), + rotation: symbols.CGDisplayRotation(id), + internal: symbols.CGDisplayIsBuiltin(id) === 1, + primary: symbols.CGDisplayIsMain(id) === 1, + }; + }); }; -/** - * Cursor position. NSEvent.mouseLocation returns an NSPoint (2-f64 struct) — - * the same struct-return wall as the frame rects — so v1 returns {0,0}. The - * bottom-left-origin flip would also be needed even if the struct were - * readable, so this is deferred behind the struct-return work. Documented. - */ -export const getCursorScreenPoint = (): Point => ({ x: 0, y: 0 }); +export const getCursorScreenPoint = (): Point => { + const [x = 0, y = 0] = readBoxed(cocoa().classes.get('NSEvent'), 'mouseLocation', 2); + return { x, y: primaryHeightOf(screens()) - y }; +}; export const cocoaScreenBackend: ScreenBackend = { getDisplays, diff --git a/tests/integration/macos/cocoa-screen.test.ts b/tests/integration/macos/cocoa-screen.test.ts index b10c80e8..10a275f0 100644 --- a/tests/integration/macos/cocoa-screen.test.ts +++ b/tests/integration/macos/cocoa-screen.test.ts @@ -1,38 +1,18 @@ import { describe, expect, test } from 'bun:test'; import { currentPlatform } from '../../../src/common/platform'; -import { - cocoaScreenBackend, - getDisplays, - loadCoreGraphicsFFI, -} from '../../../src/main/platform/macos/cocoa-screen'; +import type { RawDisplay } from '../../../src/main/api/screen'; +import { cocoaScreenBackend, getDisplays } from '../../../src/main/platform/macos/cocoa-screen'; + +const primaryOf = (displays: readonly RawDisplay[]): RawDisplay => { + const primary = displays.find((d) => d.primary); + if (primary === undefined) { + throw new Error('no primary display'); + } + return primary; +}; -/** - * The load-bearing proof that the CoreGraphics scalar-getter geometry path - * actually works on a REAL macOS host: at least one display with positive - * width/height and a scaleFactor >= 1, read live off the hardware. If bun:ffi - * could not return these scalars this test would fail with zeros or a crash. - */ if (currentPlatform() === 'macos') { describe('cocoa-screen on a real macOS host', () => { - test('loadCoreGraphicsFFI resolves the display scalar getters', () => { - const { symbols } = loadCoreGraphicsFFI(); - for (const name of [ - 'CGGetActiveDisplayList', - 'CGMainDisplayID', - 'CGDisplayPixelsWide', - 'CGDisplayPixelsHigh', - 'CGDisplayRotation', - 'CGDisplayIsBuiltin', - 'CGDisplayIsMain', - 'CGDisplayCopyDisplayMode', - 'CGDisplayModeGetWidth', - 'CGDisplayModeGetPixelWidth', - 'CGDisplayModeRelease', - ] as const) { - expect(typeof symbols[name]).toBe('function'); - } - }); - test('getDisplays returns at least one display with sane geometry', () => { const displays = getDisplays(); expect(displays.length).toBeGreaterThanOrEqual(1); @@ -42,21 +22,28 @@ if (currentPlatform() === 'macos') { expect(d.bounds.height).toBeGreaterThan(0); expect(d.scaleFactor).toBeGreaterThanOrEqual(1); expect(Number.isFinite(d.rotation)).toBe(true); - expect(typeof d.internal).toBe('boolean'); - // workArea mirrors bounds on macOS v1. - expect(d.workArea).toEqual(d.bounds); } }); - test('exactly one display reports itself as primary', () => { - const primaries = getDisplays().filter((d) => d.primary); - expect(primaries.length).toBe(1); + test('exactly one display reports itself as primary, at the global origin', () => { + const displays = getDisplays(); + expect(displays.filter((d) => d.primary).length).toBe(1); + expect(primaryOf(displays).bounds.x).toBe(0); + expect(primaryOf(displays).bounds.y).toBe(0); + }); + + test("the primary display's workArea sits below the menu bar, inside its bounds", () => { + const { bounds, workArea } = primaryOf(getDisplays()); + expect(workArea.y).toBeGreaterThan(bounds.y); + expect(workArea.y + workArea.height).toBeLessThanOrEqual(bounds.y + bounds.height); }); - test('the backend exposes a {0,0}-safe cursor point (v1 limit)', () => { - const point = cocoaScreenBackend.getCursorScreenPoint(); - expect(Number.isFinite(point.x)).toBe(true); - expect(Number.isFinite(point.y)).toBe(true); + test('the cursor point lies on some display', () => { + const { x, y } = cocoaScreenBackend.getCursorScreenPoint(); + const onDisplay = getDisplays().some( + ({ bounds: b }) => x >= b.x && x <= b.x + b.width && y >= b.y && y <= b.y + b.height, + ); + expect(onDisplay).toBe(true); }); }); } From 4ca76ce0151b9dc820b6d1f9b3ec293bd2582389 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:59:35 -0700 Subject: [PATCH 109/586] fix: let the macOS save panel open in a given directory --- src/main/platform/macos/cocoa-dialog.ts | 22 ++++++++++++++------ tests/integration/macos/cocoa-dialog.test.ts | 18 ++++++++++++++++ 2 files changed, 34 insertions(+), 6 deletions(-) diff --git a/src/main/platform/macos/cocoa-dialog.ts b/src/main/platform/macos/cocoa-dialog.ts index d4882a14..eb02067e 100644 --- a/src/main/platform/macos/cocoa-dialog.ts +++ b/src/main/platform/macos/cocoa-dialog.ts @@ -61,6 +61,8 @@ export type OpenDialogSpec = { export type SaveDialogSpec = { readonly defaultName: string; + /** Directory the panel opens at; absent = system default / last location. */ + readonly defaultDirectory?: string; /** Allowed file extensions (without dots); empty means any file. */ readonly extensions: ReadonlyArray; }; @@ -75,6 +77,16 @@ const nsArrayOfStrings = (strings: ReadonlyArray): Handle => { return array; }; +const setDirectory = (panel: Handle, path: string): void => { + const rt = cocoa(); + const url = msgSendPtr( + rt.classes.get('NSURL'), + rt.selectors.get('fileURLWithPath:'), + nsString(path), + ); + msgSendPtr(panel, rt.selectors.get('setDirectoryURL:'), url); +}; + /** Build (but do not run) an `NSAlert` for a message box. Returns its handle. */ export const buildAlert = (spec: MessageBoxSpec): Handle => { const rt = cocoa(); @@ -116,12 +128,7 @@ export const buildOpenPanel = (spec: OpenDialogSpec): Handle => { ); msgSendU8(panel, rt.selectors.get('setCanCreateDirectories:'), spec.canCreateDirectories ? 1 : 0); if (spec.defaultPath.length > 0) { - const url = msgSendPtr( - rt.classes.get('NSURL'), - rt.selectors.get('fileURLWithPath:'), - nsString(spec.defaultPath), - ); - msgSendPtr(panel, rt.selectors.get('setDirectoryURL:'), url); + setDirectory(panel, spec.defaultPath); } if (spec.extensions.length > 0) { msgSendPtr(panel, rt.selectors.get('setAllowedFileTypes:'), nsArrayOfStrings(spec.extensions)); @@ -152,6 +159,9 @@ export const showOpenDialog = (spec: OpenDialogSpec): string[] => { export const buildSavePanel = (spec: SaveDialogSpec): Handle => { const rt = cocoa(); const panel = rt.msgSend(rt.classes.get('NSSavePanel'), rt.selectors.get('savePanel')); + if (spec.defaultDirectory !== undefined && spec.defaultDirectory.length > 0) { + setDirectory(panel, spec.defaultDirectory); + } if (spec.defaultName.length > 0) { msgSendPtr(panel, rt.selectors.get('setNameFieldStringValue:'), nsString(spec.defaultName)); } diff --git a/tests/integration/macos/cocoa-dialog.test.ts b/tests/integration/macos/cocoa-dialog.test.ts index 82d3eea0..97b8d157 100644 --- a/tests/integration/macos/cocoa-dialog.test.ts +++ b/tests/integration/macos/cocoa-dialog.test.ts @@ -6,6 +6,7 @@ import { buildOpenPanel, buildSavePanel, } from '../../../src/main/platform/macos/cocoa-dialog'; +import { nsStringToString } from '../../../src/main/platform/macos/cocoa-foundation'; import { msgSendReturnsI64 } from '../../../src/main/platform/macos/cocoa-msgsend-variants'; import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; @@ -81,6 +82,23 @@ if (currentPlatform() === 'macos') { expect(buildSavePanel({ defaultName: 'untitled.txt', extensions: [] })).not.toBe(0n); }); + test('buildSavePanel opens in defaultDirectory with defaultName in the name field', () => { + const rt = cocoa(); + const panel = buildSavePanel({ + defaultName: 'report.pdf', + defaultDirectory: '/Library', + extensions: [], + }); + const directory = rt.msgSend( + rt.msgSend(panel, rt.selectors.get('directoryURL')), + rt.selectors.get('path'), + ); + expect(nsStringToString(directory)).toBe('/Library'); + expect(nsStringToString(rt.msgSend(panel, rt.selectors.get('nameFieldStringValue')))).toBe( + 'report.pdf', + ); + }); + test('buildSavePanel tolerates an empty default name', () => { expect(buildSavePanel({ defaultName: '', extensions: ['md'] })).not.toBe(0n); }); From 7a67b40c3b187736df3622af80869384b3083ae5 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:59:55 -0700 Subject: [PATCH 110/586] chore: trim Windows core comments to the comment rules --- src/main/platform/windows/win32-ffi.ts | 115 ++++++++---------- src/main/platform/windows/win32.ts | 27 +--- src/main/platform/windows/windows-backend.ts | 36 ++---- .../windows/windows-message-window.ts | 22 +--- .../platform/windows/windows-native-window.ts | 74 +++-------- src/main/platform/windows/windows-run-loop.ts | 30 ++--- 6 files changed, 99 insertions(+), 205 deletions(-) diff --git a/src/main/platform/windows/win32-ffi.ts b/src/main/platform/windows/win32-ffi.ts index e6e07c84..74d29839 100644 --- a/src/main/platform/windows/win32-ffi.ts +++ b/src/main/platform/windows/win32-ffi.ts @@ -2,14 +2,9 @@ import { FFIType } from 'bun:ffi'; import { dlopen } from '../dlopen'; import { winLibraryAccessor } from './win32'; -/** - * Handle discipline (see `win32.ts`): every `HWND`/`HINSTANCE`/`HMENU`/`HCURSOR` - * is declared `u64` and carried as a `bigint`, NOT `ptr` — a Win32 handle is an - * opaque kernel value, not a virtual address. Real pointers (the `WNDCLASSEXW` - * and `MSG` struct buffers, wide strings) are passed as `ptr`. - */ +// Handles are u64 bigints, never ptr (the rule lives in win32.ts). -/** user32.dll — window classes, windows, and the message pump. */ +/** user32.dll - window classes, windows, and the message pump. */ const USER32_SYMBOLS = { // (const WNDCLASSEXW *) -> ATOM RegisterClassExW: { args: [FFIType.ptr], returns: FFIType.u16 }, @@ -68,12 +63,12 @@ const USER32_SYMBOLS = { args: [FFIType.u64, FFIType.u32, FFIType.u64, FFIType.i64], returns: FFIType.i64, }, - // (HWND, UINT msg, WPARAM, LPARAM) -> BOOL — posts to the queue (the pump sees it) + // (HWND, UINT msg, WPARAM, LPARAM) -> BOOL - posts to the queue (the pump sees it) PostMessageW: { args: [FFIType.u64, FFIType.u32, FFIType.u64, FFIType.i64], returns: FFIType.i32, }, - // () -> BOOL — release mouse capture, so a custom-titlebar drag can hand off to + // () -> BOOL - release mouse capture, so a custom-titlebar drag can hand off to // the system move loop via WM_NCLBUTTONDOWN/HTCAPTION. ReleaseCapture: { args: [], returns: FFIType.i32 }, // (HWND, HWND insertAfter, int x, int y, int cx, int cy, UINT flags) -> BOOL @@ -89,68 +84,68 @@ const USER32_SYMBOLS = { ], returns: FFIType.i32, }, - // (HWND) -> BOOL — is the window minimised? + // (HWND) -> BOOL - is the window minimised? IsIconic: { args: [FFIType.u64], returns: FFIType.i32 }, - // (HWND) -> BOOL — is the window maximised? + // (HWND) -> BOOL - is the window maximised? IsZoomed: { args: [FFIType.u64], returns: FFIType.i32 }, - // (HWND, LPRECT) -> BOOL — the window's bounds in screen coordinates. + // (HWND, LPRECT) -> BOOL - the window's bounds in screen coordinates. GetWindowRect: { args: [FFIType.u64, FFIType.ptr], returns: FFIType.i32 }, // (HWND, WINDOWPLACEMENT *) -> BOOL - set `length` first; rcNormalPosition is the restored rect. GetWindowPlacement: { args: [FFIType.u64, FFIType.ptr], returns: FFIType.i32 }, - // (HWND) -> BOOL — bring the window to the foreground and focus it. + // (HWND) -> BOOL - bring the window to the foreground and focus it. SetForegroundWindow: { args: [FFIType.u64], returns: FFIType.i32 }, - // () -> HWND — the window the user is currently working with. + // () -> HWND - the window the user is currently working with. GetForegroundWindow: { args: [], returns: FFIType.u64 }, - // (HWND, int nIndex) -> LONG_PTR — read a window style word (GWL_STYLE/EXSTYLE). + // (HWND, int nIndex) -> LONG_PTR - read a window style word (GWL_STYLE/EXSTYLE). GetWindowLongPtrW: { args: [FFIType.u64, FFIType.i32], returns: FFIType.i64 }, - // (HWND, int nIndex, LONG_PTR) -> LONG_PTR — write a window style word. + // (HWND, int nIndex, LONG_PTR) -> LONG_PTR - write a window style word. SetWindowLongPtrW: { args: [FFIType.u64, FFIType.i32, FFIType.i64], returns: FFIType.i64 }, - // (HWND, COLORREF, BYTE alpha, DWORD flags) -> BOOL — per-window opacity. + // (HWND, COLORREF, BYTE alpha, DWORD flags) -> BOOL - per-window opacity. SetLayeredWindowAttributes: { args: [FFIType.u64, FFIType.u32, FFIType.u8, FFIType.u32], returns: FFIType.i32, }, - // (int nIndex) -> int — a system metric (e.g. primary screen width/height). + // (int nIndex) -> int - a system metric (e.g. primary screen width/height). GetSystemMetrics: { args: [FFIType.i32], returns: FFIType.i32 }, // ── Clipboard (used by the clipboard backend) ──────────────────────────── - // (HWND) -> BOOL — open the clipboard for the current task. + // (HWND) -> BOOL - open the clipboard for the current task. OpenClipboard: { args: [FFIType.u64], returns: FFIType.i32 }, - // () -> BOOL — close it (release ownership of the open). + // () -> BOOL - close it (release ownership of the open). CloseClipboard: { args: [], returns: FFIType.i32 }, - // () -> BOOL — empty + take ownership (the caller must hold it open). + // () -> BOOL - empty + take ownership (the caller must hold it open). EmptyClipboard: { args: [], returns: FFIType.i32 }, - // (UINT format) -> HANDLE — the clipboard still OWNS the returned handle. + // (UINT format) -> HANDLE - the clipboard still OWNS the returned handle. GetClipboardData: { args: [FFIType.u32], returns: FFIType.u64 }, - // (UINT format, HANDLE) -> HANDLE — the clipboard TAKES ownership of the handle. + // (UINT format, HANDLE) -> HANDLE - the clipboard TAKES ownership of the handle. SetClipboardData: { args: [FFIType.u32, FFIType.u64], returns: FFIType.u64 }, // (UINT format) -> BOOL IsClipboardFormatAvailable: { args: [FFIType.u32], returns: FFIType.i32 }, - // (LPCWSTR) -> UINT — register/look up a named format (e.g. "HTML Format"). + // (LPCWSTR) -> UINT - register/look up a named format (e.g. "HTML Format"). RegisterClipboardFormatW: { args: [FFIType.ptr], returns: FFIType.u32 }, // ── Global hot keys (used by the globalShortcut backend) ───────────────── - // (HWND, int id, UINT fsModifiers, UINT vk) -> BOOL — claim a system-wide hot + // (HWND, int id, UINT fsModifiers, UINT vk) -> BOOL - claim a system-wide hot // key; HWND NULL posts WM_HOTKEY to the calling thread's queue (the pump sees it). RegisterHotKey: { args: [FFIType.u64, FFIType.i32, FFIType.u32, FFIType.u32], returns: FFIType.i32, }, - // (HWND, int id) -> BOOL — release a hot key claimed with RegisterHotKey. + // (HWND, int id) -> BOOL - release a hot key claimed with RegisterHotKey. UnregisterHotKey: { args: [FFIType.u64, FFIType.i32], returns: FFIType.i32 }, // ── Displays + cursor (used by the screen backend) ─────────────────────── - // (HDC, LPCRECT clip, MONITORENUMPROC, LPARAM) -> BOOL — enumerate monitors; + // (HDC, LPCRECT clip, MONITORENUMPROC, LPARAM) -> BOOL - enumerate monitors; // the callback (a JSCallback function pointer) fires once per monitor. EnumDisplayMonitors: { args: [FFIType.u64, FFIType.ptr, FFIType.ptr, FFIType.i64], returns: FFIType.i32, }, - // (HMONITOR, LPMONITORINFO) -> BOOL — bounds, work area, and primary flag. + // (HMONITOR, LPMONITORINFO) -> BOOL - bounds, work area, and primary flag. GetMonitorInfoW: { args: [FFIType.u64, FFIType.ptr], returns: FFIType.i32 }, - // (LPPOINT) -> BOOL — the cursor position in screen coordinates. + // (LPPOINT) -> BOOL - the cursor position in screen coordinates. GetCursorPos: { args: [FFIType.ptr], returns: FFIType.i32 }, - // (UINT uType) -> BOOL — play a system sound (shell.beep). 0xFFFFFFFF = a simple beep. + // (UINT uType) -> BOOL - play a system sound (shell.beep). 0xFFFFFFFF = a simple beep. MessageBeep: { args: [FFIType.u32], returns: FFIType.i32 }, // ── Icons (used by the tray backend) ───────────────────────────────────── @@ -159,30 +154,30 @@ const USER32_SYMBOLS = { args: [FFIType.u64, FFIType.ptr, FFIType.u32, FFIType.i32, FFIType.i32, FFIType.u32], returns: FFIType.u64, }, - // (HINSTANCE, LPCWSTR name) -> HICON — load a standard/system icon (int resource). + // (HINSTANCE, LPCWSTR name) -> HICON - load a standard/system icon (int resource). LoadIconW: { args: [FFIType.u64, FFIType.u64], returns: FFIType.u64 }, - // (HICON) -> BOOL — free an icon loaded for the tray. + // (HICON) -> BOOL - free an icon loaded for the tray. DestroyIcon: { args: [FFIType.u64], returns: FFIType.i32 }, - // (HWND, LPCWSTR text, LPCWSTR caption, UINT type) -> int — a modal message box. + // (HWND, LPCWSTR text, LPCWSTR caption, UINT type) -> int - a modal message box. MessageBoxW: { args: [FFIType.u64, FFIType.ptr, FFIType.ptr, FFIType.u32], returns: FFIType.i32 }, // ── Menus (used by the menu backend) ───────────────────────────────────── - // () -> HMENU — a new, empty popup (context) menu. + // () -> HMENU - a new, empty popup (context) menu. CreatePopupMenu: { args: [], returns: FFIType.u64 }, - // (HMENU, UINT flags, UINT_PTR idOrSubmenu, LPCWSTR text) -> BOOL — append an item. + // (HMENU, UINT flags, UINT_PTR idOrSubmenu, LPCWSTR text) -> BOOL - append an item. AppendMenuW: { args: [FFIType.u64, FFIType.u32, FFIType.u64, FFIType.ptr], returns: FFIType.i32, }, - // (HMENU) -> BOOL — destroy a menu and its submenus. + // (HMENU) -> BOOL - destroy a menu and its submenus. DestroyMenu: { args: [FFIType.u64], returns: FFIType.i32 }, - // (HMENU) -> int — number of items (for tests). + // (HMENU) -> int - number of items (for tests). GetMenuItemCount: { args: [FFIType.u64], returns: FFIType.i32 }, - // (HWND) -> HMENU — the window's current menu bar (0 if none). + // (HWND) -> HMENU - the window's current menu bar (0 if none). GetMenu: { args: [FFIType.u64], returns: FFIType.u64 }, - // (HMENU, int pos) -> UINT — the command id at a position (-1 for a popup/submenu). + // (HMENU, int pos) -> UINT - the command id at a position (-1 for a popup/submenu). GetMenuItemID: { args: [FFIType.u64, FFIType.i32], returns: FFIType.u32 }, - // (HMENU, UINT flags, int x, int y, int reserved, HWND, LPRECT) -> BOOL/cmd — + // (HMENU, UINT flags, int x, int y, int reserved, HWND, LPRECT) -> BOOL/cmd - // show a context menu modally; with TPM_RETURNCMD it returns the chosen command id. TrackPopupMenu: { args: [ @@ -196,63 +191,61 @@ const USER32_SYMBOLS = { ], returns: FFIType.i32, }, - // () -> BOOL — end the active menu (used re-entrantly from an item's click). + // () -> BOOL - end the active menu; only reachable from a native callback while it tracks. EndMenu: { args: [], returns: FFIType.i32 }, - // (HWND, LPPOINT) -> BOOL — convert client coordinates to screen coordinates. + // (HWND, LPPOINT) -> BOOL - convert client coordinates to screen coordinates. ClientToScreen: { args: [FFIType.u64, FFIType.ptr], returns: FFIType.i32 }, - // () -> HMENU — a new, empty menu BAR (the container SetMenu attaches to a window; + // () -> HMENU - a new, empty menu BAR (the container SetMenu attaches to a window; // distinct from CreatePopupMenu, which makes a vertical submenu/context menu). CreateMenu: { args: [], returns: FFIType.u64 }, - // (HWND, HMENU) -> BOOL — attach (or detach with NULL) a menu bar to a window. + // (HWND, HMENU) -> BOOL - attach (or detach with NULL) a menu bar to a window. SetMenu: { args: [FFIType.u64, FFIType.u64], returns: FFIType.i32 }, - // (HWND) -> BOOL — repaint the menu bar after its contents change. + // (HWND) -> BOOL - repaint the menu bar after its contents change. DrawMenuBar: { args: [FFIType.u64], returns: FFIType.i32 }, } as const; -/** kernel32.dll — the running module handle, DLL-search dir, and proc lookup. */ +/** kernel32.dll - the running module handle, DLL-search dir, and proc lookup. */ const KERNEL32_SYMBOLS = { // (LPCWSTR moduleName | NULL) -> HMODULE GetModuleHandleW: { args: [FFIType.ptr], returns: FFIType.u64 }, - // (LPCWSTR pathName | NULL) -> BOOL — adds one directory to the DLL search path. + // (LPCWSTR pathName | NULL) -> BOOL - adds one directory to the DLL search path. // The Windows substitute for $ORIGIN: it lets a bundled engine's WebKit2.dll // resolve its own dependency closure (ICU, libcurl, ...) from the engine dir. SetDllDirectoryW: { args: [FFIType.ptr], returns: FFIType.i32 }, - // (HMODULE, LPCSTR procName) -> FARPROC — used to get the address of the system - // DefWindowProcW so a web-host child window can use it as a NATIVE window - // procedure (a JSCallback WndProc cannot survive WebKit's re-entrant flood). + // (HMODULE, LPCSTR procName) -> FARPROC - DefWindowProcW's address, the WKView host's + // native proc (D043). GetProcAddress: { args: [FFIType.u64, FFIType.cstring], returns: FFIType.u64 }, - // (HANDLE process, UINT exitCode) -> BOOL — hard-terminate. Used to exit the - // app WITHOUT running WebKit's static/DLL-detach teardown, which crashes. + // (HANDLE process, UINT exitCode) -> BOOL - exit without WebKit's crashing teardown (D043). TerminateProcess: { args: [FFIType.u64, FFIType.u32], returns: FFIType.i32 }, - // (EXECUTION_STATE esFlags) -> EXECUTION_STATE — block system/display sleep for + // (EXECUTION_STATE esFlags) -> EXECUTION_STATE - block system/display sleep for // the calling thread (powerSaveBlocker). Returns the previous state (0 on error). SetThreadExecutionState: { args: [FFIType.u32], returns: FFIType.u32 }, // ── Movable global memory (clipboard transfer buffers) ─────────────────── // (UINT uFlags, SIZE_T dwBytes) -> HGLOBAL GlobalAlloc: { args: [FFIType.u32, FFIType.u64], returns: FFIType.u64 }, - // (HGLOBAL) -> LPVOID — lock a movable block and get its real address. + // (HGLOBAL) -> LPVOID - lock a movable block and get its real address. GlobalLock: { args: [FFIType.u64], returns: FFIType.ptr }, // (HGLOBAL) -> BOOL GlobalUnlock: { args: [FFIType.u64], returns: FFIType.i32 }, - // (HGLOBAL) -> SIZE_T — the block's byte size. + // (HGLOBAL) -> SIZE_T - the block's byte size. GlobalSize: { args: [FFIType.u64], returns: FFIType.u64 }, - // (HGLOBAL) -> HGLOBAL — free a block we still own (NULL on success). + // (HGLOBAL) -> HGLOBAL - free a block we still own (NULL on success). GlobalFree: { args: [FFIType.u64], returns: FFIType.u64 }, - // (HLOCAL) -> HLOCAL — free a block the system allocated for us (e.g. a DPAPI + // (HLOCAL) -> HLOCAL - free a block the system allocated for us (e.g. a DPAPI // CryptProtectData output blob), NULL on success. LocalFree: { args: [FFIType.u64], returns: FFIType.u64 }, } as const; -/** ole32.dll — COM/OLE, which WebKit's Windows port requires initialised per-thread. */ +/** ole32.dll - COM/OLE, which WebKit's Windows port requires initialised per-thread. */ const OLE32_SYMBOLS = { // (LPVOID reserved) -> HRESULT OleInitialize: { args: [FFIType.ptr], returns: FFIType.i32 }, - // (LPVOID) -> void — free memory the shell allocated for us (e.g. a folder PIDL). + // (LPVOID) -> void - free memory the shell allocated for us (e.g. a folder PIDL). CoTaskMemFree: { args: [FFIType.u64], returns: FFIType.void }, - // (HGLOBAL, BOOL fDeleteOnRelease, IStream** ppstm) -> HRESULT — wrap memory in a stream. + // (HGLOBAL, BOOL fDeleteOnRelease, IStream** ppstm) -> HRESULT - wrap memory in a stream. CreateStreamOnHGlobal: { args: [FFIType.u64, FFIType.i32, FFIType.ptr], returns: FFIType.i32 }, - // (IStream* pstm, HGLOBAL* phglobal) -> HRESULT — recover the backing memory handle. + // (IStream* pstm, HGLOBAL* phglobal) -> HRESULT - recover the backing memory handle. GetHGlobalFromStream: { args: [FFIType.u64, FFIType.ptr], returns: FFIType.i32 }, } as const; diff --git a/src/main/platform/windows/win32.ts b/src/main/platform/windows/win32.ts index 48e3a8b4..c58f9765 100644 --- a/src/main/platform/windows/win32.ts +++ b/src/main/platform/windows/win32.ts @@ -1,26 +1,13 @@ -/** - * Every Win32 handle (`HWND`, `HMENU`, `HINSTANCE`, `HICON`, ...) flows through - * the codebase as a `bigint` and crosses the FFI boundary as `u64`, NOT as a - * Bun `Pointer`. A `HANDLE` is an opaque kernel value, not a virtual address, so - * Bun's 52-bit pointer representation would corrupt its high bits — the same - * truncation hazard the macOS backend avoids for tagged pointers (D029). Real - * pointers (struct buffers, wide strings) are passed with `ptr()` as usual. - */ +// Every Win32 handle (HWND, HMENU, HINSTANCE, ...) is a `bigint` declared `u64`, never +// `ptr`: pseudo-handles and sentinels such as (HWND)-1 exceed 2^53 and a Bun Pointer +// truncates them (the D029 hazard). Only real buffers (structs, strings) go through ptr(). import { type Pointer, ptr, read } from 'bun:ffi'; import { FFIError, UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; import type { Rect } from '../native'; -/** - * Encode a JS string as a null-terminated UTF-16LE byte sequence suitable for a - * Win32 wide-character (`LPCWSTR`) argument — the `wstr` sibling of {@link cstr}. - * - * Modern Win32 and the WebKit C API are UTF-16; Windows is little-endian, and a - * `WCHAR` is one UTF-16 code unit, so each `charCodeAt` unit is emitted as two - * little-endian bytes (surrogate pairs become their two units) followed by a - * 16-bit NUL. The caller pins the buffer (e.g. `ptr(wstr(s))`) for the call. - */ +/** A NUL-terminated UTF-16LE `LPCWSTR`; the caller keeps it alive across the call. */ export const wstr = (input: string): Uint8Array => Buffer.from(`${input}\0`, 'utf16le'); /** Read a native `RECT` (left, top, right, bottom as LONGs) at `offset` as a {@link Rect}. */ @@ -58,11 +45,7 @@ export const registerWindowClass = ( } }; -/** - * Build a memoising accessor for a Windows-only resource. The accessor opens the - * resource on first call and caches it; it throws {@link UnsupportedPlatformError} - * on any non-Windows host so importing modules stay safe to load everywhere. - */ +/** Memoise `open` on first call; throws {@link UnsupportedPlatformError} off Windows. */ export const winLibraryAccessor = (name: string, open: () => T): (() => T) => { let cached: T | undefined; return () => { diff --git a/src/main/platform/windows/windows-backend.ts b/src/main/platform/windows/windows-backend.ts index a48c3fc7..f722da24 100644 --- a/src/main/platform/windows/windows-backend.ts +++ b/src/main/platform/windows/windows-backend.ts @@ -15,12 +15,6 @@ import { ensureOleInitialized, NativeWin32Window, pollWindows } from './windows- import { createWindowsDrain } from './windows-run-loop'; import { WindowsWebContents } from './windows-web-contents'; -/** - * Windows {@link NativeApplication} backend on Win32 + WinCairo WebKit (D024). The pump - * drains the message queue non-blocking (`PeekMessage`, never `GetMessage`); the window - * that hosts WebKit has no JSCallback WndProc, which its re-entrant flood would crash. - */ - const SW_MAXIMIZE = 3; const SW_MINIMIZE = 6; const SW_RESTORE = 9; @@ -45,8 +39,6 @@ const STYLE_RESIZABLE = 0x00050000n; // WS_THICKFRAME | WS_MAXIMIZEBOX const SM_CXSCREEN = 0; const SM_CYSCREEN = 1; -// TrackPopupMenu flags: return the chosen command id, anchor top-left, honor the -// right mouse button. const TPM_RETURNCMD = 0x0100; const TPM_RIGHTBUTTON = 0x0002; @@ -73,16 +65,13 @@ class WindowsWindow implements NativeWindow { width: options.width, height: options.height, show: false, - // Hosts a WebKit view: hide on close rather than destroy (see commitClose). + // A WebKit host hides on close, never destroys (D043). destroyOnClose: false, ...(options.resizable !== undefined ? { resizable: options.resizable } : {}), ...(options.frame !== undefined ? { frame: options.frame } : {}), }); - // Size the web view to the CLIENT area, not the window size: `options.width`/ - // `height` are the outer window size (Electron semantics, incl. the title bar + - // borders), so the hosted view must fit the smaller client rect or its right/ - // bottom edge is clipped by the frame. The resize poll only fires on a delta, so - // the initial size has to be the client size up front. + // options.width/height are the OUTER size (Electron); a view that size is clipped by + // the frame, and the poll only refits on a change, so start at the client size. const client = this.#native.getClientSize(); this.#webContents = new WindowsWebContents( this.#native.hwnd(), @@ -91,14 +80,10 @@ class WindowsWindow implements NativeWindow { options.preloadScript, ); this.#native.setResizeHook((width, height) => this.#webContents.resize(width, height)); - // Mirror the application menu bar onto this window, and route its WM_COMMAND - // (dispatched by the frame proc) to the realizer's stored onClick handlers. this.#appMenuTarget = { setMenuBar: (bar) => this.#native.setMenuBar(bar) }; this.#native.onMenuCommand((commandId) => windowsMenuRealizer.dispatchMenuCommand(commandId)); windowsMenuRealizer.registerAppMenuWindow(this.#appMenuTarget); this.#webContents.onWindowOp((op) => this.#handleWindowOp(op)); - // On the committed-close path, tear down the web contents (reject pending - // execs, release the view) before surfacing `closed` to the api layer. this.#native.onClosed(() => { windowsMenuRealizer.unregisterAppMenuWindow(this.#appMenuTarget); try { @@ -347,9 +332,6 @@ class WindowsWindow implements NativeWindow { } onWindowEvent(type: WindowEventType, callback: () => void): void { - // focus/blur/move/resize/maximize/minimize/restore are surfaced by the pump poll - // (pollWindows); show/hide fire from the window directly; ready-to-show fires - // on the first did-finish-load. The close/closed pair flows through onClose/onClosed. this.#native.onWindowEvent(type, callback); } @@ -363,8 +345,8 @@ class WindowsWindow implements NativeWindow { dv.setInt32(4, y, true); const pointPtr = ptr(point); user32.ClientToScreen(hwnd, pointPtr); - // Modal (a nested menu-tracking loop, like macOS); returns the chosen command - // id, or 0 when dismissed. The realized HMENU is ours to destroy afterward. + // Modal: Bun stalls until the menu closes. Returns the command id (0 = dismissed); + // the realized HMENU is ours to destroy. const command = user32.TrackPopupMenu( menuHandle, TPM_RETURNCMD | TPM_RIGHTBUTTON, @@ -381,15 +363,12 @@ class WindowsWindow implements NativeWindow { } closePopupMenu(): void { - // Ends the active menu — meaningful re-entrantly (e.g. from an item's click). + // Only reachable from a native callback while a menu tracks: its modal loop stalls Bun timers. loadUser32().symbols.EndMenu(); } } -/** - * Windows {@link NativeApplication}: initializes COM, drives the cooperative pump, - * and owns the set of live windows. - */ +/** Windows {@link NativeApplication}: owns the live windows and drives the cooperative pump. */ export class WindowsApplication implements NativeApplication { #pump: CooperativePump | undefined; #started = false; @@ -407,6 +386,7 @@ export class WindowsApplication implements NativeApplication { const drainMessages = createWindowsDrain((_hwnd, message, wParam) => windowsGlobalShortcutBackend.dispatchHotkeyMessage(message, wParam), ); + // ponytail: fixed 16ms poll wakes an idle app ~60x/s; upgrade = MsgWaitForMultipleObjectsEx with AdaptiveBlockingPump backoff (D047) this.#pump = new CooperativePump(() => { drainMessages(); pollWindows(); diff --git a/src/main/platform/windows/windows-message-window.ts b/src/main/platform/windows/windows-message-window.ts index ac633bf5..3de55b46 100644 --- a/src/main/platform/windows/windows-message-window.ts +++ b/src/main/platform/windows/windows-message-window.ts @@ -3,14 +3,10 @@ import { FFIError } from '../../../common/errors'; import { registerWindowClass, wstr } from './win32'; import { loadKernel32, loadUser32 } from './win32-ffi'; -/** - * A hidden, non-WebKit Win32 window that receives system notifications - * (`WM_POWERBROADCAST`, `WM_WTSSESSION_CHANGE`, a tray icon's callback). It hosts no - * WebKit, so a JSCallback WndProc is safe here (unlike `windows-native-window.ts`). - */ +// Hidden windows for system notifications (power, session, tray). They host no WebKit, +// so a JSCallback WndProc is safe here (D043). const CLASS_NAME = 'BunmaskaMessageWindow'; -/** `WS_EX_TOOLWINDOW` — keep the (never-shown) window out of the taskbar/alt-tab. */ const WS_EX_TOOLWINDOW = 0x00000080; const WS_OVERLAPPED = 0x00000000; const WM_CLOSE = 0x0010; @@ -26,7 +22,7 @@ export type MessageWindow = { const handlersByHwnd = new Map(); -/** Lazily-created shared state: the registered class + the retained WndProc. */ +// Retained for the process: the registered class calls this proc until exit. let registered: { readonly wndProc: JSCallback } | undefined; /** Register the window class once, wiring the shared dispatching WndProc. */ @@ -42,7 +38,7 @@ const ensureClassRegistered = (): void => { try { handler(message, wParam, lParam); } catch { - // A throwing JS handler must never propagate into the native WndProc. + // Same rule as the frame proc: never propagate into native code. } } // An external WM_CLOSE must not destroy it; only destroy() does. @@ -57,16 +53,10 @@ const ensureClassRegistered = (): void => { const hInstance = loadKernel32().symbols.GetModuleHandleW(null); registerWindowClass(user32, CLASS_NAME, BigInt(wndProcPtr), hInstance); - // Retain the JSCallback for the whole process (the class references it forever). registered = { wndProc }; }; -/** - * Create a hidden top-level window whose messages are delivered to `handler`. - * Top-level (not message-only) so it receives broadcast `WM_POWERBROADCAST`; the - * `WS_EX_TOOLWINDOW` style keeps it invisible to the user. The window is never - * shown. - */ +/** A never-shown top-level window feeding `handler`; not message-only, so it gets broadcasts. */ export const createMessageWindow = (handler: MessageHandler): MessageWindow => { ensureClassRegistered(); const user32 = loadUser32().symbols; @@ -80,7 +70,7 @@ export const createMessageWindow = (handler: MessageHandler): MessageWindow => { 0, 0, 0, - 0n, // no parent — a (hidden) top-level window receives WM_POWERBROADCAST + 0n, 0n, hInstance, null, diff --git a/src/main/platform/windows/windows-native-window.ts b/src/main/platform/windows/windows-native-window.ts index 2eb3fcfb..ee5e9843 100644 --- a/src/main/platform/windows/windows-native-window.ts +++ b/src/main/platform/windows/windows-native-window.ts @@ -6,14 +6,9 @@ import type { Rect, WindowEventType } from '../native'; import { readRect, registerWindowClass, wstr } from './win32'; import { loadKernel32, loadOle32, loadUser32 } from './win32-ffi'; -/** - * The window that DIRECTLY hosts the WebKit view MUST use a native window procedure: - * WebKit floods its immediate host with re-entrant messages during a load, which a - * `bun:ffi` `JSCallback` WndProc cannot survive. So the WebKit view lives in a - * native-`DefWindowProcW` CHILD ({@link createNativeChildHost}), while the TOP-LEVEL - * frame uses a JSCallback proc — safe because the flood stops at the immediate child host - * and does not propagate up to the parent (see `menu-frame-spike.ts`). - */ +// The WKView's direct host must keep the native DefWindowProcW: WebKit's re-entrant +// flood during a load crashes a JSCallback WndProc (D043). Only the top-level frame, +// above that native child, runs a JSCallback proc. const NATIVE_WINDOW_CLASS_NAME = 'BunmaskaNativeWindow'; const FRAME_WINDOW_CLASS_NAME = 'BunmaskaFrameWindow'; @@ -22,7 +17,6 @@ const RECT_SIZE = 16; const WINDOWPLACEMENT_SIZE = 44; const RC_NORMAL_POSITION_OFFSET = 28; const IDC_ARROW = 32512; -/** `WM_COMMAND` — a menu selection (or control/accelerator) notification. */ const WM_COMMAND = 0x0111; const WM_CLOSE = 0x0010; const WM_GETMINMAXINFO = 0x0024; @@ -42,15 +36,13 @@ const SW_HIDE = 0; const SW_SHOWNOACTIVATE = 4; const SW_SHOW = 5; -/** `WM_NCLBUTTONDOWN` + `HTCAPTION`: tell the system to start moving the window - * (used to drag a frameless window from a custom `-webkit-app-region`-style bar). */ const WM_NCLBUTTONDOWN = 0x00a1; const HTCAPTION = 2; let oleInitialized = false; let classRegistered = false; -/** Initialise COM on this thread once — WinCairo WebKit requires it. */ +/** Initialise OLE on this thread once; WinCairo WebKit requires it. */ export const ensureOleInitialized = (): void => { if (oleInitialized) { return; @@ -69,7 +61,7 @@ const ensureNativeWindowClass = (): bigint => { if (classRegistered) { return hInstance; } - // Use the system DefWindowProcW directly as the class window procedure. + // The class proc IS the native DefWindowProcW, never a JSCallback (D043). const user32Module = kernel32.symbols.GetModuleHandleW(ptr(wstr('user32.dll'))); const defWindowProc = kernel32.symbols.GetProcAddress(user32Module, cstr('DefWindowProcW')); if (defWindowProc === 0n) { @@ -82,17 +74,11 @@ const ensureNativeWindowClass = (): bigint => { return hInstance; }; -// Frame-class shared state: the registered class + its retained JSCallback proc. let frameClassRegistered = false; +// Retained for the process: the registered class calls this proc until exit. let frameWndProc: JSCallback | undefined; -/** - * Register the top-level FRAME window class once, wiring a shared JSCallback - * WndProc. The proc dispatches a menu `WM_COMMAND` (a SENT message the pump can't - * see) to the owning window's `menuCommand` handler and forwards everything else - * to `DefWindowProcW`. Safe despite hosting WebKit (in a native child) — see the - * module header. Returns the `HINSTANCE`. - */ +/** Register the top-level frame class and its JSCallback proc once; returns the `HINSTANCE`. */ const ensureFrameWindowClass = (): bigint => { const kernel32 = loadKernel32(); const hInstance = kernel32.symbols.GetModuleHandleW(null); @@ -161,10 +147,10 @@ interface NativeWindowHandlers { closed: boolean; /** Preventable close: return `true` to veto (the window stays open). */ onClose?: () => boolean; - /** Fired once after the window is destroyed. */ + /** Fired once, before the window is hidden or destroyed. */ onClosed?: () => void; readonly events: Map void>; - /** Internal resize sink (resizes the hosted view) — fired before the `resize` event. */ + /** Refits the hosted view; runs before the `resize` event. */ resizeHook?: (width: number, height: number) => void; /** Minimum outer size in pixels; 0 leaves the system default. */ minWidth: number; @@ -248,44 +234,34 @@ const requestClose = (hwnd: bigint, handlers: NativeWindowHandlers): void => { commitClose(hwnd, handlers); }; -/** Run the committed-close path once: tear down the view, then destroy the window. */ +/** Run the committed close once: onClosed quiesces the view, then the window hides or goes. */ const commitClose = (hwnd: bigint, handlers: NativeWindowHandlers): void => { if (handlers.closed) { return; } handlers.closed = true; - // Detach + free any menu bar this window owns before tearing the window down. if (handlers.menuBar !== undefined && handlers.menuBar !== 0n) { const user32 = loadUser32().symbols; user32.SetMenu(hwnd, 0n); user32.DestroyMenu(handlers.menuBar); delete handlers.menuBar; } - // Quiesce the hosted view first (the onClosed handler clears WebKit's clients - // and detaches the view), THEN finish the window. try { handlers.onClosed?.(); } finally { if (handlers.destroyOnClose) { loadUser32().symbols.DestroyWindow(hwnd); } else { - // A WebKit-hosting window: synchronously destroying it crashes WebKit's - // multi-process teardown through bun:ffi, so hide it and let the OS reclaim - // the view + its WebProcess at process exit (see `.admin/WINDOWS.md`). + // Never DestroyWindow a live WebKit host: its teardown crashes through bun:ffi (D043). loadUser32().symbols.ShowWindow(hwnd, SW_HIDE); } windowRegistry.delete(hwnd); } }; -/** - * Poll every live window and fire the changed non-preventable lifecycle events - * (move / resize / maximize / unmaximize / minimize / restore / focus / blur). Called - * each pump tick: WebKit's host uses a native WndProc, so these SENT-only state - * changes never reach the message queue and must be observed by polling. `show` - * and `hide` are fired directly from {@link NativeWin32Window.show}/`hide`. - */ +/** Fire the changed lifecycle events of every live window; `show`/`hide` fire from the window. */ export const pollWindows = (): void => { + // ponytail: polled per tick, so modal move/size loops defer events to mouse-up; upgrade = WM_SIZE/WM_MOVE in the frame proc, after an engine run if (windowRegistry.size === 0) { return; } @@ -355,11 +331,11 @@ export interface NativeWin32WindowOptions { readonly show: boolean; readonly resizable?: boolean; readonly frame?: boolean; - /** `false` hides on close instead of DestroyWindow (required for a WebKit host, D043). Default true. */ + /** Default true; `false` hides on close instead, as a WebKit host requires (D043). */ readonly destroyOnClose?: boolean; } -/** A live top-level native-WndProc window that can host a WebKit view. */ +/** A top-level frame window; a WebKit view goes in its {@link createNativeChildHost} child. */ export class NativeWin32Window { readonly #hwnd: bigint; readonly #handlers: NativeWindowHandlers; @@ -367,8 +343,6 @@ export class NativeWin32Window { constructor(options: NativeWin32WindowOptions) { this.#handlers = newHandlers(options.destroyOnClose ?? true); ensureOleInitialized(); - // The TOP-LEVEL frame uses the JSCallback frame class (so a menu bar's - // WM_COMMAND is dispatchable); the WebKit view lives in a native child. const hInstance = ensureFrameWindowClass(); const hwnd = loadUser32().symbols.CreateWindowExW( 0, @@ -427,7 +401,7 @@ export class NativeWin32Window { this.#handlers.events.set(type, callback); } - /** Fire a lifecycle event to its handler (for events not surfaced by polling). */ + /** Fire a lifecycle event the poll does not observe. */ emit(type: WindowEventType): void { this.#handlers.events.get(type)?.(); } @@ -447,24 +421,14 @@ export class NativeWin32Window { this.#handlers.menuCommand = handler; } - /** - * Begin an interactive window move — the equivalent of dragging the title bar, - * for frameless windows with a custom (`-webkit-app-region: drag`-style) bar. - * Releases mouse capture (the web view's child window holds it after mousedown) - * and hands off to the system's move loop, so dragging feels native (edge snap, - * Aero shake, etc.). Called from the renderer over the window-op message channel. - */ + /** Hand a frameless title-bar drag to the system move loop (D045); the view holds the capture. */ startWindowDrag(): void { const user32 = loadUser32().symbols; user32.ReleaseCapture(); user32.SendMessageW(this.#hwnd, WM_NCLBUTTONDOWN, BigInt(HTCAPTION), 0n); } - /** - * Attach `menuBar` (an HMENU) as this window's menu bar, or remove it with - * `null`. Takes ownership: the previous bar is destroyed, and so is this one when - * the window closes. - */ + /** Attach an HMENU bar, or `null` to remove it; owned from here, destroyed when replaced or closed. */ setMenuBar(menuBar: bigint | null): void { const user32 = loadUser32().symbols; const previous = this.#handlers.menuBar; @@ -496,8 +460,6 @@ export class NativeWin32Window { const rect = new Uint8Array(RECT_SIZE); const rectPtr = ptr(rect); loadUser32().symbols.GetClientRect(this.#hwnd, rectPtr); - // Native writes are only visible via read.* on the pointer, never through - // the backing JS array (the rule windows-run-loop.ts documents). return { width: read.i32(rectPtr, 8), height: read.i32(rectPtr, 12) }; } diff --git a/src/main/platform/windows/windows-run-loop.ts b/src/main/platform/windows/windows-run-loop.ts index 4fc7c680..fda04454 100644 --- a/src/main/platform/windows/windows-run-loop.ts +++ b/src/main/platform/windows/windows-run-loop.ts @@ -1,37 +1,25 @@ import { ptr, read } from 'bun:ffi'; import { loadUser32 } from './win32-ffi'; -/** - * Each tick removes and dispatches up to {@link DRAIN_BUDGET} queued messages - * with a NON-BLOCKING `PeekMessage`/`TranslateMessage`/`DispatchMessage` loop. - * It must NEVER call `GetMessage` (which blocks until a message arrives) nor a - * web engine's own modal message loop — blocking the thread Bun owns crashes Bun - * (D019/D020). The per-tick budget bounds how long one drain can run so it can't - * starve Bun's own event loop under a message flood. - */ +// Never GetMessage or any blocking wait on the Bun thread (D019/D020/D043). The +// system's own modal loops (window move/size, menus) still stall Bun until they end. -/** `PeekMessage` removal flag: pull the message out of the queue. */ const PM_REMOVE = 0x0001; /** - * `sizeof(MSG)` on x64: `HWND hwnd`(8) + `UINT message`(4) + padding(4) + + * `sizeof(MSG)` on LLP64: `HWND hwnd`(8) + `UINT message`(4) + padding(4) + * `WPARAM wParam`(8) + `LPARAM lParam`(8) + `DWORD time`(4) + `POINT pt`(8) + * `DWORD lPrivate`(4) = 48 bytes. */ const MSG_SIZE = 48; -/** Max messages dispatched per tick before yielding back to Bun's loop. */ +/** Bounds one tick under a message flood so Bun's own loop is never starved. */ const DRAIN_BUDGET = 256; /** Sees each posted message before dispatch; `true` means handled, so the drain skips it. */ export type MessageInspector = (hwnd: bigint, message: number, wParam: bigint) => boolean; -/** - * Build the non-blocking Windows drain. The `MSG` buffer is allocated once and - * reused across ticks; `PeekMessage(hwnd=NULL)` services every window on the - * calling (Bun main) thread. An optional {@link MessageInspector} gets first look - * at each message (for backend lifecycle routing) and can swallow it. - */ +/** Build the per-tick drain for every window on this thread; the `MSG` buffer is reused. */ export const createWindowsDrain = (inspect?: MessageInspector): (() => void) => { const user32 = loadUser32(); const msg = new Uint8Array(MSG_SIZE); @@ -41,15 +29,13 @@ export const createWindowsDrain = (inspect?: MessageInspector): (() => void) => while (budget > 0 && user32.symbols.PeekMessageW(msgPtr, 0n, 0, 0, PM_REMOVE) !== 0) { budget -= 1; if (inspect !== undefined) { - // Read the MSG fields from the POINTER, not the backing Uint8Array: bun's - // `ptr()` hands FFI a buffer that the JS array does not reflect for native - // writes, so PeekMessage's output is only visible via `read.*` on msgPtr. - // MSG layout (x64): hwnd@0 (u64), message@8 (u32), wParam@16 (u64). + // Never touch msg.buffer after ptr(msg): JSC moves the storage and msgPtr dangles. + // MSG layout: hwnd@0 (u64), message@8 (u32), wParam@16 (u64). const hwnd = read.u64(msgPtr, 0); const message = read.u32(msgPtr, 8); const wParam = read.u64(msgPtr, 16); if (inspect(hwnd, message, wParam)) { - continue; // handled by the backend — skip default dispatch + continue; } } user32.symbols.TranslateMessage(msgPtr); From ba6d24a09610a3625a308c4f71225446843a5a76 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:00:05 -0700 Subject: [PATCH 111/586] chore: trim macOS FFI comments to the comment rules --- src/main/platform/macos/carbon-ffi.ts | 35 ++------- src/main/platform/macos/cocoa-block.ts | 40 ++++------- src/main/platform/macos/cocoa-class-cache.ts | 14 +--- src/main/platform/macos/cocoa-ffi.ts | 25 ++----- src/main/platform/macos/cocoa-foundation.ts | 6 +- .../platform/macos/cocoa-msgsend-variants.ts | 72 ++----------------- .../platform/macos/cocoa-runtime-class.ts | 41 +++-------- src/main/platform/macos/cocoa-runtime.ts | 14 +--- .../platform/macos/cocoa-selector-cache.ts | 7 -- src/main/platform/macos/cocoa-webkit.ts | 10 ++- .../platform/macos/cocoa-window-bounds.ts | 14 +--- .../platform/macos/core-graphics-image-ffi.ts | 14 +--- src/main/platform/macos/objc.ts | 16 +---- src/main/platform/macos/security-ffi.ts | 19 ++--- tests/integration/macos/cocoa-block.test.ts | 9 +-- tests/integration/macos/cocoa-ffi.test.ts | 2 +- .../macos/cocoa-foundation.test.ts | 2 +- .../macos/cocoa-msgsend-f64.test.ts | 2 +- .../macos/cocoa-msgsend-i64.test.ts | 2 +- .../macos/cocoa-msgsend-ptr.test.ts | 2 +- .../macos/cocoa-msgsend-returns-u8.test.ts | 2 +- .../macos/cocoa-msgsend-u8.test.ts | 2 +- tests/integration/macos/cocoa-runtime.test.ts | 2 +- tests/integration/macos/cocoa-webkit.test.ts | 2 +- tests/integration/macos/phase0-exit.test.ts | 10 +-- .../platform/macos/cocoa-class-cache.test.ts | 2 +- 26 files changed, 76 insertions(+), 290 deletions(-) diff --git a/src/main/platform/macos/carbon-ffi.ts b/src/main/platform/macos/carbon-ffi.ts index 7262b529..3996e151 100644 --- a/src/main/platform/macos/carbon-ffi.ts +++ b/src/main/platform/macos/carbon-ffi.ts @@ -3,30 +3,14 @@ import { dlopen } from '../dlopen'; import { macOSLibraryAccessor } from './objc'; /** - * Carbon framework FFI for system-wide hot keys — the macOS half of - * `globalShortcut`. + * Carbon hot keys behind macOS `globalShortcut`: unlike an NSEvent monitor they need + * no Accessibility permission or app bundle, and they fire through the pump (D020). * - * Carbon's `RegisterEventHotKey` is the one un-bundled-friendly way to claim a - * global hot key on macOS: it works from a plain `bun main.ts` process (no - * Accessibility permission, no app bundle), and the fired events flow through - * the application's Carbon event target — which is serviced by the same main - * run loop Bunmaska already pumps (`CFRunLoopRunInMode`, D020). So a registered - * hot key dispatches through the cooperative pump with no extra wiring. - * - * ── EventHotKeyID struct-by-value (load-bearing, verified on this arm64 host) ── - * `RegisterEventHotKey` takes `EventHotKeyID` (`{ OSType signature; UInt32 id }`, - * 8 bytes) BY VALUE. `bun:ffi` has NO struct-by-value support. WORKAROUND: on - * arm64 an 8-byte struct passed by value goes in a single 64-bit register, so we - * declare that argument as `u64` and pack it as - * `BigInt(signature) | (BigInt(id) << 32n)` (signature in the low 32 bits, id in - * the high 32 — matching the struct's field order on a little-endian host). - * Measured: `RegisterEventHotKey` returns `noErr` and yields a valid - * `EventHotKeyRef`, and the handler reads the same id back from the event's - * `kEventParamHotKeyID` parameter. The workaround WORKS. - * - * `EventTypeSpec` (the type list for `InstallEventHandler`) is an array of - * `{ UInt32 eventClass; UInt32 eventKind }` structs passed BY REFERENCE — that is - * fine: we build a `Uint32Array` and pass its pointer. + * `RegisterEventHotKey` takes `EventHotKeyID { OSType signature; UInt32 id }` BY VALUE, + * which bun:ffi cannot declare. An 8-byte all-integer struct travels in one 64-bit + * register on both ABIs, so declare it `u64` and pack `BigInt(signature) | + * (BigInt(id) << 32n)`: signature in the low half, as the little-endian layout puts it. + * `EventTypeSpec` lists go BY REFERENCE, as a `Uint32Array` pointer. */ const CARBON_PATH = '/System/Library/Frameworks/Carbon.framework/Carbon'; @@ -70,11 +54,6 @@ export const CARBON_FFI_SYMBOLS = { }, } as const; -/** - * Open `Carbon.framework` and return the hot-key/event symbol table. Memoised; - * throws {@link UnsupportedPlatformError} on any non-macOS host (via the - * accessor) so the module stays importable everywhere. - */ export const loadCarbonFFI = macOSLibraryAccessor('Carbon global shortcut', () => dlopen(CARBON_PATH, CARBON_FFI_SYMBOLS), ); diff --git a/src/main/platform/macos/cocoa-block.ts b/src/main/platform/macos/cocoa-block.ts index 503e707a..7adbbae4 100644 --- a/src/main/platform/macos/cocoa-block.ts +++ b/src/main/platform/macos/cocoa-block.ts @@ -2,31 +2,22 @@ import { FFIType, JSCallback, type Pointer, ptr } from 'bun:ffi'; import { callFromNative, dataSymbolAddress, type Handle } from './objc'; /** - * Hand-built ObjC **Blocks** for bun:ffi — the primitive that unblocks every - * completion-handler-based AppKit/WebKit API (D022, now SOLVED). - * - * A Block is a C struct whose 5th field (`invoke`, at offset 0x10) is a function - * pointer the ObjC runtime calls as `invoke(block, ...args)`. We build a GLOBAL - * block (no captured variables, so the runtime never copies/frees it) whose - * `invoke` is a {@link JSCallback}: + * Hand-built ObjC Blocks for completion-handler APIs (D022b). The runtime calls a + * block as `invoke(block, ...args)`, reading `invoke` at offset 16: * * ``` * struct Block_literal { void *isa; int flags; int reserved; void *invoke; void *descriptor; } * struct Block_descriptor { unsigned long reserved; unsigned long size; } * ``` * - * - `isa` = `&_NSConcreteGlobalBlock` (resolved once via `dlsym`). - * - `flags` = `BLOCK_IS_GLOBAL` (1 << 28). No copy/dispose helpers, no signature - * (direct invocation does not need one — verified against `dispatch_async` + - * the run loop). - * - `invoke` = the JSCallback pointer; its first parameter is the block itself. + * - `isa` = `&_NSConcreteGlobalBlock`: a GLOBAL block captures nothing, so the + * runtime never copies or frees it. + * - `flags` = `BLOCK_IS_GLOBAL` (1 << 28). No copy/dispose helpers and no signature: + * direct invocation needs neither (verified with `dispatch_async` + the run loop). + * - `invoke` = a JSCallback whose first parameter is the block itself. * - * LIFETIME: a completion handler fires LATER, on the pumped run loop, so the - * literal + descriptor + JSCallback must stay reachable until then — they are - * held in {@link retained}. After the handler runs we close the JSCallback on a - * DEFERRED tick (never synchronously inside its own invocation, which would free - * the native trampoline mid-call and segfault — the same crash class as the GTK - * `runAsyncDialog` callbacks). + * The literal and JSCallback stay in {@link retained} until the block fires, then + * close on a deferred tick, never inside their own invocation (D022b). */ const BLOCK_IS_GLOBAL = 1 << 28; @@ -56,14 +47,9 @@ export const retainedBlockCount = (): number => retained.size; export type BlockArg = number | bigint | null; /** - * Build a one-shot global Block whose handler runs when the runtime invokes it. - * `argTypes` are the block's parameter FFI types AFTER the implicit leading block - * pointer (which is dropped before `handler` is called). The handler receives the - * real arguments in order. The block frees itself (deferred) after it fires, so - * this is for completion handlers that are called exactly once. - * - * Returns the block pointer as a {@link Handle} to pass to an `objc_msgSend` - * argument slot. + * Build a block for a completion handler called exactly once; it frees itself after + * firing. `argTypes` follow the implicit block pointer, which `handler` never sees. + * Declare ObjC object params as `FFIType.u64`: `ptr` loses tagged-pointer bits (D029). */ export const makeOneShotBlock = ( handler: (...args: BlockArg[]) => void, @@ -73,10 +59,8 @@ export const makeOneShotBlock = ( const cb = new JSCallback( (...all: BlockArg[]) => { if (retained.get(blockPtr)?.cancelled === false) { - // Drop the leading block pointer; hand the real args to the caller. callFromNative(undefined, () => handler(...all.slice(1))); } - // Deferred close: never free the trampoline inside its own invocation. setTimeout(() => { retained.delete(blockPtr); cb.close(); diff --git a/src/main/platform/macos/cocoa-class-cache.ts b/src/main/platform/macos/cocoa-class-cache.ts index f6deb156..afada904 100644 --- a/src/main/platform/macos/cocoa-class-cache.ts +++ b/src/main/platform/macos/cocoa-class-cache.ts @@ -1,19 +1,8 @@ import { FFIError } from '../../../common/errors'; -/** - * Memoising wrapper around Objective-C's `objc_getClass`. - * - * Unlike `sel_registerName`, `objc_getClass` returns `NULL` (`0n`) when the - * named class is not registered with the runtime. We treat that as a programmer - * error and throw {@link BunmaskaError}, but we deliberately do NOT cache NULL - * results — a dynamically loaded framework may register the class later, and - * a retry should succeed. - */ - -/** Opaque pointer-width handle returned by `objc_getClass`. */ export type ObjcClass = bigint; -/** Shape of `objc_getClass`: name → opaque class handle (or `0n` if missing). */ +/** `objc_getClass`: `0n` when the class is not registered. */ export type ClassResolver = (name: string) => ObjcClass; export class ClassCache { @@ -31,6 +20,7 @@ export class ClassCache { } const fresh = this.#resolver(name); if (fresh === 0n) { + // Never cache a miss: a framework loaded later may register the class. throw new FFIError(`Objective-C class not found: ${name}`); } this.#cache.set(name, fresh); diff --git a/src/main/platform/macos/cocoa-ffi.ts b/src/main/platform/macos/cocoa-ffi.ts index ec171fc7..c7516eac 100644 --- a/src/main/platform/macos/cocoa-ffi.ts +++ b/src/main/platform/macos/cocoa-ffi.ts @@ -20,30 +20,17 @@ const APPKIT_SYMBOLS = { }; /** - * Open `libobjc.A.dylib` plus `Foundation.framework` and `AppKit.framework`. - * - * `objc_msgSend` is variadic in C; Bun's FFI cannot express that directly, so - * we declare the simplest two-arg form here and add typed variants in later - * modules as the call sites require them. - * - * Foundation + AppKit are loaded for the side-effect of registering their - * classes (`NSString`, `NSWindow`, `NSApplication`, etc.) with the Objective-C - * runtime so subsequent `objc_getClass(...)` calls resolve them. Bun requires - * at least one symbol per `dlopen`, so we declare anchor symbols - * (`NSGetSizeAndAlignment`, `NSApplicationMain`) without invoking them. Both - * live in the dyld shared cache, which never unloads, so the handles are dropped. - * - * Throws {@link BunmaskaError} on non-macOS at call time, not at module load, so - * this module stays safely *importable* on Linux/Windows. + * Open libobjc, and Foundation + AppKit so their classes register. Bun needs one declared + * symbol per dlopen, so the framework anchors are never called; shared-cache images never + * unload, so their handles are dropped. */ export const loadCocoaFFI = macOSLibraryAccessor('loadCocoaFFI()', () => { dlopen(FOUNDATION_PATH, FOUNDATION_SYMBOLS); dlopen(APPKIT_PATH, APPKIT_SYMBOLS); - // ObjC handles (id/SEL/Class) are declared u64, not pointer: tagged-pointer - // objects (short NSString/NSNumber/NSDate) set high bits that exceed 2^53, - // which FFIType.pointer would truncate to a corrupt f64. u64 preserves the - // full 64-bit handle as a bigint. See D029. + // D029, stated once here: every ObjC handle slot (id/SEL/Class/IMP) is u64, never + // pointer. A tagged pointer (short NSString/NSNumber/NSDate) sets bits above 2^53 + // that pointer truncates to a corrupt f64; sending to that handle segfaults. return dlopen(LIBOBJC_PATH, { sel_registerName: { args: [FFIType.cstring], diff --git a/src/main/platform/macos/cocoa-foundation.ts b/src/main/platform/macos/cocoa-foundation.ts index 486d0eae..85232fa7 100644 --- a/src/main/platform/macos/cocoa-foundation.ts +++ b/src/main/platform/macos/cocoa-foundation.ts @@ -3,15 +3,13 @@ import { msgSendCStr } from './cocoa-msgsend-variants'; import { type Handle, ptrIn } from './objc'; import { cocoa } from './cocoa-runtime'; -/** Bridging helpers between JS strings and Foundation `NSString` objects. */ - -/** Create an autoreleased `NSString` from a JS string. Returns its handle. */ +/** Create an autoreleased `NSString`: it lives until the enclosing autorelease pool drains. */ export const nsString = (value: string): Handle => { const rt = cocoa(); return msgSendCStr(rt.classes.get('NSString'), rt.selectors.get('stringWithUTF8String:'), value); }; -/** Read an `NSString` handle back into a JS string. Returns `''` for a null handle. */ +/** Read an `NSString` back into a JS string; `''` for nil. */ export const nsStringToString = (handle: Handle): string => { if (handle === 0n) { return ''; diff --git a/src/main/platform/macos/cocoa-msgsend-variants.ts b/src/main/platform/macos/cocoa-msgsend-variants.ts index 2329d594..b6fb8748 100644 --- a/src/main/platform/macos/cocoa-msgsend-variants.ts +++ b/src/main/platform/macos/cocoa-msgsend-variants.ts @@ -5,24 +5,6 @@ import { type Handle, LIBOBJC_PATH, macOSLibraryAccessor } from './objc'; const { u64, u8, i64, f64, cstring } = FFIType; -/** - * Typed `objc_msgSend` variants for selectors whose signatures don't match - * the zero-extra-arg form exposed on {@link CocoaRuntime}. - * - * Bun's FFI cannot declare two distinct signatures for the same symbol name - * inside one `dlopen` call, so each variant `dlopen`s `libobjc.A.dylib` again - * with a different signature. dyld dedupes the underlying image; the cost is - * one extra `Library` wrapper object per variant. - * - * Every Objective-C object/selector slot is declared `u64` (not `pointer`) so - * tagged-pointer objects survive the FFI boundary as full-precision bigints - * (D029). Non-handle args keep their natural type (`f64`, `u8`, `i64`, - * `cstring`). - * - * Every export here is macOS-only: each throws {@link UnsupportedPlatformError} - * on other platforms. - */ - export type CGRectArgs = readonly [x: number, y: number, width: number, height: number]; // D018: arm64 passes a 4-double CGRect (an HFA) in d0-d3, exactly like four doubles. @@ -41,7 +23,7 @@ export const RECT_F64: readonly FFIType.f64[] = new Array( rectPadding(process.arch) + 4, ).fill(FFIType.f64); -/** One lazily opened `objc_msgSend` binding with its own signature. */ +/** One `objc_msgSend` signature, compiled on first use; handle slots are u64 (D029). */ const variant = ( name: string, args: Args, @@ -157,8 +139,8 @@ export const msgSendPtrReturnsU8 = (receiver: Handle, selector: Handle, arg: Han ptrReturnsU8()(receiver, selector, arg); /** - * Send a message with an `NSSize`/`CGSize` arg (two `double`s by value), e.g. - * `[window setContentSize:(NSSize){w, h}]`. + * Send an `NSSize`/`CGSize` by value. A 2-double struct needs no D018 padding: it goes + * in d0-d1 on arm64 and xmm0-1 on x86_64 (16 bytes is not MEMORY class, unlike CGRect). */ export const msgSendSize = ( receiver: Handle, @@ -167,12 +149,7 @@ export const msgSendSize = ( height: number, ): Handle => size()(receiver, selector, width, height); -/** - * Send a message taking a pointer, an `NSPoint` (two `double`s BY VALUE — the - * struct-as-doubles trick, D018), then a pointer, returning a `BOOL` — specifically - * `-[NSMenu popUpMenuPositioningItem:atLocation:inView:]`. A 2-double homogeneous-FP struct - * arg occupies the same registers as two separate doubles (proven by {@link msgSendSize}). - */ +/** Pointer, `NSPoint` by value (see {@link msgSendSize}), pointer; returns BOOL. */ export const msgSendPtrPointPtrReturnsU8 = ( receiver: Handle, selector: Handle, @@ -182,12 +159,6 @@ export const msgSendPtrPointPtrReturnsU8 = ( view: Handle, ): number => ptrPointPtrReturnsU8()(receiver, selector, item, x, y, view); -/** - * Send a message with four extra pointer-sized args — specifically - * `[WKWebView evaluateJavaScript:inFrame:inContentWorld:completionHandler:]` - * (macOS 11+). Pass `frame = 0n` (main frame) and `completionHandler = 0n` - * (`_Nullable`, fire-and-forget — no block thunk, no D022 hazard). - */ export const msgSendPtr4 = ( receiver: Handle, selector: Handle, @@ -197,12 +168,6 @@ export const msgSendPtr4 = ( arg3: Handle, ): Handle => ptr4()(receiver, selector, arg0, arg1, arg2, arg3); -/** - * Send a message with a pointer arg, an `NSInteger` arg, a `BOOL` arg, and a - * trailing pointer arg — specifically - * `[WKUserScript initWithSource:injectionTime:forMainFrameOnly:inContentWorld:]` - * (macOS 11+). - */ export const msgSendPtrI64U8Ptr = ( receiver: Handle, selector: Handle, @@ -212,11 +177,6 @@ export const msgSendPtrI64U8Ptr = ( arg3: Handle, ): Handle => ptrI64U8Ptr()(receiver, selector, arg0, arg1, arg2, arg3); -/** - * Send a message with a pointer arg and an `NSInteger`/`NSUInteger` arg — - * specifically `[NSData dataWithBytes:(const void*)ptr length:(NSUInteger)len]`, - * where the byte pointer is a pinned buffer and the length is its size. - */ export const msgSendPtrI64 = ( receiver: Handle, selector: Handle, @@ -224,12 +184,6 @@ export const msgSendPtrI64 = ( arg1: bigint, ): Handle => ptrI64()(receiver, selector, arg0, arg1); -/** - * Send a message with an `NSInteger` arg followed by a trailing pointer arg — - * specifically `[NSBitmapImageRep representationUsingType:(NSBitmapImageFileType) - * properties:(NSDictionary*)]` (the file-type enum then a nullable properties - * dictionary). - */ export const msgSendI64Ptr = ( receiver: Handle, selector: Handle, @@ -237,20 +191,10 @@ export const msgSendI64Ptr = ( arg1: Handle, ): Handle => i64Ptr()(receiver, selector, arg0, arg1); -/** - * Send a zero-extra-arg message returning a C `double` — e.g. `-[NSDate - * timeIntervalSince1970]`. Plain `objc_msgSend` is correct on BOTH ABIs: ARM64 - * returns doubles in d0, and x86_64 in xmm0 (`objc_msgSend_fpret` exists only - * for `long double` there) - no fpret variant needed. - */ +/** Returns a C double: plain `objc_msgSend` is right on both ABIs; `_fpret` is only for x86_64 long double. */ export const msgSendReturnsF64 = (receiver: Handle, selector: Handle): number => returnsF64()(receiver, selector); -/** - * Send a message with a pointer arg, an `NSInteger` arg, and a trailing pointer - * arg — specifically `[NSError errorWithDomain:code:userInfo:]` (domain string, - * integer code, nullable userInfo dictionary). - */ export const msgSendPtrI64Ptr = ( receiver: Handle, selector: Handle, @@ -259,12 +203,6 @@ export const msgSendPtrI64Ptr = ( arg2: Handle, ): Handle => ptrI64Ptr()(receiver, selector, arg0, arg1, arg2); -/** - * Send a message with two pointer args, an `NSInteger` arg, and a trailing - * pointer arg — specifically `[[NSURLResponse alloc] - * initWithURL:MIMEType:expectedContentLength:textEncodingName:]` (URL pointer, - * MIME-type NSString pointer, content length, text-encoding NSString or 0). - */ export const msgSendPtrPtrI64Ptr = ( receiver: Handle, selector: Handle, diff --git a/src/main/platform/macos/cocoa-runtime-class.ts b/src/main/platform/macos/cocoa-runtime-class.ts index 8e03c2c3..1f3bcd33 100644 --- a/src/main/platform/macos/cocoa-runtime-class.ts +++ b/src/main/platform/macos/cocoa-runtime-class.ts @@ -6,36 +6,16 @@ import { cocoa } from './cocoa-runtime'; import { callFromNative, type Handle, LIBOBJC_PATH, macOSLibraryAccessor } from './objc'; /** - * Define Objective-C classes at runtime with JS-backed methods: - * `objc_allocateClassPair` → `class_addMethod` with a `JSCallback` as the IMP → - * `objc_registerClassPair` (D026). - * - * Every Objective-C method's first two args are the implicit `self` (id) and - * `_cmd` (SEL); declared args follow. All are modelled as `u64` handles (D029). - */ - -/** - * A JS-backed method to attach to a runtime class. - * - * `returns` defaults to `'void'`. A `'bool'` method's `impl` must return `0`/`1` - * (NO/YES); a throwing one answers YES, as in Electron a throwing listener cannot - * veto. A throwing `'object'` method answers nil. See {@link callFromNative}. + * A JS-backed method for a runtime class. A throwing impl answers YES for `'bool'` + * (as in Electron, a throwing listener cannot veto) and nil for `'object'`. */ export type ObjcMethodSpec = { - /** The selector name, e.g. `userContentController:didReceiveScriptMessage:`. */ readonly selector: string; - /** The ObjC type encoding, e.g. `v@:@` (void; self, _cmd, one object arg). */ readonly typeEncoding: string; - /** The declared (post-`self`/`_cmd`) argument kinds; a BOOL is only defined in its low byte. */ + /** Kinds after `self`/`_cmd`; a BOOL is defined only in its low byte, so never read it as an object. */ readonly args: ReadonlyArray<'object' | 'bool'>; - /** Return kind; defaults to `'void'`. */ readonly returns?: 'void' | 'bool' | 'object'; - /** - * The JS implementation. Receives `(self, _cmd, ...args)` as bigint handles. - * A `returns: 'bool'` method's impl must produce `0`/`1`; a `returns: 'object'` - * method's impl must produce a `Handle` (`0n` = nil). The build wrapper reads - * that runtime value (a `() => number`/`() => Handle` is assignable here too). - */ + /** Gets `(self, _cmd, ...args)`; returns 0/1 for `'bool'`, a Handle (0n = nil) for `'object'`. */ readonly impl: (self: Handle, cmd: Handle, ...args: Handle[]) => void; }; @@ -56,8 +36,7 @@ const getRuntime = macOSLibraryAccessor('objc runtime class', () => }), ); -// JSCallbacks must outlive the ObjC class that points at them; the runtime keeps -// classes for the process lifetime, so we retain their callbacks for as long. +// Never close these: a registered class and its IMPs live for the whole process. const retainedCallbacks: JSCallback[] = []; const buildCallback = (method: ObjcMethodSpec): JSCallback => { @@ -95,10 +74,7 @@ const buildCallback = (method: ObjcMethodSpec): JSCallback => { ); }; -/** - * Allocate, populate, and register an Objective-C class. Returns the class - * handle. Throws {@link UnsupportedPlatformError} off macOS (via the accessor). - */ +/** Register an ObjC class whose IMPs are JSCallbacks (D026); throws off macOS. */ export const defineObjcClass = ( name: string, superclassName: string, @@ -108,11 +84,10 @@ export const defineObjcClass = ( const rt = cocoa(); const superclass = rt.classes.get(superclassName); const cls = runtime.symbols.objc_allocateClassPair(superclass, cstr(name), 0n); - // objc_allocateClassPair returns nil for a duplicate name; class_addMethod on - // nil then corrupts silently instead of failing here. + // Nil means the name is taken; class_addMethod on nil corrupts silently. if (cls === 0n) { throw new BunmaskaError( - `defineObjcClass: objc_allocateClassPair returned nil for ${JSON.stringify(name)} — the class name is already registered in this process`, + `defineObjcClass: objc_allocateClassPair returned nil for ${JSON.stringify(name)} - the class name is already registered in this process`, ); } diff --git a/src/main/platform/macos/cocoa-runtime.ts b/src/main/platform/macos/cocoa-runtime.ts index ffa64bee..e273abea 100644 --- a/src/main/platform/macos/cocoa-runtime.ts +++ b/src/main/platform/macos/cocoa-runtime.ts @@ -4,14 +4,6 @@ import { loadCocoaFFI } from './cocoa-ffi'; import { SelectorCache } from './cocoa-selector-cache'; import type { Handle } from './objc'; -/** - * The live Cocoa runtime — caches backed by the real `libobjc` symbols. - * - * Handles are exposed as `bigint` throughout Bunmaska (D016). The underlying FFI - * declares the `id`/`SEL`/`Class` slots as `u64`, so Bun hands us full-precision - * bigints directly — no `Pointer` round-trip and no tagged-pointer truncation - * (D029). - */ export type CocoaRuntime = { readonly selectors: SelectorCache; readonly classes: ClassCache; @@ -20,11 +12,7 @@ export type CocoaRuntime = { let cached: CocoaRuntime | undefined; -/** - * Return the shared Cocoa runtime. Lazy — `libobjc` and `Foundation` are - * opened on first call. Throws {@link UnsupportedPlatformError} (via - * `loadCocoaFFI`) on any non-macOS platform. - */ +/** The lazy process-wide Cocoa runtime (D017); throws off macOS. */ export const cocoa = (): CocoaRuntime => { if (cached !== undefined) { return cached; diff --git a/src/main/platform/macos/cocoa-selector-cache.ts b/src/main/platform/macos/cocoa-selector-cache.ts index a1981ea4..0972ec1b 100644 --- a/src/main/platform/macos/cocoa-selector-cache.ts +++ b/src/main/platform/macos/cocoa-selector-cache.ts @@ -1,12 +1,5 @@ -/** - * Memoising wrapper around `sel_registerName`: one registrar call per distinct - * selector name for the lifetime of the cache instance. - */ - -/** Opaque pointer-width handle returned by `sel_registerName`. */ export type Selector = bigint; -/** Shape of `sel_registerName`: name → opaque selector handle. */ export type SelectorRegistrar = (name: string) => Selector; export class SelectorCache { diff --git a/src/main/platform/macos/cocoa-webkit.ts b/src/main/platform/macos/cocoa-webkit.ts index 31219e63..c602b03e 100644 --- a/src/main/platform/macos/cocoa-webkit.ts +++ b/src/main/platform/macos/cocoa-webkit.ts @@ -2,14 +2,12 @@ import { nsString } from './cocoa-foundation'; import { msgSendPtr } from './cocoa-msgsend-variants'; import { cocoa } from './cocoa-runtime'; -/** - * Loads `WebKit.framework` through `NSBundle` rather than `dlopen`: modern system - * frameworks live in the dyld shared cache and expose few C symbols, but - * `[bundle load]` reliably registers their Objective-C classes. - */ - let loaded = false; +/** + * Register WebKit's classes (`WKWebView` and friends); idempotent. Loaded via NSBundle + * because Bun's dlopen needs a declared C symbol and WebKit's public API is ObjC only. + */ export const loadWebKit = (): void => { if (loaded) { return; diff --git a/src/main/platform/macos/cocoa-window-bounds.ts b/src/main/platform/macos/cocoa-window-bounds.ts index 448f00df..ff489a43 100644 --- a/src/main/platform/macos/cocoa-window-bounds.ts +++ b/src/main/platform/macos/cocoa-window-bounds.ts @@ -1,11 +1,3 @@ -/** - * Real NSWindow frame geometry via the CGWindowList, beating the - * no-struct-return wall: `-[NSWindow frame]` returns NSRect by value (blocked, - * D018), but `CGRectMakeWithDictionaryRepresentation` fills a caller-allocated - * OUT buffer. `kCGWindowBounds` is GLOBAL TOP-LEFT and frame-inclusive, which is - * exactly Electron's `getBounds` contract, so no coordinate flip on reads. - */ - import { FFIType, ptr } from 'bun:ffi'; import { dlopen } from '../dlopen'; import type { Rect } from '../native'; @@ -36,9 +28,9 @@ const loadCoreGraphics = (): ReturnType> => { }; /** - * The window's on-screen frame in global top-left coordinates, or `undefined` - * when the window server does not list it (hidden/never-shown windows) - the - * caller falls back to its tracked bounds then. + * The window's frame from the CGWindowList, since `-[NSWindow frame]` returns a struct + * (D030). `kCGWindowBounds` is global top-left and frame-inclusive, Electron's `getBounds` + * contract, so no flip. `undefined` when the server does not list the window (never shown). */ export const readWindowBounds = (window: Handle): Rect | undefined => { const rt = cocoa(); diff --git a/src/main/platform/macos/core-graphics-image-ffi.ts b/src/main/platform/macos/core-graphics-image-ffi.ts index 060064b2..f7302417 100644 --- a/src/main/platform/macos/core-graphics-image-ffi.ts +++ b/src/main/platform/macos/core-graphics-image-ffi.ts @@ -4,20 +4,13 @@ import { cgRectArgs, RECT_F64 } from './cocoa-msgsend-variants'; import { macOSLibraryAccessor } from './objc'; /** - * CoreGraphics bitmap-context symbols behind macOS `nativeImage` resize/crop. - * - * The resize/crop redraw goes through an OFFSCREEN bitmap context - * (`CGBitmapContextCreate(NULL, …)`) — a malloc-backed buffer with NO window - * server, so it works headless (no `NSApplication`, no `lockFocus`). - * - * Everything here is an opaque pointer (CGContextRef/CGImageRef/CGColorSpaceRef) - * — no struct is ever returned (D030). The one struct ARG, the `CGRect` passed to - * `CGContextDrawImage`, goes through {@link cgRectArgs} (D018). + * Offscreen CoreGraphics bitmap symbols behind macOS `nativeImage` resize/crop: no window + * server, so they work headless. Nothing returns a struct (D030). */ const CORE_GRAPHICS_PATH = '/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics'; -/** `kCGImageAlphaPremultipliedLast` — RGBA, the standard CG drawing format. */ +/** `kCGImageAlphaPremultipliedLast`: RGBA, the standard CG drawing format. */ export const KCG_ALPHA_PREMULTIPLIED_LAST = 1; const CORE_GRAPHICS_SYMBOLS = { @@ -47,7 +40,6 @@ const CORE_GRAPHICS_SYMBOLS = { }, } as const; -/** Open CoreGraphics and expose the offscreen-bitmap symbols (memoised; macOS-only). */ export const loadCoreGraphicsImageFFI = macOSLibraryAccessor('CoreGraphics nativeImage', () => { const { symbols } = dlopen(CORE_GRAPHICS_PATH, CORE_GRAPHICS_SYMBOLS); const draw = symbols.CGContextDrawImage; diff --git a/src/main/platform/macos/objc.ts b/src/main/platform/macos/objc.ts index f0815819..f651482d 100644 --- a/src/main/platform/macos/objc.ts +++ b/src/main/platform/macos/objc.ts @@ -4,15 +4,7 @@ import { currentPlatform } from '../../../common/platform'; import { cstr } from '../cstr'; import { dlopen } from '../dlopen'; -/** - * Shared Objective-C FFI primitives for the macOS backend. - * - * Every Bunmaska Objective-C handle (`id`, `SEL`, `Class`, `IMP`) flows through - * the codebase as a `bigint` (D016); the only place the `Pointer ↔ bigint` - * conversion happens is here and at each `objc_msgSend` boundary. - */ - -/** Opaque pointer-width Objective-C handle (`id`/`SEL`/`Class`/`IMP`). */ +/** An Objective-C `id`/`SEL`/`Class`/`IMP`: always a bigint (D016) in a u64 slot (D029). */ export type Handle = bigint; export const LIBOBJC_PATH = 'libobjc.A.dylib'; @@ -47,11 +39,7 @@ export const callFromNative = (fallback: T, run: () => T): T => { } }; -/** - * Build a memoising accessor for a macOS-only resource. The accessor opens the - * resource on first call and caches it; it throws {@link UnsupportedPlatformError} - * on any non-macOS host so importing modules stay safe to load everywhere. - */ +/** Memoise a macOS-only resource; throws {@link UnsupportedPlatformError} at call time elsewhere. */ export const macOSLibraryAccessor = (name: string, open: () => T): (() => T) => { let cached: T | undefined; return () => { diff --git a/src/main/platform/macos/security-ffi.ts b/src/main/platform/macos/security-ffi.ts index 02caec15..b614a1f0 100644 --- a/src/main/platform/macos/security-ffi.ts +++ b/src/main/platform/macos/security-ffi.ts @@ -3,19 +3,10 @@ import { dlopen } from '../dlopen'; import { dataSymbolAddress, macOSLibraryAccessor } from './objc'; /** - * Security.framework + CoreFoundation symbols behind the macOS Keychain backend - * of `safeStorage`. - * - * `SecItemAdd`/`SecItemCopyMatching`/`SecItemDelete` take a `CFDictionaryRef` - * query; we pass an `NSMutableDictionary` (toll-free bridged) as a `u64` handle - * to match the codebase's ObjC-handle convention (D029). The dictionary KEYS must - * be the REAL exported `kSec*` `CFStringRef` constants — SecItem compares keys by - * POINTER identity, so value-equal CFStrings are rejected (errSecParam, -50). - * - * Reading those constants needs `dlsym` + a pointer-precise memory read: Bun's - * `dlopen` only exposes FUNCTION symbols (a declared symbol is CALLED), so a DATA - * global is resolved via `dlsym(handle, name)` then `read.u64(addr, 0)` (NOT - * `BigInt(read.ptr(...))`, which round-trips through a lossy JS number — D029). + * Keychain symbols behind macOS `safeStorage`. The query dictionary's KEYS must be the + * exported `kSec*` constants: SecItem compares keys by POINTER identity, so a value-equal + * CFString fails with errSecParam (-50). Read each constant with `read.u64`, never + * `BigInt(read.ptr())`, which goes through a lossy JS number (D029). */ const SECURITY_PATH = '/System/Library/Frameworks/Security.framework/Security'; @@ -31,7 +22,7 @@ export const loadSecurityFFI = macOSLibraryAccessor('Security.framework safeStor }), ); -/** The `kSec*` / `kCF*` constants the Keychain query dictionary needs (as `CFTypeRef` handles). */ +/** The `kSec*` / `kCF*` constants the Keychain query needs, as `CFTypeRef` handles. */ export type SecConstants = { kSecClass: bigint; kSecClassGenericPassword: bigint; diff --git a/tests/integration/macos/cocoa-block.test.ts b/tests/integration/macos/cocoa-block.test.ts index 6d341fbb..86423c1a 100644 --- a/tests/integration/macos/cocoa-block.test.ts +++ b/tests/integration/macos/cocoa-block.test.ts @@ -10,14 +10,7 @@ import { nsString } from '../../../src/main/platform/macos/cocoa-foundation'; import { msgSendPtr } from '../../../src/main/platform/macos/cocoa-msgsend-variants'; import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; -/** - * Proves D022 is solved: a hand-built global ObjC Block (built by - * {@link makeOneShotBlock}) is invoked by the ObjC runtime without crashing. - * Uses `-[NSArray enumerateObjectsUsingBlock:]` — a synchronous, one-shot block - * caller (a single-element array invokes the block exactly once). The async - * run-loop-delivery path uses the identical block and is exercised by the - * completion-handler features built on top of this primitive. - */ +// A single-element NSArray invokes a block synchronously, exactly once (D022b). if (currentPlatform() === 'macos') { describe('cocoa-block (hand-built ObjC Blocks)', () => { const flush = (): Promise => new Promise((resolve) => setTimeout(resolve, 0)); diff --git a/tests/integration/macos/cocoa-ffi.test.ts b/tests/integration/macos/cocoa-ffi.test.ts index 4aa9afaa..8c6e89e6 100644 --- a/tests/integration/macos/cocoa-ffi.test.ts +++ b/tests/integration/macos/cocoa-ffi.test.ts @@ -15,7 +15,7 @@ if (currentPlatform() === 'macos') { expect(sel).not.toBe(0n); }); - test('sel_registerName is idempotent — same name yields the same selector pointer', () => { + test('sel_registerName is idempotent - same name yields the same selector pointer', () => { const lib = loadCocoaFFI(); const a = lib.symbols.sel_registerName(cstr('release')); const b = lib.symbols.sel_registerName(cstr('release')); diff --git a/tests/integration/macos/cocoa-foundation.test.ts b/tests/integration/macos/cocoa-foundation.test.ts index 862efec0..69d188e9 100644 --- a/tests/integration/macos/cocoa-foundation.test.ts +++ b/tests/integration/macos/cocoa-foundation.test.ts @@ -17,7 +17,7 @@ if (currentPlatform() === 'macos') { }); test('round-trips UTF-8 multibyte content', () => { - expect(nsStringToString(nsString('café — 日本語'))).toBe('café — 日本語'); + expect(nsStringToString(nsString('café → 日本語'))).toBe('café → 日本語'); }); test('nsStringToString returns empty string for a null handle', () => { diff --git a/tests/integration/macos/cocoa-msgsend-f64.test.ts b/tests/integration/macos/cocoa-msgsend-f64.test.ts index 0a87b0a0..5e6ea135 100644 --- a/tests/integration/macos/cocoa-msgsend-f64.test.ts +++ b/tests/integration/macos/cocoa-msgsend-f64.test.ts @@ -4,7 +4,7 @@ import { msgSendF64 } from '../../../src/main/platform/macos/cocoa-msgsend-varia import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; if (currentPlatform() === 'macos') { - describe('msgSendF64 — one-extra-f64-arg variant', () => { + describe('msgSendF64 - one-extra-f64-arg variant', () => { test('[NSDate dateWithTimeIntervalSinceNow:0.5] returns a non-zero NSDate', () => { const rt = cocoa(); const nsDate = rt.classes.get('NSDate'); diff --git a/tests/integration/macos/cocoa-msgsend-i64.test.ts b/tests/integration/macos/cocoa-msgsend-i64.test.ts index f99c729c..5c73b496 100644 --- a/tests/integration/macos/cocoa-msgsend-i64.test.ts +++ b/tests/integration/macos/cocoa-msgsend-i64.test.ts @@ -4,7 +4,7 @@ import { msgSendI64 } from '../../../src/main/platform/macos/cocoa-msgsend-varia import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; if (currentPlatform() === 'macos') { - describe('msgSendI64 — one-extra-i64-arg variant', () => { + describe('msgSendI64 - one-extra-i64-arg variant', () => { test('[NSNumber numberWithInteger:42] returns a non-zero NSNumber', () => { const rt = cocoa(); const nsNumber = rt.classes.get('NSNumber'); diff --git a/tests/integration/macos/cocoa-msgsend-ptr.test.ts b/tests/integration/macos/cocoa-msgsend-ptr.test.ts index 627bfcfa..1186eda7 100644 --- a/tests/integration/macos/cocoa-msgsend-ptr.test.ts +++ b/tests/integration/macos/cocoa-msgsend-ptr.test.ts @@ -4,7 +4,7 @@ import { msgSendPtr } from '../../../src/main/platform/macos/cocoa-msgsend-varia import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; if (currentPlatform() === 'macos') { - describe('msgSendPtr — one-extra-pointer-arg variant', () => { + describe('msgSendPtr - one-extra-pointer-arg variant', () => { test('[NSWindow performSelector:@selector(alloc)] returns an allocated instance', () => { const rt = cocoa(); const nsWindow = rt.classes.get('NSWindow'); diff --git a/tests/integration/macos/cocoa-msgsend-returns-u8.test.ts b/tests/integration/macos/cocoa-msgsend-returns-u8.test.ts index a9b4b6d0..ba9ce20a 100644 --- a/tests/integration/macos/cocoa-msgsend-returns-u8.test.ts +++ b/tests/integration/macos/cocoa-msgsend-returns-u8.test.ts @@ -4,7 +4,7 @@ import { msgSendReturnsU8 } from '../../../src/main/platform/macos/cocoa-msgsend import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; if (currentPlatform() === 'macos') { - describe('msgSendReturnsU8 — BOOL-returning, zero-extra-arg variant', () => { + describe('msgSendReturnsU8 - BOOL-returning, zero-extra-arg variant', () => { test('[NSObject_instance isProxy] returns 0 (NO)', () => { const rt = cocoa(); const nsObject = rt.classes.get('NSObject'); diff --git a/tests/integration/macos/cocoa-msgsend-u8.test.ts b/tests/integration/macos/cocoa-msgsend-u8.test.ts index 542a9e9d..15de5827 100644 --- a/tests/integration/macos/cocoa-msgsend-u8.test.ts +++ b/tests/integration/macos/cocoa-msgsend-u8.test.ts @@ -4,7 +4,7 @@ import { msgSendU8 } from '../../../src/main/platform/macos/cocoa-msgsend-varian import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; if (currentPlatform() === 'macos') { - describe('msgSendU8 — one-extra-u8-arg variant', () => { + describe('msgSendU8 - one-extra-u8-arg variant', () => { test('[NSNumber numberWithBool:1] returns a non-zero NSNumber instance', () => { const rt = cocoa(); const nsNumber = rt.classes.get('NSNumber'); diff --git a/tests/integration/macos/cocoa-runtime.test.ts b/tests/integration/macos/cocoa-runtime.test.ts index f3c365aa..73ec5bc3 100644 --- a/tests/integration/macos/cocoa-runtime.test.ts +++ b/tests/integration/macos/cocoa-runtime.test.ts @@ -15,7 +15,7 @@ if (currentPlatform() === 'macos') { expect(sel).not.toBe(0n); }); - test('selectors.get is cached — same name yields same bigint', () => { + test('selectors.get is cached - same name yields same bigint', () => { const a = cocoa().selectors.get('release'); const b = cocoa().selectors.get('release'); expect(b).toBe(a); diff --git a/tests/integration/macos/cocoa-webkit.test.ts b/tests/integration/macos/cocoa-webkit.test.ts index 399c1dff..6bcbcec5 100644 --- a/tests/integration/macos/cocoa-webkit.test.ts +++ b/tests/integration/macos/cocoa-webkit.test.ts @@ -20,7 +20,7 @@ if (currentPlatform() === 'macos') { expect(cocoa().classes.get('WKUserContentController')).not.toBe(0n); }); - test('is idempotent — repeated calls are safe', () => { + test('is idempotent - repeated calls are safe', () => { loadWebKit(); loadWebKit(); expect(cocoa().classes.get('WKWebView')).not.toBe(0n); diff --git a/tests/integration/macos/phase0-exit.test.ts b/tests/integration/macos/phase0-exit.test.ts index 8dd05a71..d6a1220a 100644 --- a/tests/integration/macos/phase0-exit.test.ts +++ b/tests/integration/macos/phase0-exit.test.ts @@ -17,7 +17,7 @@ const NS_APPLICATION_ACTIVATION_POLICY_REGULAR = 0n; const NS_BACKING_STORE_BUFFERED = 2n; if (currentPlatform() === 'macos') { - describe('Phase 0 macOS exit — drive AppKit end-to-end from Bun via bun:ffi', () => { + describe('Phase 0 macOS exit - drive AppKit end-to-end from Bun via bun:ffi', () => { test('full NSApplication + NSWindow choreography yields a live, named window', () => { const rt = cocoa(); @@ -52,14 +52,14 @@ if (currentPlatform() === 'macos') { ); expect(window).not.toBe(0n); - // 5. [window makeKeyAndOrderFront:nil] — schedules the window for display + // 5. [window makeKeyAndOrderFront:nil] - schedules the window for display msgSendPtr(window, rt.selectors.get('makeKeyAndOrderFront:'), 0n); - // 6. [NSApp activateIgnoringOtherApps:YES] — brings the app frontmost + // 6. [NSApp activateIgnoringOtherApps:YES] - brings the app frontmost msgSendU8(app, rt.selectors.get('activateIgnoringOtherApps:'), 1); // 7. [window contentView] is auto-created during init and is a non-nil - // NSView — proves the selector dispatch table on a fully-initialized + // NSView - proves the selector dispatch table on a fully-initialized // NSWindow works. (We avoid `[window title]` because windows in a // non-bundled process can legitimately have nil titles.) const contentView = rt.msgSend(window, rt.selectors.get('contentView')); @@ -67,7 +67,7 @@ if (currentPlatform() === 'macos') { // 8. [window isVisible] returns 0 or 1. On a headless CI runner without // a window server this may legitimately return 0 even with a valid - // window object — we assert only that the call returns a JS number. + // window object - we assert only that the call returns a JS number. const visible = msgSendReturnsU8(window, rt.selectors.get('isVisible')); expect(typeof visible).toBe('number'); expect(visible === 0 || visible === 1).toBe(true); diff --git a/tests/unit/main/platform/macos/cocoa-class-cache.test.ts b/tests/unit/main/platform/macos/cocoa-class-cache.test.ts index 940dde39..5e87adf4 100644 --- a/tests/unit/main/platform/macos/cocoa-class-cache.test.ts +++ b/tests/unit/main/platform/macos/cocoa-class-cache.test.ts @@ -59,7 +59,7 @@ describe('ClassCache.get', () => { expect(() => cache.get('MissingClass')).toThrow(/Objective-C class not found: MissingClass/); }); - test('does not cache NULL results — a later successful lookup wins', () => { + test('does not cache NULL results - a later successful lookup wins', () => { let count = 0; const resolver: ClassResolver = () => { count += 1; From faeb8e631d65224b4a3a96a6d6c0f6d819ec0923 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:00:15 -0700 Subject: [PATCH 112/586] chore: trim app slice comments to the comment rules --- src/electron.ts | 16 ++------- src/main/api/app-environment.ts | 12 ++----- src/main/api/app-locale.ts | 10 ++---- src/main/api/app-metadata.ts | 10 +----- src/main/api/app.ts | 44 ++++--------------------- src/main/api/single-instance-backend.ts | 11 ++----- src/main/api/single-instance.ts | 23 ++++--------- src/main/bootstrap.ts | 18 +++------- src/main/module-list.ts | 13 ++------ src/main/native-app.ts | 7 +--- 10 files changed, 33 insertions(+), 131 deletions(-) diff --git a/src/electron.ts b/src/electron.ts index b08797ea..132ddd0b 100644 --- a/src/electron.ts +++ b/src/electron.ts @@ -1,15 +1,9 @@ import * as bunmaska from './index'; import { isImplemented, KNOWN_ELECTRON_MODULES, notImplementedMessage } from './main/module-list'; -/** - * The drop-in `electron` compatibility surface (REQUIREMENTS §8). A KNOWN-but-not- - * yet-implemented module name (e.g. `electron.autoUpdater`) throws - * {@link notImplementedMessage}; an unknown name still returns `undefined`. - */ - const KNOWN: ReadonlySet = new Set(KNOWN_ELECTRON_MODULES); -/** Wrap `base` so unimplemented Electron module names throw on access. */ +/** The drop-in `electron` surface (D032): a known-but-unimplemented module name throws, an unknown one is `undefined`. */ export const createElectronShim = ( base: Record = bunmaska as unknown as Record, ): Record => @@ -22,12 +16,8 @@ export const createElectronShim = ( }, }); -/** - * Named re-exports, so the documented `import { app } from 'bunmaska/electron'` - * works. A named import of an unimplemented module fails at import time with a - * standard ESM error; the default export's Proxy is what turns a PROPERTY access - * into the actionable {@link notImplementedMessage}. - */ +// Named imports of an unimplemented module fail at ESM link time with a generic +// error; only the default export's Proxy turns the access into notImplementedMessage. export * from './index'; const electron = createElectronShim() as typeof bunmaska; diff --git a/src/main/api/app-environment.ts b/src/main/api/app-environment.ts index f8ac17f7..7c5e0a1a 100644 --- a/src/main/api/app-environment.ts +++ b/src/main/api/app-environment.ts @@ -5,11 +5,6 @@ import { currentPlatform, type Platform } from '../../common/platform'; import { findManifest, type Manifest, type ManifestReader, readManifest } from './app-metadata'; import { normalizeLocale, parsePreferredLanguages } from './app-locale'; -/** - * Assembles the host facts the `app` module needs — paths, manifest, locale, - * packaged-state — from injected primitives. - */ - export type EnvironmentDeps = { readonly platform: Platform; readonly home: string; @@ -19,11 +14,11 @@ export type EnvironmentDeps = { readonly mainScript: string; readonly cwd: string; readonly env: Readonly>; - /** The raw locale tag from `Intl` or `$LANG`. */ + /** The raw `Intl` locale tag. */ readonly locale: string; readonly readFile: ManifestReader; readonly exit: (code: number) => void; - /** Spawn a detached copy of the app on exit (backs `app.relaunch`). */ + /** Spawns the app again once this process exits (`app.relaunch`). */ readonly relaunch: (execPath: string, args: string[]) => void; }; @@ -32,8 +27,8 @@ export type AppEnvironment = { readonly home: string; readonly temp: string; readonly execPath: string; - /** A compiled binary's own directory, else the nearest `package.json` directory, else cwd. */ readonly appPath: string; + /** `process.env`, plus the Linux `user-dirs.dirs` entries. */ readonly env: Readonly>; readonly manifest: Manifest | undefined; /** Normalized BCP-47 locale (`''` if unknown). */ @@ -110,7 +105,6 @@ const safeRead: ManifestReader = (path) => { } }; -/** Built from the live host: `os`/`process`/`fs`/`Intl`. */ export const defaultAppEnvironment = (): AppEnvironment => buildAppEnvironment({ platform: currentPlatform(), diff --git a/src/main/api/app-locale.ts b/src/main/api/app-locale.ts index d3bcea5b..067aa532 100644 --- a/src/main/api/app-locale.ts +++ b/src/main/api/app-locale.ts @@ -1,10 +1,7 @@ /** POSIX placeholder locales that carry no real language information. */ const POSIX_PLACEHOLDERS: ReadonlySet = new Set(['C', 'POSIX']); -/** - * `en_US.UTF-8` → `en-US`. Returns `''` for the POSIX `C`/`POSIX` locales and - * for empty input. - */ +/** `en_US.UTF-8` → `en-US`; `''` for empty input and the POSIX `C`/`POSIX` locales. */ export const normalizeLocale = (raw: string): string => { const base = raw.split('.')[0]?.split('@')[0] ?? ''; if (base.length === 0 || POSIX_PLACEHOLDERS.has(base)) { @@ -22,10 +19,7 @@ export const localeCountryCode = (locale: string): string => { } }; -/** - * Most-preferred first, from the colon-separated `$LANGUAGE` list, falling back - * to `$LANG`. POSIX placeholders and blanks are dropped. - */ +/** Most-preferred first, from the colon-separated `$LANGUAGE`, else `$LANG`; placeholders and blanks dropped. */ export const parsePreferredLanguages = ( env: Readonly>, ): string[] => { diff --git a/src/main/api/app-metadata.ts b/src/main/api/app-metadata.ts index 66362951..04e0886b 100644 --- a/src/main/api/app-metadata.ts +++ b/src/main/api/app-metadata.ts @@ -1,17 +1,9 @@ import { dirname, join } from 'node:path'; -/** - * Resolution of the consuming app's name and version: walk up from the main - * module's directory to the nearest `package.json`, as Electron does. - */ - export const DEFAULT_APP_NAME = 'bunmaska-app'; export const DEFAULT_APP_VERSION = '0.0.0'; -/** - * Each field is explicitly `| undefined` (not merely optional) so a parsed - * manifest can set a key to `undefined` under `exactOptionalPropertyTypes`. - */ +/** Fields are `| undefined`, not just optional, so a parse can store `undefined` (`exactOptionalPropertyTypes`). */ export type Manifest = { readonly name?: string | undefined; readonly productName?: string | undefined; diff --git a/src/main/api/app.ts b/src/main/api/app.ts index 0d4cbf58..2f0660d2 100644 --- a/src/main/api/app.ts +++ b/src/main/api/app.ts @@ -12,13 +12,7 @@ import { nativeApp } from '../native-app'; import { createLockBackend } from './single-instance-backend'; import { SingleInstanceManager } from './single-instance'; -/** - * Application lifecycle controller — the drop-in equivalent of Electron's `app`. - * - * Extends Node's {@link EventEmitter} so the full listener API matches - * Electron's contract (D023). Events: `ready`, `before-quit`, `will-quit`, - * `window-all-closed`, `quit`. - */ +/** Electron's `app`; an EventEmitter so the full listener API matches (D023). */ export class App extends EventEmitter { #ready = false; #quitting = false; @@ -40,12 +34,7 @@ export class App extends EventEmitter { this.#env = env; } - /** - * Reset mutable state and app-level window-event listeners. Lifecycle - * listeners (`before-quit`/`will-quit`/`quit`) are left intact so the native - * bootstrap wiring survives. - * @internal - */ + /** @internal Keeps lifecycle listeners, so the bootstrap wiring survives. */ resetForTesting(): void { this.#env = undefined; this.#quitting = false; @@ -89,10 +78,7 @@ export class App extends EventEmitter { }); } - /** - * Mark the app ready and emit `ready`. Idempotent. - * @internal Invoked by the native bootstrap. - */ + /** @internal Idempotent; called by the native bootstrap. */ markReady(): void { if (this.#ready) { return; @@ -103,10 +89,7 @@ export class App extends EventEmitter { queueMicrotask(() => this.emit('ready')); } - /** - * Register the native bootstrap to run on the first {@link whenReady}. - * @internal - */ + /** @internal Runs on the first {@link whenReady}. */ setStartHook(hook: () => void): void { this.#startHook = hook; } @@ -133,11 +116,7 @@ export class App extends EventEmitter { return resolveAppVersion(this.#environment().manifest); } - /** - * The default User-Agent applied to new windows whose session has no explicit - * override (Electron's `app.userAgentFallback`). `''` means "use the platform - * WebKit default". A per-session `session.setUserAgent` takes precedence. - */ + /** `''` means the WebKit default; a per-session `session.setUserAgent` wins. */ get userAgentFallback(): string { return this.#userAgentFallback; } @@ -252,10 +231,7 @@ export class App extends EventEmitter { return getDock(); } - /** - * Set the app's badge count. On macOS shows it on the dock tile; the value is - * always cached for {@link getBadgeCount}. Returns whether it was displayed. - */ + /** Always cached for {@link getBadgeCount}; returns whether the dock showed it (macOS only). */ setBadgeCount(count = 0): boolean { this.#badgeCount = count; return displayBadgeCount(count); @@ -301,12 +277,7 @@ export class App extends EventEmitter { this.#singleInstance = manager; } - /** - * Acquire the single-instance lock. Returns `true` if this is the primary - * instance; `false` if another instance already holds it (in which case it has - * been handed this process's argv/cwd via its `second-instance` event, and the - * caller should quit). - */ + /** `false` when another instance holds the lock; it receives this argv/cwd asynchronously. */ requestSingleInstanceLock(additionalData: unknown = undefined): boolean { const payload = { argv: [...process.argv], cwd: process.cwd(), additionalData }; return this.#singleInstanceManager().request(payload, (p) => { @@ -364,5 +335,4 @@ export class App extends EventEmitter { } } -/** The application lifecycle singleton — Electron's `app`. */ export const app = new App(); diff --git a/src/main/api/single-instance-backend.ts b/src/main/api/single-instance-backend.ts index c831f811..44bf0497 100644 --- a/src/main/api/single-instance-backend.ts +++ b/src/main/api/single-instance-backend.ts @@ -3,15 +3,11 @@ import { dirname } from 'node:path'; import { createLogger } from '../../common/logger'; import type { LockBackend } from './single-instance'; -/** - * The live {@link LockBackend}. Stateful — it holds the listening server so - * {@link LockBackend.stop} can close it — so each lock gets its own instance. - */ - const log = createLogger('single-instance'); type UnixSocketListener = { stop(closeActiveConnections?: boolean): void }; +/** Stateful (it holds the server `stop` closes): one instance per lock. */ export const createLockBackend = (): LockBackend => { let server: UnixSocketListener | undefined; let removeLockOnExit: (() => void) | undefined; @@ -28,7 +24,7 @@ export const createLockBackend = (): LockBackend => { tryCreateLock(lockPath, pid) { try { mkdirSync(dirname(lockPath), { recursive: true }); - // `wx` fails if the file already exists — the atomic acquire. + // `wx` fails if the file already exists: the atomic acquire. writeFileSync(lockPath, String(pid), { flag: 'wx' }); // A lock left behind names a pid the OS will reuse, blocking every later launch. // Prepended so it runs before the Windows TerminateProcess exit hook (D043). @@ -51,11 +47,10 @@ export const createLockBackend = (): LockBackend => { isAlive(pid) { try { - // Signal 0 performs only the existence/permission check. process.kill(pid, 0); return true; } catch (error) { - // EPERM means the process exists but is owned by another user — alive. + // EPERM: the process exists but belongs to another user, so it is alive. return (error as NodeJS.ErrnoException).code === 'EPERM'; } }, diff --git a/src/main/api/single-instance.ts b/src/main/api/single-instance.ts index 8f1167cb..4945d411 100644 --- a/src/main/api/single-instance.ts +++ b/src/main/api/single-instance.ts @@ -1,11 +1,5 @@ -/** - * Single-instance lock + second-instance messaging (Electron's - * `requestSingleInstanceLock` / `second-instance`). - * - * The primary/secondary decision must stay SYNCHRONOUS — Electron's contract: - * an atomically created pidfile that already names a live process makes this - * process a secondary. Argv hand-off to the primary uses a unix socket. - */ +// The primary/secondary decision must stay SYNCHRONOUS (Electron's contract, D031): an atomic +// pidfile naming a live process makes this a secondary. The argv hand-off rides a unix socket. export type SecondInstancePayload = { readonly argv: string[]; @@ -25,12 +19,12 @@ export type LockBackend = { /** `undefined` if the lock file is missing or unreadable. */ readLockPid(lockPath: string): number | undefined; isAlive(pid: number): boolean; - /** Removes the stale lock file and its socket. */ + /** Removes the stale lock file (a stale socket is replaced by `startServer`). */ clearLock(lockPath: string): void; startServer(socketPath: string, onMessage: (json: string) => void): void; /** Fire-and-forget. */ notify(socketPath: string, json: string): void; - /** Stops the server and removes the lock + socket. */ + /** Stops the server and removes the lock and socket. */ stop(lockPath: string, socketPath: string): void; }; @@ -74,10 +68,7 @@ export class SingleInstanceManager { return this.#locked; } - /** - * `false` means another live instance holds the lock and has been handed - * `payload`, which surfaces there via its own `request` callback. - */ + /** `false` means another live instance holds the lock; `payload` is sent to it asynchronously. */ request( payload: SecondInstancePayload, onSecondInstance: (p: SecondInstancePayload) => void, @@ -93,8 +84,8 @@ export class SingleInstanceManager { this.#backend.notify(this.#paths.socketPath, encodePayload(payload)); return false; } - // The recorded primary is gone — reclaim the stale lock and retry once. - this.#backend.clearLock(this.#paths.lockPath); + // The recorded primary is gone: reclaim the stale lock and retry once. + this.#backend.clearLock(this.#paths.lockPath); // ponytail: races a concurrent reclaim and trusts a reusable pid; flock/LockFileEx fixes both return this.#acquire(onSecondInstance); } diff --git a/src/main/bootstrap.ts b/src/main/bootstrap.ts index 36d5c494..6ed1335c 100644 --- a/src/main/bootstrap.ts +++ b/src/main/bootstrap.ts @@ -4,15 +4,10 @@ import { nativeTheme } from './api/native-theme'; import { powerMonitor } from './api/power-monitor'; import { nativeApp } from './native-app'; -/** - * Wires the platform-agnostic {@link app} singleton to the native backend. - * Imported for its side effects by the public barrel, and kept separate from both - * `app` and `BrowserWindow` to avoid an import cycle. - */ +// Wires `app` to the native backend; separate from `app` and `BrowserWindow` to avoid an import cycle. let started = false; -/** Start the native app once and mark {@link app} ready when it signals ready. */ export const ensureNativeStarted = (): void => { if (started) { return; @@ -21,16 +16,13 @@ export const ensureNativeStarted = (): void => { const native = nativeApp(); native.onReady(() => { app.markReady(); - // The runtime is up (NSApp / GTK initialised), so the OS observers can safely - // attach their native notification hooks now. + // Observers attach native hooks, which need NSApp / GTK initialised first. nativeTheme.startObserving(); powerMonitor.startObserving(); }); - // macOS Dock-reopen → Electron's `activate` (Linux backends omit onActivate). native.onActivate?.((hasVisibleWindows) => { app.emit('activate', makeCancelableEvent(), hasVisibleWindows); }); - // macOS file/URL associations → Electron's `open-url` / `open-file`. native.onOpenUrl?.((url) => { app.emit('open-url', makeCancelableEvent(), url); }); @@ -45,7 +37,7 @@ export const ensureNativeStarted = (): void => { } }; -/** Reset the one-shot guard. Test-only. */ +/** @internal */ export const resetBootstrapForTesting = (): void => { started = false; }; @@ -58,7 +50,5 @@ app.on('newListener', (event: string | symbol) => { setTimeout(ensureNativeStarted, 0); } }); -// `quit` fires only after `before-quit` and `will-quit` had their chance to veto, -// so a vetoed quit leaves the run loop pumping (stopping it on `will-quit` killed -// every later native callback in an app that cancelled its own quit). +// Stop the pump on `quit`, never `will-quit`: a vetoed quit would kill every later native callback. app.on('quit', () => nativeApp().quit()); diff --git a/src/main/module-list.ts b/src/main/module-list.ts index 951a17f9..1c1c8bd3 100644 --- a/src/main/module-list.ts +++ b/src/main/module-list.ts @@ -1,12 +1,6 @@ /** - * The canonical map of Electron's main-process module names and which ones - * Bunmaska implements today (D028). - */ - -/** - * Every main-process module `require('electron')` exposes, from Electron's - * `lib/browser/api/module-list.ts`. Kept in sync by hand, not generated, so adding - * a name is a conscious parity decision. + * Every module `require('electron')` exposes in the main process (Electron's browser and + * common `module-list.ts`, D028). Synced by hand: adding a name is a parity decision. */ export const KNOWN_ELECTRON_MODULES = [ 'app', @@ -55,7 +49,6 @@ export const KNOWN_ELECTRON_MODULES = [ export type ElectronModuleName = (typeof KNOWN_ELECTRON_MODULES)[number]; -/** The modules Bunmaska actually ships. Grows phase by phase. */ export const IMPLEMENTED_MODULES = [ 'app', 'autoUpdater', @@ -82,9 +75,7 @@ export const IMPLEMENTED_MODULES = [ const implemented: ReadonlySet = new Set(IMPLEMENTED_MODULES); -/** Whether Bunmaska implements the given module today. */ export const isImplemented = (name: string): boolean => implemented.has(name); -/** The actionable error message for a not-yet-implemented Electron module. */ export const notImplementedMessage = (name: string): string => `Bunmaska: '${name}' is not yet implemented. Track progress at https://github.com/ipfizz/bunmaska`; diff --git a/src/main/native-app.ts b/src/main/native-app.ts index d791b0b6..804b0806 100644 --- a/src/main/native-app.ts +++ b/src/main/native-app.ts @@ -1,14 +1,9 @@ import { createNativeApplication } from './platform/index'; import type { NativeApplication } from './platform/native'; -/** - * Process-wide lazy singleton for the native application backend: exactly one per - * process, so everything shares one run-loop pump and one window registry. - */ - let instance: NativeApplication | undefined; -/** Return the shared native application, creating it on first use. */ +/** Exactly one backend per process, so everything shares one run-loop pump and window registry. */ export const nativeApp = (): NativeApplication => { if (instance === undefined) { instance = createNativeApplication(); From dcffc4820e2fd210d1109d5cc44083a720860f5d Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:00:17 -0700 Subject: [PATCH 113/586] test: pin the macOS crop y-flip with a two-colour fixture --- .../integration/macos/cocoa-native-image.test.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/tests/integration/macos/cocoa-native-image.test.ts b/tests/integration/macos/cocoa-native-image.test.ts index 4a975937..70914aee 100644 --- a/tests/integration/macos/cocoa-native-image.test.ts +++ b/tests/integration/macos/cocoa-native-image.test.ts @@ -1,6 +1,10 @@ import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; +import { toArrayBuffer } from 'bun:ffi'; import { currentPlatform } from '../../../src/common/platform'; import { nativeImage, setNativeImageBackendForTesting } from '../../../src/main/api/native-image'; +import { cocoaNativeImageBackend } from '../../../src/main/platform/macos/cocoa-native-image'; +import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; +import { ptrIn } from '../../../src/main/platform/macos/objc'; import { removeTinyPngFile, TINY_PNG_HEIGHT, @@ -9,6 +13,10 @@ import { writeTinyPngFile, } from '../../fixtures/tiny-png'; +/** 1x2 RGBA PNG: an opaque red pixel above an opaque blue one. */ +const RED_OVER_BLUE_1X2_PNG = + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVR4nGP4z8Dwn4GB4f9/ABH4A/3f152fAAAAAElFTkSuQmCC'; + /** 1x1 8-bit gray+alpha PNG; AppKit's PNG encoder fails on such a rep directly. */ const GRAY_ALPHA_1X1_PNG = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=='; @@ -112,6 +120,13 @@ if (currentPlatform() === 'macos') { expect(img.toPNG().length).toBeGreaterThan(0); }); + test('crop measures y from the top edge', () => { + const source = cocoaNativeImageBackend.decode(Buffer.from(RED_OVER_BLUE_1X2_PNG, 'base64')); + const top = cocoaNativeImageBackend.crop(source.handle, 0, 0, 1, 1); + const pixels = cocoa().msgSend(top.handle, cocoa().selectors.get('bitmapData')); + expect([...new Uint8Array(toArrayBuffer(ptrIn(pixels), 0, 4))]).toEqual([255, 0, 0, 255]); + }); + test('resize/crop of an empty image stay empty', () => { const empty = nativeImage.createFromPath('/no/such.png'); expect(empty.resize({ width: 4, height: 4 }).isEmpty()).toBe(true); From 97d0e16a331b7b6f8fae5a0fbff0696794557b39 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:00:18 -0700 Subject: [PATCH 114/586] chore: correct stale Windows test comments and dashes --- tests/integration/windows/app-menu.test.ts | 6 +++--- tests/integration/windows/windows-native-window.test.ts | 6 +----- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/tests/integration/windows/app-menu.test.ts b/tests/integration/windows/app-menu.test.ts index 80951efb..fdc8aa61 100644 --- a/tests/integration/windows/app-menu.test.ts +++ b/tests/integration/windows/app-menu.test.ts @@ -7,7 +7,7 @@ import { createWindowsMenuRealizer } from '../../../src/main/platform/windows/wi import { NativeWin32Window } from '../../../src/main/platform/windows/windows-native-window'; /** - * The application menu BAR on Windows — pure Win32 (no WebKit engine needed). A + * The application menu BAR on Windows - pure Win32 (no WebKit engine needed). A * realizer mirrors the menu onto each registered window via a real `CreateMenu` * bar + `SetMenu`; a menu click arrives as `WM_COMMAND` on the window's JSCallback * frame proc, which routes it to the realizer's stored `onClick`. These tests drive @@ -68,7 +68,7 @@ describe.skipIf(!isWindows)('Windows application menu bar', () => { user32.SendMessageW(native.hwnd(), WM_COMMAND, BigInt(quitId), 0n); expect(clicked).toBe(1); - // Position 1 is the "Help" submenu — popups have no command id. + // Position 1 is the "Help" submenu - popups have no command id. expect(user32.GetMenuItemID(bar, 1) >>> 0).toBe(0xffffffff); } finally { native.destroy(); @@ -127,7 +127,7 @@ describe.skipIf(!isWindows)('Windows application menu bar', () => { // Engine-gated: the menu bar coexisting with a LIVE WebKit view (the JSCallback // frame proc must keep driving the runtime; the menu-bar client-area shrink must // not disturb the hosted WKView). Spawned in a subprocess like the other engine -// probes — WebKit's multi-process IPC does not coexist with the bun:test host. +// probes - WebKit's multi-process IPC does not coexist with the bun:test host. const hasEngine = isWindows && resolveWindowsEngineDir() !== undefined; describe.skipIf(!hasEngine)('application menu bar with a live engine', () => { test('executeJavaScript still works with an application menu attached', async () => { diff --git a/tests/integration/windows/windows-native-window.test.ts b/tests/integration/windows/windows-native-window.test.ts index b33779b1..c94b29b8 100644 --- a/tests/integration/windows/windows-native-window.test.ts +++ b/tests/integration/windows/windows-native-window.test.ts @@ -16,11 +16,7 @@ const SWP_NOMOVE_NOZORDER_NOACTIVATE = 0x0002 | 0x0004 | 0x0010; const SWP_NOZORDER_NOACTIVATE = 0x0004 | 0x0010; const SWP_NOSIZE_NOZORDER_NOACTIVATE = 0x0001 | 0x0004 | 0x0010; -/** - * Windows-only. Drives REAL native-WndProc top-level windows (the kind that can - * host WebKit) and proves the preventable close is routed from the message PUMP - * (a posted `WM_SYSCOMMAND`/`SC_CLOSE`), not a JSCallback WndProc. - */ +/** Windows-only: real frame windows, with every close path routed through the veto. */ const isWindows = currentPlatform() === 'windows'; const WM_CLOSE = 0x0010; const GWL_STYLE = -16; From a61a09ddc2524db1ca4765dc3d8201ea7243894c Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:00:32 -0700 Subject: [PATCH 115/586] test: drop the cannot-fail selector check from the popup test --- tests/integration/macos/cocoa-menu-popup.test.ts | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/tests/integration/macos/cocoa-menu-popup.test.ts b/tests/integration/macos/cocoa-menu-popup.test.ts index 6dc3df47..891fbafe 100644 --- a/tests/integration/macos/cocoa-menu-popup.test.ts +++ b/tests/integration/macos/cocoa-menu-popup.test.ts @@ -1,18 +1,12 @@ import { describe, expect, test } from 'bun:test'; import { currentPlatform } from '../../../src/common/platform'; import { cancelMenuTracking, realizeMenu } from '../../../src/main/platform/macos/cocoa-menu'; -import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; -/** - * Build-side checks for the macOS context-menu popup. The BLOCKING show - * (`popUpMenuPositioningItem:atLocation:inView:`) runs a nested AppKit tracking loop until a - * human dismisses it, so — exactly like `cocoa-dialog`'s `runModal` — it is NOT invoked - * unattended in CI; it is exercised in real apps. Here we verify the wiring: the selector - * resolves, a menu realizes, and `cancelMenuTracking` is a safe no-op when not tracking. - */ +// The popup itself blocks in a nested tracking loop until a human dismisses it (D040), so only +// the cancel path runs unattended; a wrong selector here aborts the process. if (currentPlatform() === 'macos') { - describe('cocoa-menu popup (build-side)', () => { - test('the popUp selector resolves and cancelMenuTracking is a safe no-op', () => { + describe('cocoa-menu popup', () => { + test('cancelMenuTracking on a menu that is not tracking is a no-op', () => { const menu = realizeMenu([ { label: 'Copy', @@ -22,7 +16,6 @@ if (currentPlatform() === 'macos') { onClick: () => undefined, }, ]); - expect(cocoa().selectors.get('popUpMenuPositioningItem:atLocation:inView:')).not.toBe(0n); expect(() => cancelMenuTracking(menu)).not.toThrow(); }); }); From bfe640401a211feaabbf594c1032638f22a3f826 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:00:36 -0700 Subject: [PATCH 116/586] chore: replace em dashes in the app slice tests --- tests/integration/single-instance-backend.test.ts | 4 ++-- tests/unit/entry-barrel.test.ts | 2 +- tests/unit/main/api/app-environment.test.ts | 8 ++++---- tests/unit/main/api/app-paths.test.ts | 12 ++++++------ 4 files changed, 13 insertions(+), 13 deletions(-) diff --git a/tests/integration/single-instance-backend.test.ts b/tests/integration/single-instance-backend.test.ts index 37a63de4..766ca9bb 100644 --- a/tests/integration/single-instance-backend.test.ts +++ b/tests/integration/single-instance-backend.test.ts @@ -14,7 +14,7 @@ import { createLockBackend } from '../../src/main/api/single-instance-backend'; const delay = (ms: number): Promise => new Promise((resolve) => setTimeout(resolve, ms)); -describe('createLockBackend — pidfile', () => { +describe('createLockBackend - pidfile', () => { let dir: string; let lockPath: string; @@ -87,7 +87,7 @@ describe('createLockBackend — pidfile', () => { }); }); -describe('createLockBackend — socket hand-off', () => { +describe('createLockBackend - socket hand-off', () => { let dir: string; let socketPath: string; let lockPath: string; diff --git a/tests/unit/entry-barrel.test.ts b/tests/unit/entry-barrel.test.ts index 47fd9bd6..e30e9cd6 100644 --- a/tests/unit/entry-barrel.test.ts +++ b/tests/unit/entry-barrel.test.ts @@ -8,7 +8,7 @@ import * as bunmaska from '../../src'; * tsc cannot: that importing them actually works (src/main/index.ts opens with * `import './bootstrap'`, so a cycle or a throwing side effect fails at import time, * before any assertion runs), and that what `IMPLEMENTED_MODULES` claims is really - * there — src/electron.ts throws for a KNOWN module that is not implemented, so a + * there - src/electron.ts throws for a KNOWN module that is not implemented, so a * module claimed-but-not-exported silently degrades to `electron.foo === undefined`. */ diff --git a/tests/unit/main/api/app-environment.test.ts b/tests/unit/main/api/app-environment.test.ts index da0f81ca..c6d3671e 100644 --- a/tests/unit/main/api/app-environment.test.ts +++ b/tests/unit/main/api/app-environment.test.ts @@ -30,7 +30,7 @@ const deps = (overrides: Partial = {}): EnvironmentDeps => ({ const build = (overrides: Partial = {}): AppEnvironment => buildAppEnvironment(deps(overrides)); -describe('buildAppEnvironment — manifest & appPath', () => { +describe('buildAppEnvironment - manifest & appPath', () => { test('finds the manifest by walking up from the main script dir', () => { const env = build(); expect(env.manifest?.name).toBe('demo'); @@ -81,7 +81,7 @@ describe('buildAppEnvironment - compiled binary', () => { }); }); -describe('buildAppEnvironment — locale & languages', () => { +describe('buildAppEnvironment - locale & languages', () => { test('normalizes the raw locale', () => { expect(build({ locale: 'en_US.UTF-8' }).locale).toBe('en-US'); }); @@ -105,7 +105,7 @@ describe('buildAppEnvironment — locale & languages', () => { }); }); -describe('buildAppEnvironment — isPackaged', () => { +describe('buildAppEnvironment - isPackaged', () => { test('is false when launched via the bun dev runner', () => { expect(build({ execPath: '/opt/homebrew/bin/bun' }).isPackaged).toBe(false); }); @@ -129,7 +129,7 @@ describe('buildAppEnvironment — isPackaged', () => { }); }); -describe('buildAppEnvironment — passthrough', () => { +describe('buildAppEnvironment - passthrough', () => { test('carries home/temp/execPath/env/exit through', () => { let exited = -1; const env = build({ diff --git a/tests/unit/main/api/app-paths.test.ts b/tests/unit/main/api/app-paths.test.ts index 7f22ac30..9ffa7e94 100644 --- a/tests/unit/main/api/app-paths.test.ts +++ b/tests/unit/main/api/app-paths.test.ts @@ -33,7 +33,7 @@ const winEnv = (overrides: Partial = {}): PathEnvironment => ({ ...overrides, }); -describe('resolveAppPath — cross-platform names', () => { +describe('resolveAppPath - cross-platform names', () => { test('home is the home dir on both platforms', () => { expect(resolveAppPath('home', macEnv())).toBe('/Users/ada'); expect(resolveAppPath('home', linuxEnv())).toBe('/home/ada'); @@ -53,7 +53,7 @@ describe('resolveAppPath — cross-platform names', () => { }); }); -describe('resolveAppPath — macOS conventions', () => { +describe('resolveAppPath - macOS conventions', () => { test('appData is ~/Library/Application Support', () => { expect(resolveAppPath('appData', macEnv())).toBe('/Users/ada/Library/Application Support'); }); @@ -94,7 +94,7 @@ describe('resolveAppPath — macOS conventions', () => { }); }); -describe('resolveAppPath — Linux XDG conventions', () => { +describe('resolveAppPath - Linux XDG conventions', () => { test('appData defaults to ~/.config', () => { expect(resolveAppPath('appData', linuxEnv())).toBe('/home/ada/.config'); }); @@ -125,7 +125,7 @@ describe('resolveAppPath — Linux XDG conventions', () => { }); }); -describe('resolveAppPath — Windows conventions', () => { +describe('resolveAppPath - Windows conventions', () => { test('home and temp pass through', () => { expect(resolveAppPath('home', winEnv())).toBe('C:\\Users\\ada'); expect(resolveAppPath('temp', winEnv())).toBe('C:\\Users\\ada\\AppData\\Local\\Temp'); @@ -169,9 +169,9 @@ describe('resolveAppPath — Windows conventions', () => { }); }); -describe('resolveAppPath — errors', () => { +describe('resolveAppPath - errors', () => { test('throws InvalidArgumentError on an unknown name', () => { - // @ts-expect-error — exercising the runtime guard with an invalid name + // @ts-expect-error - exercising the runtime guard with an invalid name expect(() => resolveAppPath('nope', macEnv())).toThrow(InvalidArgumentError); }); }); From 5e4704125ef714441b7ba7c854aff3765ddb6fae Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:00:38 -0700 Subject: [PATCH 117/586] test: fail Linux GTK tests without a display instead of passing --- tests/helpers/require-gtk-display.ts | 8 +++ .../linux/execute-javascript-e2e.test.ts | 8 +-- tests/integration/linux/gtk-run-loop.test.ts | 13 ++--- tests/integration/linux/linux-backend.test.ts | 16 ++---- tests/integration/linux/protocol-e2e.test.ts | 6 +- .../linux/top-frame-injection.test.ts | 6 +- tests/integration/linux/window-events.test.ts | 57 +++++-------------- 7 files changed, 37 insertions(+), 77 deletions(-) create mode 100644 tests/helpers/require-gtk-display.ts diff --git a/tests/helpers/require-gtk-display.ts b/tests/helpers/require-gtk-display.ts new file mode 100644 index 00000000..7ea5e663 --- /dev/null +++ b/tests/helpers/require-gtk-display.ts @@ -0,0 +1,8 @@ +import { loadGtkFFI } from '../../src/main/platform/linux/gtk-ffi'; + +/** A Linux GTK test without a display fails loudly instead of passing with zero assertions. */ +export const requireGtkDisplay = (): void => { + if (loadGtkFFI().symbols.gtk_init_check() === 0) { + throw new Error('gtk_init_check failed: no display (run under xvfb-run)'); + } +}; diff --git a/tests/integration/linux/execute-javascript-e2e.test.ts b/tests/integration/linux/execute-javascript-e2e.test.ts index 1cafb7a1..cd0eed12 100644 --- a/tests/integration/linux/execute-javascript-e2e.test.ts +++ b/tests/integration/linux/execute-javascript-e2e.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from 'bun:test'; -import { loadGtkFFI } from '../../../src/main/platform/linux/gtk-ffi'; +import { requireGtkDisplay } from '../../helpers/require-gtk-display'; import { createLinuxApplication } from '../../../src/main/platform/linux/linux-backend'; import type { NativeApplication, NativeWebContents } from '../../../src/main/platform/native'; @@ -33,11 +33,7 @@ const pumpUntil = async (predicate: () => boolean, budgetMs: number): Promise { test('expression, Promise, object round-trip, and throw all settle correctly', async () => { - // gtk_init_check must succeed under Xvfb; if not, there is no display and - // the rest cannot run — skip rather than fail. - if (loadGtkFFI().symbols.gtk_init_check() === 0) { - return; - } + requireGtkDisplay(); const app: NativeApplication = createLinuxApplication(); app.start(); diff --git a/tests/integration/linux/gtk-run-loop.test.ts b/tests/integration/linux/gtk-run-loop.test.ts index 84188af5..31843efe 100644 --- a/tests/integration/linux/gtk-run-loop.test.ts +++ b/tests/integration/linux/gtk-run-loop.test.ts @@ -2,14 +2,13 @@ import { describe, expect, test } from 'bun:test'; import { currentPlatform } from '../../../src/common/platform'; import { createLinuxDrain } from '../../../src/main/platform/linux/gtk-run-loop'; -if (currentPlatform() === 'linux') { - describe('createLinuxDrain', () => { - test('returns a drain that runs many times without crashing', () => { - const drain = createLinuxDrain(); +describe.skipIf(currentPlatform() !== 'linux')('createLinuxDrain', () => { + test('drains repeatedly without throwing or blocking', () => { + const drain = createLinuxDrain(); + expect(() => { for (let i = 0; i < 50; i += 1) { drain(); } - expect(typeof drain).toBe('function'); - }); + }).not.toThrow(); }); -} +}); diff --git a/tests/integration/linux/linux-backend.test.ts b/tests/integration/linux/linux-backend.test.ts index 6a66d36d..e68cc30e 100644 --- a/tests/integration/linux/linux-backend.test.ts +++ b/tests/integration/linux/linux-backend.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from 'bun:test'; -import { loadGtkFFI } from '../../../src/main/platform/linux/gtk-ffi'; +import { requireGtkDisplay } from '../../helpers/require-gtk-display'; import { createLinuxApplication } from '../../../src/main/platform/linux/linux-backend'; import type { NativeWindow } from '../../../src/main/platform/native'; @@ -34,11 +34,7 @@ const pumpUntil = async (predicate: () => boolean, budgetMs: number): Promise { test('init + window + webview lifecycle and IPC round-trip', async () => { - // gtk_init_check must succeed under Xvfb; if not, there is no display and - // the rest cannot run — skip rather than fail. - if (loadGtkFFI().symbols.gtk_init_check() === 0) { - return; - } + requireGtkDisplay(); const app = createLinuxApplication(); app.start(); @@ -127,9 +123,7 @@ describe.skipIf(!isLinux)('Linux backend end-to-end', () => { }); test('openDevTools exists and does not throw', async () => { - if (loadGtkFFI().symbols.gtk_init_check() === 0) { - return; - } + requireGtkDisplay(); const app = createLinuxApplication(); app.start(); const window: NativeWindow = app.createWindow({ @@ -149,9 +143,7 @@ describe.skipIf(!isLinux)('Linux backend end-to-end', () => { }); test('runtime setters (resizable/opacity/minSize/center) drive GTK without throwing', async () => { - if (loadGtkFFI().symbols.gtk_init_check() === 0) { - return; - } + requireGtkDisplay(); const app = createLinuxApplication(); app.start(); const window: NativeWindow = app.createWindow({ diff --git a/tests/integration/linux/protocol-e2e.test.ts b/tests/integration/linux/protocol-e2e.test.ts index 239104cb..111bb1e5 100644 --- a/tests/integration/linux/protocol-e2e.test.ts +++ b/tests/integration/linux/protocol-e2e.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from 'bun:test'; +import { requireGtkDisplay } from '../../helpers/require-gtk-display'; import { protocol } from '../../../src/main/api/protocol'; -import { loadGtkFFI } from '../../../src/main/platform/linux/gtk-ffi'; import { createLinuxApplication } from '../../../src/main/platform/linux/linux-backend'; import type { NativeApplication, NativeWebContents } from '../../../src/main/platform/native'; @@ -34,9 +34,7 @@ const SERVED_HTML = '

HELLO

'; describe.skipIf(!isLinux)('custom app:// scheme over real WebKitGTK', () => { test('loads app://host/index.html and reads the served DOM back', async () => { - if (loadGtkFFI().symbols.gtk_init_check() === 0) { - return; - } + requireGtkDisplay(); protocol.handle('app', (request) => { if (request.url === 'app://host/index.html') { diff --git a/tests/integration/linux/top-frame-injection.test.ts b/tests/integration/linux/top-frame-injection.test.ts index 4ae51d86..159692fc 100644 --- a/tests/integration/linux/top-frame-injection.test.ts +++ b/tests/integration/linux/top-frame-injection.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from 'bun:test'; -import { loadGtkFFI } from '../../../src/main/platform/linux/gtk-ffi'; +import { requireGtkDisplay } from '../../helpers/require-gtk-display'; import { createLinuxApplication } from '../../../src/main/platform/linux/linux-backend'; /** Electron runs preloads and dom-ready in the main frame only (nodeIntegrationInSubFrames off). */ @@ -14,9 +14,7 @@ const pumpUntil = async (predicate: () => boolean, budgetMs: number): Promise { test('an iframe gets no preload, no exposed API and no dom-ready', async () => { - if (loadGtkFFI().symbols.gtk_init_check() === 0) { - return; - } + requireGtkDisplay(); const app = createLinuxApplication(); app.start(); const window = app.createWindow({ diff --git a/tests/integration/linux/window-events.test.ts b/tests/integration/linux/window-events.test.ts index cf3b862b..701fe357 100644 --- a/tests/integration/linux/window-events.test.ts +++ b/tests/integration/linux/window-events.test.ts @@ -1,24 +1,11 @@ import { describe, expect, test } from 'bun:test'; -import { loadGtkFFI } from '../../../src/main/platform/linux/gtk-ffi'; +import { requireGtkDisplay } from '../../helpers/require-gtk-display'; import { createLinuxApplication } from '../../../src/main/platform/linux/linux-backend'; import type { NativeWindow, WindowEventType } from '../../../src/main/platform/native'; -/** - * BrowserWindow lifecycle events + preventable close on REAL GTK4. - * - * CI-gated (Linux + Xvfb only); inert on macOS via `describe.skipIf`. Pumps the - * cooperative GLib loop cooperatively, within the 30s test budget. Proves: - * - `resize` fires via notify::default-width/height when the window is resized, - * - a `close` veto keeps the window open (close-request returns TRUE), - * - a non-prevented close fires `closed` and runs the teardown (a pending - * executeJavaScript settles instead of crashing on a freed view). - * - * `focus`/`blur` (notify::is-active) and `maximize`/`unmaximize` - * (notify::maximized) depend on the window manager under Xvfb, which does not - * reliably grant focus or honor maximize; those edges are covered by the unit - * suite's fake. `minimize`/`restore` are DEFERRED on Linux (no observable GTK4 - * minimized property). - */ +// Real GTK 4 under Xvfb, which has no window manager to grant focus or honour maximize. +// Every close here is programmatic; the title-bar close-request path is not driven (ponytail: +// needs gtk_window_close in gtk-ffi plus a way to reach the GtkWindow). const isLinux = process.platform === 'linux'; @@ -35,9 +22,7 @@ const pumpUntil = async (predicate: () => boolean, budgetMs: number): Promise { test('resize event fires and preventable close vetoes then closes', async () => { - if (loadGtkFFI().symbols.gtk_init_check() === 0) { - return; - } + requireGtkDisplay(); const app = createLinuxApplication(); app.start(); const window: NativeWindow = app.createWindow({ @@ -72,31 +57,21 @@ describe.skipIf(!isLinux)('Linux window lifecycle events end-to-end', () => { }); window.close(); - await pump(100); expect(closed).toBe(0); - // A pending exec before the real close should settle (not crash) when the - // close-path teardown runs. - const pending = window.webContents.executeJavaScript('1 + 1').catch(() => 'settled'); - + // No await before close(), so the result cannot arrive first: teardown settles it. + const pending = window.webContents.executeJavaScript('1 + 1'); prevent = false; window.close(); - await pumpUntil(() => closed > 0, 2000); + expect(closed).toBe(1); - // The pending exec SETTLES without crashing on a freed view — the point of - // the close-path teardown. Depending on timing it is `undefined` (teardown - // resolves in-flight execs to undefined), `2` (the result arrived first), or - // `'settled'` (rejected + caught); any of these proves no use-after-free. - const settled = await pending; - expect(settled === undefined || settled === 2 || settled === 'settled').toBe(true); + expect(await pending).toBeUndefined(); app.quit(); }); test('a throwing close listener still closes and tears the window down', async () => { - if (loadGtkFFI().symbols.gtk_init_check() === 0) { - return; - } + requireGtkDisplay(); const app = createLinuxApplication(); app.start(); const window = app.createWindow({ @@ -121,9 +96,7 @@ describe.skipIf(!isLinux)('Linux window lifecycle events end-to-end', () => { }); test('getBounds of a hidden window reports the size last set', () => { - if (loadGtkFFI().symbols.gtk_init_check() === 0) { - return; - } + requireGtkDisplay(); const app = createLinuxApplication(); app.start(); const window = app.createWindow({ width: 800, height: 600, title: 'Hidden', show: false }); @@ -136,9 +109,7 @@ describe.skipIf(!isLinux)('Linux window lifecycle events end-to-end', () => { }); test('calls after close never touch the freed window or view', () => { - if (loadGtkFFI().symbols.gtk_init_check() === 0) { - return; - } + requireGtkDisplay(); const app = createLinuxApplication(); app.start(); const window = app.createWindow({ width: 200, height: 120, title: 'After Close', show: true }); @@ -159,9 +130,7 @@ describe.skipIf(!isLinux)('Linux window lifecycle events end-to-end', () => { }); test('a close listener that destroys the window does not destroy it twice', () => { - if (loadGtkFFI().symbols.gtk_init_check() === 0) { - return; - } + requireGtkDisplay(); const app = createLinuxApplication(); app.start(); const window = app.createWindow({ From ade4f5770143cd7f2b42b9007dfd2d68292eed92 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:39:25 -0700 Subject: [PATCH 118/586] fix: drop non-string script message bodies instead of aborting --- .../macos/cocoa-script-message-handler.ts | 11 +++- .../cocoa-script-message-handler.test.ts | 63 ++++++++++++++++--- 2 files changed, 66 insertions(+), 8 deletions(-) diff --git a/src/main/platform/macos/cocoa-script-message-handler.ts b/src/main/platform/macos/cocoa-script-message-handler.ts index f7d6e108..9cace59b 100644 --- a/src/main/platform/macos/cocoa-script-message-handler.ts +++ b/src/main/platform/macos/cocoa-script-message-handler.ts @@ -1,4 +1,5 @@ import { nsStringToString } from './cocoa-foundation'; +import { msgSendPtrReturnsU8 } from './cocoa-msgsend-variants'; import { cocoa } from './cocoa-runtime'; import { defineObjcClass } from './cocoa-runtime-class'; import type { Handle } from './objc'; @@ -34,7 +35,15 @@ const ensureHandlerClass = (): Handle => { return; } const body = rt.msgSend(message, rt.selectors.get('body')); - callback(nsStringToString(body)); + // Any page can post null/1/{}; UTF8String on a non-NSString is an uncatchable NSException. + const isString = msgSendPtrReturnsU8( + body, + rt.selectors.get('isKindOfClass:'), + rt.classes.get('NSString'), + ); + if (isString === 1) { + callback(nsStringToString(body)); + } }, }, ]); diff --git a/tests/integration/macos/cocoa-script-message-handler.test.ts b/tests/integration/macos/cocoa-script-message-handler.test.ts index 9d6887ed..6c0ac711 100644 --- a/tests/integration/macos/cocoa-script-message-handler.test.ts +++ b/tests/integration/macos/cocoa-script-message-handler.test.ts @@ -1,17 +1,66 @@ import { describe, expect, test } from 'bun:test'; import { currentPlatform } from '../../../src/common/platform'; +import { nsString } from '../../../src/main/platform/macos/cocoa-foundation'; +import { msgSendI64, msgSendPtrPtr } from '../../../src/main/platform/macos/cocoa-msgsend-variants'; +import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; +import { defineObjcClass } from '../../../src/main/platform/macos/cocoa-runtime-class'; import { createScriptMessageHandler } from '../../../src/main/platform/macos/cocoa-script-message-handler'; +import type { Handle } from '../../../src/main/platform/macos/objc'; + +let nextBody: Handle = 0n; +let fakeMessageClass: Handle | undefined; + +/** A stand-in for `WKScriptMessage` whose `-body` returns `body`. */ +const fakeMessage = (body: Handle): Handle => { + const rt = cocoa(); + fakeMessageClass ??= defineObjcClass('BunmaskaTestScriptMessage', 'NSObject', [ + { selector: 'body', typeEncoding: '@@:', args: [], returns: 'object', impl: () => nextBody }, + ]); + nextBody = body; + return rt.msgSend( + rt.msgSend(fakeMessageClass, rt.selectors.get('alloc')), + rt.selectors.get('init'), + ); +}; + +const post = (handler: Handle, body: Handle): void => { + const sel = cocoa().selectors.get('userContentController:didReceiveScriptMessage:'); + msgSendPtrPtr(handler, sel, 0n, fakeMessage(body)); +}; if (currentPlatform() === 'macos') { - describe('createScriptMessageHandler', () => { - test('returns a non-null handler instance handle', () => { - expect(createScriptMessageHandler(() => undefined).handle).not.toBe(0n); + describe('BunmaskaScriptMessageHandler', () => { + test('a string body reaches the callback', () => { + const seen: string[] = []; + const handler = createScriptMessageHandler((json) => seen.push(json)); + post(handler.handle, nsString('{"a":1}')); + expect(seen).toEqual(['{"a":1}']); + handler.dispose(); + }); + + test('non-string bodies are dropped instead of aborting the process', () => { + const rt = cocoa(); + const seen: string[] = []; + const handler = createScriptMessageHandler((json) => seen.push(json)); + post(handler.handle, rt.msgSend(rt.classes.get('NSNull'), rt.selectors.get('null'))); + post( + handler.handle, + msgSendI64(rt.classes.get('NSNumber'), rt.selectors.get('numberWithLongLong:'), 1n), + ); + post(handler.handle, 0n); + expect(seen).toEqual([]); + handler.dispose(); }); - test('distinct handlers get distinct instance handles', () => { - const a = createScriptMessageHandler(() => undefined); - const b = createScriptMessageHandler(() => undefined); - expect(a.handle).not.toBe(b.handle); + test('dispose stops routing messages to the callback', () => { + const rt = cocoa(); + const seen: string[] = []; + const handler = createScriptMessageHandler((json) => seen.push(json)); + rt.msgSend(handler.handle, rt.selectors.get('retain')); + handler.dispose(); + post(handler.handle, nsString('late')); + expect(seen).toEqual([]); + rt.msgSend(handler.handle, rt.selectors.get('release')); }); }); } From e9eff4f7ec49e28dfd1fef06f06c3a527ab37989 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:40:06 -0700 Subject: [PATCH 119/586] fix: emit open-file for file URLs delivered through openURLs --- src/main/platform/macos/cocoa-app-delegate.ts | 20 +++----- .../macos/cocoa-app-delegate.test.ts | 51 +++++++++---------- 2 files changed, 30 insertions(+), 41 deletions(-) diff --git a/src/main/platform/macos/cocoa-app-delegate.ts b/src/main/platform/macos/cocoa-app-delegate.ts index 69d1375e..911333ab 100644 --- a/src/main/platform/macos/cocoa-app-delegate.ts +++ b/src/main/platform/macos/cocoa-app-delegate.ts @@ -1,5 +1,5 @@ import { nsStringToString } from './cocoa-foundation'; -import { msgSendI64, msgSendReturnsI64 } from './cocoa-msgsend-variants'; +import { msgSendI64, msgSendReturnsI64, msgSendReturnsU8 } from './cocoa-msgsend-variants'; import { cocoa } from './cocoa-runtime'; import { defineObjcClass } from './cocoa-runtime-class'; import type { Handle } from './objc'; @@ -53,21 +53,15 @@ const ensureDelegateClass = (): Handle => { const count = msgSendReturnsI64(urls, rt.selectors.get('count')); for (let i = 0n; i < count; i += 1n) { const url = msgSendI64(urls, rt.selectors.get('objectAtIndex:'), i); - current?.openUrl(nsStringToString(rt.msgSend(url, rt.selectors.get('absoluteString')))); + // AppKit never calls application:openFile: once openURLs: exists; split file URLs here. + if (msgSendReturnsU8(url, rt.selectors.get('isFileURL')) === 1) { + current?.openFile(nsStringToString(rt.msgSend(url, rt.selectors.get('path')))); + } else { + current?.openUrl(nsStringToString(rt.msgSend(url, rt.selectors.get('absoluteString')))); + } } }, }, - { - // BOOL application:(NSApplication*)app openFile:(NSString*)filename - selector: 'application:openFile:', - typeEncoding: 'c@:@@', - args: ['object', 'object'], - returns: 'bool', - impl: (_self, _cmd, _app, filename) => { - current?.openFile(nsStringToString(filename)); - return 1; - }, - }, ]); return delegateClass; }; diff --git a/tests/integration/macos/cocoa-app-delegate.test.ts b/tests/integration/macos/cocoa-app-delegate.test.ts index ddae74f4..3de66b95 100644 --- a/tests/integration/macos/cocoa-app-delegate.test.ts +++ b/tests/integration/macos/cocoa-app-delegate.test.ts @@ -8,14 +8,7 @@ import { nsString } from '../../../src/main/platform/macos/cocoa-foundation'; import { msgSendPtr, msgSendPtrPtr } from '../../../src/main/platform/macos/cocoa-msgsend-variants'; import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; -/** - * Drives the runtime `BunmaskaAppDelegate` against the real Objective-C runtime. - * The delegate-callback routing uses the same `defineObjcClass` JSCallback - * mechanism as the (CI-proven) window/navigation delegates; here we prove the - * class builds, installs as `NSApp`'s delegate, and routes `openURLs:`/`openFile:` - * to the JS handlers (the events AppKit normally fires for deep links / file - * associations). - */ +/** Drives the runtime `BunmaskaAppDelegate` by sending its selectors directly. */ const NOOP_HANDLERS: AppDelegateHandlers = { activate: () => undefined, @@ -23,13 +16,9 @@ const NOOP_HANDLERS: AppDelegateHandlers = { openFile: () => undefined, }; -if (currentPlatform() === 'macos') { - describe('BunmaskaAppDelegate on the real macOS runtime', () => { - test('createAppDelegate returns a live instance', () => { - const delegate = createAppDelegate(NOOP_HANDLERS); - expect(delegate.handle).not.toBe(0n); - }); - +describe.skipIf(currentPlatform() !== 'macos')( + 'BunmaskaAppDelegate on the real macOS runtime', + () => { test('installs on NSApp and reads back via -delegate', () => { const rt = cocoa(); const nsApp = rt.msgSend( @@ -63,26 +52,32 @@ if (currentPlatform() === 'macos') { expect(seen).toEqual(['myapp://open/x']); }); - test('application:openFile: routes the path to the openFile handler', () => { + test('application:openURLs: routes a file URL to openFile as a path', () => { const rt = cocoa(); - let seen: string | undefined; + const urls: string[] = []; + const files: string[] = []; const delegate = createAppDelegate({ ...NOOP_HANDLERS, - openFile: (p) => { - seen = p; - }, + openUrl: (u) => urls.push(u), + openFile: (p) => files.push(p), }); const nsApp = rt.msgSend( rt.classes.get('NSApplication'), rt.selectors.get('sharedApplication'), ); - msgSendPtrPtr( - delegate.handle, - rt.selectors.get('application:openFile:'), - nsApp, - nsString('/tmp/bunmaska-open.txt'), + const url = msgSendPtr( + rt.classes.get('NSURL'), + rt.selectors.get('fileURLWithPath:'), + nsString('/tmp/bunmaska open.txt'), ); - expect(seen).toBe('/tmp/bunmaska-open.txt'); + const array = msgSendPtr( + rt.classes.get('NSArray'), + rt.selectors.get('arrayWithObject:'), + url, + ); + msgSendPtrPtr(delegate.handle, rt.selectors.get('application:openURLs:'), nsApp, array); + expect(files).toEqual(['/tmp/bunmaska open.txt']); + expect(urls).toEqual([]); }); - }); -} + }, +); From 51795408e16692a50df9e48c292c5a64cb10dec5 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:40:43 -0700 Subject: [PATCH 120/586] fix: return the Dock reopen flag and read only its BOOL byte --- src/main/platform/macos/cocoa-app-delegate.ts | 9 ++--- .../macos/cocoa-app-delegate.test.ts | 34 ++++++++++++++++--- 2 files changed, 34 insertions(+), 9 deletions(-) diff --git a/src/main/platform/macos/cocoa-app-delegate.ts b/src/main/platform/macos/cocoa-app-delegate.ts index 911333ab..b9969b8c 100644 --- a/src/main/platform/macos/cocoa-app-delegate.ts +++ b/src/main/platform/macos/cocoa-app-delegate.ts @@ -37,10 +37,11 @@ const ensureDelegateClass = (): Handle => { typeEncoding: 'c@:@c', args: ['object', 'object'], returns: 'bool', - impl: (_self, _cmd, _sender, hasVisibleWindows) => { - current?.activate(hasVisibleWindows === 1n); - // Return YES so AppKit performs its default reopen behavior. - return 1; + impl: (_self, _cmd, _sender, flag) => { + // Only the low byte of a BOOL register is defined by the ABI. + const hasVisibleWindows = (flag & 0xffn) !== 0n; + current?.activate(hasVisibleWindows); + return hasVisibleWindows ? 1 : 0; }, }, { diff --git a/tests/integration/macos/cocoa-app-delegate.test.ts b/tests/integration/macos/cocoa-app-delegate.test.ts index 3de66b95..ccf1d816 100644 --- a/tests/integration/macos/cocoa-app-delegate.test.ts +++ b/tests/integration/macos/cocoa-app-delegate.test.ts @@ -1,3 +1,4 @@ +import { dlopen, FFIType } from 'bun:ffi'; import { describe, expect, test } from 'bun:test'; import { currentPlatform } from '../../../src/common/platform'; import { @@ -10,15 +11,30 @@ import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; /** Drives the runtime `BunmaskaAppDelegate` by sending its selectors directly. */ +/** `objc_msgSend(id, SEL, id, u64) -> BOOL`; the u64 lets a test put junk above the BOOL byte. */ +const sendReopen = (delegate: bigint, flag: bigint): number => { + const lib = dlopen('libobjc.A.dylib', { + objc_msgSend: { + args: [FFIType.u64, FFIType.u64, FFIType.u64, FFIType.u64], + returns: FFIType.u8, + }, + }); + try { + const sel = cocoa().selectors.get('applicationShouldHandleReopen:hasVisibleWindows:'); + return lib.symbols.objc_msgSend(delegate, sel, 0n, flag); + } finally { + lib.close(); + } +}; + const NOOP_HANDLERS: AppDelegateHandlers = { activate: () => undefined, openUrl: () => undefined, openFile: () => undefined, }; -describe.skipIf(currentPlatform() !== 'macos')( - 'BunmaskaAppDelegate on the real macOS runtime', - () => { +if (currentPlatform() === 'macos') { + describe('BunmaskaAppDelegate on the real macOS runtime', () => { test('installs on NSApp and reads back via -delegate', () => { const rt = cocoa(); const nsApp = rt.msgSend( @@ -30,6 +46,14 @@ describe.skipIf(currentPlatform() !== 'macos')( expect(rt.msgSend(nsApp, rt.selectors.get('delegate'))).toBe(delegate.handle); }); + test('Dock reopen reports the BOOL flag and returns it, as Electron does', () => { + const seen: boolean[] = []; + const delegate = createAppDelegate({ ...NOOP_HANDLERS, activate: (v) => seen.push(v) }); + expect(sendReopen(delegate.handle, 0n)).toBe(0); + expect(sendReopen(delegate.handle, 0x1_0000_0001n)).toBe(1); + expect(seen).toEqual([false, true]); + }); + test('application:openURLs: routes each URL to the openUrl handler', () => { const rt = cocoa(); const seen: string[] = []; @@ -79,5 +103,5 @@ describe.skipIf(currentPlatform() !== 'macos')( expect(files).toEqual(['/tmp/bunmaska open.txt']); expect(urls).toEqual([]); }); - }, -); + }); +} From 2ed9b7640b8625169cf01699663ba0d594d5d09a Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:41:52 -0700 Subject: [PATCH 121/586] fix: release the NSURLResponse after serving a scheme task --- .../macos/cocoa-url-scheme-handler.ts | 1 + .../macos/cocoa-url-scheme-handler.test.ts | 129 ++++++++++++++++++ .../macos/cocoa-url-scheme-handler.test.ts | 51 ------- 3 files changed, 130 insertions(+), 51 deletions(-) create mode 100644 tests/integration/macos/cocoa-url-scheme-handler.test.ts delete mode 100644 tests/unit/main/platform/macos/cocoa-url-scheme-handler.test.ts diff --git a/src/main/platform/macos/cocoa-url-scheme-handler.ts b/src/main/platform/macos/cocoa-url-scheme-handler.ts index 3f4a1e04..a96b4d8e 100644 --- a/src/main/platform/macos/cocoa-url-scheme-handler.ts +++ b/src/main/platform/macos/cocoa-url-scheme-handler.ts @@ -111,6 +111,7 @@ const serveTask = (task: Handle, url: string, built: BuiltProtocolResponse): voi ); msgSendPtr(task, rt.selectors.get('didReceiveResponse:'), response); + rt.msgSend(response, rt.selectors.get('release')); msgSendPtr(task, rt.selectors.get('didReceiveData:'), data); rt.msgSend(task, rt.selectors.get('didFinish')); }; diff --git a/tests/integration/macos/cocoa-url-scheme-handler.test.ts b/tests/integration/macos/cocoa-url-scheme-handler.test.ts new file mode 100644 index 00000000..196e14f5 --- /dev/null +++ b/tests/integration/macos/cocoa-url-scheme-handler.test.ts @@ -0,0 +1,129 @@ +import { afterEach, describe, expect, test } from 'bun:test'; +import { currentPlatform } from '../../../src/common/platform'; +import type { BuiltProtocolResponse } from '../../../src/main/api/protocol'; +import { nsString, nsStringToString } from '../../../src/main/platform/macos/cocoa-foundation'; +import { + msgSendPtr, + msgSendReturnsI64, +} from '../../../src/main/platform/macos/cocoa-msgsend-variants'; +import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; +import { defineObjcClass } from '../../../src/main/platform/macos/cocoa-runtime-class'; +import { + handleStartTask, + setUrlSchemeDispatcherForTesting, +} from '../../../src/main/platform/macos/cocoa-url-scheme-handler'; +import type { Handle } from '../../../src/main/platform/macos/objc'; + +type TaskLog = { + request: Handle; + response: Handle; + dataLength: bigint; + finished: number; + failed: number; +}; + +const log: TaskLog = { request: 0n, response: 0n, dataLength: -1n, finished: 0, failed: 0 }; +let taskClass: Handle | undefined; + +/** A stand-in `WKURLSchemeTask` that records what the handler drives it through. */ +const fakeTask = (url: string): Handle => { + const rt = cocoa(); + const retain = (h: Handle): Handle => rt.msgSend(h, rt.selectors.get('retain')); + taskClass ??= defineObjcClass('BunmaskaTestSchemeTask', 'NSObject', [ + { + selector: 'request', + typeEncoding: '@@:', + args: [], + returns: 'object', + impl: () => log.request, + }, + { + selector: 'didReceiveResponse:', + typeEncoding: 'v@:@', + args: ['object'], + impl: (_self, _cmd, response) => { + // WebKit keeps the response it is handed, so retain it the same way. + log.response = retain(response); + }, + }, + { + selector: 'didReceiveData:', + typeEncoding: 'v@:@', + args: ['object'], + impl: (_self, _cmd, data) => { + log.dataLength = msgSendReturnsI64(data, rt.selectors.get('length')); + }, + }, + { + selector: 'didFinish', + typeEncoding: 'v@:', + args: [], + impl: () => { + log.finished += 1; + }, + }, + { + selector: 'didFailWithError:', + typeEncoding: 'v@:@', + args: ['object'], + impl: () => { + log.failed += 1; + }, + }, + ]); + const nsUrl = msgSendPtr( + rt.classes.get('NSURL'), + rt.selectors.get('URLWithString:'), + nsString(url), + ); + log.request = retain( + msgSendPtr(rt.classes.get('NSURLRequest'), rt.selectors.get('requestWithURL:'), nsUrl), + ); + log.response = 0n; + log.dataLength = -1n; + log.finished = 0; + log.failed = 0; + return rt.msgSend(rt.msgSend(taskClass, rt.selectors.get('alloc')), rt.selectors.get('init')); +}; + +const serve = (built: BuiltProtocolResponse | undefined): string[] => { + const seen: string[] = []; + setUrlSchemeDispatcherForTesting((url) => { + seen.push(url); + return built; + }); + handleStartTask(fakeTask('app://host/index.html')); + return seen; +}; + +const responseString = (selector: string): string => + nsStringToString(cocoa().msgSend(log.response, cocoa().selectors.get(selector))); + +afterEach(() => { + setUrlSchemeDispatcherForTesting(undefined); +}); + +describe.skipIf(currentPlatform() !== 'macos')('BunmaskaURLSchemeHandler task serving', () => { + test('serves the dispatched body with its MIME type and length, then finishes', () => { + const bytes = new TextEncoder().encode('

hi

'); + const seen = serve({ bytes, mimeType: 'text/html' }); + expect(seen).toEqual(['app://host/index.html']); + expect(responseString('MIMEType')).toBe('text/html'); + expect(msgSendReturnsI64(log.response, cocoa().selectors.get('expectedContentLength'))).toBe( + BigInt(bytes.length), + ); + expect(log.dataLength).toBe(BigInt(bytes.length)); + expect([log.finished, log.failed]).toEqual([1, 0]); + }); + + test('the handler does not keep its own reference to the response', () => { + serve({ bytes: new Uint8Array([1, 2, 3]), mimeType: 'application/octet-stream' }); + // Only the fake task's retain is left; a leaked +1 from alloc/init would make this 2. + expect(msgSendReturnsI64(log.response, cocoa().selectors.get('retainCount'))).toBe(1n); + }); + + test('a declined request fails the task', () => { + serve(undefined); + expect([log.finished, log.failed]).toEqual([0, 1]); + }); +}); diff --git a/tests/unit/main/platform/macos/cocoa-url-scheme-handler.test.ts b/tests/unit/main/platform/macos/cocoa-url-scheme-handler.test.ts deleted file mode 100644 index 11c3e04c..00000000 --- a/tests/unit/main/platform/macos/cocoa-url-scheme-handler.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test'; -import { currentPlatform } from '../../../../../src/common/platform'; -import { - createUrlSchemeHandler, - handleStartTask, - setUrlSchemeDispatcherForTesting, -} from '../../../../../src/main/platform/macos/cocoa-url-scheme-handler'; - -/** - * Host-safe unit tests for the macOS `WKURLSchemeHandler` module. - * - * The IMP cannot be invoked without a real `WKURLSchemeTask`, so the end-to-end - * serve path is proven by the macOS integration test. Here we assert the module - * exports the expected seam and that the injectable dispatcher is wired (so a - * test can substitute the serve/decline decision). - */ - -afterEach(() => { - setUrlSchemeDispatcherForTesting(undefined); -}); - -describe('cocoa-url-scheme-handler exports', () => { - test('createUrlSchemeHandler is a function', () => { - expect(typeof createUrlSchemeHandler).toBe('function'); - }); - - test('handleStartTask is a function', () => { - expect(typeof handleStartTask).toBe('function'); - }); - - test('setUrlSchemeDispatcherForTesting is a function', () => { - expect(typeof setUrlSchemeDispatcherForTesting).toBe('function'); - }); -}); - -// macOS-only: handleStartTask drives the ObjC runtime (to read the task's URL), -// which is unavailable off macOS — on Linux it bails to the decline path without -// reaching the dispatcher, so this seam test must run on macOS only. -describe.skipIf(currentPlatform() !== 'macos')('dispatcher injection seam', () => { - test('a substituted dispatcher receiving a null task url declines without throwing', () => { - let seen: string | undefined; - setUrlSchemeDispatcherForTesting((url) => { - seen = url; - return undefined; - }); - // task = 0n: on macOS requestUrlOf returns '' (the dispatcher is still called - // with the empty url); the decline path (failTask) is best-effort. - expect(() => handleStartTask(0n)).not.toThrow(); - expect(seen).toBe(''); - }); -}); From 5c52710de7485a359c090f3029c44b500feab838 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:42:22 -0700 Subject: [PATCH 122/586] fix: split the charset out of a scheme response MIME type --- src/main/platform/macos/cocoa-url-scheme-handler.ts | 10 ++++++++-- .../integration/macos/cocoa-url-scheme-handler.test.ts | 6 ++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/main/platform/macos/cocoa-url-scheme-handler.ts b/src/main/platform/macos/cocoa-url-scheme-handler.ts index a96b4d8e..8fc5e9fd 100644 --- a/src/main/platform/macos/cocoa-url-scheme-handler.ts +++ b/src/main/platform/macos/cocoa-url-scheme-handler.ts @@ -101,13 +101,19 @@ const serveTask = (task: Handle, url: string, built: BuiltProtocolResponse): voi BigInt(bytes.length), ); + // NSURLResponse keeps MIMEType verbatim; a `; charset=x` suffix belongs in the encoding. + const [mimeType = '', ...params] = built.mimeType.split(';').map((part) => part.trim()); + const charset = params + .find((p) => /^charset=/i.test(p)) + ?.slice(8) + .replaceAll('"', ''); const response = msgSendPtrPtrI64Ptr( rt.msgSend(rt.classes.get('NSURLResponse'), rt.selectors.get('alloc')), rt.selectors.get('initWithURL:MIMEType:expectedContentLength:textEncodingName:'), nsUrl(url), - nsString(built.mimeType), + nsString(mimeType), BigInt(bytes.length), - nsString('utf-8'), + nsString(charset || 'utf-8'), ); msgSendPtr(task, rt.selectors.get('didReceiveResponse:'), response); diff --git a/tests/integration/macos/cocoa-url-scheme-handler.test.ts b/tests/integration/macos/cocoa-url-scheme-handler.test.ts index 196e14f5..26d40330 100644 --- a/tests/integration/macos/cocoa-url-scheme-handler.test.ts +++ b/tests/integration/macos/cocoa-url-scheme-handler.test.ts @@ -116,6 +116,12 @@ describe.skipIf(currentPlatform() !== 'macos')('BunmaskaURLSchemeHandler task se expect([log.finished, log.failed]).toEqual([1, 0]); }); + test('a charset parameter becomes the text encoding, not part of the MIME type', () => { + serve({ bytes: new Uint8Array([65]), mimeType: 'text/html; charset="Shift_JIS"' }); + expect(responseString('MIMEType')).toBe('text/html'); + expect(responseString('textEncodingName')).toBe('Shift_JIS'); + }); + test('the handler does not keep its own reference to the response', () => { serve({ bytes: new Uint8Array([1, 2, 3]), mimeType: 'application/octet-stream' }); // Only the fake task's retain is left; a leaked +1 from alloc/init would make this 2. From d8e5ae5b9ad3210736392b287cbe84aae4384943 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:42:53 -0700 Subject: [PATCH 123/586] fix: share one URL scheme handler instead of leaking one per window --- .../platform/macos/cocoa-url-scheme-handler.ts | 18 +++++++++--------- .../macos/cocoa-url-scheme-handler.test.ts | 7 +++++++ 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/src/main/platform/macos/cocoa-url-scheme-handler.ts b/src/main/platform/macos/cocoa-url-scheme-handler.ts index 8fc5e9fd..f2f9a440 100644 --- a/src/main/platform/macos/cocoa-url-scheme-handler.ts +++ b/src/main/platform/macos/cocoa-url-scheme-handler.ts @@ -175,14 +175,14 @@ export type UrlSchemeHandler = { readonly handle: Handle; }; -/** - * Create a shared `WKURLSchemeHandler` instance. The instance routes every - * scheme through {@link protocol.dispatch}, so one instance serves all - * registered schemes on a given configuration. - */ +let shared: UrlSchemeHandler | undefined; + +/** The process-wide `WKURLSchemeHandler`; it holds no per-window state, so every configuration shares it. */ export const createUrlSchemeHandler = (): UrlSchemeHandler => { - const rt = cocoa(); - const cls = ensureHandlerClass(); - const handle = rt.msgSend(rt.msgSend(cls, rt.selectors.get('alloc')), rt.selectors.get('init')); - return { handle }; + if (shared === undefined) { + const rt = cocoa(); + const alloc = rt.msgSend(ensureHandlerClass(), rt.selectors.get('alloc')); + shared = { handle: rt.msgSend(alloc, rt.selectors.get('init')) }; + } + return shared; }; diff --git a/tests/integration/macos/cocoa-url-scheme-handler.test.ts b/tests/integration/macos/cocoa-url-scheme-handler.test.ts index 26d40330..60173d86 100644 --- a/tests/integration/macos/cocoa-url-scheme-handler.test.ts +++ b/tests/integration/macos/cocoa-url-scheme-handler.test.ts @@ -9,6 +9,7 @@ import { import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; import { defineObjcClass } from '../../../src/main/platform/macos/cocoa-runtime-class'; import { + createUrlSchemeHandler, handleStartTask, setUrlSchemeDispatcherForTesting, } from '../../../src/main/platform/macos/cocoa-url-scheme-handler'; @@ -133,3 +134,9 @@ describe.skipIf(currentPlatform() !== 'macos')('BunmaskaURLSchemeHandler task se expect([log.finished, log.failed]).toEqual([0, 1]); }); }); + +describe.skipIf(currentPlatform() !== 'macos')('createUrlSchemeHandler', () => { + test('every window shares one handler instance instead of leaking one each', () => { + expect(createUrlSchemeHandler().handle).toBe(createUrlSchemeHandler().handle); + }); +}); From 1e4376671c57bca5e1b9ea857b5831ec022207ce Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:43:25 -0700 Subject: [PATCH 124/586] refactor: pass the request NSURL straight to the scheme response --- .../macos/cocoa-url-scheme-handler.ts | 29 ++------ .../macos/cocoa-url-scheme-handler.test.ts | 66 ++++++++++--------- 2 files changed, 41 insertions(+), 54 deletions(-) diff --git a/src/main/platform/macos/cocoa-url-scheme-handler.ts b/src/main/platform/macos/cocoa-url-scheme-handler.ts index f2f9a440..dea07a85 100644 --- a/src/main/platform/macos/cocoa-url-scheme-handler.ts +++ b/src/main/platform/macos/cocoa-url-scheme-handler.ts @@ -41,26 +41,6 @@ export const setUrlSchemeDispatcherForTesting = ( dispatcher = fake ?? protocol.dispatch; }; -/** Read the absolute string of a `WKURLSchemeTask`'s request URL. */ -const requestUrlOf = (task: Handle): string => { - const rt = cocoa(); - const request = rt.msgSend(task, rt.selectors.get('request')); - if (request === 0n) { - return ''; - } - const url = rt.msgSend(request, rt.selectors.get('URL')); - if (url === 0n) { - return ''; - } - return nsStringToString(rt.msgSend(url, rt.selectors.get('absoluteString'))); -}; - -/** Build an `NSURL` from a string for the response's URL field. */ -const nsUrl = (url: string): Handle => { - const rt = cocoa(); - return msgSendPtr(rt.classes.get('NSURL'), rt.selectors.get('URLWithString:'), nsString(url)); -}; - /** * Fail `task` with an `NSError` (no registered handler / declined / empty body). * Best-effort: a task that WebKit has already finished/stopped throws on a @@ -87,7 +67,7 @@ const failTask = (task: Handle): void => { * `NSURLResponse` for `url`, then drive the task through * `didReceiveResponse:` → `didReceiveData:` → `didFinish`. */ -const serveTask = (task: Handle, url: string, built: BuiltProtocolResponse): void => { +const serveTask = (task: Handle, url: Handle, built: BuiltProtocolResponse): void => { const rt = cocoa(); // NSData dataWithBytes:length: copies, so `bytes` only needs to outlive this // call — no long-lived pinning. A zero-length body still produces a valid @@ -110,7 +90,7 @@ const serveTask = (task: Handle, url: string, built: BuiltProtocolResponse): voi const response = msgSendPtrPtrI64Ptr( rt.msgSend(rt.classes.get('NSURLResponse'), rt.selectors.get('alloc')), rt.selectors.get('initWithURL:MIMEType:expectedContentLength:textEncodingName:'), - nsUrl(url), + url, nsString(mimeType), BigInt(bytes.length), nsString(charset || 'utf-8'), @@ -128,8 +108,9 @@ const serveTask = (task: Handle, url: string, built: BuiltProtocolResponse): voi */ export const handleStartTask = (task: Handle): void => { try { - const url = requestUrlOf(task); - const built = dispatcher(url); + const rt = cocoa(); + const url = rt.msgSend(rt.msgSend(task, rt.selectors.get('request')), rt.selectors.get('URL')); + const built = dispatcher(nsStringToString(rt.msgSend(url, rt.selectors.get('absoluteString')))); if (built === undefined) { failTask(task); return; diff --git a/tests/integration/macos/cocoa-url-scheme-handler.test.ts b/tests/integration/macos/cocoa-url-scheme-handler.test.ts index 60173d86..604e35b8 100644 --- a/tests/integration/macos/cocoa-url-scheme-handler.test.ts +++ b/tests/integration/macos/cocoa-url-scheme-handler.test.ts @@ -104,39 +104,45 @@ afterEach(() => { setUrlSchemeDispatcherForTesting(undefined); }); -describe.skipIf(currentPlatform() !== 'macos')('BunmaskaURLSchemeHandler task serving', () => { - test('serves the dispatched body with its MIME type and length, then finishes', () => { - const bytes = new TextEncoder().encode('

hi

'); - const seen = serve({ bytes, mimeType: 'text/html' }); - expect(seen).toEqual(['app://host/index.html']); - expect(responseString('MIMEType')).toBe('text/html'); - expect(msgSendReturnsI64(log.response, cocoa().selectors.get('expectedContentLength'))).toBe( - BigInt(bytes.length), - ); - expect(log.dataLength).toBe(BigInt(bytes.length)); - expect([log.finished, log.failed]).toEqual([1, 0]); - }); +if (currentPlatform() === 'macos') { + describe('BunmaskaURLSchemeHandler task serving', () => { + test('serves the dispatched body with its MIME type and length, then finishes', () => { + const bytes = new TextEncoder().encode('

hi

'); + const seen = serve({ bytes, mimeType: 'text/html' }); + expect(seen).toEqual(['app://host/index.html']); + expect(responseString('MIMEType')).toBe('text/html'); + const responseUrl = cocoa().msgSend(log.response, cocoa().selectors.get('URL')); + expect( + nsStringToString(cocoa().msgSend(responseUrl, cocoa().selectors.get('absoluteString'))), + ).toBe('app://host/index.html'); + expect(msgSendReturnsI64(log.response, cocoa().selectors.get('expectedContentLength'))).toBe( + BigInt(bytes.length), + ); + expect(log.dataLength).toBe(BigInt(bytes.length)); + expect([log.finished, log.failed]).toEqual([1, 0]); + }); - test('a charset parameter becomes the text encoding, not part of the MIME type', () => { - serve({ bytes: new Uint8Array([65]), mimeType: 'text/html; charset="Shift_JIS"' }); - expect(responseString('MIMEType')).toBe('text/html'); - expect(responseString('textEncodingName')).toBe('Shift_JIS'); - }); + test('a charset parameter becomes the text encoding, not part of the MIME type', () => { + serve({ bytes: new Uint8Array([65]), mimeType: 'text/html; charset="Shift_JIS"' }); + expect(responseString('MIMEType')).toBe('text/html'); + expect(responseString('textEncodingName')).toBe('Shift_JIS'); + }); - test('the handler does not keep its own reference to the response', () => { - serve({ bytes: new Uint8Array([1, 2, 3]), mimeType: 'application/octet-stream' }); - // Only the fake task's retain is left; a leaked +1 from alloc/init would make this 2. - expect(msgSendReturnsI64(log.response, cocoa().selectors.get('retainCount'))).toBe(1n); - }); + test('the handler does not keep its own reference to the response', () => { + serve({ bytes: new Uint8Array([1, 2, 3]), mimeType: 'application/octet-stream' }); + // Only the fake task's retain is left; a leaked +1 from alloc/init would make this 2. + expect(msgSendReturnsI64(log.response, cocoa().selectors.get('retainCount'))).toBe(1n); + }); - test('a declined request fails the task', () => { - serve(undefined); - expect([log.finished, log.failed]).toEqual([0, 1]); + test('a declined request fails the task', () => { + serve(undefined); + expect([log.finished, log.failed]).toEqual([0, 1]); + }); }); -}); -describe.skipIf(currentPlatform() !== 'macos')('createUrlSchemeHandler', () => { - test('every window shares one handler instance instead of leaking one each', () => { - expect(createUrlSchemeHandler().handle).toBe(createUrlSchemeHandler().handle); + describe('createUrlSchemeHandler', () => { + test('every window shares one handler instance instead of leaking one each', () => { + expect(createUrlSchemeHandler().handle).toBe(createUrlSchemeHandler().handle); + }); }); -}); +} From bd0a4d783995423d33fced132c5ca8aa4d1012af Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:45:14 -0700 Subject: [PATCH 125/586] fix: persist httpOnly and default SameSite to lax on macOS cookies --- src/main/platform/macos/cocoa-cookies.ts | 68 ++++++++++--------- tests/integration/macos/cocoa-cookies.test.ts | 24 +++++++ tests/integration/macos/cookies.test.ts | 2 + 3 files changed, 63 insertions(+), 31 deletions(-) create mode 100644 tests/integration/macos/cocoa-cookies.test.ts diff --git a/src/main/platform/macos/cocoa-cookies.ts b/src/main/platform/macos/cocoa-cookies.ts index d9a2a8a0..56edbd49 100644 --- a/src/main/platform/macos/cocoa-cookies.ts +++ b/src/main/platform/macos/cocoa-cookies.ts @@ -116,40 +116,46 @@ export const getCookies = (filter: CookieFilter): Promise => }); }); -/** - * Store one cookie via `cookieWithProperties:` + `setCookie:completionHandler:`. - * `httpOnly` is accepted but NOT persisted: NSHTTPCookie exposes no public - * HttpOnly property key, so the flag is read-only on macOS. - */ +/** Build an autoreleased `NSHTTPCookie` for `cookie`, or `0n` when Foundation rejects it. */ +export const nsHTTPCookie = (cookie: Cookie): Handle => { + const rt = cocoa(); + const dict = rt.msgSend(rt.classes.get('NSMutableDictionary'), rt.selectors.get('dictionary')); + const setProperty = (key: string, value: Handle): void => { + msgSendPtrPtr(dict, rt.selectors.get('setObject:forKey:'), value, nsString(key)); + }; + setProperty('Name', nsString(cookie.name)); + setProperty('Value', nsString(cookie.value)); + setProperty('Domain', nsString(cookie.domain)); + setProperty('Path', nsString(cookie.path)); + // Electron defaults sameSite to lax; the key and value are NSHTTPCookieSameSitePolicy/Lax. + setProperty('SameSite', nsString('lax')); + if (cookie.secure) { + setProperty('Secure', nsString('TRUE')); + } + if (cookie.httpOnly) { + setProperty('HttpOnly', nsString('TRUE')); + } + if (cookie.expirationDate !== undefined) { + setProperty( + 'Expires', + msgSendF64( + rt.classes.get('NSDate'), + rt.selectors.get('dateWithTimeIntervalSince1970:'), + cookie.expirationDate, + ), + ); + } + return msgSendPtr( + rt.classes.get('NSHTTPCookie'), + rt.selectors.get('cookieWithProperties:'), + dict, + ); +}; + export const setCookie = (cookie: Cookie): Promise => bounded('cookies.set', (resolve, reject) => { const rt = cocoa(); - const dict = rt.msgSend(rt.classes.get('NSMutableDictionary'), rt.selectors.get('dictionary')); - const setProperty = (key: string, value: Handle): void => { - msgSendPtrPtr(dict, rt.selectors.get('setObject:forKey:'), value, nsString(key)); - }; - setProperty('Name', nsString(cookie.name)); - setProperty('Value', nsString(cookie.value)); - setProperty('Domain', nsString(cookie.domain)); - setProperty('Path', nsString(cookie.path)); - if (cookie.secure) { - setProperty('Secure', nsString('TRUE')); - } - if (cookie.expirationDate !== undefined) { - setProperty( - 'Expires', - msgSendF64( - rt.classes.get('NSDate'), - rt.selectors.get('dateWithTimeIntervalSince1970:'), - cookie.expirationDate, - ), - ); - } - const nsCookie = msgSendPtr( - rt.classes.get('NSHTTPCookie'), - rt.selectors.get('cookieWithProperties:'), - dict, - ); + const nsCookie = nsHTTPCookie(cookie); if (nsCookie === 0n) { reject( new InvalidArgumentError('cookies.set: NSHTTPCookie rejected the properties (empty name?)'), diff --git a/tests/integration/macos/cocoa-cookies.test.ts b/tests/integration/macos/cocoa-cookies.test.ts new file mode 100644 index 00000000..2428100c --- /dev/null +++ b/tests/integration/macos/cocoa-cookies.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, test } from 'bun:test'; +import { currentPlatform } from '../../../src/common/platform'; +import { nsHTTPCookie } from '../../../src/main/platform/macos/cocoa-cookies'; +import { nsStringToString } from '../../../src/main/platform/macos/cocoa-foundation'; +import { msgSendReturnsU8 } from '../../../src/main/platform/macos/cocoa-msgsend-variants'; +import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; + +const BASE = { name: 'n', value: 'v', domain: '.example.com', path: '/', secure: false }; + +if (currentPlatform() === 'macos') { + describe('nsHTTPCookie', () => { + test('carries httpOnly and defaults SameSite to lax as Electron does', () => { + const rt = cocoa(); + const cookie = nsHTTPCookie({ ...BASE, httpOnly: true }); + expect(msgSendReturnsU8(cookie, rt.selectors.get('isHTTPOnly'))).toBe(1); + expect(nsStringToString(rt.msgSend(cookie, rt.selectors.get('sameSitePolicy')))).toBe('lax'); + }); + + test('leaves httpOnly off when not requested', () => { + const cookie = nsHTTPCookie({ ...BASE, httpOnly: false }); + expect(msgSendReturnsU8(cookie, cocoa().selectors.get('isHTTPOnly'))).toBe(0); + }); + }); +} diff --git a/tests/integration/macos/cookies.test.ts b/tests/integration/macos/cookies.test.ts index fc902cd3..90be3c78 100644 --- a/tests/integration/macos/cookies.test.ts +++ b/tests/integration/macos/cookies.test.ts @@ -21,6 +21,7 @@ if (currentPlatform() === 'macos') { name, value: 'roundtrip', secure: true, + httpOnly: true, expirationDate, }); @@ -31,6 +32,7 @@ if (currentPlatform() === 'macos') { expect(cookie?.domain).toBe('cookies.bunmaska.test'); expect(cookie?.path).toBe('/'); expect(cookie?.secure).toBe(true); + expect(cookie?.httpOnly).toBe(true); expect(cookie?.expirationDate).toBeCloseTo(expirationDate, 0); // The url filter enforces the secure flag: http must not see it. From 2d15bc2d2572c6371a3e83f5858f0d8573a60b18 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:46:28 -0700 Subject: [PATCH 126/586] fix: load WebKit in clearStorageData and reject instead of throwing --- src/main/platform/macos/cocoa-cookies.ts | 37 ++++++++------- src/main/platform/macos/cocoa-website-data.ts | 47 +++++-------------- .../macos/cocoa-website-data.test.ts | 22 +++++++++ 3 files changed, 55 insertions(+), 51 deletions(-) create mode 100644 tests/integration/macos/cocoa-website-data.test.ts diff --git a/src/main/platform/macos/cocoa-cookies.ts b/src/main/platform/macos/cocoa-cookies.ts index 56edbd49..1ef569af 100644 --- a/src/main/platform/macos/cocoa-cookies.ts +++ b/src/main/platform/macos/cocoa-cookies.ts @@ -25,7 +25,7 @@ import type { Handle } from './objc'; * is a one-shot Block (D022b) fired on the pumped run loop. */ -const COOKIE_TIMEOUT_MS = 15_000; +const TIMEOUT_MS = 15_000; /** The default data store's `WKHTTPCookieStore`. */ const cookieStore = (): Handle => { @@ -40,30 +40,35 @@ const cookieStore = (): Handle => { return rt.msgSend(store, rt.selectors.get('httpCookieStore')); }; -/** Run `run` with settle callbacks under the bounded cookie-op deadline. */ -const bounded = ( +const asError = (cause: unknown): Error => + cause instanceof Error ? cause : new Error(String(cause)); + +/** + * Run `run` with settle callbacks under a deadline; a throw from `run` rejects. A timed-out + * Block is never cancelled: WebKit may still invoke it, and a closed trampoline would SIGSEGV. + */ +export const bounded = ( label: string, run: (resolve: (value: T) => void, reject: (error: Error) => void) => void, ): Promise => new Promise((resolve, reject) => { const timer = setTimeout(() => { - reject(new Error(`${label} timed out after ${COOKIE_TIMEOUT_MS}ms`)); - }, COOKIE_TIMEOUT_MS); - run( - (value) => { + reject(new Error(`${label} timed out after ${TIMEOUT_MS}ms`)); + }, TIMEOUT_MS); + const fail = (error: Error): void => { + clearTimeout(timer); + reject(error); + }; + try { + run((value) => { clearTimeout(timer); resolve(value); - }, - (error) => { - clearTimeout(timer); - reject(error); - }, - ); + }, fail); + } catch (cause) { + fail(asError(cause)); + } }); -const asError = (cause: unknown): Error => - cause instanceof Error ? cause : new Error(String(cause)); - /** Read one `NSHTTPCookie` into the shared {@link Cookie} shape. */ const readCookie = (handle: Handle): Cookie => { const rt = cocoa(); diff --git a/src/main/platform/macos/cocoa-website-data.ts b/src/main/platform/macos/cocoa-website-data.ts index f45ff6b6..e8f54f8d 100644 --- a/src/main/platform/macos/cocoa-website-data.ts +++ b/src/main/platform/macos/cocoa-website-data.ts @@ -1,43 +1,20 @@ import { makeOneShotBlock } from './cocoa-block'; +import { bounded } from './cocoa-cookies'; import { msgSendPtr3 } from './cocoa-msgsend-variants'; import { cocoa } from './cocoa-runtime'; +import { loadWebKit } from './cocoa-webkit'; -/** - * macOS website-data management via `WKWebsiteDataStore`. - * - * The completion handler is a hand-built ObjC Block (D022b) that fires on the - * pumped run loop, so the returned Promise settles when the removal finishes. - */ - -const CLEAR_TIMEOUT_MS = 15000; - -/** Remove all website data from the default store; resolves when it completes. */ -export const clearStorageData = (): Promise => { - const rt = cocoa(); - const store = rt.msgSend( - rt.classes.get('WKWebsiteDataStore'), - rt.selectors.get('defaultDataStore'), - ); - const types = rt.msgSend( - rt.classes.get('WKWebsiteDataStore'), - rt.selectors.get('allWebsiteDataTypes'), - ); - const since = rt.msgSend(rt.classes.get('NSDate'), rt.selectors.get('distantPast')); - return new Promise((resolve, reject) => { - const timer = setTimeout(() => { - reject(new Error(`clearStorageData timed out after ${CLEAR_TIMEOUT_MS}ms`)); - }, CLEAR_TIMEOUT_MS); - // Completion handler is ^(void) — no arguments beyond the implicit block. - const block = makeOneShotBlock(() => { - clearTimeout(timer); - resolve(); - }, []); +/** Remove all website data from the default store; resolves when it completes (D022b). */ +export const clearStorageData = (): Promise => + bounded('clearStorageData', (resolve) => { + loadWebKit(); + const rt = cocoa(); + const store = rt.classes.get('WKWebsiteDataStore'); msgSendPtr3( - store, + rt.msgSend(store, rt.selectors.get('defaultDataStore')), rt.selectors.get('removeDataOfTypes:modifiedSince:completionHandler:'), - types, - since, - block, + rt.msgSend(store, rt.selectors.get('allWebsiteDataTypes')), + rt.msgSend(rt.classes.get('NSDate'), rt.selectors.get('distantPast')), + makeOneShotBlock(() => resolve(undefined), []), ); }); -}; diff --git a/tests/integration/macos/cocoa-website-data.test.ts b/tests/integration/macos/cocoa-website-data.test.ts new file mode 100644 index 00000000..89e3f4dd --- /dev/null +++ b/tests/integration/macos/cocoa-website-data.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, test } from 'bun:test'; +import { join } from 'node:path'; +import { currentPlatform } from '../../../src/common/platform'; + +const MODULE = join(import.meta.dir, '../../../src/main/platform/macos/cocoa-website-data.ts'); + +describe.skipIf(currentPlatform() !== 'macos')('clearStorageData', () => { + test('works in a fresh process where WebKit is not loaded yet', () => { + // Only a fresh process shows the pre-WebKit state; this suite has already loaded it. + const script = `import { clearStorageData } from ${JSON.stringify(MODULE)}; +const result = clearStorageData(); +const outcome = await Promise.race([ + result.then(() => 'settled', (error) => String(error)), + Bun.sleep(100).then(() => 'pending'), +]); +console.log(outcome); +process.exit(0);`; + const proc = Bun.spawnSync(['bun', '-e', script], { stdout: 'pipe', stderr: 'pipe' }); + expect(proc.stderr.toString()).toBe(''); + expect(proc.stdout.toString().trim()).toMatch(/^(pending|settled)$/); + }); +}); From cac42df195f5fd0a584837d3953cd9e355414504 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:47:35 -0700 Subject: [PATCH 127/586] fix: report common NSURL load errors as Chromium net error codes --- .../macos/cocoa-navigation-delegate.ts | 13 +++- .../macos/cocoa-navigation-delegate.test.ts | 61 ++++++++++++++++--- 2 files changed, 65 insertions(+), 9 deletions(-) diff --git a/src/main/platform/macos/cocoa-navigation-delegate.ts b/src/main/platform/macos/cocoa-navigation-delegate.ts index 2af82bdf..b02bccb6 100644 --- a/src/main/platform/macos/cocoa-navigation-delegate.ts +++ b/src/main/platform/macos/cocoa-navigation-delegate.ts @@ -14,11 +14,22 @@ const registry = new Map void>(); let delegateClass: Handle | undefined; +/** NSURLErrorDomain codes Electron apps branch on, as the Chromium net errors Electron reports. */ +const NET_ERROR_BY_NSURL_CODE: ReadonlyMap = new Map([ + [-999, -3], // cancelled: ERR_ABORTED + [-1001, -7], // timed out: ERR_TIMED_OUT + [-1003, -105], // cannot find host: ERR_NAME_NOT_RESOLVED + [-1009, -106], // not connected: ERR_INTERNET_DISCONNECTED +]); + const failEvent = (error: Handle): NativeNavigationEvent => { const rt = cocoa(); + const code = Number(msgSendReturnsI64(error, rt.selectors.get('code'))); + const domain = nsStringToString(rt.msgSend(error, rt.selectors.get('domain'))); + const netError = domain === 'NSURLErrorDomain' ? NET_ERROR_BY_NSURL_CODE.get(code) : undefined; return { type: 'did-fail-load', - errorCode: Number(msgSendReturnsI64(error, rt.selectors.get('code'))), + errorCode: netError ?? code, errorDescription: nsStringToString(rt.msgSend(error, rt.selectors.get('localizedDescription'))), }; }; diff --git a/tests/integration/macos/cocoa-navigation-delegate.test.ts b/tests/integration/macos/cocoa-navigation-delegate.test.ts index e703d9a2..61a00328 100644 --- a/tests/integration/macos/cocoa-navigation-delegate.test.ts +++ b/tests/integration/macos/cocoa-navigation-delegate.test.ts @@ -1,21 +1,65 @@ import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; import { currentPlatform } from '../../../src/common/platform'; import { createMacOSApplication } from '../../../src/main/platform/macos/cocoa-backend'; +import { nsString } from '../../../src/main/platform/macos/cocoa-foundation'; +import { + msgSendPtr3, + msgSendPtrI64Ptr, + msgSendPtrPtr, +} from '../../../src/main/platform/macos/cocoa-msgsend-variants'; import { createNavigationDelegate } from '../../../src/main/platform/macos/cocoa-navigation-delegate'; -import type { NativeApplication } from '../../../src/main/platform/native'; +import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; +import type { Handle } from '../../../src/main/platform/macos/objc'; +import type { NativeApplication, NativeNavigationEvent } from '../../../src/main/platform/native'; const delay = (ms: number): Promise => new Promise((resolve) => setTimeout(resolve, ms)); +const nsError = (domain: string, code: bigint): Handle => { + const rt = cocoa(); + const info = msgSendPtrPtr( + rt.classes.get('NSDictionary'), + rt.selectors.get('dictionaryWithObject:forKey:'), + nsString('boom'), + nsString('NSLocalizedDescription'), + ); + return msgSendPtrI64Ptr( + rt.classes.get('NSError'), + rt.selectors.get('errorWithDomain:code:userInfo:'), + nsString(domain), + code, + info, + ); +}; + +const failWith = (domain: string, code: bigint): NativeNavigationEvent[] => { + const seen: NativeNavigationEvent[] = []; + const delegate = createNavigationDelegate((event) => seen.push(event)); + const sel = cocoa().selectors.get('webView:didFailNavigation:withError:'); + msgSendPtr3(delegate.handle, sel, 0n, 0n, nsError(domain, code)); + delegate.destroy(); + return seen; +}; + if (currentPlatform() === 'macos') { - describe('createNavigationDelegate', () => { - test('returns a non-null delegate instance handle', () => { - expect(createNavigationDelegate(() => undefined).handle).not.toBe(0n); + describe('did-fail-load error codes', () => { + test('a cancelled load reports Chromium ERR_ABORTED (-3), then stops loading', () => { + expect(failWith('NSURLErrorDomain', -999n)).toEqual([ + { type: 'did-fail-load', errorCode: -3, errorDescription: 'boom' }, + { type: 'did-stop-loading' }, + ]); + }); + + test('common NSURLErrorDomain codes map to their Chromium net errors', () => { + const codeOf = (code: bigint): number | undefined => { + const [event] = failWith('NSURLErrorDomain', code); + return event?.type === 'did-fail-load' ? event.errorCode : undefined; + }; + expect([codeOf(-1003n), codeOf(-1001n), codeOf(-1009n)]).toEqual([-105, -7, -106]); }); - test('distinct delegates get distinct instance handles', () => { - const a = createNavigationDelegate(() => undefined); - const b = createNavigationDelegate(() => undefined); - expect(a.handle).not.toBe(b.handle); + test('a code from another domain passes through unchanged', () => { + const [event] = failWith('BunmaskaTestDomain', -999n); + expect(event).toEqual({ type: 'did-fail-load', errorCode: -999, errorDescription: 'boom' }); }); }); @@ -45,6 +89,7 @@ if (currentPlatform() === 'macos') { while (loads === 0 && Date.now() < deadline) { await delay(50); } + win.close(); expect(loads).toBeGreaterThan(0); }); }); From 818f6d09d3f00f1b61eb38f8f19bfc83c1225d63 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:49:34 -0700 Subject: [PATCH 128/586] test: replace cannot-fail macOS delegate tests with selector sends --- tests/integration/macos/cocoa-app.test.ts | 37 ++++---- .../macos/cocoa-ui-delegate.test.ts | 50 ++++++++-- .../macos/cocoa-window-delegate.test.ts | 92 ++++++++----------- 3 files changed, 101 insertions(+), 78 deletions(-) diff --git a/tests/integration/macos/cocoa-app.test.ts b/tests/integration/macos/cocoa-app.test.ts index 67cb949c..98f5edf5 100644 --- a/tests/integration/macos/cocoa-app.test.ts +++ b/tests/integration/macos/cocoa-app.test.ts @@ -1,25 +1,32 @@ import { describe, expect, test } from 'bun:test'; import { currentPlatform } from '../../../src/common/platform'; import { - bounceDock, getDockBadge, - isActive, - isHidden, setActivationPolicy, setDockBadge, - showAboutPanel, } from '../../../src/main/platform/macos/cocoa-app'; +import { + msgSendI64, + msgSendReturnsI64, +} from '../../../src/main/platform/macos/cocoa-msgsend-variants'; +import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; -/** Drives the real NSApplication app-level operations on macOS. */ if (currentPlatform() === 'macos') { describe('cocoa-app NSApplication operations', () => { - test('setActivationPolicy does not throw', () => { - expect(() => setActivationPolicy('regular')).not.toThrow(); - }); - - test('isActive / isHidden return booleans', () => { - expect(typeof isActive()).toBe('boolean'); - expect(typeof isHidden()).toBe('boolean'); + test('setActivationPolicy applies the NSApplicationActivationPolicy value', () => { + const rt = cocoa(); + const nsApp = rt.msgSend( + rt.classes.get('NSApplication'), + rt.selectors.get('sharedApplication'), + ); + const policy = (): bigint => msgSendReturnsI64(nsApp, rt.selectors.get('activationPolicy')); + const before = policy(); + try { + setActivationPolicy('accessory'); + expect(policy()).toBe(1n); + } finally { + msgSendI64(nsApp, rt.selectors.get('setActivationPolicy:'), before); + } }); test('dock badge round-trips and clears', () => { @@ -28,11 +35,5 @@ if (currentPlatform() === 'macos') { setDockBadge(''); expect(getDockBadge()).toBe(''); }); - - // Not invoked: showAboutPanel opens a window, bounceDock bounces the dock. - test('bounceDock and showAboutPanel resolve as callable exports', () => { - expect(typeof bounceDock).toBe('function'); - expect(typeof showAboutPanel).toBe('function'); - }); }); } diff --git a/tests/integration/macos/cocoa-ui-delegate.test.ts b/tests/integration/macos/cocoa-ui-delegate.test.ts index 722a356b..c7fc552a 100644 --- a/tests/integration/macos/cocoa-ui-delegate.test.ts +++ b/tests/integration/macos/cocoa-ui-delegate.test.ts @@ -1,13 +1,47 @@ import { describe, expect, test } from 'bun:test'; import { currentPlatform } from '../../../src/common/platform'; +import { nsString } from '../../../src/main/platform/macos/cocoa-foundation'; +import { msgSendPtr, msgSendPtr4 } from '../../../src/main/platform/macos/cocoa-msgsend-variants'; +import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; +import { defineObjcClass } from '../../../src/main/platform/macos/cocoa-runtime-class'; import { createUIDelegate } from '../../../src/main/platform/macos/cocoa-ui-delegate'; +import type { Handle } from '../../../src/main/platform/macos/objc'; -// Builds the runtime WKUIDelegate class (exercising the 'object'-return IMP path) -// and allocates an instance — no window, so safe to run in the standard suite. -if (currentPlatform() === 'macos') { - describe('BunmaskaUIDelegate on the real macOS runtime', () => { - test('createUIDelegate returns a live instance', () => { - expect(createUIDelegate(() => undefined).handle).not.toBe(0n); - }); +let request: Handle = 0n; +let actionClass: Handle | undefined; + +/** A stand-in `WKNavigationAction` whose `-request` targets `url`. */ +const navigationAction = (url: string): Handle => { + const rt = cocoa(); + actionClass ??= defineObjcClass('BunmaskaTestNavigationAction', 'NSObject', [ + { selector: 'request', typeEncoding: '@@:', args: [], returns: 'object', impl: () => request }, + ]); + const nsUrl = msgSendPtr( + rt.classes.get('NSURL'), + rt.selectors.get('URLWithString:'), + nsString(url), + ); + request = msgSendPtr(rt.classes.get('NSURLRequest'), rt.selectors.get('requestWithURL:'), nsUrl); + rt.msgSend(request, rt.selectors.get('retain')); + return rt.msgSend(rt.msgSend(actionClass, rt.selectors.get('alloc')), rt.selectors.get('init')); +}; + +describe.skipIf(currentPlatform() !== 'macos')('BunmaskaUIDelegate', () => { + test('window.open hands the target URL to the handler and creates no child view', () => { + const seen: string[] = []; + const delegate = createUIDelegate((url) => seen.push(url)); + const created = msgSendPtr4( + delegate.handle, + cocoa().selectors.get( + 'webView:createWebViewWithConfiguration:forNavigationAction:windowFeatures:', + ), + 0n, + 0n, + navigationAction('https://example.com/popup'), + 0n, + ); + expect(created).toBe(0n); + expect(seen).toEqual(['https://example.com/popup']); + delegate.destroy(); }); -} +}); diff --git a/tests/integration/macos/cocoa-window-delegate.test.ts b/tests/integration/macos/cocoa-window-delegate.test.ts index 5f2de117..8bb0c26f 100644 --- a/tests/integration/macos/cocoa-window-delegate.test.ts +++ b/tests/integration/macos/cocoa-window-delegate.test.ts @@ -5,59 +5,31 @@ import { msgSendReturnsU8, } from '../../../src/main/platform/macos/cocoa-msgsend-variants'; import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; -import { createWindowDelegate } from '../../../src/main/platform/macos/cocoa-window-delegate'; +import { + createWindowDelegate, + type WindowDelegateHandlers, +} from '../../../src/main/platform/macos/cocoa-window-delegate'; import type { WindowEventType } from '../../../src/main/platform/native'; -/** - * Unit-ish coverage of the NSWindowDelegate bridge against the live ObjC - * runtime: sending its selectors directly (no real NSWindow) proves the IMP - * routing — `windowShouldClose:` returns the inverted veto, `windowWillClose:` - * runs `willClose`, and each notification routes to the right event type. - */ +const handlers = (overrides: Partial = {}): WindowDelegateHandlers => ({ + shouldClose: () => false, + willClose: () => undefined, + event: () => undefined, + ...overrides, +}); if (currentPlatform() === 'macos') { describe('createWindowDelegate', () => { - test('returns a non-null delegate instance handle', () => { - const d = createWindowDelegate({ - shouldClose: () => false, - willClose: () => undefined, - event: () => undefined, - }); - expect(d.handle).not.toBe(0n); - }); - - test('distinct delegates get distinct instance handles', () => { - const a = createWindowDelegate({ - shouldClose: () => false, - willClose: () => undefined, - event: () => undefined, - }); - const b = createWindowDelegate({ - shouldClose: () => false, - willClose: () => undefined, - event: () => undefined, - }); - expect(a.handle).not.toBe(b.handle); - }); - test('windowShouldClose: returns NO (0) when the listener vetoes', () => { const rt = cocoa(); - const d = createWindowDelegate({ - shouldClose: () => true, - willClose: () => undefined, - event: () => undefined, - }); + const d = createWindowDelegate(handlers({ shouldClose: () => true })); const result = msgSendReturnsU8(d.handle, rt.selectors.get('windowShouldClose:')); expect(result).toBe(0); }); test('windowShouldClose: returns YES (1) when the listener allows', () => { const rt = cocoa(); - const d = createWindowDelegate({ - shouldClose: () => false, - willClose: () => undefined, - event: () => undefined, - }); + const d = createWindowDelegate(handlers()); const result = msgSendReturnsU8(d.handle, rt.selectors.get('windowShouldClose:')); expect(result).toBe(1); }); @@ -65,13 +37,13 @@ if (currentPlatform() === 'macos') { test('windowWillClose: runs the willClose handler', () => { const rt = cocoa(); let closed = 0; - const d = createWindowDelegate({ - shouldClose: () => false, - willClose: () => { - closed += 1; - }, - event: () => undefined, - }); + const d = createWindowDelegate( + handlers({ + willClose: () => { + closed += 1; + }, + }), + ); msgSendPtr(d.handle, rt.selectors.get('windowWillClose:'), 0n); expect(closed).toBe(1); }); @@ -79,15 +51,12 @@ if (currentPlatform() === 'macos') { test('notification selectors route to the right event types', () => { const rt = cocoa(); const seen: WindowEventType[] = []; - const d = createWindowDelegate({ - shouldClose: () => false, - willClose: () => undefined, - event: (type) => seen.push(type), - }); + const d = createWindowDelegate(handlers({ event: (type) => seen.push(type) })); const map: ReadonlyArray = [ ['windowDidBecomeKey:', 'focus'], ['windowDidResignKey:', 'blur'], ['windowDidResize:', 'resize'], + ['windowDidMove:', 'move'], ['windowDidMiniaturize:', 'minimize'], ['windowDidDeminiaturize:', 'restore'], ]; @@ -96,5 +65,24 @@ if (currentPlatform() === 'macos') { } expect(seen).toEqual(map.map(([, type]) => type)); }); + + test('destroy stops routing: close is allowed and willClose no longer runs', () => { + const rt = cocoa(); + let closed = 0; + const d = createWindowDelegate( + handlers({ + shouldClose: () => true, + willClose: () => { + closed += 1; + }, + }), + ); + rt.msgSend(d.handle, rt.selectors.get('retain')); + d.destroy(); + expect(msgSendReturnsU8(d.handle, rt.selectors.get('windowShouldClose:'))).toBe(1); + msgSendPtr(d.handle, rt.selectors.get('windowWillClose:'), 0n); + expect(closed).toBe(0); + rt.msgSend(d.handle, rt.selectors.get('release')); + }); }); } From 8eaa695b89f00177c363dfc8ea46cc53bdea8868 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:50:01 -0700 Subject: [PATCH 129/586] refactor: delete dead observer array and unused content-world exports --- .../platform/macos/cocoa-content-world.ts | 14 ---------- .../macos/cocoa-notification-observer.ts | 2 -- .../macos/cocoa-content-world.test.ts | 27 +------------------ 3 files changed, 1 insertion(+), 42 deletions(-) diff --git a/src/main/platform/macos/cocoa-content-world.ts b/src/main/platform/macos/cocoa-content-world.ts index 64f52054..edd51d90 100644 --- a/src/main/platform/macos/cocoa-content-world.ts +++ b/src/main/platform/macos/cocoa-content-world.ts @@ -51,17 +51,3 @@ export const pageWorld = (): Handle => { const rt = cocoa(); return rt.msgSend(rt.classes.get('WKContentWorld'), rt.selectors.get('pageWorld')); }; - -/** - * Return `+[WKContentWorld defaultClientWorld]` (WebKit's default client world). - * Used immediately; do NOT cache without sending `-retain` first. - */ -export const defaultClientWorld = (): Handle => { - const rt = cocoa(); - return rt.msgSend(rt.classes.get('WKContentWorld'), rt.selectors.get('defaultClientWorld')); -}; - -/** Clear the memoised world handles. Test-only. */ -export const resetContentWorldCacheForTesting = (): void => { - worldCache.clear(); -}; diff --git a/src/main/platform/macos/cocoa-notification-observer.ts b/src/main/platform/macos/cocoa-notification-observer.ts index 61224419..d07536fa 100644 --- a/src/main/platform/macos/cocoa-notification-observer.ts +++ b/src/main/platform/macos/cocoa-notification-observer.ts @@ -15,7 +15,6 @@ import type { Handle } from './objc'; */ const registry = new Map void>(); -const retainedObservers: Handle[] = []; let observerClass: Handle | undefined; const ensureObserverClass = (): Handle => { @@ -60,7 +59,6 @@ export const observeNotification = (center: Handle, name: string, onPost: () => const cls = ensureObserverClass(); const observer = rt.msgSend(rt.msgSend(cls, rt.selectors.get('alloc')), rt.selectors.get('init')); registry.set(observer, onPost); - retainedObservers.push(observer); msgSendPtr4( center, rt.selectors.get('addObserver:selector:name:object:'), diff --git a/tests/integration/macos/cocoa-content-world.test.ts b/tests/integration/macos/cocoa-content-world.test.ts index d4d4b44c..3287a218 100644 --- a/tests/integration/macos/cocoa-content-world.test.ts +++ b/tests/integration/macos/cocoa-content-world.test.ts @@ -1,30 +1,12 @@ import { describe, expect, test } from 'bun:test'; import { currentPlatform } from '../../../src/common/platform'; -import { - defaultClientWorld, - getContentWorld, - pageWorld, - resetContentWorldCacheForTesting, -} from '../../../src/main/platform/macos/cocoa-content-world'; -import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; +import { getContentWorld, pageWorld } from '../../../src/main/platform/macos/cocoa-content-world'; import { loadWebKit } from '../../../src/main/platform/macos/cocoa-webkit'; if (currentPlatform() === 'macos') { describe('WKContentWorld', () => { - test('the class resolves via objc_getClass once WebKit is loaded', () => { - loadWebKit(); - expect(cocoa().classes.get('WKContentWorld')).not.toBe(0n); - }); - - test('worldWithName: returns a non-zero world handle', () => { - loadWebKit(); - resetContentWorldCacheForTesting(); - expect(getContentWorld('BunmaskaPreload')).not.toBe(0n); - }); - test('the same name returns the same (interned + memoised) handle', () => { loadWebKit(); - resetContentWorldCacheForTesting(); const a = getContentWorld('BunmaskaPreload'); const b = getContentWorld('BunmaskaPreload'); expect(b).toBe(a); @@ -32,7 +14,6 @@ if (currentPlatform() === 'macos') { test('a different name returns a different world handle', () => { loadWebKit(); - resetContentWorldCacheForTesting(); const preload = getContentWorld('BunmaskaPreload'); const other = getContentWorld('SomethingElse'); expect(other).not.toBe(preload); @@ -40,15 +21,9 @@ if (currentPlatform() === 'macos') { test('pageWorld is non-zero and distinct from the named preload world', () => { loadWebKit(); - resetContentWorldCacheForTesting(); const page = pageWorld(); expect(page).not.toBe(0n); expect(page).not.toBe(getContentWorld('BunmaskaPreload')); }); - - test('defaultClientWorld is non-zero', () => { - loadWebKit(); - expect(defaultClientWorld()).not.toBe(0n); - }); }); } From 064c543cc4faf0310b727c11401fce9618523833 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:55:05 -0700 Subject: [PATCH 130/586] fix: show alert, confirm and file-input panels as sheets on macOS --- src/main/platform/macos/cocoa-ui-delegate.ts | 132 +++++++++++++++-- .../macos/cocoa-ui-delegate.test.ts | 140 +++++++++++++++--- 2 files changed, 244 insertions(+), 28 deletions(-) diff --git a/src/main/platform/macos/cocoa-ui-delegate.ts b/src/main/platform/macos/cocoa-ui-delegate.ts index 99a44f0e..b9e95c2d 100644 --- a/src/main/platform/macos/cocoa-ui-delegate.ts +++ b/src/main/platform/macos/cocoa-ui-delegate.ts @@ -1,22 +1,90 @@ +import { CFunction, FFIType, read } from 'bun:ffi'; +import { dlopen } from '../dlopen'; +import { makeOneShotBlock } from './cocoa-block'; +import { buildAlert, buildOpenPanel } from './cocoa-dialog'; import { nsStringToString } from './cocoa-foundation'; +import { msgSendPtrPtr, msgSendReturnsU8 } from './cocoa-msgsend-variants'; import { cocoa } from './cocoa-runtime'; import { defineObjcClass } from './cocoa-runtime-class'; -import type { Handle } from './objc'; +import { type Handle, macOSLibraryAccessor, ptrIn } from './objc'; /** - * Bridges `WKUIDelegate` window-open requests to JS (D026). - * - * `webView:createWebViewWithConfiguration:forNavigationAction:windowFeatures:` is - * WebKit's hook for `window.open` / `target=_blank`. We read the target URL from - * the navigation action, hand it to the registered JS handler, and return nil — - * i.e. no child web view is created (v1 supports the deny path; the app typically - * opens the URL externally from its handler). + * Bridges `WKUIDelegate` to JS (D026): window.open, alert, confirm and ``. + * `prompt()` stays unimplemented, so WebKit returns null, matching Electron's unsupported prompt. */ +const NS_MODAL_RESPONSE_CANCEL = 0n; +const NS_MODAL_RESPONSE_OK = 1n; +const NS_ALERT_FIRST_BUTTON_RETURN = 1000n; + const registry = new Map void>(); let delegateClass: Handle | undefined; +const blockRuntime = macOSLibraryAccessor('libSystem blocks', () => + dlopen('/usr/lib/libSystem.B.dylib', { + _Block_copy: { args: [FFIType.u64], returns: FFIType.u64 }, + _Block_release: { args: [FFIType.u64], returns: FFIType.void }, + }), +); + +/** + * Copy WebKit's completion block and return a one-shot caller for it. WebKit raises an + * uncatchable NSException if the block is freed uncalled, so every path must call the reply. + */ +const holdReply = ( + block: Handle, + argTypes: FFIType[], +): ((...args: (number | bigint)[]) => void) => { + const blocks = blockRuntime().symbols; + const held = blocks._Block_copy(block); + return (...args) => { + // A Block's invoke pointer lives at offset 16 and takes the block itself first (D022b). + const invoke = CFunction({ + ptr: read.u64(ptrIn(held), 16), + args: [FFIType.u64, ...argTypes], + returns: FFIType.void, + }); + try { + invoke(held, ...args); + } finally { + invoke.close(); + blocks._Block_release(held); + } + }; +}; + +/** Show `sheet` (+1, consumed) on the web view's window; with no window, `onEnd` gets cancel. */ +const runSheet = (webView: Handle, sheet: Handle, onEnd: (response: bigint) => void): void => { + const rt = cocoa(); + const release = (): void => { + rt.msgSend(sheet, rt.selectors.get('release')); + }; + const window = rt.msgSend(webView, rt.selectors.get('window')); + if (window === 0n) { + release(); + onEnd(NS_MODAL_RESPONSE_CANCEL); + return; + } + const done = makeOneShotBlock( + (response) => { + onEnd(BigInt(response ?? 0)); + // AppKit is still inside the sheet's own method here; release on a later tick. + setTimeout(release, 0); + }, + [FFIType.i64], + ); + msgSendPtrPtr( + sheet, + rt.selectors.get('beginSheetModalForWindow:completionHandler:'), + window, + done, + ); +}; + +const messageAlert = (message: Handle, buttons: string[]): Handle => + buildAlert({ message: nsStringToString(message), detail: '', buttons }); + const ensureDelegateClass = (): Handle => { if (delegateClass !== undefined) { return delegateClass; @@ -37,7 +105,53 @@ const ensureDelegateClass = (): Handle => { url === 0n ? '' : nsStringToString(rt.msgSend(url, rt.selectors.get('absoluteString'))), ); } - return 0n; + // nil: no child web view; the app opens the URL from its handler. + return 0n; // ponytail: deny-only, allowing needs a child BrowserWindow + }, + }, + { + selector: 'webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:completionHandler:', + typeEncoding: 'v@:@@@@?', + args: ['object', 'object', 'object', 'object'], + impl: (_self, _cmd, webView, message, _frame, completion) => { + const reply = holdReply(completion, []); + runSheet(webView, messageAlert(message, ['OK']), () => reply()); + }, + }, + { + selector: 'webView:runJavaScriptConfirmPanelWithMessage:initiatedByFrame:completionHandler:', + typeEncoding: 'v@:@@@@?', + args: ['object', 'object', 'object', 'object'], + impl: (_self, _cmd, webView, message, _frame, completion) => { + const reply = holdReply(completion, [FFIType.u8]); + runSheet(webView, messageAlert(message, ['OK', 'Cancel']), (response) => + reply(response === NS_ALERT_FIRST_BUTTON_RETURN ? 1 : 0), + ); + }, + }, + { + selector: 'webView:runOpenPanelWithParameters:initiatedByFrame:completionHandler:', + typeEncoding: 'v@:@@@@?', + args: ['object', 'object', 'object', 'object'], + impl: (_self, _cmd, webView, parameters, _frame, completion) => { + const rt = cocoa(); + const reply = holdReply(completion, [FFIType.u64]); + const flag = (name: string): boolean => + msgSendReturnsU8(parameters, rt.selectors.get(name)) === 1; + const panel = buildOpenPanel({ + canChooseFiles: true, + canChooseDirectories: flag('allowsDirectories'), + allowsMultipleSelection: flag('allowsMultipleSelection'), + canCreateDirectories: false, + defaultPath: '', + extensions: [], + }); + rt.msgSend(panel, rt.selectors.get('retain')); + runSheet(webView, panel, (response) => + reply( + response === NS_MODAL_RESPONSE_OK ? rt.msgSend(panel, rt.selectors.get('URLs')) : 0n, + ), + ); }, }, ]); diff --git a/tests/integration/macos/cocoa-ui-delegate.test.ts b/tests/integration/macos/cocoa-ui-delegate.test.ts index c7fc552a..71c93a8c 100644 --- a/tests/integration/macos/cocoa-ui-delegate.test.ts +++ b/tests/integration/macos/cocoa-ui-delegate.test.ts @@ -1,7 +1,17 @@ +import { FFIType } from 'bun:ffi'; import { describe, expect, test } from 'bun:test'; import { currentPlatform } from '../../../src/common/platform'; +import { createMacOSApplication } from '../../../src/main/platform/macos/cocoa-backend'; +import { type BlockArg, makeOneShotBlock } from '../../../src/main/platform/macos/cocoa-block'; import { nsString } from '../../../src/main/platform/macos/cocoa-foundation'; -import { msgSendPtr, msgSendPtr4 } from '../../../src/main/platform/macos/cocoa-msgsend-variants'; +import { + msgSendI64, + msgSendInitWithContentRect, + msgSendPtr, + msgSendPtr4, + msgSendPtrI64, + msgSendReturnsI64, +} from '../../../src/main/platform/macos/cocoa-msgsend-variants'; import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; import { defineObjcClass } from '../../../src/main/platform/macos/cocoa-runtime-class'; import { createUIDelegate } from '../../../src/main/platform/macos/cocoa-ui-delegate'; @@ -26,22 +36,114 @@ const navigationAction = (url: string): Handle => { return rt.msgSend(rt.msgSend(actionClass, rt.selectors.get('alloc')), rt.selectors.get('init')); }; -describe.skipIf(currentPlatform() !== 'macos')('BunmaskaUIDelegate', () => { - test('window.open hands the target URL to the handler and creates no child view', () => { - const seen: string[] = []; - const delegate = createUIDelegate((url) => seen.push(url)); - const created = msgSendPtr4( - delegate.handle, - cocoa().selectors.get( - 'webView:createWebViewWithConfiguration:forNavigationAction:windowFeatures:', - ), - 0n, - 0n, - navigationAction('https://example.com/popup'), - 0n, - ); - expect(created).toBe(0n); - expect(seen).toEqual(['https://example.com/popup']); - delegate.destroy(); +const ALERT = 'webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:completionHandler:'; +const CONFIRM = 'webView:runJavaScriptConfirmPanelWithMessage:initiatedByFrame:completionHandler:'; +const OPEN = 'webView:runOpenPanelWithParameters:initiatedByFrame:completionHandler:'; + +/** Send a panel selector with a completion block; resolves with the block's argument. */ +const runPanel = (selector: string, webView: Handle, argTypes: FFIType[]): Promise => + new Promise((resolve) => { + const delegate = createUIDelegate(() => undefined); + const done = makeOneShotBlock((arg = null) => resolve(arg), argTypes); + const sel = cocoa().selectors.get(selector); + // The second argument is the message NSString, or the WKOpenPanelParameters (nil here). + const second = selector === OPEN ? 0n : nsString('Sure?'); + msgSendPtr4(delegate.handle, sel, webView, second, 0n, done); + }); + +const withDeadline = (promise: Promise, ms: number): Promise => + Promise.race([promise, Bun.sleep(ms).then(() => 'timeout' as const)]); + +if (currentPlatform() === 'macos') { + describe('BunmaskaUIDelegate', () => { + test('alert, confirm and file input with no window reply at once as cancelled', async () => { + expect(await withDeadline(runPanel(ALERT, 0n, []), 2000)).toBe(null); + expect(await withDeadline(runPanel(CONFIRM, 0n, [FFIType.u8]), 2000)).toBe(0); + expect(await withDeadline(runPanel(OPEN, 0n, [FFIType.u64]), 2000)).toBe(0n); + }); + + test('confirm shows a sheet on the web view window and replies with the clicked button', async () => { + const rt = cocoa(); + const app = createMacOSApplication(); + app.start(); + const window = msgSendInitWithContentRect( + rt.msgSend(rt.classes.get('NSWindow'), rt.selectors.get('alloc')), + rt.selectors.get('initWithContentRect:styleMask:backing:defer:'), + [100, 100, 400, 300], + 1n, + 2n, + false, + ); + try { + msgSendPtr(window, rt.selectors.get('makeKeyAndOrderFront:'), 0n); + const webView = rt.msgSend(window, rt.selectors.get('contentView')); + const reply = runPanel(CONFIRM, webView, [FFIType.u8]); + const sheet = rt.msgSend(window, rt.selectors.get('attachedSheet')); + expect(sheet).not.toBe(0n); + msgSendPtrI64(window, rt.selectors.get('endSheet:returnCode:'), sheet, 1000n); + expect(await withDeadline(reply, 5000)).toBe(1); + } finally { + rt.msgSend(window, rt.selectors.get('close')); + app.quit(); + } + }); + + test('a page confirm() gets a sheet from WebKit and sees the answer', async () => { + const rt = cocoa(); + const app = createMacOSApplication(); + app.start(); + const win = app.createWindow({ width: 400, height: 300, title: 'confirm', show: true }); + try { + win.webContents.loadHTML( + '', + 'about:blank', + ); + const nsApp = rt.msgSend( + rt.classes.get('NSApplication'), + rt.selectors.get('sharedApplication'), + ); + let host = 0n; + let sheet = 0n; + for (let waited = 0; sheet === 0n && waited < 5000; waited += 50) { + await Bun.sleep(50); + // Re-read each tick: the array is autoreleased and the pump drains the pool. + const windows = rt.msgSend(nsApp, rt.selectors.get('windows')); + const count = msgSendReturnsI64(windows, rt.selectors.get('count')); + for (let i = 0n; i < count && sheet === 0n; i += 1n) { + host = msgSendI64(windows, rt.selectors.get('objectAtIndex:'), i); + sheet = rt.msgSend(host, rt.selectors.get('attachedSheet')); + } + } + expect(sheet).not.toBe(0n); + msgSendPtrI64(host, rt.selectors.get('endSheet:returnCode:'), sheet, 1000n); + let title: unknown = ''; + for (let waited = 0; title !== 'true' && waited < 5000; waited += 50) { + await Bun.sleep(50); + title = await win.webContents.executeJavaScript('document.title'); + } + expect(title).toBe('true'); + } finally { + win.close(); + app.quit(); + } + }); + + test('window.open hands the target URL to the handler and creates no child view', () => { + const seen: string[] = []; + const delegate = createUIDelegate((url) => seen.push(url)); + const created = msgSendPtr4( + delegate.handle, + cocoa().selectors.get( + 'webView:createWebViewWithConfiguration:forNavigationAction:windowFeatures:', + ), + 0n, + 0n, + navigationAction('https://example.com/popup'), + 0n, + ); + expect(created).toBe(0n); + expect(seen).toEqual(['https://example.com/popup']); + delegate.destroy(); + }); }); -}); +} From e97ba33700e24588bd3079100dc99ccc87b23246 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:58:59 -0700 Subject: [PATCH 131/586] chore: trim macOS delegate and web-data comments to the comment rules --- src/main/platform/macos/cocoa-app-delegate.ts | 13 +----- src/main/platform/macos/cocoa-app.ts | 14 +----- .../platform/macos/cocoa-content-world.ts | 30 +++---------- src/main/platform/macos/cocoa-cookies.ts | 13 ++---- .../macos/cocoa-navigation-delegate.ts | 5 +-- .../macos/cocoa-notification-observer.ts | 18 +++----- .../macos/cocoa-script-message-handler.ts | 22 ++-------- .../macos/cocoa-url-scheme-handler.ts | 43 +++---------------- .../platform/macos/cocoa-window-delegate.ts | 36 +++------------- 9 files changed, 32 insertions(+), 162 deletions(-) diff --git a/src/main/platform/macos/cocoa-app-delegate.ts b/src/main/platform/macos/cocoa-app-delegate.ts index b9969b8c..90e8dea8 100644 --- a/src/main/platform/macos/cocoa-app-delegate.ts +++ b/src/main/platform/macos/cocoa-app-delegate.ts @@ -4,15 +4,6 @@ import { cocoa } from './cocoa-runtime'; import { defineObjcClass } from './cocoa-runtime-class'; import type { Handle } from './objc'; -/** - * Bridges `NSApplicationDelegate` callbacks to JS (D026). - * - * `applicationShouldHandleReopen:hasVisibleWindows:` is AppKit's Dock-reopen - * hook and the source of Electron's `activate` event. The delegate object is - * created with `alloc`/`init` (retain count +1) and never released, so it - * outlives `NSApp` (which holds its delegate weakly). - */ - /** JS handlers an `NSApplicationDelegate` instance routes callbacks to. */ export type AppDelegateHandlers = { /** The app was re-activated; `hasVisibleWindows` is AppKit's flag. */ @@ -73,8 +64,8 @@ export type AppDelegate = { }; /** - * Create an `NSApplicationDelegate` instance routing callbacks to `handlers`. - * There is one application delegate per process; the most recent handlers win. + * Create the app delegate; the most recent `handlers` win. Its alloc/init +1 is never + * released because `NSApp` holds its delegate weakly. */ export const createAppDelegate = (handlers: AppDelegateHandlers): AppDelegate => { const rt = cocoa(); diff --git a/src/main/platform/macos/cocoa-app.ts b/src/main/platform/macos/cocoa-app.ts index 944a28ea..3621c9b5 100644 --- a/src/main/platform/macos/cocoa-app.ts +++ b/src/main/platform/macos/cocoa-app.ts @@ -3,17 +3,7 @@ import { msgSendI64, msgSendPtr, msgSendReturnsU8 } from './cocoa-msgsend-varian import { cocoa } from './cocoa-runtime'; import type { Handle } from './objc'; -/** - * macOS application-level operations on `NSApplication` (D026/D029), backing the - * macOS-only parts of Electron's `app`. - * - * `NSApp` is `[NSApplication sharedApplication]` — idempotent — so each call - * re-fetches it rather than depending on the backend exposing its private handle - * across the platform seam (D024). All args are scalars/objects (no struct - * returns), so everything is pure `bun:ffi`. - */ - -/** Electron's activation-policy names → `NSApplicationActivationPolicy` values. */ +/** Electron's activation-policy names as `NSApplicationActivationPolicy` values. */ const ACTIVATION_POLICY: Readonly> = { regular: 0n, accessory: 1n, @@ -39,7 +29,6 @@ export const setActivationPolicy = (policy: 'regular' | 'accessory' | 'prohibite msgSendI64(nsApp(), rt.selectors.get('setActivationPolicy:'), ACTIVATION_POLICY[policy] ?? 0n); }; -/** Hide all application windows (without minimizing). */ export const hide = (): void => { msgSendPtr(nsApp(), cocoa().selectors.get('hide:'), 0n); }; @@ -52,7 +41,6 @@ export const show = (): void => { export const isHidden = (): boolean => msgSendReturnsU8(nsApp(), cocoa().selectors.get('isHidden')) === 1; -/** Whether the application is the active (frontmost) app. */ export const isActive = (): boolean => msgSendReturnsU8(nsApp(), cocoa().selectors.get('isActive')) === 1; diff --git a/src/main/platform/macos/cocoa-content-world.ts b/src/main/platform/macos/cocoa-content-world.ts index edd51d90..47866460 100644 --- a/src/main/platform/macos/cocoa-content-world.ts +++ b/src/main/platform/macos/cocoa-content-world.ts @@ -3,26 +3,11 @@ import { msgSendPtr } from './cocoa-msgsend-variants'; import { cocoa } from './cocoa-runtime'; import type { Handle } from './objc'; -/** - * `WKContentWorld` accessors — the macOS half of context isolation. - * - * A `WKContentWorld` is a named JavaScript world that shares the page's DOM but - * has its own global object. Injecting the `__bunmaska` bridge + user preload into - * a dedicated named world (`BunmaskaPreload`) keeps them invisible to page scripts - * (Electron `contextIsolation: true`). - * - * `WKContentWorld` resolves only once `WebKit.framework` is loaded (call - * `loadWebKit()` first). Worlds are interned by WebKit — `+worldWithName:` with - * the same name returns the same world — and we additionally memoise the handle - * per process so repeated injections reuse one bigint. - */ +/** `WKContentWorld` accessors for context isolation. Call `loadWebKit()` first. */ const worldCache = new Map(); -/** - * Return the named `WKContentWorld` handle, creating it on first use and caching - * it per process. Same name → same handle. Requires `loadWebKit()` to have run. - */ +/** The named world, retained and cached for the process lifetime. */ export const getContentWorld = (name: string): Handle => { const cached = worldCache.get(name); if (cached !== undefined) { @@ -34,19 +19,14 @@ export const getContentWorld = (name: string): Handle => { rt.selectors.get('worldWithName:'), nsString(name), ); - // `worldWithName:` returns an autoreleased object; retain before caching so it - // cannot dangle when the cooperative pump drains the autorelease pool. This is - // a process-lifetime singleton, so the matching release is never needed. + // Never cache an autoreleased world without -retain: the pump drains the pool and + // the cached handle dangles. Process-lifetime, so it is never released. rt.msgSend(world, rt.selectors.get('retain')); worldCache.set(name, world); return world; }; -/** - * Return the shared `+[WKContentWorld pageWorld]` (the page's main world). Used - * immediately by callers, so it is not cached — do NOT cache the result of this - * (or `worldWithName:`) without sending `-retain` first. - */ +/** The page's main world; autoreleased, so use it immediately (see the retain rule above). */ export const pageWorld = (): Handle => { const rt = cocoa(); return rt.msgSend(rt.classes.get('WKContentWorld'), rt.selectors.get('pageWorld')); diff --git a/src/main/platform/macos/cocoa-cookies.ts b/src/main/platform/macos/cocoa-cookies.ts index 1ef569af..774c6d8d 100644 --- a/src/main/platform/macos/cocoa-cookies.ts +++ b/src/main/platform/macos/cocoa-cookies.ts @@ -20,17 +20,11 @@ import { cocoa } from './cocoa-runtime'; import { loadWebKit } from './cocoa-webkit'; import type { Handle } from './objc'; -/** - * `session.cookies` on macOS via `WKHTTPCookieStore`. Every completion handler - * is a one-shot Block (D022b) fired on the pumped run loop. - */ - const TIMEOUT_MS = 15_000; /** The default data store's `WKHTTPCookieStore`. */ const cookieStore = (): Handle => { - // WKWebsiteDataStore registers only once WebKit.framework is loaded; without - // this, cookies called before any window exists fail with class-not-found. + // WKWebsiteDataStore exists only once WebKit is loaded; before any window it is class-not-found. loadWebKit(); const rt = cocoa(); const store = rt.msgSend( @@ -87,9 +81,8 @@ const readCookie = (handle: Handle): Cookie => { }; /** - * Fetch every cookie handle via `getAllCookies:`. `onCookies` runs INSIDE the - * completion block, while the autoreleased NSArray still owns the cookies - any - * per-cookie native call (e.g. `deleteCookie:`) must be issued there, not later. + * `onCookies` runs INSIDE the `getAllCookies:` block, while the autoreleased NSArray still + * owns the cookies: issue every per-cookie native call (e.g. `deleteCookie:`) there, not later. */ const getAllCookieHandles = (onCookies: (handles: Handle[]) => void): void => { const rt = cocoa(); diff --git a/src/main/platform/macos/cocoa-navigation-delegate.ts b/src/main/platform/macos/cocoa-navigation-delegate.ts index b02bccb6..105d3c52 100644 --- a/src/main/platform/macos/cocoa-navigation-delegate.ts +++ b/src/main/platform/macos/cocoa-navigation-delegate.ts @@ -5,10 +5,7 @@ import { cocoa } from './cocoa-runtime'; import { defineObjcClass } from './cocoa-runtime-class'; import type { Handle } from './objc'; -/** - * Bridges `WKNavigationDelegate` callbacks to JS (D026), one instance per web - * view, routed by the `self` handle delivered to the IMP. - */ +/** `WKNavigationDelegate` bridge (D026): one instance per web view, routed by the IMP's `self`. */ const registry = new Map void>(); diff --git a/src/main/platform/macos/cocoa-notification-observer.ts b/src/main/platform/macos/cocoa-notification-observer.ts index d07536fa..8cb7ef56 100644 --- a/src/main/platform/macos/cocoa-notification-observer.ts +++ b/src/main/platform/macos/cocoa-notification-observer.ts @@ -4,15 +4,7 @@ import { cocoa } from './cocoa-runtime'; import { defineObjcClass } from './cocoa-runtime-class'; import type { Handle } from './objc'; -/** - * A reusable Cocoa notification observer (D034). - * - * One shared `BunmaskaNotificationObserver` class (defined once at runtime, D026) - * carries a single `bunmaskaNotify:` selector; each registration owns an instance - * whose JS handler is looked up by the instance handle. The instance is retained - * for the process lifetime — notification centers do NOT retain their observers. - * Notifications are delivered on the pumped main run loop (D020/D021). - */ +/** Cocoa notification observers (D034). */ const registry = new Map void>(); let observerClass: Handle | undefined; @@ -34,14 +26,14 @@ const ensureObserverClass = (): Handle => { return observerClass; }; -/** `[[NSWorkspace sharedWorkspace] notificationCenter]` — the source of sleep/wake events. */ +/** The NSWorkspace center: sleep and wake. */ export const workspaceNotificationCenter = (): Handle => { const rt = cocoa(); const workspace = rt.msgSend(rt.classes.get('NSWorkspace'), rt.selectors.get('sharedWorkspace')); return rt.msgSend(workspace, rt.selectors.get('notificationCenter')); }; -/** `[NSDistributedNotificationCenter defaultCenter]` — system-wide notifications (appearance, lock). */ +/** The distributed center: system-wide appearance and screen-lock notifications. */ export const distributedNotificationCenter = (): Handle => { const rt = cocoa(); return rt.msgSend( @@ -51,8 +43,8 @@ export const distributedNotificationCenter = (): Handle => { }; /** - * Register `onPost` to fire whenever `name` is posted on `center`. The observer - * instance is retained for the process lifetime. + * Call `onPost` whenever `name` is posted on `center`. The observer's alloc/init +1 is + * never released: notification centers do NOT retain their observers. */ export const observeNotification = (center: Handle, name: string, onPost: () => void): void => { const rt = cocoa(); diff --git a/src/main/platform/macos/cocoa-script-message-handler.ts b/src/main/platform/macos/cocoa-script-message-handler.ts index 9cace59b..10de1f2b 100644 --- a/src/main/platform/macos/cocoa-script-message-handler.ts +++ b/src/main/platform/macos/cocoa-script-message-handler.ts @@ -4,16 +4,7 @@ import { cocoa } from './cocoa-runtime'; import { defineObjcClass } from './cocoa-runtime-class'; import type { Handle } from './objc'; -/** - * Bridges `WKScriptMessageHandler` callbacks to JS. - * - * WebKit requires a real Objective-C object conforming to - * `WKScriptMessageHandler` to receive - * `window.webkit.messageHandlers..postMessage(...)`. We define that class - * once at runtime (D026), allocate one instance per web view, and route each - * instance's messages to its registered JS callback by keying on the `self` - * handle delivered to the IMP. - */ +/** `WKScriptMessageHandler` bridge (D021, D026): one instance per web view, routed by `self`. */ const registry = new Map void>(); @@ -54,18 +45,13 @@ export type ScriptMessageHandler = { /** The Objective-C handler instance to pass to `addScriptMessageHandler:name:`. */ readonly handle: Handle; /** - * Drop the per-window routing entry and release the native instance. Call from - * the owning window's `close()` AFTER detaching it from the - * `userContentController` so a late message can no longer reach a freed - * callback. Idempotent. + * Unroute and release. Idempotent. Call only AFTER detaching from the + * `userContentController`, or a late message reaches a freed instance. */ dispose(): void; }; -/** - * Create a `WKScriptMessageHandler` instance whose messages are delivered to - * `onEnvelope` as the raw JSON string the renderer posted. - */ +/** Create a handler that passes each posted string body to `onEnvelope` as raw JSON. */ export const createScriptMessageHandler = ( onEnvelope: (envelopeJson: string) => void, ): ScriptMessageHandler => { diff --git a/src/main/platform/macos/cocoa-url-scheme-handler.ts b/src/main/platform/macos/cocoa-url-scheme-handler.ts index dea07a85..12bb4b51 100644 --- a/src/main/platform/macos/cocoa-url-scheme-handler.ts +++ b/src/main/platform/macos/cocoa-url-scheme-handler.ts @@ -12,26 +12,11 @@ import { cocoa } from './cocoa-runtime'; import { defineObjcClass } from './cocoa-runtime-class'; import type { Handle } from './objc'; -/** - * Bridges `WKURLSchemeHandler` callbacks to the `protocol` module on macOS. - * - * A `WKWebView` routes a custom scheme here (via `setURLSchemeHandler:forURLScheme:` - * on its `WKWebViewConfiguration`) and we serve the task synchronously. - * - * The class is defined once at runtime via {@link defineObjcClass} (D026); its - * IMP `JSCallback`s are retained for the process lifetime by the runtime-class - * helper's `retainedCallbacks`, so they are NEVER freed inside their own - * invocation (the JSCallback-lifecycle discipline that prevents the SIGSEGV). - */ - const log = createLogger('macos-url-scheme-handler'); -/** The Bunmaska error domain for a failed custom-scheme task. */ const ERROR_DOMAIN = 'BunmaskaProtocol'; -/** `NSURLErrorResourceUnavailable`-ish code for an unhandled/declined request. */ -const ERROR_CODE_NO_HANDLER = -1100n; +const ERROR_CODE_NO_HANDLER = -1100n; // NSURLErrorFileDoesNotExist -/** The dispatcher the IMP calls to serve a URL; defaults to {@link protocol.dispatch}. */ let dispatcher: (url: string) => BuiltProtocolResponse | undefined = protocol.dispatch; /** Override the URL dispatcher. Test-only. */ @@ -41,11 +26,7 @@ export const setUrlSchemeDispatcherForTesting = ( dispatcher = fake ?? protocol.dispatch; }; -/** - * Fail `task` with an `NSError` (no registered handler / declined / empty body). - * Best-effort: a task that WebKit has already finished/stopped throws on a - * second response, so swallow. - */ +/** Fail `task` as declined. The catch covers JS/FFI errors only; an NSException aborts. */ const failTask = (task: Handle): void => { try { const rt = cocoa(); @@ -62,16 +43,9 @@ const failTask = (task: Handle): void => { } }; -/** - * Serve `built` to `task`: build an `NSData` from the bytes and an - * `NSURLResponse` for `url`, then drive the task through - * `didReceiveResponse:` → `didReceiveData:` → `didFinish`. - */ const serveTask = (task: Handle, url: Handle, built: BuiltProtocolResponse): void => { const rt = cocoa(); - // NSData dataWithBytes:length: copies, so `bytes` only needs to outlive this - // call — no long-lived pinning. A zero-length body still produces a valid - // (empty) NSData. + // dataWithBytes:length: copies, so `bytes` only has to outlive this call. const bytes = built.bytes; const dataPtr = bytes.length === 0 ? 0n : BigInt(ptr(bytes)); const data = msgSendPtrI64( @@ -102,10 +76,7 @@ const serveTask = (task: Handle, url: Handle, built: BuiltProtocolResponse): voi rt.msgSend(task, rt.selectors.get('didFinish')); }; -/** - * @internal The body of `webView:startURLSchemeTask:`. Never throws out into the - * IMP (any error fails the task instead). - */ +/** @internal `webView:startURLSchemeTask:`; never throws into the IMP, any error fails the task. */ export const handleStartTask = (task: Handle): void => { try { const rt = cocoa(); @@ -133,7 +104,6 @@ const ensureHandlerClass = (): Handle => { selector: 'webView:startURLSchemeTask:', typeEncoding: 'v@:@@', args: ['object', 'object'], - // (self, _cmd, webView, task) — the task is the 2nd declared arg. impl: (_self, _cmd, _webView, task) => { handleStartTask(task); }, @@ -142,8 +112,7 @@ const ensureHandlerClass = (): Handle => { selector: 'webView:stopURLSchemeTask:', typeEncoding: 'v@:@@', args: ['object', 'object'], - // We serve synchronously, so there is nothing to cancel — but the selector - // MUST exist or WebKit refuses the handler (the protocol requires both). + // Tasks finish synchronously, but WebKit rejects a handler without this selector. impl: () => undefined, }, ]); @@ -158,7 +127,7 @@ export type UrlSchemeHandler = { let shared: UrlSchemeHandler | undefined; -/** The process-wide `WKURLSchemeHandler`; it holds no per-window state, so every configuration shares it. */ +/** The process-wide handler: it has no per-window state, so every configuration shares it. */ export const createUrlSchemeHandler = (): UrlSchemeHandler => { if (shared === undefined) { const rt = cocoa(); diff --git a/src/main/platform/macos/cocoa-window-delegate.ts b/src/main/platform/macos/cocoa-window-delegate.ts index 60dc72cd..3cdf8c7f 100644 --- a/src/main/platform/macos/cocoa-window-delegate.ts +++ b/src/main/platform/macos/cocoa-window-delegate.ts @@ -3,29 +3,13 @@ import { defineObjcClass } from './cocoa-runtime-class'; import type { WindowEventType } from '../native'; import type { Handle } from './objc'; -/** - * Bridges `NSWindowDelegate` notifications to JS. - * - * The class is defined once at runtime (D026) with one instance per window; each - * instance routes its callbacks by keying on the `self` handle given to the IMP. - * - * The IMP `JSCallback`s are retained for the process lifetime by - * {@link defineObjcClass} (the runtime keeps the class forever), so they are - * NEVER closed inside their own invocation — matching the JSCallback-lifetime - * discipline of `cocoa-navigation-delegate.ts` / `gtk-signals.ts`. - * - * CLOSE PATH (the use-after-free fix): `windowShouldClose:` consults the JS - * veto (returning 0 to keep the window open); `windowWillClose:` runs the - * window's teardown on EVERY close path — title-bar red button, programmatic - * `-close`, and `app.quit()` — so a post-close `executeJavaScript` can never - * touch a freed `WKWebView`. - */ +/** `NSWindowDelegate` bridge (D026): one instance per window, routed by the IMP's `self`. */ /** The per-window JS handlers an `NSWindowDelegate` routes notifications to. */ export type WindowDelegateHandlers = { /** Return `true` to VETO the close (windowShouldClose: returns NO). */ readonly shouldClose: () => boolean; - /** Run AFTER AppKit has committed to closing (windowWillClose:). */ + /** Runs on every close path once AppKit has committed (windowWillClose:). */ readonly willClose: () => void; /** A non-preventable lifecycle event fired. */ readonly event: (type: WindowEventType) => void; @@ -35,11 +19,7 @@ const registry = new Map(); let delegateClass: Handle | undefined; -/** - * Map of `NSWindowDelegate` notification selectors to the lifecycle event they - * surface. `windowShouldClose:`/`windowWillClose:` are handled separately - * because they are preventable / teardown-bearing, not plain events. - */ +/** Plain notifications; the preventable close pair is handled separately below. */ const NOTIFICATION_EVENTS: ReadonlyArray = [ ['windowDidBecomeKey:', 'focus'], ['windowDidResignKey:', 'blur'], @@ -54,7 +34,6 @@ const ensureDelegateClass = (): Handle => { return delegateClass; } delegateClass = defineObjcClass('BunmaskaWindowDelegate', 'NSObject', [ - // windowShouldClose: returns a BOOL — return 0 (NO) to veto, 1 (YES) to allow. { selector: 'windowShouldClose:', typeEncoding: 'c@:@', @@ -65,8 +44,7 @@ const ensureDelegateClass = (): Handle => { if (handlers === undefined) { return 1; } - // shouldClose() returns true to VETO; windowShouldClose: returns NO(0) to - // veto. Invert. + // Inverted: shouldClose() is true to veto, the BOOL is NO (0) to veto. return handlers.shouldClose() ? 0 : 1; }, }, @@ -97,11 +75,7 @@ export type WindowDelegate = { readonly destroy: () => void; }; -/** - * Create an `NSWindowDelegate` instance routing notifications to `handlers`. - * Set it as the window's delegate via `setDelegate:`. The instance is retained - * by the registry for the window's lifetime. - */ +/** Create a delegate routing to `handlers`; the instance is owned +1 until `destroy()`. */ export const createWindowDelegate = (handlers: WindowDelegateHandlers): WindowDelegate => { const rt = cocoa(); const cls = ensureDelegateClass(); From b43554315bd7f8ebe6a96366fd5d7b69a3ee1b34 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 09:59:00 -0700 Subject: [PATCH 132/586] test: let the pre-WebKit clearStorageData probe settle before exiting --- .../macos/cocoa-website-data.test.ts | 26 ++++++++++++------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/tests/integration/macos/cocoa-website-data.test.ts b/tests/integration/macos/cocoa-website-data.test.ts index 89e3f4dd..ff695e87 100644 --- a/tests/integration/macos/cocoa-website-data.test.ts +++ b/tests/integration/macos/cocoa-website-data.test.ts @@ -2,21 +2,27 @@ import { describe, expect, test } from 'bun:test'; import { join } from 'node:path'; import { currentPlatform } from '../../../src/common/platform'; -const MODULE = join(import.meta.dir, '../../../src/main/platform/macos/cocoa-website-data.ts'); +const MACOS = join(import.meta.dir, '../../../src/main/platform/macos'); -describe.skipIf(currentPlatform() !== 'macos')('clearStorageData', () => { - test('works in a fresh process where WebKit is not loaded yet', () => { - // Only a fresh process shows the pre-WebKit state; this suite has already loaded it. - const script = `import { clearStorageData } from ${JSON.stringify(MODULE)}; +if (currentPlatform() === 'macos') { + describe('clearStorageData', () => { + test('works when called before WebKit is loaded', () => { + // Only a fresh process shows the pre-WebKit state; this suite has already loaded it. + const script = `import { clearStorageData } from ${JSON.stringify(`${MACOS}/cocoa-website-data.ts`)}; +import { createMacOSApplication } from ${JSON.stringify(`${MACOS}/cocoa-backend.ts`)}; const result = clearStorageData(); +const app = createMacOSApplication(); +app.start(); const outcome = await Promise.race([ result.then(() => 'settled', (error) => String(error)), - Bun.sleep(100).then(() => 'pending'), + Bun.sleep(10000).then(() => 'pending'), ]); console.log(outcome); +app.quit(); process.exit(0);`; - const proc = Bun.spawnSync(['bun', '-e', script], { stdout: 'pipe', stderr: 'pipe' }); - expect(proc.stderr.toString()).toBe(''); - expect(proc.stdout.toString().trim()).toMatch(/^(pending|settled)$/); + const proc = Bun.spawnSync(['bun', '-e', script], { stdout: 'pipe', stderr: 'pipe' }); + expect(proc.stderr.toString()).toBe(''); + expect(proc.stdout.toString().trim()).toBe('settled'); + }); }); -}); +} From c8c67f18aa5121d8d1921faf2f34e012aa0e920b Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:00:47 -0700 Subject: [PATCH 133/586] refactor: drop dead target-class and callback state in macOS backends --- src/main/platform/macos/carbon-global-shortcut.ts | 3 +-- src/main/platform/macos/cocoa-menu.ts | 3 +-- src/main/platform/macos/cocoa-tray.ts | 3 +-- 3 files changed, 3 insertions(+), 6 deletions(-) diff --git a/src/main/platform/macos/carbon-global-shortcut.ts b/src/main/platform/macos/carbon-global-shortcut.ts index 4e566253..c324ba7e 100644 --- a/src/main/platform/macos/carbon-global-shortcut.ts +++ b/src/main/platform/macos/carbon-global-shortcut.ts @@ -33,7 +33,6 @@ const EVENT_NOT_HANDLED_ERR = -9874; type Registration = { readonly id: number; readonly hotKeyRef: bigint; - readonly callback: () => void; }; const byAccelerator = new Map(); @@ -136,7 +135,7 @@ const register = (accelerator: string, callback: () => void): boolean => { return false; } byId.set(id, callback); - byAccelerator.set(accelerator, { id, hotKeyRef, callback }); + byAccelerator.set(accelerator, { id, hotKeyRef }); return true; }; diff --git a/src/main/platform/macos/cocoa-menu.ts b/src/main/platform/macos/cocoa-menu.ts index a0e6a833..0da06d62 100644 --- a/src/main/platform/macos/cocoa-menu.ts +++ b/src/main/platform/macos/cocoa-menu.ts @@ -47,7 +47,6 @@ export type NativeMenuItemSpec = { const clickRegistry = new Map(); -let targetClass: Handle | undefined; let sharedTarget: Handle | undefined; const setState = (item: Handle, on: boolean): void => { @@ -81,7 +80,7 @@ const ensureTarget = (): Handle => { return sharedTarget; } const rt = cocoa(); - targetClass = defineObjcClass('BunmaskaMenuTarget', 'NSObject', [ + const targetClass = defineObjcClass('BunmaskaMenuTarget', 'NSObject', [ { selector: 'bunmaskaMenuAction:', typeEncoding: 'v@:@', diff --git a/src/main/platform/macos/cocoa-tray.ts b/src/main/platform/macos/cocoa-tray.ts index ef65dac5..20d49244 100644 --- a/src/main/platform/macos/cocoa-tray.ts +++ b/src/main/platform/macos/cocoa-tray.ts @@ -30,7 +30,6 @@ const NS_VARIABLE_STATUS_ITEM_LENGTH = -1; const clickRegistry = new Map void>(); -let targetClass: Handle | undefined; let sharedTarget: Handle | undefined; const ensureTarget = (): Handle => { @@ -38,7 +37,7 @@ const ensureTarget = (): Handle => { return sharedTarget; } const rt = cocoa(); - targetClass = defineObjcClass('BunmaskaTrayTarget', 'NSObject', [ + const targetClass = defineObjcClass('BunmaskaTrayTarget', 'NSObject', [ { selector: 'bunmaskaTrayAction:', typeEncoding: 'v@:@', From 522fe2a55b2ec4b1af289995387643a311303776 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:00:54 -0700 Subject: [PATCH 134/586] chore: trim window, ipc and session comments to the comment rules --- src/main/api/browser-window.ts | 41 +++++++----------------------- src/main/api/cookie-util.ts | 9 +++---- src/main/api/ipc-main.ts | 14 ++--------- src/main/api/preload.ts | 12 ++------- src/main/api/protocol.ts | 36 +++++--------------------- src/main/api/session.ts | 46 +++++++++++----------------------- src/main/api/web-contents.ts | 35 +++++++------------------- src/main/ipc/exec-wrapper.ts | 25 ++++++------------ src/main/ipc/ipc-protocol.ts | 7 +----- 9 files changed, 55 insertions(+), 170 deletions(-) diff --git a/src/main/api/browser-window.ts b/src/main/api/browser-window.ts index 23c973e9..259ec5e6 100644 --- a/src/main/api/browser-window.ts +++ b/src/main/api/browser-window.ts @@ -12,24 +12,11 @@ import { loadPreloadScript } from './preload'; import { session } from './session'; import { type LoadFileOptions, objectDestroyedError, WebContents } from './web-contents'; -/** - * A top-level application window — the drop-in equivalent of Electron's - * `BrowserWindow`. Extends Node {@link EventEmitter} (D023). Content operations - * delegate to {@link WebContents} (D025); a process-wide registry backs the - * `getAllWindows` / `fromId` statics. - */ - export type WebPreferences = { /** - * Path to a JavaScript file run before the page's own scripts, after the - * built-in `window.__bunmaska` bridge. Read synchronously at window - * construction. - * - * Runs in a dedicated ISOLATED world (Electron `contextIsolation: true`): it - * shares the page's DOM but has its own global, so `window.__bunmaska`, - * `ipcRenderer`, and anything the preload defines are invisible to page - * scripts. Use `contextBridge.exposeInMainWorld` to expose a controlled, - * async, structured-clone-copyable surface to the page. + * Script run before the page's own, in an isolated world (`contextIsolation: true`); expose + * to the page with `contextBridge.exposeInMainWorld`. Windows has no isolated world yet: the + * preload and `__bunmaska` are page-visible there, so treat loaded content as trusted. */ readonly preload?: string; }; @@ -53,7 +40,7 @@ const DEFAULT_WIDTH = 800; const DEFAULT_HEIGHT = 600; const DEFAULT_TITLE = 'Bunmaska'; -/** Non-preventable — re-emitted verbatim from the seam. */ +/** Non-preventable, re-emitted verbatim from the seam. */ const WINDOW_EVENT_TYPES: readonly WindowEventType[] = [ 'focus', 'blur', @@ -69,7 +56,6 @@ const WINDOW_EVENT_TYPES: readonly WindowEventType[] = [ ]; const registry = new Map(); -/** So `Menu.popup` can anchor to a window without a menu→window import cycle. */ const popupTargets = new WeakMap(); let nextId = 1; @@ -82,6 +68,7 @@ export const resetWindowRegistryForTesting = (): void => { nextId = 1; }; +/** Electron's `BrowserWindow`; content methods delegate to {@link WebContents} (D023, D025). */ export class BrowserWindow extends EventEmitter { /** Process-unique and never reused within a run. */ readonly id: number; @@ -96,8 +83,6 @@ export class BrowserWindow extends EventEmitter { constructor(options: BrowserWindowOptions = {}) { super(); ensureNativeStarted(); - // In dev, the first window installs the stdin reload listener so a renderer - // change refreshes the page in place instead of restarting the whole app. if (process.env['BUNMASKA_DEV'] === '1' && !devReloadInstalled) { devReloadInstalled = true; startDevReload(() => { @@ -110,8 +95,7 @@ export class BrowserWindow extends EventEmitter { nextId += 1; this.#resizable = options.resizable ?? true; - // Dev only: a supervisor restart is a fresh process, so the first window - // seeds its bounds from the state file to reopen where the developer left it. + // Dev only: a supervisor restart is a fresh process, so window 1 reopens at its last bounds. const devStatePath = process.env['BUNMASKA_DEV_STATE']; const devBounds = this.id === 1 ? readDevWindowState(devStatePath) : undefined; if (devBounds !== undefined) { @@ -133,8 +117,6 @@ export class BrowserWindow extends EventEmitter { popupMenu: (handle, x, y) => this.#native.popupMenu(handle, x, y), closePopupMenu: () => this.#native.closePopupMenu(), }); - // Apply the effective default User-Agent before this window's first - // navigation: a per-session override wins, else the app-wide fallback. const sessionUserAgent = session.defaultSession.getUserAgent(); const effectiveUserAgent = sessionUserAgent !== '' ? sessionUserAgent : app.userAgentFallback; if (effectiveUserAgent !== '') { @@ -191,11 +173,7 @@ export class BrowserWindow extends EventEmitter { return this.#window; } - /** - * When the last window closes, emit `app`'s `window-all-closed`. Replicating - * Electron's default: if no listener handles it, quit the app (a subscriber - * takes over the decision by listening). - */ + /** Electron's default: the last close quits unless `window-all-closed` has a listener. */ #emitWindowAllClosedIfLast(): void { if (registry.size > 0) { return; @@ -280,7 +258,7 @@ export class BrowserWindow extends EventEmitter { return [this.#minWidth, this.#minHeight]; } - /** Best-effort on Linux/Wayland. */ + /** No-op on Linux (GTK4 has no client-side positioning). */ center(): void { this.#native.center(); } @@ -372,8 +350,7 @@ export class BrowserWindow extends EventEmitter { } } -// Let Menu.popup resolve a target window (focused → most-recent) without importing -// BrowserWindow into menu.ts (which would cycle). The registry is creation-ordered. +// Menu.popup resolves its window through this, so menu.ts never imports this module (a cycle). installWindowResolver({ focused: () => { const window = BrowserWindow.getFocusedWindow(); diff --git a/src/main/api/cookie-util.ts b/src/main/api/cookie-util.ts index bf50881e..31df8d94 100644 --- a/src/main/api/cookie-util.ts +++ b/src/main/api/cookie-util.ts @@ -1,6 +1,6 @@ import { InvalidArgumentError } from '../../common/errors'; -/** Pure cookie matching/normalization shared by the session API and every backend. */ +// Pure cookie matching/normalization shared by the session API and every backend. /** Electron's `Cookie` subset: `expirationDate` is unix seconds; absent = session cookie. */ export type Cookie = { @@ -35,7 +35,7 @@ export type CookieSetDetails = { const stripDot = (domain: string): string => (domain.startsWith('.') ? domain.slice(1) : domain); -/** RFC 6265 domain-match: `host` equals `cookieDomain` or is a subdomain of it. */ +/** `host` equals `cookieDomain` or is a subdomain of it, a leading dot ignored. */ export const domainMatches = (cookieDomain: string, host: string): boolean => { const domain = stripDot(cookieDomain); return host === domain || host.endsWith(`.${domain}`); @@ -77,9 +77,8 @@ export const filterCookies = (cookies: ReadonlyArray, filter: CookieFilt }; /** - * The cookies `cookies.remove(url, name)` deletes: name equal, url host within the - * cookie domain, url path within the cookie path. `secure` is deliberately ignored - * so an http url can remove a secure cookie (removal is not a send). + * What `cookies.remove(url, name)` deletes: same name, sent to `url`'s host and path. `secure` + * is ignored on purpose so an http url can remove a secure cookie (removal is not a send). */ export const cookiesToRemove = ( cookies: ReadonlyArray, diff --git a/src/main/api/ipc-main.ts b/src/main/api/ipc-main.ts index e7c8fd35..71435cb8 100644 --- a/src/main/api/ipc-main.ts +++ b/src/main/api/ipc-main.ts @@ -2,12 +2,6 @@ import { createLogger } from '../../common/logger'; import type { InvokeEnvelope, ReplyEnvelope, SendEnvelope } from '../ipc/ipc-protocol'; import type { WebContents } from './web-contents'; -/** - * Main-process IPC — the drop-in equivalent of Electron's `ipcMain`. At most one - * `handle` handler per channel; the transport calls - * {@link IpcMainImpl.dispatch}. - */ - export type IpcMainInvokeEvent = { readonly sender: WebContents; }; @@ -79,11 +73,7 @@ export class IpcMainImpl { this.#handlers.delete(channel); } - /** - * Returns a reply envelope for `invoke` (success or error), `undefined` for - * `send`. - * @internal Called by the IPC transport. - */ + /** @internal The transport's entry: a reply envelope for `invoke`, `undefined` for `send`. */ async dispatch( envelope: SendEnvelope | InvokeEnvelope, event: IpcMainEvent, @@ -123,5 +113,5 @@ export class IpcMainImpl { } } -/** The main-process IPC singleton — Electron's `ipcMain`. */ +/** Electron's `ipcMain`. */ export const ipcMain = new IpcMainImpl(); diff --git a/src/main/api/preload.ts b/src/main/api/preload.ts index c17c1dde..cf32a35d 100644 --- a/src/main/api/preload.ts +++ b/src/main/api/preload.ts @@ -1,9 +1,4 @@ -/** - * A preload runs as a CLASSIC script, so a top-level `import` would throw and - * silently kill it (and any `window.api` it exposes) — module-syntax preloads - * are bundled into an IIFE instead. - */ - +// Classic-script injection: ESM preloads are bundled to an IIFE (D046). import { resolve } from 'node:path'; import { InvalidArgumentError } from '../../common/errors'; import { @@ -13,10 +8,7 @@ import { usesModuleSyntax, } from '../../common/preload-bundle'; -/** - * Resolve and load a `webPreferences.preload` into the classic-script string - * injected at document-start. Returns `undefined` when no preload is set. - */ +/** The classic-script source for `webPreferences.preload`, or `undefined` when unset. */ export const loadPreloadScript = ( preload: string | undefined, bundler: PreloadBundler = defaultPreloadBundler, diff --git a/src/main/api/protocol.ts b/src/main/api/protocol.ts index 399ca5f1..cd803d1b 100644 --- a/src/main/api/protocol.ts +++ b/src/main/api/protocol.ts @@ -1,17 +1,6 @@ import { InvalidArgumentError } from '../../common/errors'; -/** - * Custom URL-scheme registration — the drop-in equivalent of Electron's - * `protocol` module (v1). Custom schemes MUST be registered on the web-view - * config BEFORE the view exists; the backends read - * {@link protocol.getRegisteredSchemes} at web-view creation. - */ - -/** - * What a protocol handler returns for a request. `data` is the response body - * (a `string` is UTF-8 encoded; a `Uint8Array` is served verbatim). `mimeType` - * defaults to `text/html`. - */ +/** String `data` is UTF-8 encoded, bytes go out verbatim; `mimeType` defaults to `text/html`. */ export type ProtocolResponse = { readonly data: string | Uint8Array; readonly mimeType?: string; @@ -29,7 +18,6 @@ export type BuiltProtocolResponse = { readonly mimeType: string; }; -/** The default MIME type when a handler does not specify one. */ export const DEFAULT_MIME_TYPE = 'text/html'; /** Canonical registry key: lowercased, trimmed, trailing `:` or `://` stripped. */ @@ -39,11 +27,7 @@ export const normalizeScheme = (scheme: string): string => .toLowerCase() .replace(/:(\/\/)?$/, ''); -/** - * Extract the (lowercased) scheme from a full URL, or `undefined` if the URL has - * no `scheme:` prefix. Does not depend on `URL` so a custom scheme parses even - * where the WHATWG parser would reject it. - */ +/** Lowercased scheme of `url`, or `undefined`; avoids `URL`, which rejects some custom schemes. */ export const schemeOfUrl = (url: string): string | undefined => { const match = /^([a-zA-Z][a-zA-Z0-9+.-]*):/.exec(url); return match?.[1]?.toLowerCase(); @@ -86,10 +70,8 @@ const ENGINE_SCHEMES: ReadonlySet = new Set([ ]); /** - * Register `handler` to serve requests for `scheme`; re-registering replaces it. - * - * Schemes must be registered BEFORE the window/web view that serves them is - * created — the backends read {@link getRegisteredSchemes} at view creation. + * Re-registering replaces the handler. Register BEFORE creating the window that serves the + * scheme: the backends read {@link getRegisteredSchemes} only at web-view creation. */ const handle = (scheme: string, handler: ProtocolHandler): void => { const normalized = normalizeScheme(scheme); @@ -104,21 +86,15 @@ const handle = (scheme: string, handler: ProtocolHandler): void => { registry.set(normalized, handler); }; -/** Remove the handler for `scheme`. No-op if it was not registered. */ const unhandle = (scheme: string): void => { registry.delete(normalizeScheme(scheme)); }; -/** Whether `scheme` currently has a registered handler. */ const isProtocolHandled = (scheme: string): boolean => registry.has(normalizeScheme(scheme)); -/** Every currently registered scheme, normalized. */ const getRegisteredSchemes = (): string[] => [...registry.keys()]; -/** - * Serve `url`. Returns `undefined` for an unregistered scheme, an unparseable - * URL, or a handler that declined. - */ +/** `undefined` for an unregistered scheme, an unparseable URL, or a handler that declined. */ const dispatch = (url: string): BuiltProtocolResponse | undefined => { const scheme = schemeOfUrl(url); if (scheme === undefined) { @@ -131,7 +107,7 @@ const dispatch = (url: string): BuiltProtocolResponse | undefined => { return buildProtocolResponse(handler, { url }); }; -/** The `protocol` module — Electron-compatible custom URL-scheme registration. */ +/** Electron's `protocol`, for custom schemes only. */ export const protocol = { handle, unhandle, diff --git a/src/main/api/session.ts b/src/main/api/session.ts index afdf964d..10f896e7 100644 --- a/src/main/api/session.ts +++ b/src/main/api/session.ts @@ -1,12 +1,4 @@ -/** - * Session - a drop-in subset of Electron's `session` / `Session`. - * - * `setUserAgent(ua)` applies only to windows created AFTERWARD, at construction - * (before their first navigation); change a live one with - * `webContents.setUserAgent(ua)`. Kept free of a `BrowserWindow` import so it - * can be read at window construction without a cycle. - */ - +// No BrowserWindow import: windows read the session at construction (a cycle otherwise). import { InvalidArgumentError, UnsupportedPlatformError } from '../../common/errors'; import { selectBackend } from '../platform/index'; import { ensureNativeStarted } from '../bootstrap'; @@ -23,9 +15,9 @@ import { windowsSessionBackend } from '../platform/windows/windows-session'; export type SessionBackend = { clearStorageData(): Promise; - /** Resolve the cookies matching `filter` (already filtered by the backend). */ + /** Already filtered by the backend. */ getCookies(filter: CookieFilter): Promise; - /** Store a fully normalized cookie (the API layer derives domain/path). */ + /** A fully normalized cookie; the api layer derives domain and path. */ setCookie(cookie: Cookie): Promise; /** Delete every cookie named `name` that matches `url`'s host and path. */ removeCookie(url: string, name: string): Promise; @@ -39,11 +31,10 @@ const macosBackend: SessionBackend = { }; const linuxBackend: SessionBackend = { - // WebKitWebsiteDataManager clearing is a follow-up (see PARITY.md). clearStorageData: () => Promise.reject( new UnsupportedPlatformError('session.clearStorageData is not yet wired on Linux'), - ), + ), // ponytail: wire WebKitWebsiteDataManager clearing getCookies: (filter) => linuxCookies.getCookies(filter), setCookie: (cookie) => linuxCookies.setCookie(cookie), removeCookie: (url, name) => linuxCookies.removeCookie(url, name), @@ -62,33 +53,27 @@ export const setSessionBackendForTesting = (fake: SessionBackend | undefined): v setForTesting(fake); }; -/** - * Electron's `session.cookies` subset. Works on macOS and Linux; every method - * rejects on Windows (the WinCairo WebKit C API gap - see windows-session.ts). - */ +/** Electron's `session.cookies` subset; every method rejects on Windows (no WinCairo API). */ export class Cookies { /** - * Start the native app first: cookie completion handlers are delivered by the - * run-loop pump, so a call before start would hang to its timeout instead. + * Completion handlers arrive on the run-loop pump, so a call before start would hang to its + * timeout. A fake backend has no pump, and unit tests must never need a display. */ #ensureStarted(): void { - // With a fake backend installed there is no pump to start, and unit tests - // must never require a display. if (!fakeInstalled) { ensureNativeStarted(); } } - /** Resolve the cookies matching `filter` (all cookies when omitted). */ + /** All cookies when `filter` is omitted. */ get(filter: CookieFilter = {}): Promise { this.#ensureStarted(); return getBackend().getCookies(filter); } /** - * Store a cookie. `details.url` is required; domain/path derive from it when - * absent. macOS accepts but cannot persist `httpOnly` (no public NSHTTPCookie - * property key); Linux persists it. + * Domain and path derive from `details.url`; an explicit `domain` is dot-prefixed. macOS + * cannot persist `httpOnly` (no public NSHTTPCookie key); Linux does. */ async set(details: CookieSetDetails): Promise { if (typeof details.url !== 'string' || details.url === '') { @@ -98,7 +83,7 @@ export class Cookies { return getBackend().setCookie(cookieFromSetDetails(details)); } - /** Delete every cookie named `name` matching `url`'s host and path. */ + /** Deletes every cookie named `name` that would be sent to `url`, `secure` aside. */ async remove(url: string, name: string): Promise { if (typeof url !== 'string' || url === '') { throw new InvalidArgumentError('cookies.remove requires a url'); @@ -114,15 +99,14 @@ export class Cookies { export class Session { #userAgent = ''; - /** Cookie store access (Electron's `session.cookies`). */ readonly cookies = new Cookies(); - /** The session's User-Agent override, or `''` when none is set. */ + /** `''` when no override is set. */ getUserAgent(): string { return this.#userAgent; } - /** Applies to web contents created after this call, not to existing ones. */ + /** Applies to windows created afterwards; use `webContents.setUserAgent` for a live one. */ setUserAgent(userAgent: string): void { this.#userAgent = userAgent; } @@ -132,13 +116,13 @@ export class Session { return getBackend().clearStorageData(); } - /** Clear the override (revert to the platform default). Test-only convenience. */ + /** @internal */ resetForTesting(): void { this.#userAgent = ''; } } -/** The `session` module - Electron's `session.defaultSession`. */ +/** Electron's `session`, with `defaultSession` only. */ export const session: { readonly defaultSession: Session } = { defaultSession: new Session(), }; diff --git a/src/main/api/web-contents.ts b/src/main/api/web-contents.ts index 882b8418..45a6b2fc 100644 --- a/src/main/api/web-contents.ts +++ b/src/main/api/web-contents.ts @@ -13,13 +13,6 @@ import type { import { ipcMain } from './ipc-main'; import { type NativeImage, nativeImage } from './native-image'; -/** - * Controls and observes the content rendered inside a {@link BrowserWindow} — - * the drop-in equivalent of Electron's `webContents`. Content methods on - * `BrowserWindow` delegate here (D025). Construction bridges the native web view - * to the {@link ipcMain} singleton, so there is no per-window IPC wiring. - */ - const log = createLogger('web-contents'); export type LoadFileOptions = { @@ -72,6 +65,7 @@ const buildRemoveCssScript = (key: string): string => } })()`; +/** Electron's `webContents`; construction wires its view to {@link ipcMain} (D025). */ export class WebContents extends EventEmitter { /** Process-unique and never reused within a run. */ readonly id: number; @@ -127,10 +121,7 @@ export class WebContents extends EventEmitter { this.#native.loadURL(url); } - /** - * The path is percent-encoded, so spaces/`#`/`?` in the FILE NAME load - * correctly — pass a fragment via `options.hash`, never inside `filePath`. - */ + /** `filePath` is percent-encoded, so a fragment goes in `options.hash`, never in the path. */ loadFile(filePath: string, options?: LoadFileOptions): void { const absolute = isAbsolute(filePath) ? filePath : resolve(filePath); if (absolute.startsWith('\\\\')) { @@ -193,22 +184,19 @@ export class WebContents extends EventEmitter { } /** - * Resolves to the script's COMPLETION value; a returned Promise is awaited. - * Only JSON-serializable results survive (`JSON.stringify` semantics). + * Resolves to the script's COMPLETION value, a returned Promise awaited; a result JSON cannot + * encode rejects. Runs through page-world `eval`, so a CSP without 'unsafe-eval' rejects it. */ async executeJavaScript(code: string): Promise { return this.#native.executeJavaScript(code); } - /** - * macOS only: neither WebKitGTK nor the WinCairo C API exposes a - * page-to-PDF-bytes call, so Linux and Windows reject. - */ + /** macOS only; WebKitGTK and WinCairo have no page-to-PDF call, so Linux and Windows reject. */ async printToPDF(): Promise { return Buffer.from(await this.#native.printToPDF()); } - /** macOS and Linux; Windows rejects until its snapshot path is wired. */ + /** macOS and Linux; Windows rejects (WinCairo has no UI-process snapshot). */ async capturePage(): Promise { return nativeImage.createFromBuffer(await this.#native.capturePage()); } @@ -258,11 +246,7 @@ export class WebContents extends EventEmitter { return this.#userAgent; } - /** - * The page receives a real `isTrusted === true` event, which a - * script-dispatched event cannot fake. Implemented on Windows; other backends - * throw `UnsupportedPlatformError`. - */ + /** Delivers an `isTrusted` event through the engine; Windows only, macOS and Linux throw. */ 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 @@ -285,9 +269,8 @@ export class WebContents extends EventEmitter { } /** - * The native popup is ALWAYS blocked in v1, `allow` included — child-window - * creation is unsupported, so apps typically `shell.openExternal(url)` and - * return `deny`. + * The popup is always blocked, `allow` included (no child windows), so apps typically + * `shell.openExternal(url)` and return `deny`. Windows never calls the handler. */ setWindowOpenHandler(handler: (details: { url: string }) => { action: 'allow' | 'deny' }): void { this.#native.setWindowOpenHandler((url) => { diff --git a/src/main/ipc/exec-wrapper.ts b/src/main/ipc/exec-wrapper.ts index bfdd5633..f937163e 100644 --- a/src/main/ipc/exec-wrapper.ts +++ b/src/main/ipc/exec-wrapper.ts @@ -1,23 +1,12 @@ -/** - * Builds the page-world wrapper script for `WebContents.executeJavaScript`. - * - * On every backend the completion handler cannot be passed to the native - * `evaluateJavaScript` call (a real Objective-C block crashes Bun on macOS, D022; - * a per-call `GAsyncReadyCallback` JSCallback is closed mid-invocation on Linux, - * freeing its trampoline), so the result comes back out-of-band: the wrapper posts - * `{ execId, ok, result?, error? }` as JSON to the `handlerName` message handler, - * and only JSON-serializable results survive. - * - * User code runs via indirect `(0, eval)` so a bare expression resolves to its - * completion value, matching Electron. - */ -/** - * How long `executeJavaScript` waits for its out-of-band result before rejecting. - * Generous (2 min) and identical on every backend, so long in-page work is not - * cut off. - */ +/** How long `executeJavaScript` waits for its out-of-band result, on every backend. */ export const EXEC_TIMEOUT_MS = 120_000; +/** + * The page-world wrapper for `executeJavaScript`. It posts `{ execId, ok, result | error }` as + * JSON to `handlerName` so every backend shares one out-of-band path (on Linux a per-call + * GAsyncReadyCallback JSCallback would be closed mid-invocation; D022b blocks would work on + * macOS). Indirect `(0, eval)` resolves a bare expression to its completion value, as Electron. + */ export const buildExecWrapper = (execId: number, handlerName: string, code: string): string => { const id = JSON.stringify(execId); const name = JSON.stringify(handlerName); diff --git a/src/main/ipc/ipc-protocol.ts b/src/main/ipc/ipc-protocol.ts index 9c10243f..b7e91170 100644 --- a/src/main/ipc/ipc-protocol.ts +++ b/src/main/ipc/ipc-protocol.ts @@ -1,11 +1,6 @@ import { InvalidArgumentError } from '../../common/errors'; -/** - * Wire protocol for Bunmaska IPC (D021) — JSON envelopes crossing renderer ⇄ main. - * - `send` — fire-and-forget event on a channel (either direction). - * - `invoke` — request expecting a `reply`, correlated by `id` (renderer→main). - * - `reply` — response to an `invoke` (main→renderer). - */ +// JSON wire format for IPC (D021): send (either way) | invoke (id-correlated) | reply. export type SendEnvelope = { readonly kind: 'send'; From 946dcbe9be502898961b91ed38ed3a8e3c4883fc Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:00:56 -0700 Subject: [PATCH 135/586] chore: correct the seam contract and trim platform comments --- src/main/platform/cstr.ts | 5 +- src/main/platform/dlopen.ts | 8 +- src/main/platform/dom-ready.ts | 10 +- src/main/platform/index.ts | 13 +- src/main/platform/native.ts | 206 ++++++++------------------- src/main/platform/window-controls.ts | 27 +--- 6 files changed, 75 insertions(+), 194 deletions(-) diff --git a/src/main/platform/cstr.ts b/src/main/platform/cstr.ts index 4350efaa..34ce21c5 100644 --- a/src/main/platform/cstr.ts +++ b/src/main/platform/cstr.ts @@ -1,5 +1,2 @@ -/** - * Encode a JS string as a null-terminated UTF-8 buffer for a C `const char *`. - * Bun's `FFIType.cstring` does not add the trailing null itself — the caller must. - */ +/** UTF-8 for a C `const char *`, NUL-terminated here because `FFIType.cstring` does not. */ export const cstr = (input: string): Uint8Array => new TextEncoder().encode(`${input}\0`); diff --git a/src/main/platform/dlopen.ts b/src/main/platform/dlopen.ts index 0d7c52b9..7782b992 100644 --- a/src/main/platform/dlopen.ts +++ b/src/main/platform/dlopen.ts @@ -1,11 +1,9 @@ import { dlopen as bunDlopen, type FFIFunction, type Library, type Pointer } from 'bun:ffi'; /** - * `dlopen` with pointer returns typed as `Pointer | null`. bun-types 1.4 widens a - * `FFIType.ptr` return to `Pointer | bigint | null`, but the runtime hands back a - * number (probed on Bun 1.4.2: `malloc` returns `typeof "number"`), and every - * backend already treats a pointer as one. Narrowing here keeps the `bigint` - * branch out of all the call sites. `u64` returns stay `bigint`. + * bun-types 1.4 widens a `FFIType.ptr` return to `Pointer | bigint | null`, but the runtime + * returns a number (probed on Bun 1.4.2), so pointer returns narrow to `Pointer | null` here + * instead of at every call site. `u64` returns stay `bigint`. */ type NarrowReturn = [R] extends [bigint] ? R diff --git a/src/main/platform/dom-ready.ts b/src/main/platform/dom-ready.ts index 9e2c0479..f8b1e22c 100644 --- a/src/main/platform/dom-ready.ts +++ b/src/main/platform/dom-ready.ts @@ -1,13 +1,7 @@ -/** - * Page-world `dom-ready` injection: no native delegate reports DOMContentLoaded, so - * a page-world script posts to a dedicated script-message handler that the backend - * routes to a `dom-ready` navigation event. Every backend injects this same script. - */ - -/** The page-world script-message handler name the dom-ready script posts to. */ +// No native delegate reports DOMContentLoaded, so every backend injects this page-world +// script; it posts for the main frame only, as Electron's `dom-ready` does. export const DOM_READY_HANDLER_NAME = 'bunmaskaDomReady'; -/** The page-world script that fires once the document is ready. */ export const generateDomReadyScript = (): string => `(() => { if (window !== window.top) { diff --git a/src/main/platform/index.ts b/src/main/platform/index.ts index 5b8e18d1..9e98a6d8 100644 --- a/src/main/platform/index.ts +++ b/src/main/platform/index.ts @@ -5,11 +5,7 @@ import { createMacOSApplication } from './macos/cocoa-backend'; import type { NativeApplication } from './native'; import { createWindowsApplication } from './windows/windows-backend'; -/** - * The single runtime platform-selection point; nothing above `platform/` imports a - * concrete backend directly (D024). Every backend's FFI loaders are lazy, so - * importing the Windows backend on macOS (and vice versa) opens no shared object. - */ +/** Every backend's FFI loaders are lazy, so importing another OS's backend opens no library. */ export const createNativeApplication = (): NativeApplication => { const platform = currentPlatform(); switch (platform) { @@ -24,17 +20,14 @@ export const createNativeApplication = (): NativeApplication => { } }; -/** - * One backend per platform, resolved on first use, with a test override. - * `fallback` is for modules that degrade instead of throwing (safeStorage). - */ +/** One backend per platform, picked on every call, with a test override. */ export const selectBackend = ( name: string, backends: { readonly macos: () => T; readonly linux: () => T; readonly windows: () => T; - readonly fallback?: () => T; + readonly fallback?: () => T; // ponytail: unreachable, currentPlatform() throws first }, ): { readonly get: () => T; readonly setForTesting: (fake: T | undefined) => void } => { let override: T | undefined; diff --git a/src/main/platform/native.ts b/src/main/platform/native.ts index 7922cb67..3b4086c9 100644 --- a/src/main/platform/native.ts +++ b/src/main/platform/native.ts @@ -1,10 +1,7 @@ -/** - * Backend-neutral contracts for the native platform layer: no platform-specific - * handle (`id`, `SEL`, `GtkWidget*`) ever appears here — the seam speaks only plain - * TS: numbers, strings, and callbacks (D024). - */ +// The backend seam (D024): plain TS values and callbacks; a native handle crosses only as an +// opaque bigint (popupMenu). This JSDoc is the contract every backend implements. -/** A rectangle in screen/content coordinates. */ +/** Screen or content coordinates. */ export type Rect = { readonly x: number; readonly y: number; @@ -12,32 +9,25 @@ export type Rect = { readonly height: number; }; -/** Options for creating a native window + its embedded web view. */ export type NativeWindowOptions = { readonly width: number; readonly height: number; readonly title: string; readonly show: boolean; - /** Whether the window is user-resizable (default `true`). */ + /** Default `true`. */ readonly resizable?: boolean; - /** Whether to draw the OS title bar / frame (default `true`; `false` = frameless). */ + /** `false` is frameless; default `true`. */ readonly frame?: boolean; - /** Whether to open in fullscreen (default `false`). */ + /** Default `false`. */ readonly fullscreen?: boolean; /** - * Resolved source of the user preload script, injected at document-start in - * all frames AFTER the built-in bridge bootstrap. Undefined when no preload - * was configured. The api layer resolves the path and reads the file; the - * seam carries only the source string, never a path or handle (D024). + * User preload SOURCE (never a path, D024), injected at document-start after the bridge + * bootstrap. Every backend injects it into sub-frames too, cross-origin iframes included. */ readonly preloadScript?: string; }; -/** - * A navigation lifecycle event surfaced from the backend, mapped 1:1 to an - * Electron `webContents` event. `did-fail-load` carries the failure detail - * (`errorCode`/`errorDescription`); the others carry none. - */ +/** Maps 1:1 to the Electron `webContents` event; only `did-fail-load` carries detail. */ export type NativeNavigationEvent = | { readonly type: 'did-start-loading' } | { readonly type: 'did-stop-loading' } @@ -50,117 +40,79 @@ export type NativeNavigationEvent = readonly errorDescription: string; }; -/** A mouse button for a synthesized {@link MouseInputEvent}. */ export type MouseButton = 'left' | 'middle' | 'right'; -/** - * A synthesized mouse event — the subset of Electron's `MouseInputEvent` Bunmaska - * delivers. Coordinates are logical pixels relative to the top-left of the web - * view's content area. - */ +/** Electron's `MouseInputEvent` subset; logical pixels from the web view's top-left. */ export type MouseInputEvent = { readonly type: 'mouseDown' | 'mouseUp' | 'mouseMove'; readonly x: number; readonly y: number; - /** The button for `mouseDown`/`mouseUp` (default `left`). Ignored for `mouseMove`. */ + /** Default `left`; ignored for `mouseMove`. */ readonly button?: MouseButton; }; -/** - * A synthesized keyboard event — the subset of Electron's `KeyboardInputEvent` - * Bunmaska delivers. `keyCode` is an Electron accelerator key string: a single - * character (`'a'`, `'5'`) or a named key (`'Enter'`, `'Escape'`, `'Tab'`). - */ +/** Electron's `KeyboardInputEvent` subset; `keyCode` is an accelerator key (`'a'`, `'Enter'`). */ export type KeyboardInputEvent = { readonly type: 'keyDown' | 'keyUp' | 'char'; readonly keyCode: string; }; -/** An input event accepted by {@link NativeWebContents.sendInputEvent}. */ export type NativeInputEvent = MouseInputEvent | KeyboardInputEvent; /** - * The web view embedded in a window. Bunmaska's `WebContents` delegates to this. - * - * The IPC surface (renderer messaging + navigation callbacks) is added to this - * interface in the IPC phase, alongside its implementation — kept out until - * then so the contract never advertises a method the backend does not provide. + * The web view in a window. The api layer registers each `on*` callback once per view; a + * backend that also listens internally must keep both (append, never replace), or its own + * hook silently disappears (Linux derives `ready-to-show` from `onNavigation`). */ export interface NativeWebContents { - /** Navigate to a URL (http/https/file/about). */ + /** Any URL WebKit loads, registered custom schemes included. */ loadURL(url: string): void; - /** Load an inline HTML string with an optional base URL for relative refs. */ + /** @internal Test hook; no api-layer caller. */ loadHTML(html: string, baseUrl?: string): void; - /** The web view's current URL, or `''` before the first navigation. */ + /** `''` before the first navigation. */ getURL(): string; - /** The page's current title, or `''` if none. */ + /** `''` if the page has none. */ getTitle(): string; - /** Reload the current page. */ reload(): void; - /** Reload the current page, bypassing the cache. */ reloadIgnoringCache(): void; - /** Stop any in-progress load. */ stop(): void; - /** Navigate back one entry in the session history, if possible. */ goBack(): void; - /** Navigate forward one entry in the session history, if possible. */ goForward(): void; - /** Whether there is a previous history entry to go back to. */ canGoBack(): boolean; - /** Whether there is a next history entry to go forward to. */ canGoForward(): boolean; /** - * Evaluate JS in the page world and resolve to the script's completion value - * (Electron semantics). Only JSON-serializable results survive the boundary - * (`JSON.stringify` semantics); a thrown error or rejected Promise rejects. + * Runs in the page world and resolves to the completion value. Only JSON-serializable + * results survive (anything else rejects); a throw or a rejected Promise rejects. */ executeJavaScript(code: string): Promise; - /** - * Render the page to a PDF and resolve to its bytes (Electron's `printToPDF`). - * Rejects on platforms without a page-to-PDF API (WebKitGTK, WinCairo). - */ + /** PDF bytes; rejects on Linux and Windows (no page-to-PDF API). */ printToPDF(): Promise; - /** - * Capture the page to a PNG image and resolve to its bytes (Electron's - * `capturePage`). Rejects where it is not yet wired (Windows). - */ + /** PNG bytes; rejects on Windows (WinCairo has no UI-process snapshot). */ capturePage(): Promise; - /** Open the native web inspector (devtools) for this view. Best-effort. */ + /** Best-effort. */ openDevTools(): void; - /** Close the native web inspector (devtools) for this view. Best-effort. */ + /** Best-effort. */ closeDevTools(): void; - /** Set the page zoom factor (`1` = 100%). */ + /** `1` is 100%. */ setZoomFactor(factor: number): void; - /** Override the User-Agent string sent on subsequent navigations. */ + /** Applies to subsequent navigations. */ setUserAgent(userAgent: string): void; /** - * Synthesize a trusted input event into the page (Electron's - * `webContents.sendInputEvent`). Delivered through the engine's native input - * path, so the page sees `isTrusted === true` — unlike a script-dispatched DOM - * event. Implemented on Windows (WinCairo); other backends throw until wired. + * 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. */ sendInputEvent(event: NativeInputEvent): void; - /** Deliver a raw IPC envelope (JSON) to the renderer's preload bridge. */ + /** Delivers a raw JSON envelope to the renderer's bridge. */ sendEnvelopeToRenderer(envelopeJson: string): void; - /** Register a callback for raw IPC envelopes (JSON) posted by the renderer. */ onRendererEnvelope(callback: (envelopeJson: string) => void): void; - /** Register a callback for navigation lifecycle events. */ onNavigation(callback: (event: NativeNavigationEvent) => void): void; - /** - * Register a callback invoked when the page requests a new window - * (`window.open` / `target=_blank`), receiving the target URL. The native - * popup is always blocked (v1); the handler decides what to do with the URL. - */ + /** Gets the URL of a `window.open`; the popup is always blocked. Windows never calls it. */ setWindowOpenHandler(callback: (url: string) => void): void; } /** - * Non-preventable window lifecycle events surfaced from the backend. - * - * Each maps to an Electron `BrowserWindow` event of the same name. The - * preventable `close` is NOT in this set — it flows through {@link - * NativeWindow.onClose} so a listener can veto it; the final `closed` flows - * through {@link NativeWindow.onClosed}. + * Non-preventable `BrowserWindow` events of the same name. The vetoable `close` flows through + * {@link NativeWindow.onClose} and the final `closed` through {@link NativeWindow.onClosed}. */ export type WindowEventType = | 'focus' @@ -175,129 +127,91 @@ export type WindowEventType = | 'restore' | 'ready-to-show'; -/** A native top-level window. */ export interface NativeWindow { - /** The window's web contents. */ readonly webContents: NativeWebContents; setTitle(title: string): void; getTitle(): string; setSize(width: number, height: number): void; getBounds(): Rect; - /** Move the window's top-left corner to `(x, y)` (best-effort on macOS/Wayland). */ + /** Top-left corner; a no-op on Linux (GTK4 has no client-side positioning). */ setPosition(x: number, y: number): void; - /** Set the window's position AND size in one call (best-effort on macOS/Wayland). */ + /** Linux applies the size only. */ setBounds(bounds: Rect): void; - /** Enable or disable user resizing of the window. */ setResizable(resizable: boolean): void; - /** Set the window's opacity in `[0, 1]` (`1` = fully opaque). */ + /** `[0, 1]`; `1` is fully opaque. */ setOpacity(opacity: number): void; - /** Constrain the window's minimum content size. */ + /** Constrains the CONTENT size. */ setMinimumSize(width: number, height: number): void; - /** Center the window on the current screen (best-effort on Linux/Wayland). */ + /** No-op on Linux. */ center(): void; show(): void; hide(): void; isVisible(): boolean; - /** Bring the window to the front and give it keyboard focus. */ focus(): void; - /** Minimize the window to the dock/taskbar. */ minimize(): void; - /** Maximize (zoom) the window to fill the available screen area. */ maximize(): void; - /** Restore a maximized window to its previous size. */ unmaximize(): void; isMaximized(): boolean; isMinimized(): boolean; - /** Restore a minimized window. */ + /** Un-minimizes. */ restore(): void; - /** Whether the window currently has keyboard focus. */ isFocused(): boolean; - /** Enter or leave fullscreen. */ setFullScreen(flag: boolean): void; isFullScreen(): boolean; - /** Keep the window above others (macOS; best-effort/no-op elsewhere). */ + /** No-op on Linux (GTK4 dropped keep-above). */ setAlwaysOnTop(flag: boolean): void; - /** Close and destroy the window. Idempotent. */ + /** A close REQUEST: consults {@link onClose}, so it can be vetoed. Idempotent. */ close(): void; - /** Force-close the window, bypassing the preventable `close` listener. */ + /** Closes without consulting {@link onClose}. */ destroy(): void; - /** Register a callback fired once when the window is closed. */ + /** Fires once, after teardown. */ onClosed(callback: () => void): void; - /** - * Register a callback for a non-preventable window lifecycle event. The same - * type may be registered once; the backend invokes it each time the native - * event fires. - */ + /** One registration per type; invoked each time the native event fires. */ onWindowEvent(type: WindowEventType, callback: () => void): void; /** - * Register the preventable-close callback, consulted BEFORE the window closes - * on EVERY close path (title-bar button, programmatic `close()`, app quit). - * Return `true` to VETO the close (the window stays open); return `false` to - * allow it, after which the backend runs teardown and fires `onClosed`. + * Consulted before the title-bar button or `close()` closes the window: return `true` to + * VETO (the window stays open), `false` to allow, after which teardown runs and `onClosed` + * fires. Linux and Windows app quit also routes through it; macOS app quit does not. */ onClose(callback: () => boolean): void; /** - * Show `menuHandle` (a realized native menu) as a context menu anchored to this - * window at content-relative (`x`, `y`). macOS: BLOCKING — runs AppKit's nested - * menu-tracking loop until dismissed (the same nested-loop class as the modal - * dialogs, D020-safe). Linux: non-blocking — the popover shows and item - * activation arrives later via the cooperative pump. + * Shows a realized native menu at content-relative (`x`, `y`). macOS and Windows BLOCK in a + * nested menu-tracking loop until dismissed (D020-safe); Windows also destroys the handle. + * Linux is non-blocking: activation arrives later via the cooperative pump. */ popupMenu(menuHandle: bigint, x: number, y: number): void; - /** Dismiss a context menu shown by {@link popupMenu}. Idempotent / best-effort. */ + /** Best-effort; idempotent. */ closePopupMenu(): void; } -/** - * macOS-only application operations (AppKit's `NSApplication`): activation - * policy, hide/show, and the dock tile. Present only on the macOS backend - * ({@link NativeApplication.appKit}); other platforms omit it. - */ +/** AppKit-only application operations; other backends omit {@link NativeApplication.appKit}. */ export interface NativeAppKit { setActivationPolicy(policy: 'regular' | 'accessory' | 'prohibited'): void; hide(): void; show(): void; isHidden(): boolean; isActive(): boolean; - /** Set the dock-tile badge label (empty string clears it). */ + /** `''` clears it. */ setDockBadge(label: string): void; - /** The current dock-tile badge label, or `''`. */ getDockBadge(): string; - /** Bounce the dock icon (`critical` bounces until focused). */ + /** `critical` bounces until the app is focused. */ bounceDock(critical: boolean): void; } -/** The native application host: lifecycle + window factory. */ export interface NativeApplication { - /** Bootstrap the native app and begin pumping its run loop. Idempotent. */ + /** Starts pumping the native run loop. Idempotent. */ start(): void; - /** Register a callback fired once the app is ready to create windows. */ onReady(callback: () => void): void; - /** Create a native window. */ createWindow(options: NativeWindowOptions): NativeWindow; - /** Stop the run loop and release the application. */ + /** Stops the pump; Linux and Windows first close every window (vetoable). */ quit(): void; - /** - * Register a callback fired when the app is re-activated (Electron's `activate` - * — e.g. a macOS Dock-icon click), receiving whether any windows are visible. - * Optional: platforms without an activation concept (Linux) omit it. Must be - * registered before {@link start}. - */ + /** Electron's `activate` (a Dock-icon click). macOS only; register before {@link start}. */ onActivate?(callback: (hasVisibleWindows: boolean) => void): void; - /** - * Register a callback for an OS request to open a URL (custom-scheme deep link; - * Electron's `open-url`). macOS-only; other backends omit it. Register before - * {@link start}. - */ + /** Electron's `open-url` (a deep link). macOS only; register before {@link start}. */ onOpenUrl?(callback: (url: string) => void): void; - /** - * Register a callback for an OS request to open a file path (file association; - * Electron's `open-file`). macOS-only; other backends omit it. Register before - * {@link start}. - */ + /** Electron's `open-file` (a file association). macOS only; register before {@link start}. */ onOpenFile?(callback: (path: string) => void): void; - /** macOS-only AppKit application operations (activation, hide/show, dock). */ readonly appKit?: NativeAppKit; - /** Show the platform's standard about panel (Electron's `showAboutPanel`). */ + /** macOS and Linux. */ showAboutPanel?(): void; } diff --git a/src/main/platform/window-controls.ts b/src/main/platform/window-controls.ts index dd3358bc..8ce0e024 100644 --- a/src/main/platform/window-controls.ts +++ b/src/main/platform/window-controls.ts @@ -1,27 +1,12 @@ -/** - * The built-in page-world script for custom (frameless) title bars. It does up to - * two things: - * - * 1. (Native-op-channel platforms only.) Exposes `window.__bunmaska.window` - * controls that post `{ op }` to the `bunmaskaWindow` message handler. GATED: - * on a platform with a real isolated world (macOS/Linux) the page world must - * NOT carry a `__bunmaska` handle — that would defeat context isolation. Only - * Windows, whose bridge already lives in the page world, opts in. - * 2. MIRRORS `--app-region` onto `-webkit-app-region`, which macOS WKWebView - * honors for window dragging; custom properties inherit, giving Electron's - * app-region cascade. Engines that ignore it (WinCairo, WebKitGTK) fall back - * to the native window-op handler in (1). - * - * The mirror observes structural changes only, not the `style` attribute it writes, - * so it cannot loop. - */ +// Frameless title bars (D045): mirrors `--app-region` onto `-webkit-app-region`, which only +// macOS WKWebView drags off. The mirror never observes the `style` attribute it writes, so it +// cannot loop. ponytail: no Linux drag yet, wire gdk_toplevel_begin_move via the isolated bridge. export const WINDOW_HANDLER_NAME = 'bunmaskaWindow'; /** - * Build the page-world title-bar script. Pass `nativeOpChannel: true` ONLY where the - * page world IS the bridge world (Windows, which has no separate isolated world); - * on macOS/Linux it must stay false so the page world carries no `__bunmaska` - * handle, leaving only the `--app-region` mirror macOS drags natively off. + * `nativeOpChannel` adds `window.__bunmaska.window` controls and a mousedown drag. Pass it ONLY + * where the page world IS the bridge world (Windows): on macOS/Linux a page-world `__bunmaska` + * would defeat context isolation. */ export function windowControlsScript(options: { nativeOpChannel?: boolean } = {}): string { const ops = options.nativeOpChannel From 5b06d693c1326bd7da1f02143698237a60378b74 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:01:09 -0700 Subject: [PATCH 136/586] fix: read macOS window frames from AppKit and center new windows --- src/main/platform/macos/cocoa-backend.ts | 78 +++++++------------ tests/integration/macos/cocoa-backend.test.ts | 48 +++++++++++- 2 files changed, 74 insertions(+), 52 deletions(-) diff --git a/src/main/platform/macos/cocoa-backend.ts b/src/main/platform/macos/cocoa-backend.ts index 496552d3..c2fa161d 100644 --- a/src/main/platform/macos/cocoa-backend.ts +++ b/src/main/platform/macos/cocoa-backend.ts @@ -1,4 +1,4 @@ -import { FFIType } from 'bun:ffi'; +import { FFIType, ptr } from 'bun:ffi'; import { UnsupportedPlatformError } from '../../../common/errors'; import { createLogger } from '../../../common/logger'; import { @@ -40,6 +40,7 @@ import { msgSendPtr3, msgSendPtr4, msgSendPtrI64U8Ptr, + msgSendPtrI64, msgSendPtrPtr, msgSendPtrReturnsU8, msgSendReturnsI64, @@ -52,7 +53,6 @@ import { createNavigationDelegate } from './cocoa-navigation-delegate'; import { createMacOSDrain } from './cocoa-run-loop'; import { primaryDisplayHeight } from './cocoa-screen'; import { msgSendRectU8 } from './cocoa-msgsend-variants'; -import { readWindowBounds } from './cocoa-window-bounds'; import { createScriptMessageHandler } from './cocoa-script-message-handler'; import { cocoa } from './cocoa-runtime'; import { defineObjcClass } from './cocoa-runtime-class'; @@ -599,8 +599,6 @@ class MacOSWindow implements NativeWindow { readonly #contents: MacOSWebContents; readonly #teardown: () => void; readonly #releaseNative: () => void; - #bounds: Rect; - #frameKnown = false; #tornDown = false; #onClosed: (() => void) | undefined; #onClose: (() => boolean) | undefined; @@ -610,7 +608,6 @@ class MacOSWindow implements NativeWindow { constructor( window: Handle, contents: MacOSWebContents, - bounds: Rect, teardown: () => void, releaseNative: () => void, ) { @@ -618,7 +615,6 @@ class MacOSWindow implements NativeWindow { this.#contents = contents; this.#teardown = teardown; this.#releaseNative = releaseNative; - this.#bounds = bounds; } get webContents(): NativeWebContents { @@ -672,16 +668,6 @@ class MacOSWindow implements NativeWindow { this.emitEvent(zoomed ? 'maximize' : 'unmaximize'); } } - // A user drag/resize is the one path that moves the frame without going - // through our setters; the delegate fires AFTER the window server settles, - // so this is the safe moment to trust its answer. - if (type === 'move' || type === 'resize') { - const real = readWindowBounds(this.#window); - if (real !== undefined) { - this.#bounds = real; - this.#frameKnown = true; - } - } this.#eventHandlers.get(type)?.(); } @@ -702,26 +688,39 @@ class MacOSWindow implements NativeWindow { [rect.x, bottomLeftY, rect.width, rect.height], true, ); - this.#bounds = { ...rect }; - this.#frameKnown = true; } - /** Anchor for a setter: tracked once known, else the server, else tracked. */ - #currentFrame(): Rect { - if (this.#frameKnown) { - return this.#bounds; + /** + * The FRAME rect in top-left global space. `-frame` returns a struct by value + * (D018), so it is read through KVC into an out buffer: AppKit's own model, + * current right after setFrame: and for never-shown windows, unlike the + * asynchronously updated window-server list. + */ + #frame(): Rect { + if (this.#tornDown) { + return { x: 0, y: 0, width: 0, height: 0 }; } - return readWindowBounds(this.#window) ?? this.#bounds; + const rt = cocoa(); + const value = msgSendPtr(this.#window, rt.selectors.get('valueForKey:'), nsString('frame')); + const out = new Float64Array(4); + msgSendPtrI64( + value, + rt.selectors.get('getValue:size:'), + BigInt(ptr(out)), + BigInt(out.byteLength), + ); + const [x = 0, y = 0, width = 0, height = 0] = out; + return { x, y: primaryDisplayHeight() - y - height, width, height }; } setSize(width: number, height: number): void { // Electron's setSize is the WINDOW (frame) size; keep the top-left anchored. - const current = this.#currentFrame(); + const current = this.#frame(); this.#setFrameTopLeft({ x: current.x, y: current.y, width, height }); } setPosition(x: number, y: number): void { - const current = this.#currentFrame(); + const current = this.#frame(); this.#setFrameTopLeft({ x, y, width: current.width, height: current.height }); } @@ -730,19 +729,7 @@ class MacOSWindow implements NativeWindow { } getBounds(): Rect { - // The tracked rect is authoritative once a frame was set or observed: the - // window server updates ASYNCHRONOUSLY, so reading it right after our own - // setFrame would return the stale pre-set rect. Until then (a never-moved - // window whose tracked rect is the creation CONTENT size), one server read - // upgrades to the real frame. - if (!this.#frameKnown) { - const real = readWindowBounds(this.#window); - if (real !== undefined) { - this.#bounds = real; - this.#frameKnown = true; - } - } - return { ...this.#bounds }; + return this.#frame(); } setResizable(resizable: boolean): void { @@ -1046,6 +1033,8 @@ class MacOSApplication implements NativeApplication { // close would dealloc it while we still hold the handle (use-after-free). We // own the lifetime — release explicitly in teardown 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')), @@ -1234,18 +1223,7 @@ class MacOSApplication implements NativeApplication { cocoa().msgSend(window, rt.selectors.get('release')); }; - nativeWindow = new MacOSWindow( - window, - contents, - { - x: 0, - y: 0, - width: options.width, - height: options.height, - }, - teardown, - releaseNative, - ); + nativeWindow = new MacOSWindow(window, contents, teardown, releaseNative); // Set the NSWindowDelegate: it routes `windowShouldClose:` (the preventable // veto) and `windowWillClose:` (teardown + `closed`) plus the key/resize/ diff --git a/tests/integration/macos/cocoa-backend.test.ts b/tests/integration/macos/cocoa-backend.test.ts index b895a668..fd3ae67c 100644 --- a/tests/integration/macos/cocoa-backend.test.ts +++ b/tests/integration/macos/cocoa-backend.test.ts @@ -8,6 +8,7 @@ import { nsString, nsStringToString } from '../../../src/main/platform/macos/coc import { msgSendI64, msgSendPtr, + msgSendPtrI64, msgSendReturnsI64, msgSendReturnsU8, } from '../../../src/main/platform/macos/cocoa-msgsend-variants'; @@ -58,6 +59,15 @@ const weakRefs = (): { }; }; +/** An object's KVC `frame` (NSRect) in Cocoa's bottom-left space. */ +const kvcRect = (object: bigint): { x: number; y: number; width: number; height: number } => { + const rt = cocoa(); + const value = msgSendPtr(object, rt.selectors.get('valueForKey:'), nsString('frame')); + const out = new Float64Array(4); + msgSendPtrI64(value, rt.selectors.get('getValue:size:'), BigInt(ptr(out)), 32n); + return { x: out[0] ?? 0, y: out[1] ?? 0, width: out[2] ?? 0, height: out[3] ?? 0 }; +}; + const waitFor = async (predicate: () => boolean, ms = 3_000): Promise => { const deadline = performance.now() + ms; while (!predicate() && performance.now() < deadline) { @@ -111,13 +121,47 @@ if (currentPlatform() === 'macos') { } }); - test('setSize updates the reported bounds', () => { + test('setSize keeps the top-left corner', () => { const app = createMacOSApplication(); app.start(); try { const win = app.createWindow({ width: 400, height: 300, title: 't', show: false }); + const before = win.getBounds(); win.setSize(640, 480); - expect(win.getBounds()).toEqual({ x: 0, y: 0, width: 640, height: 480 }); + expect(win.getBounds()).toEqual({ x: before.x, y: before.y, width: 640, height: 480 }); + win.destroy(); + } finally { + app.quit(); + } + }); + + test('a never-shown window opens centered and reports its real frame', () => { + const app = createMacOSApplication(); + app.start(); + try { + const win = app.createWindow({ + width: 320, + height: 240, + title: 'hidden-frame', + show: false, + }); + const content = kvcRect( + cocoa().msgSend(nsWindowTitled('hidden-frame'), cocoa().selectors.get('contentView')), + ); + const bounds = win.getBounds(); + expect(bounds.x).toBeGreaterThan(0); + expect(bounds.width).toBe(320); + expect(bounds.height).toBeGreaterThan(content.height); + win.setPosition(100, 120); + expect(win.getBounds()).toEqual({ ...bounds, x: 100, y: 120 }); + win.center(); + expect(win.getBounds()).toEqual(bounds); + expect( + kvcRect( + cocoa().msgSend(nsWindowTitled('hidden-frame'), cocoa().selectors.get('contentView')), + ).height, + ).toBe(240); + win.destroy(); } finally { app.quit(); } From 770b254c93eba397fdd9d5758e104093dfd8701b Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:01:36 -0700 Subject: [PATCH 137/586] chore: replace em dashes in the window and ipc tests --- tests/integration/macos/ipc-e2e.test.ts | 2 +- tests/integration/macos/window-events.test.ts | 4 ++-- tests/unit/main/platform/window-controls.test.ts | 9 +-------- 3 files changed, 4 insertions(+), 11 deletions(-) diff --git a/tests/integration/macos/ipc-e2e.test.ts b/tests/integration/macos/ipc-e2e.test.ts index 4f746132..c58043df 100644 --- a/tests/integration/macos/ipc-e2e.test.ts +++ b/tests/integration/macos/ipc-e2e.test.ts @@ -13,7 +13,7 @@ import type { NativeApplication, NativeWindow } from '../../../src/main/platform * isolation), so the renderer-side test logic ships as a PRELOAD (which runs in * that world) and is triggered via `sendEnvelopeToRenderer` (which also targets * the isolated world). Page-world `executeJavaScript` can no longer reach - * `__bunmaska` — that is the isolation guarantee, proven in `isolation-e2e.test.ts`. + * `__bunmaska` - that is the isolation guarantee, proven in `isolation-e2e.test.ts`. */ const delay = (ms: number): Promise => new Promise((resolve) => setTimeout(resolve, ms)); diff --git a/tests/integration/macos/window-events.test.ts b/tests/integration/macos/window-events.test.ts index 9175fe4a..c036d36c 100644 --- a/tests/integration/macos/window-events.test.ts +++ b/tests/integration/macos/window-events.test.ts @@ -58,7 +58,7 @@ if (currentPlatform() === 'macos') { // `resize` proves the NSWindowDelegate notifications are delivered on the // real backend (windowDidResize:). `focus`/`blur` map to // windowDidBecomeKey:/windowDidResignKey:, which a headless test process - // never receives because it cannot acquire keyboard focus — those are + // never receives because it cannot acquire keyboard focus - those are // covered by the unit suite's fake instead. (Documented platform limit.) const win = new BrowserWindow({ width: 360, height: 240, title: 'resize', show: true }); try { @@ -122,7 +122,7 @@ if (currentPlatform() === 'macos') { expect(win.isDestroyed()).toBe(true); // CRUCIAL use-after-free check: a post-close exec must NOT touch the freed - // WKWebView — the #destroyed guard set by the close-path teardown rejects + // WKWebView - the #destroyed guard set by the close-path teardown rejects // it cleanly instead of crashing. await expect(win.webContents.executeJavaScript('1 + 1')).rejects.toThrow(/destroyed/); }); diff --git a/tests/unit/main/platform/window-controls.test.ts b/tests/unit/main/platform/window-controls.test.ts index f3389b7c..eef98069 100644 --- a/tests/unit/main/platform/window-controls.test.ts +++ b/tests/unit/main/platform/window-controls.test.ts @@ -4,14 +4,7 @@ import { windowControlsScript, } from '../../../../src/main/platform/window-controls'; -/** - * Regression guard for the page-world title-bar script. On platforms with a real - * isolated world (macOS/Linux) the page world must NEVER carry a `__bunmaska` - * handle — that defeats context isolation (and trips the isolation e2e tests). The - * control global is opt-in via `nativeOpChannel`, which only the page-world-bridge - * platform (Windows) sets. This unit test runs on every OS, so the leak is caught - * on Windows CI too, not only on the macOS/Linux e2e runners. - */ +// Runs on every OS, so a page-world `__bunmaska` leak is caught on Windows CI too. describe('windowControlsScript', () => { test('the default (isolated-world platforms) never leaks a __bunmaska handle', () => { const script = windowControlsScript(); From 22bfa9b85921390fcb28d8067092f14494d40671 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:01:40 -0700 Subject: [PATCH 138/586] refactor: drop the unused utility and fullSizeContentView style flags --- src/main/platform/macos/cocoa-style-mask.ts | 10 ---------- .../unit/main/platform/macos/cocoa-style-mask.test.ts | 8 -------- 2 files changed, 18 deletions(-) diff --git a/src/main/platform/macos/cocoa-style-mask.ts b/src/main/platform/macos/cocoa-style-mask.ts index a72c8295..28142490 100644 --- a/src/main/platform/macos/cocoa-style-mask.ts +++ b/src/main/platform/macos/cocoa-style-mask.ts @@ -8,8 +8,6 @@ export type CocoaWindowStyle = { readonly closable?: boolean; readonly miniaturizable?: boolean; readonly resizable?: boolean; - readonly utility?: boolean; - readonly fullSizeContentView?: boolean; }; const STYLE_BITS = { @@ -17,8 +15,6 @@ const STYLE_BITS = { closable: 1 << 1, miniaturizable: 1 << 2, resizable: 1 << 3, - utility: 1 << 4, - fullSizeContentView: 1 << 15, } as const; export const STANDARD_WINDOW_STYLE: CocoaWindowStyle = Object.freeze({ @@ -42,11 +38,5 @@ export const computeWindowStyleMask = (style: CocoaWindowStyle): number => { if (style.resizable === true) { mask |= STYLE_BITS.resizable; } - if (style.utility === true) { - mask |= STYLE_BITS.utility; - } - if (style.fullSizeContentView === true) { - mask |= STYLE_BITS.fullSizeContentView; - } return mask; }; diff --git a/tests/unit/main/platform/macos/cocoa-style-mask.test.ts b/tests/unit/main/platform/macos/cocoa-style-mask.test.ts index 243a2f81..e6eacc72 100644 --- a/tests/unit/main/platform/macos/cocoa-style-mask.test.ts +++ b/tests/unit/main/platform/macos/cocoa-style-mask.test.ts @@ -25,14 +25,6 @@ describe('computeWindowStyleMask', () => { expect(computeWindowStyleMask({ resizable: true })).toBe(1 << 3); }); - test('utility-only is bit 4 (16)', () => { - expect(computeWindowStyleMask({ utility: true })).toBe(1 << 4); - }); - - test('fullSizeContentView-only is bit 15 (32768)', () => { - expect(computeWindowStyleMask({ fullSizeContentView: true })).toBe(1 << 15); - }); - test('combines independent flags via bitwise OR', () => { const mask = computeWindowStyleMask({ titled: true, From 2e709486d25ac3e5a8583d8d7309e11a9e352f5f Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:02:29 -0700 Subject: [PATCH 139/586] test: cover the macOS pre-load send queue with a single send --- tests/integration/macos/cocoa-backend.test.ts | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/tests/integration/macos/cocoa-backend.test.ts b/tests/integration/macos/cocoa-backend.test.ts index fd3ae67c..8f6b4268 100644 --- a/tests/integration/macos/cocoa-backend.test.ts +++ b/tests/integration/macos/cocoa-backend.test.ts @@ -2,6 +2,7 @@ import { describe, expect, jest, test } from 'bun:test'; 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 { retainedBlockCount } from '../../../src/main/platform/macos/cocoa-block'; import { nsString, nsStringToString } from '../../../src/main/platform/macos/cocoa-foundation'; @@ -198,6 +199,33 @@ if (currentPlatform() === 'macos') { } }); + test('a send before the first load reaches the preload exactly once', async () => { + const app = createMacOSApplication(); + app.start(); + try { + const win = app.createWindow({ + width: 320, + height: 240, + title: 't', + show: true, + preloadScript: + "window.__bunmaska.on('early', function (n) { window.__bunmaska.send('got', n); });", + }); + const received: string[] = []; + win.webContents.onRendererEnvelope((json) => received.push(json)); + win.webContents.sendEnvelopeToRenderer( + encodeEnvelope({ kind: 'send', channel: 'early', args: [7] }), + ); + win.webContents.loadHTML('

x

', 'about:blank'); + await waitFor(() => received.length > 0); + await delay(100); + expect(received.map(decodeEnvelope)).toEqual([{ kind: 'send', channel: 'got', args: [7] }]); + win.destroy(); + } finally { + app.quit(); + } + }); + test('executeJavaScript resolves to the script completion value', async () => { const app = createMacOSApplication(); app.start(); From 58868d17c2ba3825f825dff65acc4839608bc3eb Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:04:08 -0700 Subject: [PATCH 140/586] test: close windows and drop cannot-fail macOS backend cases --- tests/integration/macos/cocoa-backend.test.ts | 956 +++++++++--------- .../integration/macos/cocoa-run-loop.test.ts | 138 +-- 2 files changed, 517 insertions(+), 577 deletions(-) diff --git a/tests/integration/macos/cocoa-backend.test.ts b/tests/integration/macos/cocoa-backend.test.ts index 8f6b4268..84be9e6e 100644 --- a/tests/integration/macos/cocoa-backend.test.ts +++ b/tests/integration/macos/cocoa-backend.test.ts @@ -15,6 +15,7 @@ import { } from '../../../src/main/platform/macos/cocoa-msgsend-variants'; import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; import { LIBOBJC_PATH } from '../../../src/main/platform/macos/objc'; +import type { NativeWindow } from '../../../src/main/platform/native'; const delay = (ms: number): Promise => new Promise((resolve) => setTimeout(resolve, ms)); @@ -76,526 +77,517 @@ const waitFor = async (predicate: () => boolean, ms = 3_000): Promise => { } }; -if (currentPlatform() === 'macos') { - describe('MacOSApplication', () => { - test('onReady fires synchronously once started', () => { - const app = createMacOSApplication(); - let ready = false; - app.onReady(() => { - ready = true; - }); - app.start(); - try { - expect(ready).toBe(true); - } finally { - app.quit(); +/** Load `html` and resolve once the page has finished loading. */ +const loadPage = (win: NativeWindow, html: string): Promise => + new Promise((resolve) => { + win.webContents.onNavigation((event) => { + if (event.type === 'did-finish-load') { + resolve(); } }); + win.webContents.loadHTML(html, 'about:blank'); + }); - test('start is idempotent', () => { - const app = createMacOSApplication(); - app.start(); - try { - expect(() => app.start()).not.toThrow(); - } finally { - app.quit(); - } +const onMac = describe.skipIf(currentPlatform() !== 'macos'); + +onMac('MacOSApplication', () => { + test('onReady fires synchronously once started', () => { + const app = createMacOSApplication(); + let ready = false; + app.onReady(() => { + ready = true; }); + app.start(); + try { + expect(ready).toBe(true); + } finally { + app.quit(); + } }); - describe('MacOSWindow + WebContents end-to-end', () => { - test('creates a visible window with the requested title and bounds', () => { - const app = createMacOSApplication(); - app.start(); - try { - const win = app.createWindow({ - width: 480, - height: 320, - title: 'Bunmaska Test', - show: true, - }); - expect(win.isVisible()).toBe(true); - expect(win.getTitle()).toBe('Bunmaska Test'); - expect(win.getBounds().width).toBe(480); - } finally { - app.quit(); - } - }); + test('start is idempotent', () => { + const app = createMacOSApplication(); + app.start(); + try { + expect(() => app.start()).not.toThrow(); + } finally { + app.quit(); + } + }); +}); - test('setSize keeps the top-left corner', () => { - const app = createMacOSApplication(); - app.start(); - try { - const win = app.createWindow({ width: 400, height: 300, title: 't', show: false }); - const before = win.getBounds(); - win.setSize(640, 480); - expect(win.getBounds()).toEqual({ x: before.x, y: before.y, width: 640, height: 480 }); - win.destroy(); - } finally { - app.quit(); - } - }); +onMac('MacOSWindow + WebContents end-to-end', () => { + test('creates a visible window with the requested title and bounds', () => { + const app = createMacOSApplication(); + app.start(); + try { + const win = app.createWindow({ + width: 480, + height: 320, + title: 'Bunmaska Test', + show: true, + }); + expect(win.isVisible()).toBe(true); + expect(win.getTitle()).toBe('Bunmaska Test'); + expect(win.getBounds().width).toBe(480); + win.destroy(); + } finally { + app.quit(); + } + }); - test('a never-shown window opens centered and reports its real frame', () => { - const app = createMacOSApplication(); - app.start(); - try { - const win = app.createWindow({ - width: 320, - height: 240, - title: 'hidden-frame', - show: false, - }); - const content = kvcRect( - cocoa().msgSend(nsWindowTitled('hidden-frame'), cocoa().selectors.get('contentView')), - ); - const bounds = win.getBounds(); - expect(bounds.x).toBeGreaterThan(0); - expect(bounds.width).toBe(320); - expect(bounds.height).toBeGreaterThan(content.height); - win.setPosition(100, 120); - expect(win.getBounds()).toEqual({ ...bounds, x: 100, y: 120 }); - win.center(); - expect(win.getBounds()).toEqual(bounds); - expect( - kvcRect( - cocoa().msgSend(nsWindowTitled('hidden-frame'), cocoa().selectors.get('contentView')), - ).height, - ).toBe(240); - win.destroy(); - } finally { - app.quit(); - } - }); + test('setSize keeps the top-left corner', () => { + const app = createMacOSApplication(); + app.start(); + try { + const win = app.createWindow({ width: 400, height: 300, title: 't', show: false }); + const before = win.getBounds(); + win.setSize(640, 480); + expect(win.getBounds()).toEqual({ x: before.x, y: before.y, width: 640, height: 480 }); + win.destroy(); + } finally { + app.quit(); + } + }); - test('runtime setters (resizable/opacity/minSize/center) drive AppKit without throwing', () => { - const app = createMacOSApplication(); - app.start(); - try { - const win = app.createWindow({ width: 400, height: 300, title: 't', show: false }); - expect(() => { - win.setResizable(false); - win.setResizable(true); - win.setOpacity(0.5); - win.setOpacity(1); - win.setMinimumSize(320, 240); - win.center(); - }).not.toThrow(); - } finally { - app.quit(); - } - }); + test('a never-shown window opens centered and reports its real frame', () => { + const app = createMacOSApplication(); + app.start(); + try { + const win = app.createWindow({ + width: 320, + height: 240, + title: 'hidden-frame', + show: false, + }); + const content = kvcRect( + cocoa().msgSend(nsWindowTitled('hidden-frame'), cocoa().selectors.get('contentView')), + ); + const bounds = win.getBounds(); + expect(bounds.x).toBeGreaterThan(0); + expect(bounds.width).toBe(320); + expect(bounds.height).toBeGreaterThan(content.height); + win.setPosition(100, 120); + expect(win.getBounds()).toEqual({ ...bounds, x: 100, y: 120 }); + win.center(); + expect(win.getBounds()).toEqual(bounds); + expect( + kvcRect( + cocoa().msgSend(nsWindowTitled('hidden-frame'), cocoa().selectors.get('contentView')), + ).height, + ).toBe(240); + win.destroy(); + } finally { + app.quit(); + } + }); - test('loadHTML drives the webview URL to the base URL after pumping', async () => { - const app = createMacOSApplication(); - app.start(); - try { - const win = app.createWindow({ width: 400, height: 300, title: 't', show: true }); - win.webContents.loadHTML('

Bunmaska

', 'about:blank'); - await delay(250); - expect(win.webContents.getURL()).toBe('about:blank'); - } finally { - app.quit(); - } - }); + test('runtime setters (resizable/opacity/minSize/center) drive AppKit without throwing', () => { + const app = createMacOSApplication(); + app.start(); + try { + const win = app.createWindow({ width: 400, height: 300, title: 't', show: false }); + expect(() => { + win.setResizable(false); + win.setResizable(true); + win.setOpacity(0.5); + win.setOpacity(1); + win.setMinimumSize(320, 240); + win.center(); + }).not.toThrow(); + win.destroy(); + } finally { + app.quit(); + } + }); - test('a send before the first load reaches the preload exactly once', async () => { - const app = createMacOSApplication(); - app.start(); - try { - const win = app.createWindow({ - width: 320, - height: 240, - title: 't', - show: true, - preloadScript: - "window.__bunmaska.on('early', function (n) { window.__bunmaska.send('got', n); });", - }); - const received: string[] = []; - win.webContents.onRendererEnvelope((json) => received.push(json)); - win.webContents.sendEnvelopeToRenderer( - encodeEnvelope({ kind: 'send', channel: 'early', args: [7] }), - ); - win.webContents.loadHTML('

x

', 'about:blank'); - await waitFor(() => received.length > 0); - await delay(100); - expect(received.map(decodeEnvelope)).toEqual([{ kind: 'send', channel: 'got', args: [7] }]); - win.destroy(); - } finally { - app.quit(); - } - }); + test('loadHTML drives the webview URL to the base URL after pumping', async () => { + const app = createMacOSApplication(); + app.start(); + try { + const win = app.createWindow({ width: 400, height: 300, title: 't', show: true }); + await loadPage(win, '

Bunmaska

'); + expect(win.webContents.getURL()).toBe('about:blank'); + win.destroy(); + } finally { + app.quit(); + } + }); - test('executeJavaScript resolves to the script completion value', async () => { - const app = createMacOSApplication(); - app.start(); - try { - const win = app.createWindow({ width: 400, height: 300, title: 't', show: true }); - win.webContents.loadHTML('hi', 'about:blank'); - await delay(250); - const result = await win.webContents.executeJavaScript('2 + 3'); - expect(result).toBe(5); - } finally { - app.quit(); - } - }); + test('a send before the first load reaches the preload exactly once', async () => { + const app = createMacOSApplication(); + app.start(); + try { + const win = app.createWindow({ + width: 320, + height: 240, + title: 't', + show: true, + preloadScript: + "window.__bunmaska.on('early', function (n) { window.__bunmaska.send('got', n); });", + }); + const received: string[] = []; + win.webContents.onRendererEnvelope((json) => received.push(json)); + win.webContents.sendEnvelopeToRenderer( + encodeEnvelope({ kind: 'send', channel: 'early', args: [7] }), + ); + win.webContents.loadHTML('

x

', 'about:blank'); + await waitFor(() => received.length > 0); + await delay(100); + expect(received.map(decodeEnvelope)).toEqual([{ kind: 'send', channel: 'got', args: [7] }]); + win.destroy(); + } finally { + app.quit(); + } + }); - test('printToPDF renders the page to real PDF bytes via a block completion handler', async () => { - const app = createMacOSApplication(); - app.start(); - try { - const win = app.createWindow({ width: 400, height: 300, title: 't', show: true }); - win.webContents.loadHTML('

Bunmaska PDF

', 'about:blank'); - await delay(250); - const pdf = await win.webContents.printToPDF(); - expect(pdf.length).toBeGreaterThan(100); - // The PDF file magic is the ASCII bytes "%PDF". - expect(new TextDecoder().decode(pdf.slice(0, 4))).toBe('%PDF'); - } finally { - app.quit(); - } - }); + test('executeJavaScript resolves to the script completion value', async () => { + const app = createMacOSApplication(); + app.start(); + try { + const win = app.createWindow({ width: 400, height: 300, title: 't', show: true }); + await loadPage(win, 'hi'); + expect(await win.webContents.executeJavaScript('2 + 3')).toBe(5); + win.destroy(); + } finally { + app.quit(); + } + }); - test('capturePage snapshots the page to PNG bytes via a block completion handler', async () => { - const app = createMacOSApplication(); - app.start(); - try { - const win = app.createWindow({ width: 320, height: 240, title: 't', show: true }); - win.webContents.loadHTML( - 'x', - 'about:blank', - ); - await delay(300); - const png = await win.webContents.capturePage(); - expect(png.length).toBeGreaterThan(8); - // PNG file magic: \x89 P N G. - expect([...png.slice(0, 4)]).toEqual([0x89, 0x50, 0x4e, 0x47]); - } finally { - app.quit(); - } - }); + test('printToPDF renders the page to real PDF bytes via a block completion handler', async () => { + const app = createMacOSApplication(); + app.start(); + try { + const win = app.createWindow({ width: 400, height: 300, title: 't', show: true }); + await loadPage(win, '

Bunmaska PDF

'); + const pdf = await win.webContents.printToPDF(); + expect(new TextDecoder().decode(pdf.slice(0, 4))).toBe('%PDF'); + win.destroy(); + } finally { + app.quit(); + } + }); - test('a timed-out render keeps its completion block alive until WebKit calls it', async () => { - const app = createMacOSApplication(); - app.start(); + test('capturePage snapshots the page to PNG bytes via a block completion handler', async () => { + const app = createMacOSApplication(); + app.start(); + try { const win = app.createWindow({ width: 320, height: 240, title: 't', show: true }); - win.webContents.loadHTML('

render

', 'about:blank'); - await waitFor(() => win.webContents.getURL() === 'about:blank'); - // Let earlier tests' fired blocks finish their deferred cleanup before counting. - await delay(50); - // No pump while timers are faked, so WebKit cannot complete the render first. + await loadPage(win, 'x'); + const png = await win.webContents.capturePage(); + expect([...png.slice(0, 4)]).toEqual([0x89, 0x50, 0x4e, 0x47]); + win.destroy(); + } finally { app.quit(); - const pump = createMacOSApplication(); - const baseline = retainedBlockCount(); - jest.useFakeTimers(); - try { - const pdf = win.webContents.printToPDF(); - const png = win.webContents.capturePage(); - jest.advanceTimersByTime(30_001); - await expect(pdf).rejects.toThrow(/timed out/); - await expect(png).rejects.toThrow(/timed out/); - jest.advanceTimersByTime(10); - expect(retainedBlockCount()).toBe(baseline + 2); - } finally { - jest.useRealTimers(); - } - pump.start(); - try { - win.destroy(); - await waitFor(() => retainedBlockCount() === baseline); - expect(retainedBlockCount()).toBe(baseline); - } finally { - pump.quit(); - } - }); + } + }); - test('openDevTools exists and does not throw', async () => { - const app = createMacOSApplication(); - app.start(); - try { - const win = app.createWindow({ width: 400, height: 300, title: 't', show: true }); - win.webContents.loadHTML('hi', 'about:blank'); - await delay(150); - expect(typeof win.webContents.openDevTools).toBe('function'); - expect(() => win.webContents.openDevTools()).not.toThrow(); - await delay(50); - } finally { - app.quit(); - } - }); + test('a timed-out render keeps its completion block alive until WebKit calls it', async () => { + const app = createMacOSApplication(); + app.start(); + const win = app.createWindow({ width: 320, height: 240, title: 't', show: true }); + await loadPage(win, '

render

'); + // Let earlier tests' fired blocks finish their deferred cleanup before counting. + await delay(50); + // No pump while timers are faked, so WebKit cannot complete the render first. + app.quit(); + const pump = createMacOSApplication(); + const baseline = retainedBlockCount(); + jest.useFakeTimers(); + try { + const pdf = win.webContents.printToPDF(); + const png = win.webContents.capturePage(); + jest.advanceTimersByTime(30_001); + await expect(pdf).rejects.toThrow(/timed out/); + await expect(png).rejects.toThrow(/timed out/); + jest.advanceTimersByTime(10); + expect(retainedBlockCount()).toBe(baseline + 2); + } finally { + jest.useRealTimers(); + } + pump.start(); + try { + win.destroy(); + await waitFor(() => retainedBlockCount() === baseline); + expect(retainedBlockCount()).toBe(baseline); + } finally { + pump.quit(); + } + }); - test('focus leaves a hidden window hidden, like Electron', () => { - const app = createMacOSApplication(); - app.start(); - try { - const win = app.createWindow({ width: 320, height: 240, title: 't', show: false }); - win.focus(); - expect(win.isVisible()).toBe(false); - win.destroy(); - } finally { - app.quit(); - } - }); + test('focus leaves a hidden window hidden, like Electron', () => { + const app = createMacOSApplication(); + app.start(); + try { + const win = app.createWindow({ width: 320, height: 240, title: 't', show: false }); + win.focus(); + expect(win.isVisible()).toBe(false); + win.destroy(); + } finally { + app.quit(); + } + }); - test('hide makes the window not visible', () => { - const app = createMacOSApplication(); - app.start(); - try { - const win = app.createWindow({ width: 400, height: 300, title: 't', show: true }); - expect(win.isVisible()).toBe(true); - win.hide(); - expect(win.isVisible()).toBe(false); - } finally { - app.quit(); - } - }); + test('hide makes the window not visible', () => { + const app = createMacOSApplication(); + app.start(); + try { + const win = app.createWindow({ width: 400, height: 300, title: 't', show: true }); + expect(win.isVisible()).toBe(true); + win.hide(); + expect(win.isVisible()).toBe(false); + win.destroy(); + } finally { + app.quit(); + } + }); - test('every window and contents call after close is a safe no-op', async () => { - const app = createMacOSApplication(); - app.start(); - try { - const win = app.createWindow({ width: 320, height: 240, title: 'closing', show: true }); - win.webContents.loadHTML('

x

', 'about:blank'); - await waitFor(() => win.webContents.getURL() === 'about:blank'); - const events: string[] = []; - for (const type of ['show', 'hide', 'blur', 'focus', 'resize'] as const) { - win.onWindowEvent(type, () => events.push(type)); - } - win.close(); - const callEverything = (): void => { - win.show(); - win.hide(); - win.focus(); - win.setTitle('after'); - win.setBounds({ x: 10, y: 10, width: 200, height: 100 }); - win.setSize(300, 200); - win.setPosition(5, 5); - win.setResizable(false); - win.setOpacity(0.5); - win.setMinimumSize(100, 100); - win.center(); - win.minimize(); - win.restore(); - win.maximize(); - win.unmaximize(); - win.setFullScreen(true); - win.setAlwaysOnTop(true); - win.close(); - win.destroy(); - const contents = win.webContents; - contents.loadURL('about:blank'); - contents.loadHTML('

y

'); - contents.reload(); - contents.reloadIgnoringCache(); - contents.stop(); - contents.goBack(); - contents.goForward(); - contents.setZoomFactor(2); - contents.setUserAgent('ua'); - contents.openDevTools(); - contents.closeDevTools(); - contents.sendEnvelopeToRenderer('{}'); - expect(win.getTitle()).toBe(''); - expect(win.isVisible()).toBe(false); - expect(win.isFocused()).toBe(false); - expect(win.isMaximized()).toBe(false); - expect(win.isMinimized()).toBe(false); - expect(win.isFullScreen()).toBe(false); - expect(contents.getURL()).toBe(''); - expect(contents.getTitle()).toBe(''); - expect(contents.canGoBack()).toBe(false); - expect(contents.canGoForward()).toBe(false); - }; - callEverything(); - // The native objects are released on a later tick; call again once they are gone. - await Bun.sleep(100); - callEverything(); - expect(events).toEqual([]); - } finally { - app.quit(); + test('every window and contents call after close is a safe no-op', async () => { + const app = createMacOSApplication(); + app.start(); + try { + const win = app.createWindow({ width: 320, height: 240, title: 'closing', show: true }); + await loadPage(win, '

x

'); + const events: string[] = []; + for (const type of ['show', 'hide', 'blur', 'focus', 'resize'] as const) { + win.onWindowEvent(type, () => events.push(type)); } - }); - - test('a frameless window can become key, minimizes, resizes and closes', async () => { - const app = createMacOSApplication(); - app.start(); - try { - const win = app.createWindow({ - width: 320, - height: 240, - title: 'frameless', - show: true, - frame: false, - }); - const window = nsWindowTitled('frameless'); - const sel = cocoa().selectors; - expect(msgSendReturnsU8(window, sel.get('canBecomeKeyWindow'))).toBe(1); - expect(msgSendReturnsU8(window, sel.get('canBecomeMainWindow'))).toBe(1); - expect(msgSendReturnsI64(window, sel.get('styleMask')) & 8n).toBe(8n); + win.close(); + const callEverything = (): void => { + win.show(); + win.hide(); + win.focus(); + win.setTitle('after'); + win.setBounds({ x: 10, y: 10, width: 200, height: 100 }); + win.setSize(300, 200); + win.setPosition(5, 5); + win.setResizable(false); + win.setOpacity(0.5); + win.setMinimumSize(100, 100); + win.center(); win.minimize(); - await waitFor(() => win.isMinimized()); - expect(win.isMinimized()).toBe(true); - let closed = 0; - win.onClose(() => closed === 0); - win.onClosed(() => { - closed += 1; - }); - win.close(); - expect(closed).toBe(0); - win.onClose(() => false); + win.restore(); + win.maximize(); + win.unmaximize(); + win.setFullScreen(true); + win.setAlwaysOnTop(true); win.close(); - expect(closed).toBe(1); - } finally { - app.quit(); - } - }); - - test('a frameless window honours resizable: false', () => { - const app = createMacOSApplication(); - app.start(); - try { - const win = app.createWindow({ - width: 320, - height: 240, - title: 'frameless-fixed', - show: false, - frame: false, - resizable: false, - }); - const window = nsWindowTitled('frameless-fixed'); - expect(msgSendReturnsI64(window, cocoa().selectors.get('styleMask')) & 8n).toBe(0n); win.destroy(); - } finally { - app.quit(); - } - }); + const contents = win.webContents; + contents.loadURL('about:blank'); + contents.loadHTML('

y

'); + contents.reload(); + contents.reloadIgnoringCache(); + contents.stop(); + contents.goBack(); + contents.goForward(); + contents.setZoomFactor(2); + contents.setUserAgent('ua'); + contents.openDevTools(); + contents.closeDevTools(); + contents.sendEnvelopeToRenderer('{}'); + expect(win.getTitle()).toBe(''); + expect(win.isVisible()).toBe(false); + expect(win.isFocused()).toBe(false); + expect(win.isMaximized()).toBe(false); + expect(win.isMinimized()).toBe(false); + expect(win.isFullScreen()).toBe(false); + expect(contents.getURL()).toBe(''); + expect(contents.getTitle()).toBe(''); + expect(contents.canGoBack()).toBe(false); + expect(contents.canGoForward()).toBe(false); + }; + callEverything(); + // The native objects are released on a later tick; call again once they are gone. + await waitFor(() => nsWindowTitled('closing') === 0n); + expect(nsWindowTitled('closing')).toBe(0n); + callEverything(); + expect(events).toEqual([]); + } finally { + app.quit(); + } + }); - test('the preload, bridge and dom-ready run in the main frame only', async () => { - const app = createMacOSApplication(); - app.start(); - try { - const win = app.createWindow({ - width: 320, - height: 240, - title: 't', - show: true, - preloadScript: "window.__bunmaska.exposeInMainWorld('myApi', { v: 1 });", - }); - let domReady = 0; - win.webContents.onNavigation((event) => { - if (event.type === 'dom-ready') { - domReady += 1; - } - }); - win.webContents.loadHTML('', 'about:blank'); - const probe = `(() => { + test('a frameless window can become key, minimizes, resizes and closes', async () => { + const app = createMacOSApplication(); + app.start(); + try { + const win = app.createWindow({ + width: 320, + height: 240, + title: 'frameless', + show: true, + frame: false, + }); + const window = nsWindowTitled('frameless'); + const sel = cocoa().selectors; + expect(msgSendReturnsU8(window, sel.get('canBecomeKeyWindow'))).toBe(1); + expect(msgSendReturnsU8(window, sel.get('canBecomeMainWindow'))).toBe(1); + expect(msgSendReturnsI64(window, sel.get('styleMask')) & 8n).toBe(8n); + win.minimize(); + await waitFor(() => win.isMinimized()); + expect(win.isMinimized()).toBe(true); + let closed = 0; + win.onClose(() => closed === 0); + win.onClosed(() => { + closed += 1; + }); + win.close(); + expect(closed).toBe(0); + win.onClose(() => false); + win.close(); + expect(closed).toBe(1); + } finally { + app.quit(); + } + }); + + test('a frameless window honours resizable: false', () => { + const app = createMacOSApplication(); + app.start(); + try { + const win = app.createWindow({ + width: 320, + height: 240, + title: 'frameless-fixed', + show: false, + frame: false, + resizable: false, + }); + const window = nsWindowTitled('frameless-fixed'); + expect(msgSendReturnsI64(window, cocoa().selectors.get('styleMask')) & 8n).toBe(0n); + win.destroy(); + } finally { + app.quit(); + } + }); + + test('the preload, bridge and dom-ready run in the main frame only', async () => { + const app = createMacOSApplication(); + app.start(); + try { + const win = app.createWindow({ + width: 320, + height: 240, + title: 't', + show: true, + preloadScript: "window.__bunmaska.exposeInMainWorld('myApi', { v: 1 });", + }); + let domReady = 0; + win.webContents.onNavigation((event) => { + if (event.type === 'dom-ready') { + domReady += 1; + } + }); + win.webContents.loadHTML('', 'about:blank'); + const probe = `(() => { const frame = document.querySelector('iframe'); if (!frame || !frame.contentDocument || frame.contentDocument.readyState !== 'complete') { return null; } return [typeof window.myApi, typeof frame.contentWindow.myApi]; })()`; - let seen: unknown = null; - const deadline = performance.now() + 5_000; - while (seen === null && performance.now() < deadline) { - await Bun.sleep(20); - seen = await win.webContents.executeJavaScript(probe); - } - expect(seen).toEqual(['object', 'undefined']); - expect(domReady).toBe(1); - } finally { - app.quit(); + let seen: unknown = null; + const deadline = performance.now() + 5_000; + while (seen === null && performance.now() < deadline) { + await Bun.sleep(20); + seen = await win.webContents.executeJavaScript(probe); } - }); + expect(seen).toEqual(['object', 'undefined']); + expect(domReady).toBe(1); + win.destroy(); + } finally { + app.quit(); + } + }); - test('a WebKit-native or malformed protocol.handle scheme does not abort window creation', () => { - const app = createMacOSApplication(); - app.start(); - const serve = () => ({ data: 'x' }); - protocol.handle('https', serve); - protocol.handle('my_app', serve); - try { - const win = app.createWindow({ width: 320, height: 240, title: 't', show: false }); - expect(win.getTitle()).toBe('t'); - win.destroy(); - } finally { - protocol.unhandle('https'); - protocol.unhandle('my_app'); - app.quit(); - } - }); + test('a WebKit-native or malformed protocol.handle scheme does not abort window creation', () => { + const app = createMacOSApplication(); + app.start(); + const serve = () => ({ data: 'x' }); + protocol.handle('https', serve); + protocol.handle('my_app', serve); + try { + const win = app.createWindow({ width: 320, height: 240, title: 't', show: false }); + expect(win.getTitle()).toBe('t'); + win.destroy(); + } finally { + protocol.unhandle('https'); + protocol.unhandle('my_app'); + app.quit(); + } + }); - test('a closed window releases its configuration and user scripts', async () => { - const app = createMacOSApplication(); - app.start(); - const weak = weakRefs(); + test('a closed window releases its configuration and user scripts', async () => { + const app = createMacOSApplication(); + app.start(); + const weak = weakRefs(); + try { + const win = app.createWindow({ width: 320, height: 240, title: 'scripts', show: true }); + const rt = cocoa(); + const webview = rt.msgSend(nsWindowTitled('scripts'), rt.selectors.get('contentView')); + const configuration = rt.msgSend(webview, rt.selectors.get('configuration')); + const controller = rt.msgSend(configuration, rt.selectors.get('userContentController')); + const scripts = rt.msgSend(controller, rt.selectors.get('userScripts')); + const slot = weak.observe(msgSendI64(scripts, rt.selectors.get('objectAtIndex:'), 0n)); try { - const win = app.createWindow({ width: 320, height: 240, title: 'scripts', show: true }); - const rt = cocoa(); - const webview = rt.msgSend(nsWindowTitled('scripts'), rt.selectors.get('contentView')); - const configuration = rt.msgSend(webview, rt.selectors.get('configuration')); - const controller = rt.msgSend(configuration, rt.selectors.get('userContentController')); - const scripts = rt.msgSend(controller, rt.selectors.get('userScripts')); - const slot = weak.observe(msgSendI64(scripts, rt.selectors.get('objectAtIndex:'), 0n)); - try { - win.close(); - await waitFor(() => !weak.isAlive(slot)); - expect(weak.isAlive(slot)).toBe(false); - } finally { - weak.forget(slot); - } + win.close(); + await waitFor(() => !weak.isAlive(slot)); + expect(weak.isAlive(slot)).toBe(false); } finally { - app.quit(); + weak.forget(slot); } - }); + } finally { + app.quit(); + } + }); - test('windows share one URL scheme handler', () => { - const app = createMacOSApplication(); - app.start(); - protocol.handle('bmshared', () => ({ data: 'x' })); - try { - const rt = cocoa(); - const handlerOf = (title: string): bigint => { - const webview = rt.msgSend(nsWindowTitled(title), rt.selectors.get('contentView')); - const configuration = rt.msgSend(webview, rt.selectors.get('configuration')); - return msgSendPtr( - configuration, - rt.selectors.get('urlSchemeHandlerForURLScheme:'), - nsString('bmshared'), - ); - }; - const first = app.createWindow({ width: 200, height: 100, title: 'scheme-a', show: false }); - const second = app.createWindow({ - width: 200, - height: 100, - title: 'scheme-b', - show: false, - }); - expect(handlerOf('scheme-a')).not.toBe(0n); - expect(handlerOf('scheme-a')).toBe(handlerOf('scheme-b')); - first.destroy(); - second.destroy(); - } finally { - protocol.unhandle('bmshared'); - app.quit(); - } - }); + test('windows share one URL scheme handler', () => { + const app = createMacOSApplication(); + app.start(); + protocol.handle('bmshared', () => ({ data: 'x' })); + try { + const rt = cocoa(); + const handlerOf = (title: string): bigint => { + const webview = rt.msgSend(nsWindowTitled(title), rt.selectors.get('contentView')); + const configuration = rt.msgSend(webview, rt.selectors.get('configuration')); + return msgSendPtr( + configuration, + rt.selectors.get('urlSchemeHandlerForURLScheme:'), + nsString('bmshared'), + ); + }; + const first = app.createWindow({ width: 200, height: 100, title: 'scheme-a', show: false }); + const second = app.createWindow({ + width: 200, + height: 100, + title: 'scheme-b', + show: false, + }); + expect(handlerOf('scheme-a')).not.toBe(0n); + expect(handlerOf('scheme-a')).toBe(handlerOf('scheme-b')); + first.destroy(); + second.destroy(); + } finally { + protocol.unhandle('bmshared'); + app.quit(); + } + }); - test('close fires the onClosed callback once', () => { - const app = createMacOSApplication(); - app.start(); - try { - const win = app.createWindow({ width: 400, height: 300, title: 't', show: false }); - let closes = 0; - win.onClosed(() => { - closes += 1; - }); - win.close(); - win.close(); - expect(closes).toBe(1); - } finally { - app.quit(); - } - }); + test('close fires the onClosed callback once', () => { + const app = createMacOSApplication(); + app.start(); + try { + const win = app.createWindow({ width: 400, height: 300, title: 't', show: false }); + let closes = 0; + win.onClosed(() => { + closes += 1; + }); + win.close(); + win.close(); + expect(closes).toBe(1); + } finally { + app.quit(); + } }); -} +}); diff --git a/tests/integration/macos/cocoa-run-loop.test.ts b/tests/integration/macos/cocoa-run-loop.test.ts index a4fa82b2..400b5cda 100644 --- a/tests/integration/macos/cocoa-run-loop.test.ts +++ b/tests/integration/macos/cocoa-run-loop.test.ts @@ -4,104 +4,52 @@ import { createMacOSDrain, withAutoreleasePool, } from '../../../src/main/platform/macos/cocoa-run-loop'; -import { - msgSendI64, - msgSendInitWithContentRect, - msgSendPtr, - msgSendReturnsU8, - msgSendU8, -} from '../../../src/main/platform/macos/cocoa-msgsend-variants'; import { cocoa } from '../../../src/main/platform/macos/cocoa-runtime'; -import { - computeWindowStyleMask, - STANDARD_WINDOW_STYLE, -} from '../../../src/main/platform/macos/cocoa-style-mask'; -const NS_BACKING_STORE_BUFFERED = 2n; - -if (currentPlatform() === 'macos') { - describe('createMacOSDrain', () => { - test('returns a drain function that runs many times without crashing', () => { - const drain = createMacOSDrain(); - for (let i = 0; i < 50; i += 1) { - drain(0); - } - expect(typeof drain).toBe('function'); - }); - - test('each tick of any drain releases what JS autoreleased since the last tick', () => { - const rt = cocoa(); - const retainCount = (handle: bigint): bigint => - rt.msgSend(handle, rt.selectors.get('retainCount')); - const first = createMacOSDrain(); - const second = createMacOSDrain(); - const object = rt.msgSend( - rt.msgSend(rt.classes.get('NSObject'), rt.selectors.get('alloc')), - rt.selectors.get('init'), - ); - try { - for (const drain of [first, second, first, second]) { - rt.msgSend( - rt.msgSend(object, rt.selectors.get('retain')), - rt.selectors.get('autorelease'), - ); - expect(retainCount(object)).toBe(2n); - drain(0); - expect(retainCount(object)).toBe(1n); - } - } finally { - rt.msgSend(object, rt.selectors.get('release')); - } - }); - - test('withAutoreleasePool releases what its callback autoreleased and returns its value', () => { - const rt = cocoa(); - const object = rt.msgSend( - rt.msgSend(rt.classes.get('NSObject'), rt.selectors.get('alloc')), - rt.selectors.get('init'), - ); - try { - const count = withAutoreleasePool(() => { - rt.msgSend( - rt.msgSend(object, rt.selectors.get('retain')), - rt.selectors.get('autorelease'), - ); - return rt.msgSend(object, rt.selectors.get('retainCount')); - }); - expect(count).toBe(2n); - expect(rt.msgSend(object, rt.selectors.get('retainCount'))).toBe(1n); - } finally { - rt.msgSend(object, rt.selectors.get('release')); - } - }); - - test('pumping the drain makes a real NSWindow visible', () => { - const rt = cocoa(); - const app = rt.msgSend( - rt.classes.get('NSApplication'), - rt.selectors.get('sharedApplication'), - ); - msgSendI64(app, rt.selectors.get('setActivationPolicy:'), 0n); - rt.msgSend(app, rt.selectors.get('finishLaunching')); - - const allocated = rt.msgSend(rt.classes.get('NSWindow'), rt.selectors.get('alloc')); - const window = msgSendInitWithContentRect( - allocated, - rt.selectors.get('initWithContentRect:styleMask:backing:defer:'), - [200, 200, 360, 240], - BigInt(computeWindowStyleMask(STANDARD_WINDOW_STYLE)), - NS_BACKING_STORE_BUFFERED, - false, - ); - msgSendPtr(window, rt.selectors.get('makeKeyAndOrderFront:'), 0n); - msgSendU8(app, rt.selectors.get('activateIgnoringOtherApps:'), 1); - - const drain = createMacOSDrain(); - for (let i = 0; i < 60; i += 1) { +const newObject = (): bigint => { + const rt = cocoa(); + return rt.msgSend( + rt.msgSend(rt.classes.get('NSObject'), rt.selectors.get('alloc')), + rt.selectors.get('init'), + ); +}; + +const retainCount = (handle: bigint): bigint => + cocoa().msgSend(handle, cocoa().selectors.get('retainCount')); + +const retainAutorelease = (handle: bigint): void => { + const rt = cocoa(); + rt.msgSend(rt.msgSend(handle, rt.selectors.get('retain')), rt.selectors.get('autorelease')); +}; + +describe.skipIf(currentPlatform() !== 'macos')('createMacOSDrain', () => { + test('each tick of any drain releases what JS autoreleased since the last tick', () => { + const first = createMacOSDrain(); + const second = createMacOSDrain(); + const object = newObject(); + try { + for (const drain of [first, second, first, second]) { + retainAutorelease(object); + expect(retainCount(object)).toBe(2n); drain(0); + expect(retainCount(object)).toBe(1n); } + } finally { + cocoa().msgSend(object, cocoa().selectors.get('release')); + } + }); - expect(msgSendReturnsU8(window, rt.selectors.get('isVisible'))).toBe(1); - }); + test('withAutoreleasePool releases what its callback autoreleased and returns its value', () => { + const object = newObject(); + try { + const count = withAutoreleasePool(() => { + retainAutorelease(object); + return retainCount(object); + }); + expect(count).toBe(2n); + expect(retainCount(object)).toBe(1n); + } finally { + cocoa().msgSend(object, cocoa().selectors.get('release')); + } }); -} +}); From 3c417076861b5bbb21719e47b172f00d9411fafd Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:05:10 -0700 Subject: [PATCH 141/586] chore: trim macOS feature backend comments to the comment rules --- .../platform/macos/carbon-global-shortcut.ts | 23 +--------- src/main/platform/macos/carbon-keymap.ts | 20 ++------- src/main/platform/macos/cocoa-clipboard.ts | 9 +--- src/main/platform/macos/cocoa-dialog.ts | 14 +----- src/main/platform/macos/cocoa-menu.ts | 45 +++++-------------- src/main/platform/macos/cocoa-native-image.ts | 44 +++++------------- src/main/platform/macos/cocoa-native-theme.ts | 14 +----- src/main/platform/macos/cocoa-notification.ts | 45 +++---------------- .../macos/cocoa-power-save-blocker.ts | 25 +---------- src/main/platform/macos/cocoa-power.ts | 12 +---- src/main/platform/macos/cocoa-safe-storage.ts | 18 ++------ src/main/platform/macos/cocoa-screen.ts | 6 +-- src/main/platform/macos/cocoa-shell.ts | 5 --- src/main/platform/macos/cocoa-tray.ts | 25 +---------- 14 files changed, 48 insertions(+), 257 deletions(-) diff --git a/src/main/platform/macos/carbon-global-shortcut.ts b/src/main/platform/macos/carbon-global-shortcut.ts index c324ba7e..33c88131 100644 --- a/src/main/platform/macos/carbon-global-shortcut.ts +++ b/src/main/platform/macos/carbon-global-shortcut.ts @@ -5,22 +5,6 @@ import { currentPlatform } from '../../../common/platform'; import { loadCarbonFFI } from './carbon-ffi'; import { carbonModifierMask, macVirtualKeyCode } from './carbon-keymap'; -/** - * macOS `globalShortcut` backend via Carbon `RegisterEventHotKey`. - * - * - ONE process-wide event handler is installed lazily for - * `kEventClassKeyboard` / `kEventHotKeyPressed`. Its `JSCallback` is retained - * for the process lifetime (it is NEVER closed inside its own invocation — see - * the JSCallback-lifecycle SIGSEGV note). - * - Each registration gets a unique numeric id; we pack `{ signature, id }` into - * the `EventHotKeyID` u64 (the verified struct-by-value workaround) and keep an - * `id -> callback` map. When the handler fires it reads the fired id back from - * the event's `kEventParamHotKeyID` parameter and dispatches that callback. - * - * Returns `false` from `register` when the accelerator's key is not in the - * US-layout virtual-key table or when Carbon refuses the grab (non-`noErr`). - */ - const SIGNATURE = 0x53414d42; // 'SAMB' const KEYBOARD_EVENT_CLASS = 0x6b657962; // 'keyb' @@ -39,9 +23,7 @@ const byAccelerator = new Map(); const byId = new Map void>(); let nextId = 1; -// The single app event handler's JSCallback, retained for the process lifetime. -// It is intentionally never closed (closing a JSCallback from within its own -// invocation crashes; this one outlives every registration anyway). +// Never closed: it outlives every registration, and closing a JSCallback inside its own call crashes (D022b). let handlerCallback: JSCallback | undefined; let handlerInstalled = false; @@ -120,7 +102,7 @@ const register = (accelerator: string, callback: () => void): boolean => { const carbon = loadCarbonFFI(); const id = nextId; nextId += 1; - const packed = BigInt(SIGNATURE) | (BigInt(id) << 32n); + const packed = BigInt(SIGNATURE) | (BigInt(id) << 32n); // EventHotKeyID by value, see carbon-ffi.ts const outRef = new BigInt64Array(1); const rc = carbon.symbols.RegisterEventHotKey( keyCode, @@ -159,7 +141,6 @@ const unregisterAll = (): void => { } }; -/** macOS is supported whenever we are actually on macOS (Carbon is always present). */ const isSupported = (): boolean => currentPlatform() === 'macos'; export const macosGlobalShortcutBackend: GlobalShortcutBackend = { diff --git a/src/main/platform/macos/carbon-keymap.ts b/src/main/platform/macos/carbon-keymap.ts index a69cd127..05d7fcbf 100644 --- a/src/main/platform/macos/carbon-keymap.ts +++ b/src/main/platform/macos/carbon-keymap.ts @@ -1,22 +1,12 @@ import type { ParsedAccelerator } from '../../api/accelerator'; -/** - * Pure macOS-virtual-key-code + Carbon-modifier-mask tables for the Carbon - * global-shortcut backend. - * - * Carbon's `RegisterEventHotKey` wants a hardware virtual key code (US layout) - * and a modifier mask, NOT a character. These tables map our parsed accelerator - * key/modifiers onto those. Values are the canonical `kVK_*` constants from - * `HIToolbox/Events.h`. - */ - /** Carbon modifier mask bits (Events.h `cmdKey`, `shiftKey`, `optionKey`, `controlKey`). */ export const CMD_KEY = 0x100; export const SHIFT_KEY = 0x200; export const OPTION_KEY = 0x800; export const CONTROL_KEY = 0x1000; -/** US-layout virtual key codes keyed by normalised key label (`kVK_ANSI_*` / `kVK_*`). */ +/** Carbon wants hardware key codes, not characters: US-layout `kVK_*` values from Events.h. */ const VIRTUAL_KEY_CODES: ReadonlyMap = new Map([ ['A', 0], ['S', 1], @@ -102,18 +92,14 @@ const VIRTUAL_KEY_CODES: ReadonlyMap = new Map([ ['F20', 90], ]); -/** - * Map a parsed accelerator key to a macOS virtual key code, or `undefined` if - * the key has no entry in the US-layout table. - */ +/** The US-layout virtual key code for a parsed accelerator key, or `undefined` if unmapped. */ export const macVirtualKeyCode = (key: string): number | undefined => VIRTUAL_KEY_CODES.get(key.toUpperCase()); /** Build the Carbon modifier mask for a parsed accelerator (CmdOrCtrl already resolved). */ export const carbonModifierMask = (parsed: ParsedAccelerator): number => { let mask = 0; - // Electron: Super/Meta is Cmd on macOS. Ignoring parsed.super registered - // 'Super+K' as a bare-K global grab. + // Super/Meta is Cmd on macOS (Electron); dropping super turns 'Super+K' into a bare-K grab. if (parsed.meta || parsed.super) { mask |= CMD_KEY; } diff --git a/src/main/platform/macos/cocoa-clipboard.ts b/src/main/platform/macos/cocoa-clipboard.ts index 467347c5..f593e05b 100644 --- a/src/main/platform/macos/cocoa-clipboard.ts +++ b/src/main/platform/macos/cocoa-clipboard.ts @@ -3,14 +3,7 @@ import { msgSendI64, msgSendPtr, msgSendPtrPtr, msgSendReturnsI64 } from './coco import { cocoaNativeImageBackend, nsDataFromBytes, nsDataToBytes } from './cocoa-native-image'; import { cocoa } from './cocoa-runtime'; -/** - * macOS clipboard access via `NSPasteboard`. - * - * `NSPasteboardTypeString` is the UTI `public.utf8-plain-text` and - * `NSPasteboardTypeHTML` is `public.html`; we pass them by value rather than - * reading the exported constants, which is simpler and stable across macOS - * versions. Synchronous — no run-loop interaction (D020 does not apply here). - */ +// NSPasteboard reads are synchronous and never wait on the run loop, unlike the Linux clipboard (D020). const NS_PASTEBOARD_TYPE_STRING = 'public.utf8-plain-text'; const NS_PASTEBOARD_TYPE_HTML = 'public.html'; diff --git a/src/main/platform/macos/cocoa-dialog.ts b/src/main/platform/macos/cocoa-dialog.ts index eb02067e..7ab9e557 100644 --- a/src/main/platform/macos/cocoa-dialog.ts +++ b/src/main/platform/macos/cocoa-dialog.ts @@ -3,13 +3,7 @@ import { msgSendI64, msgSendPtr, msgSendReturnsI64, msgSendU8 } from './cocoa-ms import { cocoa } from './cocoa-runtime'; import type { Handle } from './objc'; -/** - * Native modal dialogs via `NSAlert`, `NSOpenPanel`, and `NSSavePanel`. - * - * Each dialog is split into a non-blocking *build* step and a *run* step that - * calls the blocking `runModal`, which spins a nested AppKit modal loop and - * cannot run on a headless CI display. - */ +// build* is split from show* because runModal blocks in a nested modal loop that CI cannot dismiss. /** `NSModalResponseOK` for save/open panels. */ const NS_MODAL_RESPONSE_OK = 1n; @@ -28,11 +22,7 @@ export type MessageBoxSpec = { readonly type?: MessageBoxType; }; -/** - * Map an Electron message-box `type` to an `NSAlertStyle` value - * (warning = 0, informational = 1, critical = 2), or `undefined` to leave the - * `NSAlert` default. - */ +/** The `NSAlertStyle` for an Electron message-box `type`; `undefined` keeps the NSAlert default. */ export const alertStyleForType = (type: MessageBoxType | undefined): bigint | undefined => { switch (type) { case 'info': diff --git a/src/main/platform/macos/cocoa-menu.ts b/src/main/platform/macos/cocoa-menu.ts index 0da06d62..1e50a469 100644 --- a/src/main/platform/macos/cocoa-menu.ts +++ b/src/main/platform/macos/cocoa-menu.ts @@ -12,22 +12,12 @@ import { cocoa } from './cocoa-runtime'; import { defineObjcClass } from './cocoa-runtime-class'; import type { Handle } from './objc'; -/** - * Builds native `NSMenu` trees from a backend-neutral menu spec and routes item - * clicks back to JS. - * - * A single shared `BunmaskaMenuTarget` class (defined once at runtime, D026) holds - * the `bunmaskaMenuAction:` selector that every clickable item points at. When an - * item fires, AppKit sends `[target bunmaskaMenuAction:item]`; the IMP looks the - * item handle up in a registry and invokes its JS click handler. - */ - /** A backend-neutral description of one menu item. */ export type NativeMenuItemSpec = { readonly label: string; readonly type: 'normal' | 'separator' | 'submenu' | 'checkbox' | 'radio'; readonly enabled: boolean; - /** Whether a checkbox/radio item renders checked (defaults to unchecked). */ + /** Initial check mark of a checkbox/radio item; absent means unchecked. */ readonly checked?: boolean; /** Single-character key equivalent (e.g. `'q'`), or `''` for none. */ readonly keyEquivalent: string; @@ -45,6 +35,7 @@ export type NativeMenuItemSpec = { readonly onClick?: () => void; }; +// Every non-role item targets one shared BunmaskaMenuTarget (D026), which looks its spec up here. const clickRegistry = new Map(); let sharedTarget: Handle | undefined; @@ -116,8 +107,8 @@ const realizeItem = (spec: NativeMenuItemSpec): Handle => { } const checkable = spec.type === 'checkbox' || spec.type === 'radio'; - // A role item's action is the native first-responder selector with a NIL target, - // so AppKit routes it up the responder chain (no BunmaskaMenuTarget / clickRegistry). + // A role item gets its first-responder selector and a nil target, so AppKit routes it up + // the responder chain like the native shortcut (D035). const isRole = spec.roleSelector !== undefined; const targeted = !isRole && (spec.type === 'normal' || checkable); // A nil action is the only way to keep a responder-chain role disabled under autoenabling. @@ -140,8 +131,7 @@ const realizeItem = (spec: NativeMenuItemSpec): Handle => { clickRegistry.set(item, spec); } - // Apply the explicit modifier mask so multi-modifier accelerators (e.g. redo's - // Shift+Cmd+Z) don't collapse to AppKit's Command-only default. + // Always set the mask: AppKit's Command-only default turns redo's Shift+Cmd+Z into Cmd+Z (D035). if (spec.keyEquivalent !== '') { msgSendI64(item, rt.selectors.get('setKeyEquivalentModifierMask:'), spec.modifierMask ?? 0n); } @@ -150,8 +140,7 @@ const realizeItem = (spec: NativeMenuItemSpec): Handle => { setState(item, spec.checked === true); } - // For role items, let AppKit auto-enable via the responder chain (Copy greys out - // when nothing is selected); only honor an explicit `enabled: false`. + // Leave role items to responder-chain validation (Copy greys out with no selection). if (!isRole) { msgSendU8(item, rt.selectors.get('setEnabled:'), spec.enabled ? 1 : 0); } else if (spec.enabled === false) { @@ -213,8 +202,7 @@ export const disposeMenu = (menu: Handle): void => { let mainMenu: Handle = 0n; let lastPopup: Handle = 0n; -/** Install `menu` as the application's main menu bar. */ -/** Install `menu` as the main menu; `0n` (nil) clears the menu bar. */ +/** Install `menu` as the main menu; `0n` (nil) clears the menu bar. The replaced menu is disposed. */ export const setApplicationMenu = (menu: Handle): void => { const rt = cocoa(); const app = rt.msgSend(rt.classes.get('NSApplication'), rt.selectors.get('sharedApplication')); @@ -228,29 +216,20 @@ export const setApplicationMenu = (menu: Handle): void => { /** @internal */ export const clickRegistrySize = (): number => clickRegistry.size; -/** Number of items in a realized menu. Used for verification. */ export const menuItemCount = (menu: Handle): number => Number(msgSendReturnsI64(menu, cocoa().selectors.get('numberOfItems'))); -/** - * Programmatically trigger the item at `index` in `menu`, as if clicked. - * Used for testing the click path without a real event loop. - */ +/** Fire the item at `index` as if clicked; drives the click path without an event loop. */ export const performMenuItem = (menu: Handle, index: number): void => { msgSendI64(menu, cocoa().selectors.get('performActionForItemAtIndex:'), BigInt(index)); }; /** - * Show `menu` as a context menu at content-relative (`x`, `y`) in `view`. - * - * BLOCKING: `popUpMenuPositioningItem:atLocation:inView:` runs a nested AppKit tracking loop - * until the user picks an item or dismisses — the same nested-modal-loop class as the dialog - * panels' `runModal` (D020: safe; the crash class was a blocking `runUntilDate:`, not an - * AppKit-owned nested loop). Item clicks route through the shared `BunmaskaMenuTarget` registry - * exactly as for an application menu. `item = nil` anchors the menu's top-left at the location. + * Show `menu` at content-relative (`x`, `y`) in `view`. BLOCKS in AppKit's nested tracking + * loop until dismissed, which D040 accepts like `runModal` (not the `runUntilDate:` crash class). */ export const popUpMenu = (menu: Handle, view: Handle, x: number, y: number): boolean => { - // ponytail: the previous popup tree lives until the next popup; freeing it on return would race a click AppKit may still deliver. + // ponytail: the last popup tree lives until the next popup, since its click may still be queued. if (lastPopup !== menu) { disposeMenu(lastPopup); lastPopup = menu; @@ -259,7 +238,7 @@ export const popUpMenu = (menu: Handle, view: Handle, x: number, y: number): boo msgSendPtrPointPtrReturnsU8( menu, cocoa().selectors.get('popUpMenuPositioningItem:atLocation:inView:'), - 0n, // item = nil + 0n, // nil item: the menu's top-left lands on the point x, y, view, diff --git a/src/main/platform/macos/cocoa-native-image.ts b/src/main/platform/macos/cocoa-native-image.ts index 71982549..eebc27d1 100644 --- a/src/main/platform/macos/cocoa-native-image.ts +++ b/src/main/platform/macos/cocoa-native-image.ts @@ -13,26 +13,8 @@ import { cocoa } from './cocoa-runtime'; import { KCG_ALPHA_PREMULTIPLIED_LAST, loadCoreGraphicsImageFFI } from './core-graphics-image-ffi'; import { type Handle, ptrIn } from './objc'; -/** - * macOS image backend for `nativeImage`, via `NSBitmapImageRep` / `NSData`. - * - * DECODE: we build an `NSBitmapImageRep` DIRECTLY from the file/data - * (`[[NSBitmapImageRep alloc] initWithData:]`) rather than going through - * `NSImage`. The rep is the unit that exposes both the scalar pixel dimensions - * and the PNG encoder, so a single object covers `getSize` and `toPNG`. - * - * SIZE WITHOUT A STRUCT — `NSImage.size` returns an `NSSize` (a struct of two - * doubles) by value, which bun:ffi CANNOT return. `NSBitmapImageRep`'s - * `pixelsWide` / `pixelsHigh` are `NSInteger` SCALARS instead, read here via the - * `i64`-returning msgSend variant. This is the entire reason we decode straight - * to a rep: no struct ever crosses the FFI boundary for sizing. - * - * BUFFER DECODE — `[[NSData alloc] initWithBytes:length:]` COPIES the source - * bytes, so the pinned `Uint8Array` need only outlive that one call. - * - * EMPTY — a nil rep (bad path / undecodable bytes) is reported as empty with a - * `0n` handle and zero dimensions; no fake placeholder image is fabricated. - */ +// Decode straight to an NSBitmapImageRep, never NSImage: NSImage.size is an NSSize struct that +// bun:ffi cannot return, while the rep's pixelsWide/pixelsHigh are scalars. /** `NSBitmapImageFileType` values. */ const NS_BITMAP_IMAGE_FILE_TYPE_PNG = 4n; @@ -54,11 +36,11 @@ export const nsDataToBytes = (data: Handle): Uint8Array => { if (bytesPtr === 0n) { return new Uint8Array(0); } - // Copy out of the autoreleased NSData-owned buffer so the result owns its bytes. + // Copy: the bytes belong to the NSData, which the caller may free right after. return new Uint8Array(toArrayBuffer(ptrIn(bytesPtr), 0, length).slice(0)); }; -/** `[[NSData alloc] initWithBytes:length:]` from a Uint8Array (copies the bytes). */ +/** `[[NSData alloc] initWithBytes:length:]` (+1): it copies, so `bytes` need only outlive the call. */ export const nsDataFromBytes = (bytes: Uint8Array): Handle => { const rt = cocoa(); const alloc = rt.msgSend(rt.classes.get('NSData'), rt.selectors.get('alloc')); @@ -71,7 +53,7 @@ export const nsDataFromBytes = (bytes: Uint8Array): Handle => { ); }; -/** `[[NSBitmapImageRep alloc] initWithData:]` — nil on undecodable data. */ +/** `[[NSBitmapImageRep alloc] initWithData:]` (+1); nil on undecodable data. */ const bitmapRepFromData = (data: Handle): Handle => { if (data === 0n) { return 0n; @@ -97,7 +79,6 @@ const decodeFromRep = (rep: Handle): DecodedImage => { const decodePath = (path: string): DecodedImage => { const rt = cocoa(); - // [NSData dataWithContentsOfFile:] is nil for a bad/unreadable path. const data = msgSendPtr( rt.classes.get('NSData'), rt.selectors.get('dataWithContentsOfFile:'), @@ -114,11 +95,8 @@ const decodeBuffer = (bytes: Uint8Array): DecodedImage => { }; /** - * Redraw a rep's `CGImage` into a NEW `width`×`height` offscreen bitmap, placing the source - * at dest rect `(dx,dy,dw,dh)`, and wrap the result as an `NSBitmapImageRep`. Headless (a - * malloc-backed CG bitmap context — no window server). The source `[rep CGImage]` is BORROWED - * (not released); the new rep is leaked for the image's lifetime (matching decode); the CG - * context / color space / output CGImage temporaries ARE released. + * Draw a rep's CGImage at dest rect (dx, dy, dw, dh) of a new width x height bitmap (headless, + * no window server). `[rep CGImage]` is borrowed; the caller owns the returned +1 rep. */ const redraw = ( handle: NativeImageHandle, @@ -164,12 +142,12 @@ const redraw = ( } const alloc = rt.msgSend(rt.classes.get('NSBitmapImageRep'), rt.selectors.get('alloc')); const rep = msgSendPtr(alloc, rt.selectors.get('initWithCGImage:'), BigInt(outImage)); - cg.CGImageRelease(outImage); // initWithCGImage: copies the pixels into the rep. + cg.CGImageRelease(outImage); // the rep retains outImage; drop our +1 return decodeFromRep(rep); }; const resize = (handle: NativeImageHandle, width: number, height: number): DecodedImage => - redraw(handle, width, height, 0, 0, width, height); // scale the whole source to fill the target + redraw(handle, width, height, 0, 0, width, height); const crop = ( handle: NativeImageHandle, @@ -181,9 +159,7 @@ const crop = ( const rt = cocoa(); const srcW = Number(msgSendReturnsI64(handle, rt.selectors.get('pixelsWide'))); const srcH = Number(msgSendReturnsI64(handle, rt.selectors.get('pixelsHigh'))); - // Draw the full source at native size into the crop-sized context, offset so the top-left - // crop window lands at the dest origin. CG uses a BOTTOM-left origin, so y flips: - // top-left (x, y) → CG dest origin (-x, -(srcH - y - height)). + // CG's origin is bottom-left: top-left crop (x, y) is dest origin (-x, -(srcH - y - height)). return redraw(handle, width, height, -x, -(srcH - y - height), srcW, srcH); }; diff --git a/src/main/platform/macos/cocoa-native-theme.ts b/src/main/platform/macos/cocoa-native-theme.ts index 854d3435..e3815dbb 100644 --- a/src/main/platform/macos/cocoa-native-theme.ts +++ b/src/main/platform/macos/cocoa-native-theme.ts @@ -3,17 +3,7 @@ import { msgSendPtr, msgSendReturnsU8 } from './cocoa-msgsend-variants'; import { distributedNotificationCenter, observeNotification } from './cocoa-notification-observer'; import { cocoa } from './cocoa-runtime'; -/** - * macOS appearance query + change observer. - * - * Reads the `AppleInterfaceStyle` user default, which is the string `"Dark"` - * when the system is in dark mode and absent (nil → `''`) otherwise. - * - * {@link observeAppearanceChange} subscribes to `AppleInterfaceThemeChangedNotification` - * on `NSDistributedNotificationCenter` (via the shared notification observer, - * D034) — the system-wide signal posted when the user toggles light/dark, which - * is delivered on the pumped run loop (D020/D021). - */ +// AppleInterfaceStyle is the string 'Dark' in dark mode and absent otherwise. const APPLE_INTERFACE_STYLE = 'AppleInterfaceStyle'; const THEME_CHANGED_NOTIFICATION = 'AppleInterfaceThemeChangedNotification'; @@ -54,7 +44,7 @@ export const shouldUseDarkColors = (): boolean => { return nsStringToString(style).toLowerCase() === 'dark'; }; -/** Fire `onChange` whenever the system appearance flips (light↔dark). */ +/** Fire `onChange` whenever the system appearance flips between light and dark (D034). */ export const observeAppearanceChange = (onChange: () => void): void => { observeNotification(distributedNotificationCenter(), THEME_CHANGED_NOTIFICATION, onChange); }; diff --git a/src/main/platform/macos/cocoa-notification.ts b/src/main/platform/macos/cocoa-notification.ts index b20d71e6..dce3eb8f 100644 --- a/src/main/platform/macos/cocoa-notification.ts +++ b/src/main/platform/macos/cocoa-notification.ts @@ -9,30 +9,8 @@ import { cocoa } from './cocoa-runtime'; import { defineObjcClass } from './cocoa-runtime-class'; import type { Handle } from './objc'; -/** - * macOS notifications via the deprecated `NSUserNotification` / - * `NSUserNotificationCenter` API — the macOS half of Bunmaska's `Notification`. - * - * WHY the deprecated API: the modern `UNUserNotificationCenter` REQUIRES a real - * app bundle (Info.plist + bundle id). Bunmaska runs un-bundled (`bun main.ts`), - * so `UNUserNotificationCenter` is non-viable here. `NSUserNotification` is the - * un-bundled-friendlier path. - * - * EMPIRICAL FINDING (measured on a real macOS host, un-bundled): the - * `NSUserNotification` class resolves, `alloc/init` and the `setTitle:` / - * `setInformativeText:` / `setSubtitle:` setters run cleanly with NO crash — but - * `[NSUserNotificationCenter defaultUserNotificationCenter]` returns **nil** - * without an app bundle. So delivery does NOT actually happen un-bundled, even - * though the FFI path is clean. Sending `deliverNotification:` to a nil center is - * a safe Objective-C no-op (verified, no SIGSEGV). - * - * Reliable macOS delivery is a PACKAGING follow-up (ship Bunmaska as a code-signed - * .app bundle with a bundle id, then migrate to `UNUserNotificationCenter`). - * - * `close` event wiring (an `NSUserNotificationCenterDelegate`) is NOT wired here: - * un-bundled there is no center to attach a delegate to, so it would never fire. - * The handle's `onClosed` is therefore a no-op on macOS (best-effort, honest). - */ +// ponytail: deprecated NSUserNotification, since UNUserNotificationCenter needs an app bundle; switch once apps always ship bundled. +// Un-bundled the default center is nil, so nothing is delivered (messaging nil is a no-op). const defaultCenter = (): Handle => { const rt = cocoa(); @@ -75,9 +53,7 @@ const buildNotification = (spec: NotificationSpec): Handle => { if (spec.subtitle.length > 0) { msgSendPtr(notification, rt.selectors.get('setSubtitle:'), nsString(spec.subtitle)); } - // `silent` suppresses the default sound. NSUserNotification plays a sound only - // if `soundName` is set, so the default (no sound) already honours silent; - // when NOT silent we opt into the default sound name. + // NSUserNotification is silent unless soundName is set. if (!spec.silent) { msgSendPtr( notification, @@ -88,10 +64,6 @@ const buildNotification = (spec: NotificationSpec): Handle => { return notification; }; -/** - * Build and (best-effort) deliver a notification. Never throws on the un-bundled - * nil-center path; sending to a nil receiver is a no-op in Objective-C. - */ const present = (spec: NotificationSpec): NotificationHandle => { const rt = cocoa(); const notification = buildNotification(spec); @@ -107,17 +79,11 @@ const present = (spec: NotificationSpec): NotificationHandle => { msgSendPtr(c, rt.selectors.get('removeDeliveredNotification:'), notification); } }, - // No center un-bundled means no delegate to fire a real close, so this is a - // documented no-op on macOS (we do not pretend to wire it). The empty body - // is `() => undefined` to satisfy Biome's noEmptyBlockStatements. - onClosed: () => undefined, + onClosed: () => undefined, // ponytail: the center reports no dismissals; poll deliveredNotifications if 'close' is needed. }; }; -/** - * Honest macOS support: `true` only when the default notification center is - * non-nil (requires an app bundle). Un-bundled this returns `false`. - */ +/** True only in a bundled app, where the default center is non-nil. */ const isSupported = (): boolean => { try { return defaultCenter() !== 0n; @@ -126,7 +92,6 @@ const isSupported = (): boolean => { } }; -/** The macOS native notification backend (NSUserNotification, un-bundled-aware). */ export const macosNotificationBackend: NotificationBackend = { isSupported, present, diff --git a/src/main/platform/macos/cocoa-power-save-blocker.ts b/src/main/platform/macos/cocoa-power-save-blocker.ts index e5df537e..e8a6058a 100644 --- a/src/main/platform/macos/cocoa-power-save-blocker.ts +++ b/src/main/platform/macos/cocoa-power-save-blocker.ts @@ -8,31 +8,11 @@ import type { import { nsString } from './cocoa-foundation'; import { macOSLibraryAccessor } from './objc'; -/** - * macOS power-save blocker via IOKit power-management assertions. - * - * `IOPMAssertionCreateWithName(assertionType, level, name, &id)` creates a named assertion - * held by `powerd`; `IOPMAssertionRelease(id)` drops it. Both are SYNCHRONOUS C calls (a - * Mach round-trip to powerd) that need NO CFRunLoop and no window, so they are safe on - * Bunmaska's pumped main thread with nothing running. - * - * Type → assertion (verified against IOKit's IOPMLib.h): - * - 'prevent-app-suspension' → kIOPMAssertPreventUserIdleSystemSleep ("PreventUserIdleSystemSleep") - * - 'prevent-display-sleep' → kIOPMAssertPreventUserIdleDisplaySleep ("PreventUserIdleDisplaySleep") - * (display-sleep prevention also keeps the system awake, matching Electron's precedence.) - * - * `IOPMAssertionID`/`IOPMAssertionLevel` are `uint32_t`; `kIOPMAssertionLevelOn = 255`; - * success is `kIOReturnSuccess = 0`. The assertion type/name are `CFStringRef`; an NSString - * is toll-free bridged to CFStringRef, so {@link nsString} yields one directly (carried as - * a u64 handle, the codebase's CF/ObjC-handle convention). The out-param `IOPMAssertionID*` - * is a one-element `Uint32Array`. - */ +// IOPMAssertion calls are synchronous Mach round-trips to powerd; no run loop needed (D038). const IOKIT_PATH = '/System/Library/Frameworks/IOKit.framework/IOKit'; -/** kIOPMAssertionLevelOn — assertion active (IOPMLib.h: 255). */ const K_IOPM_ASSERTION_LEVEL_ON = 255; -/** kIOReturnSuccess. */ const K_IO_RETURN_SUCCESS = 0; const ASSERTION_TYPE: Record = { @@ -61,7 +41,7 @@ const loadIOKitFFI = macOSLibraryAccessor('IOKit powerSaveBlocker', () => dlopen(IOKIT_PATH, IOKIT_SYMBOLS), ); -/** Create a power assertion and return its `IOPMAssertionID`, or null on failure. */ +/** The new assertion's `IOPMAssertionID`, or null on failure. */ const acquire = (type: PowerSaveBlockerType): NativeBlocker | null => { const iokit = loadIOKitFFI(); const outId = new Uint32Array(1); @@ -82,5 +62,4 @@ const release = (handle: NativeBlocker): void => { loadIOKitFFI().symbols.IOPMAssertionRelease(handle as number); }; -/** The macOS power-save-blocker backend (IOKit assertions). */ export const cocoaPowerSaveBlockerBackend: PowerSaveBlockerBackend = { acquire, release }; diff --git a/src/main/platform/macos/cocoa-power.ts b/src/main/platform/macos/cocoa-power.ts index c6349fcd..d039b6cc 100644 --- a/src/main/platform/macos/cocoa-power.ts +++ b/src/main/platform/macos/cocoa-power.ts @@ -4,17 +4,7 @@ import { workspaceNotificationCenter, } from './cocoa-notification-observer'; -/** - * macOS power + screen-lock events for `powerMonitor`. - * - * Sleep/wake are posted on the NSWorkspace notification center - * (`NSWorkspaceWillSleepNotification` / `NSWorkspaceDidWakeNotification`); screen - * lock/unlock are the (undocumented but stable, AppKit-wide) distributed - * notifications `com.apple.screenIsLocked` / `com.apple.screenIsUnlocked`. All - * four are wired through the shared notification observer (D034) and delivered on - * the pumped run loop (D020/D021). Names are passed by value, mirroring the - * appearance observer. - */ +// Screen lock/unlock use the undocumented but long-stable com.apple.screenIs(Un)locked names. const WILL_SLEEP = 'NSWorkspaceWillSleepNotification'; const DID_WAKE = 'NSWorkspaceDidWakeNotification'; diff --git a/src/main/platform/macos/cocoa-safe-storage.ts b/src/main/platform/macos/cocoa-safe-storage.ts index 2c109a9d..d4cf5217 100644 --- a/src/main/platform/macos/cocoa-safe-storage.ts +++ b/src/main/platform/macos/cocoa-safe-storage.ts @@ -8,22 +8,12 @@ import { cocoa } from './cocoa-runtime'; import type { Handle } from './objc'; import { loadSecurityFFI, secConstants } from './security-ffi'; -/** - * macOS Keychain backend for `safeStorage`. The 32-byte key is a - * `kSecClassGenericPassword` item under a fixed service+account, created on first - * use. The query is an `NSMutableDictionary` (toll-free bridged to - * `CFDictionaryRef`), avoiding `CFDictionaryCreate` and its callback-struct - * globals; the keys are the REAL exported `kSec*` constants (SecItem compares - * keys by pointer identity). The item is created with - * `kSecAttrAccessibleWhenUnlockedThisDeviceOnly` so the key is device-bound and - * never syncs to iCloud Keychain. - */ +// SecItem matches dictionary keys by pointer: always use the exported kSec* constants (security-ffi.ts). const ERR_SEC_SUCCESS = 0; const ERR_SEC_ITEM_NOT_FOUND = -25300; const ERR_SEC_DUPLICATE_ITEM = -25299; -/** `[dict setObject:value forKey:key]`. */ const dictSet = (dict: Handle, value: Handle, key: Handle): void => { const rt = cocoa(); msgSendPtrPtr(dict, rt.selectors.get('setObject:forKey:'), value, key); @@ -73,7 +63,7 @@ export const makeMacosKeychainBackend = (service: string, account: string): Keyr const data = nsDataFromBytes(key); dictSet(query, data, k.kSecValueData); cocoa().msgSend(data, cocoa().selectors.get('release')); // the dictionary retains it - // Device-bound, non-syncing accessibility. + // The file-based login keychain ignores this (it stores no pdmn), but it never syncs to iCloud. dictSet(query, k.kSecAttrAccessibleWhenUnlockedThisDeviceOnly, k.kSecAttrAccessible); const status = sec.symbols.SecItemAdd(query, null); if (status === ERR_SEC_SUCCESS) { @@ -104,7 +94,7 @@ export const makeMacosKeychainBackend = (service: string, account: string): Keyr if (addKey(fresh)) { return fresh; } - // Lost the add race — adopt the winner's key. + // Lost the add race: adopt the winner's key. const winner = lookupKey(); if (winner === null) { throw new Error('safeStorage: key vanished after a duplicate-item race'); @@ -119,7 +109,7 @@ export const deleteMacosKeychainItem = (service: string, account: string): void loadSecurityFFI().symbols.SecItemDelete(identityQuery(service, account)); }; -/** The production macOS Keychain backend. */ +// ponytail: one Keychain item for every Bunmaska app on the machine; key it by app name via api/safe-storage.ts. export const macosKeychainBackend = makeMacosKeychainBackend( 'dev.bunmaska.safeStorage', 'master-key', diff --git a/src/main/platform/macos/cocoa-screen.ts b/src/main/platform/macos/cocoa-screen.ts index 9a6f2d3a..28ff4b38 100644 --- a/src/main/platform/macos/cocoa-screen.ts +++ b/src/main/platform/macos/cocoa-screen.ts @@ -13,10 +13,8 @@ import { import { cocoa } from './cocoa-runtime'; import { type Handle, macOSLibraryAccessor } from './objc'; -/** - * macOS displays. bun:ffi cannot return an NSRect/NSPoint struct, so geometry is read - * through KVC (`valueForKey:` boxes it in an NSValue) and copied out with `getValue:size:`. - */ +// bun:ffi cannot return an NSRect/NSPoint struct, so geometry goes through KVC (valueForKey: +// boxes it in an NSValue) and is copied out with getValue:size:. const CG_PATH = '/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics'; diff --git a/src/main/platform/macos/cocoa-shell.ts b/src/main/platform/macos/cocoa-shell.ts index 185a752b..f64f0d3a 100644 --- a/src/main/platform/macos/cocoa-shell.ts +++ b/src/main/platform/macos/cocoa-shell.ts @@ -6,11 +6,6 @@ import { cocoa } from './cocoa-runtime'; import { macOSLibraryAccessor } from './objc'; import type { Handle } from './objc'; -/** - * Desktop integration via `NSWorkspace` and `NSBeep` — the macOS half of - * Electron's `shell`. - */ - const APPKIT_PATH = '/System/Library/Frameworks/AppKit.framework/AppKit'; const getNSBeep = macOSLibraryAccessor('NSBeep', () => diff --git a/src/main/platform/macos/cocoa-tray.ts b/src/main/platform/macos/cocoa-tray.ts index 20d49244..4c1a0a7c 100644 --- a/src/main/platform/macos/cocoa-tray.ts +++ b/src/main/platform/macos/cocoa-tray.ts @@ -7,25 +7,7 @@ import { cocoa } from './cocoa-runtime'; import { defineObjcClass } from './cocoa-runtime-class'; import type { Handle } from './objc'; -/** - * macOS status-bar items via `NSStatusItem` — the macOS half of Bunmaska's `Tray`. - * - * RETAIN: `[NSStatusBar systemStatusBar] statusItemWithLength:` returns an - * autoreleased item that AppKit otherwise owns; Bunmaska retains it on creation so - * the bigint handle stays valid for the tray's whole lifetime, and releases it in - * {@link TrayInstance.destroy} after `removeStatusItem:`. - * - * CLICK: the status button's target/action is wired to a retained - * `BunmaskaTrayTarget` whose IMP looks the button up in a registry and fires the - * JS `click` callback. The target object and its `JSCallback` are retained for the - * runtime's lifetime (the class is registered once and never torn down), so the - * IMP is never freed inside its own invocation — avoiding the lifecycle SIGSEGV - * class. NOTE: when a context menu is set, AppKit consumes the click to show the - * menu, so `click` fires only when no menu is set (this matches Electron's - * "menu shows on click" behaviour). - */ - -/** `NSVariableStatusItemLength` — a variable-width status item. */ +/** `NSVariableStatusItemLength`. */ const NS_VARIABLE_STATUS_ITEM_LENGTH = -1; const clickRegistry = new Map void>(); @@ -77,12 +59,11 @@ const create = (image: string, options?: TrayImageOptions): TrayInstance => { rt.selectors.get('statusItemWithLength:'), NS_VARIABLE_STATUS_ITEM_LENGTH, ); - // Retain: the returned item is autoreleased and owned by AppKit otherwise. + // statusItemWithLength: returns +0; hold our own reference until destroy() releases it. const item = rt.msgSend(rawItem, rt.selectors.get('retain')); const button = (): Handle => rt.msgSend(item, rt.selectors.get('button')); - // Guard a nil image (bad path) — set it only when it actually loaded. const applyImage = (path: string, template: boolean): void => { const btn = button(); if (btn === 0n) { @@ -118,8 +99,6 @@ const create = (image: string, options?: TrayImageOptions): TrayInstance => { applyImage(path, options?.template === true); }, setContextMenu: (menu: Menu | null) => { - // Reuse the Menu realizer so tray-menu clicks route through the shared - // BunmaskaMenuTarget registry, exactly like an application menu. const nsMenu: Handle = menu === null ? 0n : menu.realize(); msgSendPtr(item, rt.selectors.get('setMenu:'), nsMenu); disposeMenu(contextMenu); From 71b8d5deca80a89c25023f7ce8211a402eb1aeaa Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:05:25 -0700 Subject: [PATCH 142/586] test: correct the stale Carbon shortcut test header --- .../integration/macos/carbon-global-shortcut.test.ts | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/tests/integration/macos/carbon-global-shortcut.test.ts b/tests/integration/macos/carbon-global-shortcut.test.ts index df8a303f..1f624c47 100644 --- a/tests/integration/macos/carbon-global-shortcut.test.ts +++ b/tests/integration/macos/carbon-global-shortcut.test.ts @@ -40,16 +40,8 @@ const pressHotKey = (signature: number, id: number): number => { return status; }; -/** - * macOS-only. Exercises the REAL Carbon `RegisterEventHotKey` path on the host. - * - * Triggering a genuine system hot-key press headlessly is not reliably possible, - * so — like the dialog/notification construction tests — this asserts the - * register/unregister LIFECYCLE runs cleanly with no crash (no SIGSEGV from the - * retained handler JSCallback or the packed-u64 EventHotKeyID), and that state is - * tracked correctly. The packed-u64 struct-by-value workaround returning `noErr` - * is what makes `register` return `true` here. - */ +// A real key press cannot be injected headlessly, so hot-key events are synthesized and sent +// straight to the application event target, which runs the same handler. const isMac = currentPlatform() === 'macos'; describe.skipIf(!isMac)('carbon-global-shortcut (macOS)', () => { From cf4fc67090cb69d38f04338459fd82b620919e93 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:06:27 -0700 Subject: [PATCH 143/586] chore: trim macOS backend comments to the comment rules --- src/main/platform/macos/cocoa-backend.ts | 196 ++++++----------------- 1 file changed, 47 insertions(+), 149 deletions(-) diff --git a/src/main/platform/macos/cocoa-backend.ts b/src/main/platform/macos/cocoa-backend.ts index c2fa161d..a5fd9963 100644 --- a/src/main/platform/macos/cocoa-backend.ts +++ b/src/main/platform/macos/cocoa-backend.ts @@ -43,6 +43,7 @@ import { msgSendPtrI64, msgSendPtrPtr, msgSendPtrReturnsU8, + msgSendRectU8, msgSendReturnsI64, msgSendReturnsU8, msgSendSize, @@ -52,7 +53,6 @@ import { nsDataToBytes } from './cocoa-native-image'; import { createNavigationDelegate } from './cocoa-navigation-delegate'; import { createMacOSDrain } from './cocoa-run-loop'; import { primaryDisplayHeight } from './cocoa-screen'; -import { msgSendRectU8 } from './cocoa-msgsend-variants'; import { createScriptMessageHandler } from './cocoa-script-message-handler'; import { cocoa } from './cocoa-runtime'; import { defineObjcClass } from './cocoa-runtime-class'; @@ -67,12 +67,6 @@ import { loadWebKit } from './cocoa-webkit'; import { createWindowDelegate } from './cocoa-window-delegate'; import type { Handle } from './objc'; -/** - * The macOS native backend: `NativeApplication` / `NativeWindow` / - * `NativeWebContents` on the AppKit + WebKit FFI primitives and the cooperative - * CF run-loop pump (D020). Objective-C handles stay bigints (D016/D029). - */ - const log = createLogger('macos-backend'); const NS_BACKING_STORE_BUFFERED = 2n; @@ -80,7 +74,6 @@ const NS_ACTIVATION_POLICY_REGULAR = 0n; /** `NSEventMaskAny` (NSUIntegerMax): dequeue every kind of AppKit event. */ const NS_EVENT_MASK_ANY: Handle = 0xffffffffffffffffn; -/** `dequeue:YES` for `nextEventMatchingMask:`. */ const DEQUEUE_YES: Handle = 1n; /** Upper bound on events dispatched per pump tick, so a flood can't starve Bun. */ const APP_EVENT_BUDGET = 256; @@ -115,7 +108,7 @@ const nsImageToPng = (image: Handle): Uint8Array => { ); return nsDataToBytes(png); }; -/** `NSFloatingWindowLevel` — above normal windows. */ +/** `NSFloatingWindowLevel`. */ const NS_FLOATING_WINDOW_LEVEL = 3n; const WK_INJECTION_TIME_AT_DOCUMENT_START = 0n; /** Electron runs preloads in the main frame only; an iframe must never get the bridge. */ @@ -123,7 +116,7 @@ const FOR_MAIN_FRAME_ONLY = 1; const SCRIPT_MESSAGE_HANDLER_NAME = 'bunmaska'; /** Page-world handler name `executeJavaScript` posts its result to (D022). */ const EXEC_RESULT_HANDLER_NAME = 'bunmaskaExec'; -/** Reject a pending printToPDF/capturePage after this long (ms) — a bounded render op. */ +/** Milliseconds before a pending printToPDF/capturePage rejects. */ const RENDER_TIMEOUT_MS = 30_000; /** Name of the isolated `WKContentWorld` the bridge + user preload run in. */ export const PRELOAD_WORLD_NAME = 'BunmaskaPreload'; @@ -138,11 +131,7 @@ type PendingExec = { const dispatchScript = (envelopeJson: string): string => `window.__bunmaska && window.__bunmaska._dispatch(${JSON.stringify(envelopeJson)});`; -/** - * Turn on `developerExtrasEnabled` on a `WKPreferences` via KVC so the inspector - * is available. Best-effort: the key is undocumented SPI, so a failure to set it - * must not abort window creation. - */ +/** Enable the inspector through the undocumented `developerExtrasEnabled` KVC key; best-effort. */ const enableDeveloperExtras = (preferences: Handle): void => { if (preferences === 0n) { return; @@ -304,12 +293,9 @@ class MacOSWebContents implements NativeWebContents { } /** - * @internal Mark destroyed and settle every still-pending exec; called on - * window close BEFORE the web view is torn down. In-flight execs resolve to - * `undefined` — a normally closed window is not a hard error and a - * fire-and-forget caller must not receive an unhandled rejection. Any later - * `executeJavaScript` is rejected by the `#destroyed` guard without touching - * the freed web view. + * @internal Close-path teardown. In-flight execs resolve to `undefined`: a + * closed window is not an error, and a fire-and-forget caller must not get an + * unhandled rejection. */ rejectPendingExecs(): void { this.#destroyed = true; @@ -324,8 +310,7 @@ class MacOSWebContents implements NativeWebContents { /** @internal Called by the navigation delegate for each navigation event. */ deliverNavigation(event: NativeNavigationEvent): void { - // Same contract as the Linux backend: envelopes sent before the first - // finished load are queued and flushed here, not silently dropped. + // Sends before the first finished load are queued, not dropped (same contract as Linux). if (event.type === 'did-finish-load' && !this.#didFinishLoad) { this.#didFinishLoad = true; const queued = [...this.#pendingEnvelopes]; @@ -412,10 +397,8 @@ class MacOSWebContents implements NativeWebContents { } /** - * Evaluate `code` in the PAGE world (Electron's main world) and resolve to its - * completion value. A completion-handler block crashes Bun (D022), so the - * result returns out-of-band: a wrapper runs the code and posts the outcome to - * the page-world `bunmaskaExec` handler, which settles the matching Promise. + * Evaluate `code` in the page world (Electron's main world). The result comes + * back through the page-world `bunmaskaExec` handler, not a completion block (D022). */ executeJavaScript(code: string): Promise { if (this.#destroyed) { @@ -433,11 +416,7 @@ class MacOSWebContents implements NativeWebContents { }); } - /** - * Render the page to PDF via `-[WKWebView createPDFWithConfiguration:nil - * completionHandler:]`. The completion handler is a hand-built ObjC Block - * (D022b) that fires on the pumped run loop; we resolve its `NSData` bytes. - */ + /** PDF bytes from `createPDFWithConfiguration:completionHandler:` (a D022b block). */ printToPDF(): Promise { if (this.#destroyed) { return Promise.reject(new Error('printToPDF failed: web contents destroyed')); @@ -468,11 +447,7 @@ class MacOSWebContents implements NativeWebContents { }); } - /** - * Snapshot the page via `-[WKWebView takeSnapshotWithConfiguration:nil - * completionHandler:]` (a hand-built ObjC Block, D022b) and resolve the PNG - * bytes of the resulting `NSImage`. - */ + /** PNG bytes from `takeSnapshotWithConfiguration:completionHandler:` (a D022b block). */ capturePage(): Promise { if (this.#destroyed) { return Promise.reject(new Error('capturePage failed: web contents destroyed')); @@ -510,13 +485,7 @@ class MacOSWebContents implements NativeWebContents { throw new UnsupportedPlatformError('webContents.sendInputEvent is not yet supported on macOS'); } - /** - * Open the web inspector. Developer extras are enabled at view creation, so - * the inspector is always available via right-click → Inspect Element; this - * also drives it open programmatically through the private `-[WKWebView - * _inspector]` + `-[_WKInspector show]` selectors. Those are private SPI: the - * whole call is best-effort and never throws if the selectors are absent. - */ + /** Show the inspector through the private `-[WKWebView _inspector]` SPI; never throws. */ openDevTools(): void { try { const rt = cocoa(); @@ -548,7 +517,7 @@ class MacOSWebContents implements NativeWebContents { } setUserAgent(userAgent: string): void { - // WKWebView.customUserAgent; takes effect on the next navigation. + // Takes effect on the next navigation. msgSendPtr(this.#webview, cocoa().selectors.get('setCustomUserAgent:'), nsString(userAgent)); } @@ -564,11 +533,7 @@ class MacOSWebContents implements NativeWebContents { this.#evaluateInWorld(dispatchScript(envelopeJson), this.#isolatedWorld); } - /** - * Evaluate `code` in a specific `WKContentWorld` via - * `evaluateJavaScript:inFrame:inContentWorld:completionHandler:` (macOS 11+). - * `frame = 0n` (main frame), completion handler `0n` (fire-and-forget, D022). - */ + /** Fire-and-forget in `world`'s main frame: nil frame, nil completion handler (D022). */ #evaluateInWorld(code: string, world: Handle): void { const rt = cocoa(); msgSendPtr4( @@ -603,6 +568,7 @@ class MacOSWindow implements NativeWindow { #onClosed: (() => void) | undefined; #onClose: (() => boolean) | undefined; #activePopupMenu: Handle = 0n; + #zoomed = false; readonly #eventHandlers = new Map void>(); constructor( @@ -621,20 +587,15 @@ class MacOSWindow implements NativeWindow { return this.#contents; } - /** - * @internal `windowShouldClose:` hook. Consults the registered JS close - * listener (preventable). Returns true to VETO. Called by the window delegate. - */ + /** @internal `windowShouldClose:` hook; true vetoes the close. */ shouldClose(): boolean { return this.#onClose?.() === true; } /** - * @internal `windowWillClose:` hook. AppKit has committed to closing on EVERY - * path here — title-bar button, programmatic `-close`, or `app.quit()`. Run - * the idempotent teardown (settle pending execs, detach script handlers) so a - * later `executeJavaScript` can never touch a freed `WKWebView`, then fire the - * `closed` bookkeeping. THIS is the close-path use-after-free fix. + * @internal `windowWillClose:` hook, reached on every AppKit close path + * (title-bar button, performClose:, -close). Tears down before any listener + * runs, so nothing touches the web view after it. */ willClose(): void { if (this.#tornDown) { @@ -643,18 +604,14 @@ class MacOSWindow implements NativeWindow { this.#tornDown = true; // Messaging nil is a no-op, so every later call is safe once the window is released. this.#window = 0n; - // Balance our alloc of the NSWindow + WKWebView (both kept alive by - // setReleasedWhenClosed:NO) on a LATER tick — AppKit's -close is still on the - // stack here, so releasing now would risk the use-after-free that flag avoids. - // Scheduled before any listener runs, so a throwing one cannot skip it. + // Release our +1s a tick later: AppKit's -close is still on the stack here. + // Scheduled first, so a throwing listener cannot skip it. setTimeout(this.#releaseNative, 0); this.#teardown(); this.#onClosed?.(); } /** @internal Surface a non-preventable lifecycle event. Called by the delegate. */ - #zoomed = false; - emitEvent(type: WindowEventType): void { if (this.#tornDown) { return; @@ -691,10 +648,9 @@ class MacOSWindow implements NativeWindow { } /** - * The FRAME rect in top-left global space. `-frame` returns a struct by value - * (D018), so it is read through KVC into an out buffer: AppKit's own model, - * current right after setFrame: and for never-shown windows, unlike the - * asynchronously updated window-server list. + * The FRAME rect, top-left global. `-frame` returns a struct by value (D018), so + * it is read through KVC into an out buffer. Unlike the window-server list, this + * is current right after setFrame: and for a never-shown window. */ #frame(): Rect { if (this.#tornDown) { @@ -733,7 +689,6 @@ class MacOSWindow implements NativeWindow { } setResizable(resizable: boolean): void { - // Read-modify-write the style mask so other bits (titled/closable/…) survive. const mask = msgSendReturnsI64(this.#window, cocoa().selectors.get('styleMask')); const next = resizable ? mask | NS_RESIZABLE_STYLE_MASK : mask & ~NS_RESIZABLE_STYLE_MASK; msgSendI64(this.#window, cocoa().selectors.get('setStyleMask:'), next); @@ -762,15 +717,13 @@ class MacOSWindow implements NativeWindow { msgSendPtr(this.#window, rt.selectors.get('orderFront:'), 0n); } else { msgSendPtr(this.#window, rt.selectors.get('makeKeyAndOrderFront:'), 0n); - // Activate the app so the shown window comes to the foreground. const app = rt.msgSend( rt.classes.get('NSApplication'), rt.selectors.get('sharedApplication'), ); msgSendU8(app, rt.selectors.get('activateIgnoringOtherApps:'), 1); } - // AppKit has no `windowDidShow:` notification, so `show` is emitted here. A - // becomeKey notification also fires `focus` via the delegate. + // AppKit has no windowDidShow: notification; focus arrives via windowDidBecomeKey:. this.emitEvent('show'); } @@ -849,11 +802,8 @@ class MacOSWindow implements NativeWindow { if (this.#tornDown) { return; } - // Route through the SAME delegate path the title-bar red button uses: - // `-performClose:` (NOT `-close`, which bypasses the delegate) triggers - // `windowShouldClose:` (the veto) then, if allowed, `windowWillClose:` - // (teardown + `closed`). No teardown here — `willClose()` owns it, - // idempotently — so a vetoed programmatic close leaves the window fully alive. + // performClose: asks windowShouldClose: (the veto) like the title-bar button; + // -close would skip it. willClose() owns the teardown. msgSendPtr(this.#window, cocoa().selectors.get('performClose:'), 0n); } @@ -861,8 +811,7 @@ class MacOSWindow implements NativeWindow { if (this.#tornDown) { return; } - // `-close` (not `-performClose:`) fires windowWillClose: (teardown + closed) - // WITHOUT windowShouldClose:, so it bypasses the preventable veto. + // -close skips windowShouldClose:, so the veto cannot stop it. cocoa().msgSend(this.#window, cocoa().selectors.get('close')); } @@ -907,7 +856,7 @@ class MacOSApplication implements NativeApplication { #onActivate: ((hasVisibleWindows: boolean) => void) | undefined; #onOpenUrl: ((url: string) => void) | undefined; #onOpenFile: ((path: string) => void) | undefined; - // Handles the cooperative pump uses to dispatch AppKit input events each tick. + // Cached arguments for the per-tick AppKit event pump. #nextEventSel: Handle = 0n; #sendEventSel: Handle = 0n; #distantPast: Handle = 0n; @@ -935,8 +884,7 @@ class MacOSApplication implements NativeApplication { msgSendU8(this.#app, rt.selectors.get('activateIgnoringOtherApps:'), 1); } - // `nextEventMatchingMask:` runs every pump tick; cache its arguments. The - // mode string is autoreleased, so retain it for the app's lifetime. + // The mode string is autoreleased; retain it for the app's lifetime. this.#nextEventSel = rt.selectors.get('nextEventMatchingMask:untilDate:inMode:dequeue:'); this.#sendEventSel = rt.selectors.get('sendEvent:'); this.#distantPast = rt.msgSend(rt.classes.get('NSDate'), rt.selectors.get('distantPast')); @@ -954,11 +902,7 @@ class MacOSApplication implements NativeApplication { } } - /** - * Deliver pending AppKit input events to their windows — the standard - * `nextEventMatchingMask:` / `sendEvent:` loop, run non-blockingly - * (`untilDate:` distantPast) so it drains the queue and returns each tick. - */ + /** Dispatch queued AppKit input events without blocking (untilDate: distantPast). */ #pumpAppEvents(): void { if (this.#app === 0n) { return; @@ -1029,9 +973,8 @@ class MacOSApplication implements NativeApplication { false, ); - // AppKit defaults releasedWhenClosed to YES for programmatic NSWindows, so a - // close would dealloc it while we still hold the handle (use-after-free). We - // own the lifetime — release explicitly in teardown instead. + // 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')); @@ -1041,37 +984,25 @@ class MacOSApplication implements NativeApplication { rt.selectors.get('init'), ); - // Enable developer extras so the web inspector is available (right-click → - // Inspect Element, and webContents.openDevTools()). `developerExtrasEnabled` - // is a KVC key on WKPreferences; set via setValue:forKey: with an NSNumber. enableDeveloperExtras(rt.msgSend(configuration, rt.selectors.get('preferences'))); - // Wire every custom scheme registered via `protocol.handle` onto THIS - // configuration with `setURLSchemeHandler:forURLScheme:` — it can only be set - // on the config BEFORE the web view is created (not after). One shared - // `WKURLSchemeHandler` instance serves all schemes; it routes each request - // through `protocol.dispatch`. Schemes registered after this window is - // created are NOT served by it (Electron has the same before-create rule). + // A scheme handled after this window exists is not served by it (Electron's rule too). registerCustomSchemes(configuration); - // The web view (and thus its contents) does not exist until after the - // configuration is built, so the handler forwards to a late-bound contents - // reference rather than capturing it directly. + // 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'), ); - // Inject the bridge + user preload into a dedicated isolated world so they - // are invisible to page scripts (Electron `contextIsolation: true`). + // 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), ); - // Register the handler IN the isolated world so its `webkit.messageHandlers` - // binding is reachable only from there. + // Only the isolated world can reach this handler. msgSendPtr3( userContentController, rt.selectors.get('addScriptMessageHandler:contentWorld:name:'), @@ -1080,10 +1011,8 @@ class MacOSApplication implements NativeApplication { nsString(SCRIPT_MESSAGE_HANDLER_NAME), ); - // Second handler in the PAGE world: the return channel for the public - // `executeJavaScript`, whose wrapper posts its result here (D022). The page - // world is a WebKit-interned singleton, so `pageWorld()` returns the same - // handle at teardown — no need to retain the autoreleased value here. + // executeJavaScript's return channel (D022). pageWorld() is interned by WebKit, + // so teardown gets the same handle without a retain here. const execHandler = createScriptMessageHandler((json) => contents?.deliverExecResult(json)); msgSendPtr3( userContentController, @@ -1093,8 +1022,7 @@ class MacOSApplication implements NativeApplication { nsString(EXEC_RESULT_HANDLER_NAME), ); - // Page-world dom-ready channel: an injected script posts here on - // DOMContentLoaded, surfacing Electron's `dom-ready`. + // The page world's DOMContentLoaded surfaces Electron's dom-ready. const domReadyHandler = createScriptMessageHandler(() => contents?.deliverNavigation({ type: 'dom-ready' }), ); @@ -1119,27 +1047,17 @@ class MacOSApplication implements NativeApplication { rt.msgSend(userScript, rt.selectors.get('release')); }; - // Per-window cross-world channel id for contextBridge (Phase B). The page - // stub and the isolated host both bake it in at inject time. const channelId = generateChannelId(); - - // Isolated world: record the channel id, then the bridge, then the - // contextBridge host (installs `__bunmaska.exposeInMainWorld`), then the user - // preload — so `window.__bunmaska` + the channel + exposeInMainWorld all exist - // when the user preload runs and calls exposeInMainWorld. + // Order matters: exposeInMainWorld must exist before the user preload runs. addUserScript(generateIsolatedChannelSetup(channelId), isolatedWorld); addUserScript(generatePreloadBootstrap(), isolatedWorld); addUserScript(generateIsolatedHostSource(channelId), isolatedWorld); if (options.preloadScript !== undefined) { addUserScript(options.preloadScript, isolatedWorld); } - // Page world: the cross-world stub that materialises contextBridge surfaces, - // and the dom-ready notifier. addUserScript(generatePageWorldStub(channelId), pageWorld()); - // Custom (frameless) title bars: the page-world script only mirrors `--app-region` - // onto `-webkit-app-region`, which WKWebView drags natively. The window-op controls - // (`window.__bunmaska.window`) belong on the isolated-world bridge (a follow-up), - // never the page world — a `__bunmaska` handle there would defeat context isolation. + // Never put __bunmaska in the page world: it would defeat context isolation. + // ponytail: --app-region mirror only; window-op controls wait for the isolated bridge (D045) addUserScript(windowControlsScript(), pageWorld()); addUserScript(generateDomReadyScript(), pageWorld()); @@ -1153,13 +1071,9 @@ class MacOSApplication implements NativeApplication { rt.msgSend(configuration, rt.selectors.get('release')); contents = new MacOSWebContents(webview, isolatedWorld); - // Forward-declared so the navigation + window delegate closures can reference - // it; assigned once the teardown closure (below) exists. The closures only - // run on later native callbacks, after the assignment. + // Assigned below; the delegate closures only run on later native callbacks. let nativeWindow: MacOSWindow; - // `ready-to-show` is emitted once, on the FIRST finished load, reusing the - // navigation delegate's did-finish-load signal. let readyToShowEmitted = false; const navigationDelegate = createNavigationDelegate((event) => { contents?.deliverNavigation(event); @@ -1170,18 +1084,13 @@ class MacOSApplication implements NativeApplication { }); msgSendPtr(webview, rt.selectors.get('setNavigationDelegate:'), navigationDelegate.handle); - // WKUIDelegate: route window.open / target=_blank to the JS handler (returns - // nil so no child web view is created). Retained by its registry, like the - // nav delegate. + // 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)); - // Teardown run on window close: detach both handlers from their worlds, drop - // their registry entries + release the native instances, and reject any - // exec Promise still awaiting a result it can no longer receive. const teardown = (): void => { msgSendPtrPtr( userContentController, @@ -1207,15 +1116,9 @@ class MacOSApplication implements NativeApplication { contents?.rejectPendingExecs(); }; - // Deferred, post-close balance of the two objects we alloc'd and kept alive - // with setReleasedWhenClosed:NO. Detach the delegate first so no late - // notification fires, then release the WKWebView and the NSWindow (the window - // dealloc cascades to its content view). The delegate's JSCallback IMPs are - // process-lifetime (defineObjcClass) and are NOT released here. + // Detach the delegate before releasing, so no late notification fires. const releaseNative = (): void => { msgSendPtr(window, rt.selectors.get('setDelegate:'), 0n); - // The three delegates were alloc'd per window and previously leaked with - // their registry entries on every close. navigationDelegate.destroy(); uiDelegate.destroy(); windowDelegate.destroy(); @@ -1225,11 +1128,6 @@ class MacOSApplication implements NativeApplication { nativeWindow = new MacOSWindow(window, contents, teardown, releaseNative); - // Set the NSWindowDelegate: it routes `windowShouldClose:` (the preventable - // veto) and `windowWillClose:` (teardown + `closed`) plus the key/resize/ - // miniaturize lifecycle notifications into the window. The delegate's IMP - // JSCallbacks are retained for the process lifetime by `defineObjcClass`, so - // they are never freed inside their own invocation (JSCallback discipline). const windowDelegate = createWindowDelegate({ shouldClose: () => nativeWindow.shouldClose(), willClose: () => nativeWindow.willClose(), From ede389f8dfef0c6d4df6a2a723b393976d9596a8 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:07:12 -0700 Subject: [PATCH 144/586] chore: trim run-loop pump comments to the comment rules --- src/main/platform/macos/cocoa-run-loop.ts | 17 +++---------- src/main/run-loop.ts | 29 ++++++----------------- 2 files changed, 10 insertions(+), 36 deletions(-) diff --git a/src/main/platform/macos/cocoa-run-loop.ts b/src/main/platform/macos/cocoa-run-loop.ts index ede1bb0a..4761b875 100644 --- a/src/main/platform/macos/cocoa-run-loop.ts +++ b/src/main/platform/macos/cocoa-run-loop.ts @@ -3,17 +3,6 @@ import { dlopen } from '../dlopen'; import { cstr } from '../cstr'; import { bigIntOut, LIBOBJC_PATH, macOSLibraryAccessor, ptrIn } from './objc'; -/** - * macOS native run-loop drain. - * - * Returns a function the {@link AdaptiveBlockingPump} calls each tick with a - * timeout. A UI event returns it immediately (returnAfterSourceHandled), so the - * thread sleeps when idle yet wakes the instant input arrives. Returns whether a - * source was handled — the pump stays responsive while that holds and backs off - * when it doesn't. Each drain runs inside an autorelease pool so per-tick - * temporaries are released. - */ - const CORE_FOUNDATION_PATH = '/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation'; const K_CF_STRING_ENCODING_UTF8 = 0x08000100; @@ -62,9 +51,9 @@ export const withAutoreleasePool = (fn: () => T): T => { let jsPool: Pointer | null | undefined; /** - * Create the macOS drain function. Throws {@link UnsupportedPlatformError} on - * any non-macOS host (via the lazy accessors). The returned function is cheap - * to call repeatedly and never blocks. + * The macOS drain for AdaptiveBlockingPump (D047). It blocks in CFRunLoopRunInMode + * for up to `timeoutMs`, returns early once a source is handled, and reports + * whether one was. Throws UnsupportedPlatformError off macOS. */ export const createMacOSDrain = (pumpEvents?: () => void): ((timeoutMs: number) => boolean) => { const cf = getCoreFoundation(); diff --git a/src/main/run-loop.ts b/src/main/run-loop.ts index 393595e5..2d2de053 100644 --- a/src/main/run-loop.ts +++ b/src/main/run-loop.ts @@ -1,14 +1,6 @@ import { createLogger } from '../common/logger'; -/** - * Cooperative run-loop pump. - * - * Bun owns the main thread and its event loop; native UI toolkits (AppKit, GTK) - * need their own run loop pumped to process window events and render. Blocking the - * thread to do that crashes Bun (D019/D020), so the thread is instead lent to the - * native loop for a non-blocking drain (`CFRunLoopRunInMode` on macOS, - * `g_main_context_iteration` on Linux) on a fast timer. - */ +// Bun owns the main thread; the pumps lend it to the native UI loop between turns (D020, D047). const log = createLogger('run-loop'); @@ -45,7 +37,7 @@ export class CooperativePump { return this.#cancel !== undefined; } - /** Begin pumping. Idempotent — a second call while running is a no-op. */ + /** Begin pumping; a no-op while running. */ start(): void { if (this.#cancel !== undefined) { return; @@ -53,7 +45,7 @@ export class CooperativePump { this.#cancel = this.#ticker(() => this.#drainTick(), this.#intervalMs); } - /** Stop pumping. Idempotent — safe to call when not running. */ + /** Stop pumping; a no-op when stopped. */ stop(): void { if (this.#cancel === undefined) { return; @@ -92,15 +84,8 @@ const defaultScheduler: TickScheduler = (tick) => { }; /** - * Adaptive blocking run-loop pump. - * - * Drives a native drain that sleeps until a UI event or a timeout (see the - * platform `createDrain`). Each tick the drain blocks for the current timeout - * and reports whether it handled events; the pump then resets the timeout to - * its minimum (input is flowing — stay responsive) or doubles it toward the - * maximum (idle — sleep deeper for near-zero CPU). Between ticks it yields to - * Bun's loop so JS timers, microtasks and IO run. A UI event wakes the drain - * immediately, so input latency stays ~0 regardless of the idle backoff. + * Drives a drain that blocks until a UI event or its timeout (D047): the timeout + * resets to the minimum after a busy tick and doubles toward the maximum while idle. */ export class AdaptiveBlockingPump { readonly #drain: (timeoutMs: number) => boolean; @@ -129,7 +114,7 @@ export class AdaptiveBlockingPump { return this.#timeoutMs; } - /** Begin pumping. Idempotent — a second call while running is a no-op. */ + /** Begin pumping; a no-op while running. */ start(): void { if (this.#running) { return; @@ -138,7 +123,7 @@ export class AdaptiveBlockingPump { this.#tick(this.#generation); } - /** Stop pumping. Idempotent — safe to call when not running. */ + /** Stop pumping; a no-op when stopped. */ stop(): void { this.#running = false; this.#generation += 1; From ae4092d4042d04b043afc331a49c5d9f48abf10b Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:08:07 -0700 Subject: [PATCH 145/586] chore: fix the stale close-path comment and dashes in pump tests --- tests/integration/macos/window-events.test.ts | 9 ++++----- tests/unit/main/run-loop.test.ts | 4 ++-- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/tests/integration/macos/window-events.test.ts b/tests/integration/macos/window-events.test.ts index 163bb0dc..3127f94e 100644 --- a/tests/integration/macos/window-events.test.ts +++ b/tests/integration/macos/window-events.test.ts @@ -58,7 +58,7 @@ if (currentPlatform() === 'macos') { // `resize` proves the NSWindowDelegate notifications are delivered on the // real backend (windowDidResize:). `focus`/`blur` map to // windowDidBecomeKey:/windowDidResignKey:, which a headless test process - // never receives because it cannot acquire keyboard focus — those are + // never receives because it cannot acquire keyboard focus; those are // covered by the unit suite's fake instead. (Documented platform limit.) const win = new BrowserWindow({ width: 360, height: 240, title: 'resize', show: true }); try { @@ -122,15 +122,14 @@ if (currentPlatform() === 'macos') { expect(win.isDestroyed()).toBe(true); // CRUCIAL use-after-free check: a post-close exec must NOT touch the freed - // WKWebView — the #destroyed guard set by the close-path teardown rejects + // WKWebView: the #destroyed guard set by the close-path teardown rejects // it cleanly instead of crashing. await expect(win.webContents.executeJavaScript('1 + 1')).rejects.toThrow(/destroyed/); }); test('closing via the native delegate path (-close) still runs teardown', async () => { - // BrowserWindow.close() sends -close to the NSWindow, which is exactly the - // path the title-bar red button takes (windowShouldClose: → windowWillClose:). - // Proves teardown is NOT tied to a JS-only code path. + // close() sends performClose:, the title-bar button's path + // (windowShouldClose: then windowWillClose:), so teardown is not JS-only. const win = new BrowserWindow({ width: 360, height: 240, title: 'native-close', show: true }); win.loadURL('about:blank'); await delay(200); diff --git a/tests/unit/main/run-loop.test.ts b/tests/unit/main/run-loop.test.ts index ddcfa41b..0d1529b9 100644 --- a/tests/unit/main/run-loop.test.ts +++ b/tests/unit/main/run-loop.test.ts @@ -44,7 +44,7 @@ describe('CooperativePump.start / stop', () => { expect(m.cancelled()).toBe(true); }); - test('start is idempotent — a second start does not schedule a second ticker', () => { + test('a second start does not schedule a second ticker', () => { let schedules = 0; const ticker: Ticker = () => { schedules += 1; @@ -159,7 +159,7 @@ describe('AdaptiveBlockingPump start / stop', () => { expect(pump.isRunning).toBe(true); }); - test('start is idempotent — a second start does not drain twice', () => { + test('a second start does not drain twice', () => { let drains = 0; const pump = new AdaptiveBlockingPump( () => { From 65b40270455b949ba67c63bcfca30248aa903e6e Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:08:44 -0700 Subject: [PATCH 146/586] fix: reject update manifest names that inject into the install helper --- src/common/manifest.ts | 13 ++++++++++++- tests/unit/common/manifest.test.ts | 22 ++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/src/common/manifest.ts b/src/common/manifest.ts index 5f01c9e3..485689f7 100644 --- a/src/common/manifest.ts +++ b/src/common/manifest.ts @@ -40,6 +40,9 @@ export type UpdateManifest = { readonly artifact: string; }; +// biome-ignore lint/suspicious/noControlCharactersInRegex: control characters are what it rejects. +const UNSAFE_NAME_CHARS = /["%/\\\u0000-\u001f\u007f]/; + /** Serialize an {@link UpdateManifest} to the pretty JSON written to a feed. */ export const serializeUpdateManifest = (manifest: UpdateManifest): string => `${JSON.stringify(manifest, null, 2)}\n`; @@ -82,8 +85,16 @@ export const parseUpdateManifest = (json: string): UpdateManifest => { if (arch !== 'x64' && arch !== 'arm64') { throw new Error(`update manifest: "arch" must be x64 or arm64 (got ${arch})`); } + // The name becomes a path segment in the install helper scripts: no separators, + // no dot-dirs, and nothing cmd.exe expands or unquotes (`"`, `%`, control chars). + const name = str('name'); + if (name === '.' || name === '..' || UNSAFE_NAME_CHARS.test(name)) { + throw new Error( + `update manifest: "name" is not a safe bundle name (got ${JSON.stringify(name)})`, + ); + } return { - name: str('name'), + name, version: str('version'), channel: str('channel'), os, diff --git a/tests/unit/common/manifest.test.ts b/tests/unit/common/manifest.test.ts index 44c95e5d..25021fbe 100644 --- a/tests/unit/common/manifest.test.ts +++ b/tests/unit/common/manifest.test.ts @@ -136,4 +136,26 @@ describe('parseUpdateManifest / serializeUpdateManifest', () => { test('rejects a non-numeric size', () => { expect(() => parseUpdateManifest(JSON.stringify({ ...sample, size: 'big' }))).toThrow(/"size"/); }); + + test('rejects a name that could inject into the install helper or traverse out of staging', () => { + for (const name of [ + 'Demo" echo\r\ncalc.exe\r\nrem ', + 'Demo\ncalc', + '100%CMDCMDLINE%', + '../../home/victim/.ssh', + 'a/b', + 'a\\b', + '..', + '.', + 'nul\u0000byte', + ]) { + expect(() => parseUpdateManifest(JSON.stringify({ ...sample, name }))).toThrow(/"name"/); + } + }); + + test('accepts ordinary app names, including spaces and punctuation', () => { + for (const name of ['My App', "Tom & Jerry's (Beta)", 'Café 2.0', 'a..b']) { + expect(parseUpdateManifest(JSON.stringify({ ...sample, name })).name).toBe(name); + } + }); }); From fa9026b7e7cacbb345e51737a600dc7ce8466d04 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:09:46 -0700 Subject: [PATCH 147/586] fix: degrade unsupported menu roles to plain items --- src/main/api/menu.ts | 25 ++++++++++++++++++------- tests/unit/main/api/menu.test.ts | 11 +++++++++++ 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/src/main/api/menu.ts b/src/main/api/menu.ts index fb899170..1f07a58e 100644 --- a/src/main/api/menu.ts +++ b/src/main/api/menu.ts @@ -178,8 +178,18 @@ const MACRO_ROLE_SUBMENUS: Record< }, }; -const isMacroRole = (role: MenuRole | MenuMacroRole): role is MenuMacroRole => - role === 'editMenu' || role === 'windowMenu'; +const isMacroRole = (role: string): role is MenuMacroRole => + Object.hasOwn(MACRO_ROLE_SUBMENUS, role); + +const isRole = (role: string): role is MenuRole => Object.hasOwn(ROLE_DEFAULTS, role); + +/** Electron matches roles case-insensitively. */ +const ROLE_NAMES = new Map( + [...Object.keys(ROLE_DEFAULTS), ...Object.keys(MACRO_ROLE_SUBMENUS)].map((r) => [ + r.toLowerCase(), + r, + ]), +); /** `'CmdOrCtrl+Q'` → `'q'`; `''` when the key is not a single character. */ const acceleratorKey = (accelerator: string | undefined): string => { @@ -225,7 +235,8 @@ export class MenuItem { constructor(options: MenuItemOptions) { this.id = options.id; - const role = options.role; + const role = + options.role === undefined ? undefined : ROLE_NAMES.get(options.role.toLowerCase()); if (role !== undefined && isMacroRole(role)) { const macro = MACRO_ROLE_SUBMENUS[role]; this.role = undefined; @@ -238,10 +249,10 @@ export class MenuItem { this.type = 'submenu'; return; } - this.role = role; - const roleDefault = role !== undefined ? ROLE_DEFAULTS[role] : undefined; - // App-supplied label/accelerator win over the role's defaults. - this.label = options.label ?? roleDefault?.label ?? ''; + // An unsupported role degrades to a plain item labelled with the role name. + this.role = role !== undefined && isRole(role) ? role : undefined; + const roleDefault = this.role !== undefined ? ROLE_DEFAULTS[this.role] : undefined; + this.label = options.label ?? roleDefault?.label ?? options.role ?? ''; this.enabled = options.enabled ?? true; this.checked = options.checked ?? false; this.accelerator = options.accelerator ?? roleDefault?.accelerator; diff --git a/tests/unit/main/api/menu.test.ts b/tests/unit/main/api/menu.test.ts index e93f08fc..c07e1d75 100644 --- a/tests/unit/main/api/menu.test.ts +++ b/tests/unit/main/api/menu.test.ts @@ -92,6 +92,17 @@ describe('MenuItem roles', () => { expect(copy.type).toBe('normal'); }); + test('an unsupported Electron role degrades to a plain item instead of throwing', () => { + Menu.buildFromTemplate([{ role: 'toggleDevTools' as never }]).realize(); + expect(realized?.[0]).toMatchObject({ label: 'toggleDevTools', type: 'normal' }); + expect(realized?.[0]?.roleSelector).toBeUndefined(); + }); + + test('roles match case-insensitively, as in Electron', () => { + expect(new MenuItem({ role: 'selectall' as never }).role).toBe('selectAll'); + expect(new MenuItem({ role: 'editmenu' as never }).label).toBe('Edit'); + }); + test('an app-supplied label/accelerator overrides the role defaults', () => { const item = new MenuItem({ role: 'copy', From 489801e3ebdda32033af3cfdd3c9e22c7aa8f4cb Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:09:47 -0700 Subject: [PATCH 148/586] fix: sign update.json and verify it before downloading an update --- src/cli/update-artifact.ts | 17 ++++++--- src/main/api/auto-updater.ts | 44 ++++++++++++++++++------ tests/unit/cli/update-artifact.test.ts | 31 +++++++++++++++++ tests/unit/main/api/auto-updater.test.ts | 42 +++++++++++++++++----- 4 files changed, 110 insertions(+), 24 deletions(-) diff --git a/src/cli/update-artifact.ts b/src/cli/update-artifact.ts index a39145b9..313853b1 100644 --- a/src/cli/update-artifact.ts +++ b/src/cli/update-artifact.ts @@ -63,6 +63,8 @@ export type UpdateArtifactResult = { readonly manifest: UpdateManifest; /** Present only when the spec carried a signing key. */ readonly sigPath?: string; + /** `update.json.sig`; present only when the spec carried a signing key. */ + readonly manifestSigPath?: string; }; const tarThenZstd = async (bundlePath: string, outPath: string): Promise => { @@ -98,13 +100,20 @@ export const emitUpdateArtifact = async ( await deps.tarZst(spec.bundlePath, artifactPath); const bytes = deps.readBytes(artifactPath); const manifest = buildUpdateManifest(spec, bytes); + const manifestText = serializeUpdateManifest(manifest); const manifestPath = join(spec.outDir, 'update.json'); - deps.writeText(manifestPath, serializeUpdateManifest(manifest)); if (spec.signingKeyPem === undefined) { + deps.writeText(manifestPath, manifestText); return { artifactPath, manifestPath, manifest }; } - // Same detached format the runtime autoUpdater fetches as `.sig`. + // Sign before writing so a bad key leaves no unsigned update.json behind. + const artifactSig = signArtifact(spec.signingKeyPem, bytes); + const manifestSig = signArtifact(spec.signingKeyPem, new TextEncoder().encode(manifestText)); + // Same detached format the runtime autoUpdater fetches as `.sig`. const sigPath = `${artifactPath}.sig`; - deps.writeText(sigPath, `${signArtifact(spec.signingKeyPem, bytes)}\n`); - return { artifactPath, manifestPath, manifest, sigPath }; + const manifestSigPath = `${manifestPath}.sig`; + deps.writeText(manifestPath, manifestText); + deps.writeText(sigPath, `${artifactSig}\n`); + deps.writeText(manifestSigPath, `${manifestSig}\n`); + return { artifactPath, manifestPath, manifest, sigPath, manifestSigPath }; }; diff --git a/src/main/api/auto-updater.ts b/src/main/api/auto-updater.ts index 6584b04f..291ac301 100644 --- a/src/main/api/auto-updater.ts +++ b/src/main/api/auto-updater.ts @@ -135,7 +135,7 @@ export class AutoUpdaterImpl extends EventEmitter { #feedURL: string | undefined; #publicKey: string | undefined; #channel: string | undefined; - #available: UpdateManifest | undefined; + #available: { readonly manifest: UpdateManifest; readonly text: string } | undefined; #staged: StagedUpdate | undefined; constructor(deps?: Partial) { @@ -208,13 +208,27 @@ export class AutoUpdaterImpl extends EventEmitter { return error; } + /** Throws unless `.sig` is a valid publisher signature over `message`. */ + async #verifySignature( + publicKey: string, + url: string, + message: Uint8Array, + what: string, + ): Promise { + const signature = (await this.#deps.fetchText(`${url}.sig`)).trim(); + if (!verifyArtifact(publicKey, message, signature)) { + throw new Error(`autoUpdater: ${what} signature verification failed`); + } + } + /** Returns `null` when no newer version is offered. Rejects on network/manifest failure. */ async checkForUpdates(): Promise { const feedURL = this.#requireFeedURL(); this.emit('checking-for-update'); + let text: string; let manifest: UpdateManifest; try { - const text = await this.#deps.fetchText(joinUrl(feedURL, 'update.json')); + text = await this.#deps.fetchText(joinUrl(feedURL, 'update.json')); manifest = parseUpdateManifest(text); } catch (cause) { throw this.#emitError(cause); @@ -240,7 +254,7 @@ export class AutoUpdaterImpl extends EventEmitter { this.emit('update-not-available', toUpdateInfo(manifest)); return null; } - this.#available = manifest; + this.#available = { manifest, text }; this.emit('update-available', toUpdateInfo(manifest)); return { updateInfo: toUpdateInfo(manifest), manifest }; } @@ -255,14 +269,22 @@ export class AutoUpdaterImpl extends EventEmitter { */ async downloadUpdate(): Promise { const feedURL = this.#requireFeedURL(); - const manifest = this.#available; - if (manifest === undefined) { + const available = this.#available; + if (available === undefined) { throw this.#emitError( new Error('autoUpdater.downloadUpdate: no update available; call checkForUpdates first'), ); } + const { manifest } = available; try { const publicKey = this.#requirePublicKey(); + // Authenticates every field checkForUpdates acted on (version, os/arch, channel, name). + await this.#verifySignature( + publicKey, + joinUrl(feedURL, 'update.json'), + new TextEncoder().encode(available.text), + 'update.json', + ); assertSizeWithin(manifest.size, MAX_COMPRESSED_ARTIFACT_BYTES, 'compressed artifact'); const bytes = await this.#deps.fetchBytes(joinUrl(feedURL, manifest.artifact)); if (bytes.length !== manifest.size) { @@ -276,12 +298,12 @@ export class AutoUpdaterImpl extends EventEmitter { `autoUpdater: artifact hash mismatch (expected ${manifest.hash}, got ${actualHash})`, ); } - const signature = ( - await this.#deps.fetchText(joinUrl(feedURL, `${manifest.artifact}.sig`)) - ).trim(); - if (!verifyArtifact(publicKey, bytes, signature)) { - throw new Error('autoUpdater: artifact signature verification failed'); - } + await this.#verifySignature( + publicKey, + joinUrl(feedURL, manifest.artifact), + bytes, + 'artifact', + ); const tarBytes = this.#deps.decompress(bytes); assertSizeWithin(tarBytes.length, MAX_DECOMPRESSED_TAR_BYTES, 'decompressed update'); const tarPath = await this.#deps.stage(tarBytes, manifest); diff --git a/tests/unit/cli/update-artifact.test.ts b/tests/unit/cli/update-artifact.test.ts index d1a964a7..b00b037c 100644 --- a/tests/unit/cli/update-artifact.test.ts +++ b/tests/unit/cli/update-artifact.test.ts @@ -129,6 +129,37 @@ describe('emitUpdateArtifact signing', () => { expect(verifyArtifact(KEYS.publicKey, new Uint8Array([1]), sig)).toBe(false); }); + test('signs the exact update.json text into update.json.sig', async () => { + const writes = new Map(); + const result = await emitUpdateArtifact( + { ...spec('/out', '/build/My App.app'), signingKeyPem: KEYS.privateKey }, + { + tarZst: async () => undefined, + readBytes: () => new Uint8Array([9, 8, 7]), + writeText: (path, text) => writes.set(slash(path), text), + }, + ); + expect(slash(result.manifestSigPath ?? '')).toBe('/out/update.json.sig'); + const manifestBytes = new TextEncoder().encode(writes.get('/out/update.json') ?? ''); + const sig = (writes.get('/out/update.json.sig') ?? '').trim(); + expect(verifyArtifact(KEYS.publicKey, manifestBytes, sig)).toBe(true); + }); + + test('an unusable signing key fails before any feed file is written', async () => { + const writes = new Map(); + await expect( + emitUpdateArtifact( + { ...spec('/out', '/build/My App.app'), signingKeyPem: KEYS.publicKey }, + { + tarZst: async () => undefined, + readBytes: () => new Uint8Array([1]), + writeText: (path, text) => writes.set(slash(path), text), + }, + ), + ).rejects.toThrow(); + expect([...writes.keys()]).toEqual([]); + }); + test('without a signing key no .sig is written and sigPath is absent', async () => { const writes = new Map(); const result = await emitUpdateArtifact(spec('/out', '/build/My App.app'), { diff --git a/tests/unit/main/api/auto-updater.test.ts b/tests/unit/main/api/auto-updater.test.ts index 2d765739..4888e570 100644 --- a/tests/unit/main/api/auto-updater.test.ts +++ b/tests/unit/main/api/auto-updater.test.ts @@ -35,6 +35,17 @@ const manifest = (version: string): UpdateManifest => ({ artifact: 'my-app-stable-macos-arm64.tar.zst', }); +/** A feed serving `m` as update.json, signed by the publisher key, plus the artifact `.sig`. */ +const signedFeed = + (m: UpdateManifest, manifestSignedAs: UpdateManifest = m) => + async (url: string): Promise => { + if (url.endsWith('update.json.sig')) { + const signed = new TextEncoder().encode(serializeUpdateManifest(manifestSignedAs)); + return signArtifact(KEYS.privateKey, signed); + } + return url.endsWith('.sig') ? SIG : serializeUpdateManifest(m); + }; + type Harness = { updater: AutoUpdaterImpl; staged: StagedUpdate[]; @@ -47,8 +58,7 @@ const makeUpdater = (overrides: Partial, feedVersion = '2.0.0') const decompressed: Uint8Array[] = []; const events: string[] = []; const deps: Partial = { - fetchText: async (url) => - url.endsWith('.sig') ? SIG : serializeUpdateManifest(manifest(feedVersion)), + fetchText: signedFeed(manifest(feedVersion)), fetchBytes: async () => ARTIFACT, currentVersion: () => '1.0.0', currentOs: () => 'macos', @@ -205,6 +215,26 @@ describe('autoUpdater.downloadUpdate', () => { expect(h.events).toContain('error'); }); + test('refuses a re-labelled update.json before fetching the artifact (rollback guard)', async () => { + let fetched = false; + const h = makeUpdater( + { + // A genuinely signed 2.0.0 release re-served under a forged version. + fetchText: signedFeed(manifest('99.0.0'), manifest('2.0.0')), + fetchBytes: async () => { + fetched = true; + return ARTIFACT; + }, + }, + '99.0.0', + ); + h.updater.setFeedURL(FEED); + await h.updater.checkForUpdates(); + await expect(h.updater.downloadUpdate()).rejects.toThrow(/update\.json signature/); + expect(fetched).toBe(false); + expect(h.events).toContain('error'); + }); + test('rejects + emits error on an artifact size mismatch', async () => { const h = makeUpdater({ fetchBytes: async () => new Uint8Array([1, 2]) }, '2.0.0'); h.updater.setFeedURL(FEED); @@ -225,13 +255,7 @@ describe('autoUpdater.downloadUpdate', () => { let fetched = false; const h = makeUpdater( { - fetchText: async (url) => - url.endsWith('.sig') - ? SIG - : serializeUpdateManifest({ - ...manifest('2.0.0'), - size: MAX_COMPRESSED_ARTIFACT_BYTES + 1, - }), + fetchText: signedFeed({ ...manifest('2.0.0'), size: MAX_COMPRESSED_ARTIFACT_BYTES + 1 }), fetchBytes: async () => { fetched = true; return ARTIFACT; From fdfd74d55738913eb52b23b1cfd84797b270f292 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:10:08 -0700 Subject: [PATCH 149/586] fix: put Linux menu items after a separator into a visible section --- src/main/platform/linux/gtk-menu.ts | 7 +++++-- tests/unit/main/platform/linux/gtk-menu.test.ts | 12 +++++++++--- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/src/main/platform/linux/gtk-menu.ts b/src/main/platform/linux/gtk-menu.ts index 10946f41..fc5b9543 100644 --- a/src/main/platform/linux/gtk-menu.ts +++ b/src/main/platform/linux/gtk-menu.ts @@ -172,12 +172,15 @@ type WalkContext = { const appendItems = ( ctx: WalkContext, - model: bigint, + root: bigint, items: ReadonlyArray, ): void => { + let model = root; for (const spec of items) { if (spec.type === 'separator') { - ctx.b.gMenuAppendSection(model, ctx.b.gMenuNew()); + // GTK draws a divider only above a NON-empty section, so later items go inside it. + model = ctx.b.gMenuNew(); + ctx.b.gMenuAppendSection(root, model); continue; } if (spec.type === 'submenu' && spec.submenu !== undefined) { diff --git a/tests/unit/main/platform/linux/gtk-menu.test.ts b/tests/unit/main/platform/linux/gtk-menu.test.ts index e34a6e6a..809dcaac 100644 --- a/tests/unit/main/platform/linux/gtk-menu.test.ts +++ b/tests/unit/main/platform/linux/gtk-menu.test.ts @@ -216,15 +216,21 @@ describe('linuxMenuRealizer.realize (fake bindings)', () => { expect(calls.filter((c) => c.fn === 'gMenuAppend')).toHaveLength(1); }); - it('renders a separator as a fresh empty section', () => { + it('puts the items after a separator into a new section (GTK draws no empty section)', () => { const { bindings, calls } = makeFakeBindings(); setBindingsForTesting(bindings); - linuxMenuRealizer.realize([ + const handle = linuxMenuRealizer.realize([ { label: 'A', type: 'normal', enabled: true, keyEquivalent: '', onClick: () => undefined }, { label: '', type: 'separator', enabled: true, keyEquivalent: '' }, { label: 'B', type: 'normal', enabled: true, keyEquivalent: '', onClick: () => undefined }, ]); - expect(calls.filter((c) => c.fn === 'gMenuAppendSection')).toHaveLength(1); + const sections = calls.filter((c) => c.fn === 'gMenuAppendSection'); + expect(sections).toHaveLength(1); + expect(sections[0]?.args[0]).toBe(handle); + const appendedTo = (label: string): unknown => + calls.find((c) => c.fn === 'gMenuAppend' && c.args[1] === label)?.args[0]; + expect(appendedTo('A')).toBe(handle); + expect(appendedTo('B')).toBe(sections[0]?.args[1]); }); it('realizes a submenu into a child model sharing the same action group', () => { From 8b3aa81ff974fcc9b2aa8ac4b6c88ba2ff73b44c Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:10:23 -0700 Subject: [PATCH 150/586] fix: keep an explicit submenu on editMenu and windowMenu roles --- src/main/api/menu.ts | 22 ++++------------------ tests/unit/main/api/menu.test.ts | 5 +++++ 2 files changed, 9 insertions(+), 18 deletions(-) diff --git a/src/main/api/menu.ts b/src/main/api/menu.ts index 1f07a58e..f5783987 100644 --- a/src/main/api/menu.ts +++ b/src/main/api/menu.ts @@ -237,32 +237,18 @@ export class MenuItem { this.id = options.id; const role = options.role === undefined ? undefined : ROLE_NAMES.get(options.role.toLowerCase()); - if (role !== undefined && isMacroRole(role)) { - const macro = MACRO_ROLE_SUBMENUS[role]; - this.role = undefined; - this.label = options.label ?? macro.label; - this.enabled = options.enabled ?? true; - this.checked = false; - this.accelerator = undefined; - this.click = undefined; - this.submenu = Menu.buildFromTemplate(macro.submenu); - this.type = 'submenu'; - return; - } + const macro = role !== undefined && isMacroRole(role) ? MACRO_ROLE_SUBMENUS[role] : undefined; // An unsupported role degrades to a plain item labelled with the role name. this.role = role !== undefined && isRole(role) ? role : undefined; const roleDefault = this.role !== undefined ? ROLE_DEFAULTS[this.role] : undefined; - this.label = options.label ?? roleDefault?.label ?? options.role ?? ''; + this.label = options.label ?? macro?.label ?? roleDefault?.label ?? options.role ?? ''; this.enabled = options.enabled ?? true; this.checked = options.checked ?? false; this.accelerator = options.accelerator ?? roleDefault?.accelerator; this.click = options.click; + const submenu = options.submenu ?? macro?.submenu; this.submenu = - options.submenu === undefined - ? undefined - : options.submenu instanceof Menu - ? options.submenu - : Menu.buildFromTemplate(options.submenu); + submenu === undefined || submenu instanceof Menu ? submenu : Menu.buildFromTemplate(submenu); this.type = options.type ?? (this.submenu !== undefined ? 'submenu' : 'normal'); } } diff --git a/tests/unit/main/api/menu.test.ts b/tests/unit/main/api/menu.test.ts index c07e1d75..d06bfccf 100644 --- a/tests/unit/main/api/menu.test.ts +++ b/tests/unit/main/api/menu.test.ts @@ -146,6 +146,11 @@ describe('Menu macro roles', () => { ]); }); + test('a macro role keeps an explicitly supplied submenu', () => { + const item = new MenuItem({ role: 'editMenu', submenu: [{ label: 'Mine' }] }); + expect(item.submenu?.items.map((i) => i.label)).toEqual(['Mine']); + }); + test('a macro role accepts a custom label', () => { expect(new MenuItem({ role: 'editMenu', label: 'Edit…' }).label).toBe('Edit…'); }); From 7a234367a329e53fa9edf7203afddd52e651b050 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:10:29 -0700 Subject: [PATCH 151/586] fix: treat a No button as the Linux message box cancel response --- src/main/platform/linux/gtk-dialog.ts | 11 +++-------- tests/unit/main/platform/linux/gtk-dialog.test.ts | 12 ++++++++++++ 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/src/main/platform/linux/gtk-dialog.ts b/src/main/platform/linux/gtk-dialog.ts index d1be9f9f..5f929927 100644 --- a/src/main/platform/linux/gtk-dialog.ts +++ b/src/main/platform/linux/gtk-dialog.ts @@ -54,14 +54,9 @@ export const buildButtonsArray = (labels: ReadonlyArray): ButtonsArray = export const mapChooseResult = (index: number, _defaultId: number, cancelId: number): number => index >= 0 ? index : cancelId; -/** - * Compute the cancel index for a message box: the index of a button labelled - * "Cancel" (case-insensitive), else `0`. The {@link MessageBoxSpec} carries no - * explicit cancelId, so this mirrors Electron's default of treating a Cancel - * button (or the first button) as the dismissal response. - */ -const cancelIdForButtons = (buttons: ReadonlyArray): number => { - const idx = buttons.findIndex((label) => label.toLowerCase() === 'cancel'); +/** Electron's default cancelId: the first "cancel" or "no" button (case-insensitive), else 0. */ +export const cancelIdForButtons = (buttons: ReadonlyArray): number => { + const idx = buttons.findIndex((label) => ['cancel', 'no'].includes(label.toLowerCase())); return idx >= 0 ? idx : 0; }; diff --git a/tests/unit/main/platform/linux/gtk-dialog.test.ts b/tests/unit/main/platform/linux/gtk-dialog.test.ts index 27cc3cdc..829969e9 100644 --- a/tests/unit/main/platform/linux/gtk-dialog.test.ts +++ b/tests/unit/main/platform/linux/gtk-dialog.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it } from 'bun:test'; import { GASYNC_READY_CB_DEF } from '../../../../../src/main/platform/linux/gasync'; import { buildButtonsArray, + cancelIdForButtons, mapChooseResult, settleChoose, settleFilePath, @@ -69,6 +70,17 @@ describe('mapChooseResult', () => { }); }); +describe('cancelIdForButtons', () => { + it('picks the first button labelled cancel or no, case-insensitively (Electron default)', () => { + expect(cancelIdForButtons(['Yes', 'No'])).toBe(1); + expect(cancelIdForButtons(['Save', 'CANCEL', 'No'])).toBe(1); + }); + + it('falls back to 0 when no button is a cancel label', () => { + expect(cancelIdForButtons(['OK', 'Retry'])).toBe(0); + }); +}); + describe('settleChoose (injected finish-fn, no real dialog)', () => { it('resolves with the mapped button index from the injected finish-fn', () => { const fakeResult = 123 as unknown as Pointer; From 9c26621ea218c09cf53d6de68a9056a0c9f6d469 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:10:31 -0700 Subject: [PATCH 152/586] fix: stop fire-and-forget update calls from crashing on rejection --- src/main/api/auto-updater.ts | 18 +++++++++++++++-- tests/unit/main/api/auto-updater.test.ts | 25 ++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/src/main/api/auto-updater.ts b/src/main/api/auto-updater.ts index 291ac301..8bc3ca60 100644 --- a/src/main/api/auto-updater.ts +++ b/src/main/api/auto-updater.ts @@ -113,6 +113,12 @@ const httpFetchBytes = async (url: string): Promise => { return new Uint8Array(await response.arrayBuffer()); }; +/** Electron callers fire and forget, relying on the `error` event; awaiting callers still see the rejection. */ +const markHandled = (promise: Promise): Promise => { + promise.catch(() => undefined); + return promise; +}; + const stageToTmp = async (tarBytes: Uint8Array, manifest: UpdateManifest): Promise => { const tarPath = join(tmpdir(), `bunmaska-update-${manifest.hash}.tar`); writeFileSync(tarPath, tarBytes); @@ -222,7 +228,11 @@ export class AutoUpdaterImpl extends EventEmitter { } /** Returns `null` when no newer version is offered. Rejects on network/manifest failure. */ - async checkForUpdates(): Promise { + checkForUpdates(): Promise { + return markHandled(this.#check()); + } + + async #check(): Promise { const feedURL = this.#requireFeedURL(); this.emit('checking-for-update'); let text: string; @@ -267,7 +277,11 @@ export class AutoUpdaterImpl extends EventEmitter { * feed/MITM controls the manifest, so its size + hash are self-referential; * only the publisher's key can produce a valid `.sig`. */ - async downloadUpdate(): Promise { + downloadUpdate(): Promise { + return markHandled(this.#download()); + } + + async #download(): Promise { const feedURL = this.#requireFeedURL(); const available = this.#available; if (available === undefined) { diff --git a/tests/unit/main/api/auto-updater.test.ts b/tests/unit/main/api/auto-updater.test.ts index 4888e570..534e9148 100644 --- a/tests/unit/main/api/auto-updater.test.ts +++ b/tests/unit/main/api/auto-updater.test.ts @@ -281,6 +281,31 @@ describe('assertSizeWithin (zip-bomb guard)', () => { }); }); +describe('autoUpdater fire-and-forget calls (Electron style)', () => { + test('a failure reaches the error listener without an unhandled rejection', async () => { + const unhandled: unknown[] = []; + const onUnhandled = (reason: unknown): void => { + unhandled.push(reason); + }; + process.on('unhandledRejection', onUnhandled); + try { + const h = makeUpdater({ + fetchText: async () => { + throw new Error('offline'); + }, + }); + h.updater.setFeedURL(FEED); + h.updater.checkForUpdates(); + h.updater.downloadUpdate(); + await Bun.sleep(10); + expect(h.events.filter((e) => e === 'error')).toHaveLength(2); + expect(unhandled).toEqual([]); + } finally { + process.off('unhandledRejection', onUnhandled); + } + }); +}); + describe('autoUpdater.quitAndInstall', () => { test('throws when nothing is staged', () => { const { updater } = makeUpdater({}); From cd87c6fc61da0769bee9040caced32d30609696d Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:10:48 -0700 Subject: [PATCH 153/586] fix: read a single-select file dialog result up to the first NUL --- src/main/platform/windows/windows-dialog.ts | 24 ++++++++++++++-- .../platform/windows/windows-dialog.test.ts | 28 +++++++++++++++++++ 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/src/main/platform/windows/windows-dialog.ts b/src/main/platform/windows/windows-dialog.ts index 7e6df064..8078b067 100644 --- a/src/main/platform/windows/windows-dialog.ts +++ b/src/main/platform/windows/windows-dialog.ts @@ -1,4 +1,4 @@ -import { ptr, read } from 'bun:ffi'; +import { type Pointer, ptr, read } from 'bun:ffi'; import { join } from 'node:path'; import type { DialogBackend } from '../../api/dialog'; import type { MessageBoxSpec, OpenDialogSpec, SaveDialogSpec } from '../macos/cocoa-dialog'; @@ -141,6 +141,22 @@ const readPathString = (bufferPtr: ReturnType, maxWchars: number): s return String.fromCharCode(...units); }; +/** + * Decode the `lpstrFile` buffer after a confirmed file dialog. A single-select result + * stops at the first NUL: the dialog does not clear the pre-filled default name's tail. + */ +export const readFileDialogResult = ( + bufferPtr: Pointer, + maxWchars: number, + multi: boolean, +): string[] => { + if (!multi) { + const path = readPathString(bufferPtr, maxWchars); + return path.length > 0 ? [path] : []; + } + return parseSelectedPaths(readResultString(bufferPtr, maxWchars)); +}; + /** Run a `GetOpenFileNameW`/`GetSaveFileNameW`-shaped call and return the chosen path(s). */ const runFileDialog = ( call: (ofnPtr: ReturnType) => number, @@ -166,7 +182,11 @@ const runFileDialog = ( if (call(ptr(ofn)) === 0) { return []; // the user cancelled } - return parseSelectedPaths(readResultString(fileBufferPtr, FILE_BUFFER_WCHARS)); + return readFileDialogResult( + fileBufferPtr, + FILE_BUFFER_WCHARS, + (flags & OFN_ALLOWMULTISELECT) !== 0, + ); }; /** Show the legacy folder picker, returning the chosen directory or `[]` on cancel. */ diff --git a/tests/unit/main/platform/windows/windows-dialog.test.ts b/tests/unit/main/platform/windows/windows-dialog.test.ts index e80790b6..056ff98a 100644 --- a/tests/unit/main/platform/windows/windows-dialog.test.ts +++ b/tests/unit/main/platform/windows/windows-dialog.test.ts @@ -1,4 +1,5 @@ import { describe, expect, test } from 'bun:test'; +import { ptr } from 'bun:ffi'; import { join } from 'node:path'; import type { MessageBoxSpec } from '../../../../../src/main/platform/macos/cocoa-dialog'; import { @@ -6,6 +7,7 @@ import { messageBoxResponse, messageBoxUType, parseSelectedPaths, + readFileDialogResult, } from '../../../../../src/main/platform/windows/windows-dialog'; /** @@ -25,6 +27,16 @@ const IDCANCEL = 2; const IDYES = 6; const IDNO = 7; +/** A UTF-16LE `lpstrFile` buffer holding `text`, zero-padded to `wchars`. */ +const fileBuffer = (text: string, wchars: number): Uint8Array => { + const buffer = new Uint8Array(wchars * 2); + for (let i = 0; i < text.length; i += 1) { + buffer[i * 2] = text.charCodeAt(i) & 0xff; + buffer[i * 2 + 1] = text.charCodeAt(i) >> 8; + } + return buffer; +}; + const spec = (buttons: string[], type?: MessageBoxSpec['type']): MessageBoxSpec => ({ message: 'm', detail: 'd', @@ -100,3 +112,19 @@ describe('parseSelectedPaths', () => { expect(parseSelectedPaths('')).toEqual([]); }); }); + +describe('readFileDialogResult', () => { + test('a single-select result stops at the first NUL, ignoring a longer default name', () => { + // GetSaveFileNameW overwrote 'C:\\docs\\Untitled Document.txt' with a shorter path. + const buffer = fileBuffer('C:\\docs\\a.txt\0ed Document.txt\0', 64); + expect(readFileDialogResult(ptr(buffer), 64, false)).toEqual(['C:\\docs\\a.txt']); + }); + + test('a multi-select result reads the directory and names up to the double NUL', () => { + const buffer = fileBuffer('C:\\docs\0a.txt\0b.png\0', 64); + expect(readFileDialogResult(ptr(buffer), 64, true)).toEqual([ + join('C:\\docs', 'a.txt'), + join('C:\\docs', 'b.png'), + ]); + }); +}); From 9bafe341f2abd3a4e000b8d02776407b8fdc7e73 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:10:55 -0700 Subject: [PATCH 154/586] fix: accept Electron's media, lock, numpad and Insert accelerator keys --- src/main/api/accelerator.ts | 18 ++++++++++ tests/unit/main/api/accelerator.test.ts | 46 +++++++++++++++++++++++++ 2 files changed, 64 insertions(+) diff --git a/src/main/api/accelerator.ts b/src/main/api/accelerator.ts index 4ae0a353..3656680e 100644 --- a/src/main/api/accelerator.ts +++ b/src/main/api/accelerator.ts @@ -49,6 +49,24 @@ const NAMED_KEYS = new Map([ ['pageup', 'PageUp'], ['pagedown', 'PageDown'], ['plus', 'Plus'], + ['insert', 'Insert'], + ['capslock', 'Capslock'], + ['numlock', 'Numlock'], + ['scrolllock', 'Scrolllock'], + ['printscreen', 'PrintScreen'], + ['volumeup', 'VolumeUp'], + ['volumedown', 'VolumeDown'], + ['volumemute', 'VolumeMute'], + ['medianexttrack', 'MediaNextTrack'], + ['mediaprevioustrack', 'MediaPreviousTrack'], + ['mediastop', 'MediaStop'], + ['mediaplaypause', 'MediaPlayPause'], + ['numdec', 'numdec'], + ['numadd', 'numadd'], + ['numsub', 'numsub'], + ['nummult', 'nummult'], + ['numdiv', 'numdiv'], + ...Array.from({ length: 10 }, (_, digit): [string, string] => [`num${digit}`, `num${digit}`]), ]); const isFunctionKey = (token: string): boolean => /^f([1-9]|1[0-9]|2[0-4])$/i.test(token); diff --git a/tests/unit/main/api/accelerator.test.ts b/tests/unit/main/api/accelerator.test.ts index 4039b661..d20673ca 100644 --- a/tests/unit/main/api/accelerator.test.ts +++ b/tests/unit/main/api/accelerator.test.ts @@ -92,6 +92,52 @@ describe('parseAccelerator', () => { expect(onMac('CmdOrCtrl+Return')?.key).toBe('Return'); }); + test('accepts every key name in Electron keyboard-shortcuts.md', () => { + const electronKeys = [ + ...'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', + 'F1', + 'F24', + ...')!@#$%^&*(:;=<,_->.?/~`{][|\\}"', + 'Plus', + 'Space', + 'Tab', + 'Capslock', + 'Numlock', + 'Scrolllock', + 'Backspace', + 'Delete', + 'Insert', + 'Return', + 'Enter', + 'Up', + 'Down', + 'Left', + 'Right', + 'Home', + 'End', + 'PageUp', + 'PageDown', + 'Escape', + 'Esc', + 'VolumeUp', + 'VolumeDown', + 'VolumeMute', + 'MediaNextTrack', + 'MediaPreviousTrack', + 'MediaStop', + 'MediaPlayPause', + 'PrintScreen', + 'num0', + 'num9', + 'numdec', + 'numadd', + 'numsub', + 'nummult', + 'numdiv', + ]; + expect(electronKeys.filter((key) => onMac(`Shift+${key}`) === undefined)).toEqual([]); + }); + test('returns undefined for an empty string', () => { expect(onMac('')).toBeUndefined(); }); From 2c646da6f0e258bea1a1d26895970734c310be30 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:10:58 -0700 Subject: [PATCH 155/586] fix: match Linux file dialog extension filters in any letter case --- src/main/platform/linux/gtk-dialog.ts | 12 +++++++++++- tests/unit/main/platform/linux/gtk-dialog.test.ts | 9 +++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/main/platform/linux/gtk-dialog.ts b/src/main/platform/linux/gtk-dialog.ts index 5f929927..f897aa6f 100644 --- a/src/main/platform/linux/gtk-dialog.ts +++ b/src/main/platform/linux/gtk-dialog.ts @@ -153,6 +153,16 @@ const showMessageBox = (spec: { ); }; +/** A `*.ext` glob matching any letter case; GTK's add_pattern is case-sensitive off Windows. */ +export const extensionPattern = (ext: string): string => { + const chars = [...ext].map((c) => { + const lower = c.toLowerCase(); + const upper = c.toUpperCase(); + return lower === upper ? c : `[${lower}${upper}]`; + }); + return `*.${chars.join('')}`; +}; + /** Set a default `GtkFileFilter` of `*.ext` patterns, when any extension is given. */ const applyExtensionFilter = ( gtk: ReturnType, @@ -167,7 +177,7 @@ const applyExtensionFilter = ( return; } for (const ext of extensions) { - gtk.symbols.gtk_file_filter_add_pattern(filter, cstr(`*.${ext}`)); + gtk.symbols.gtk_file_filter_add_pattern(filter, cstr(extensionPattern(ext))); } gtk.symbols.gtk_file_dialog_set_default_filter(fileDialog, filter); }; diff --git a/tests/unit/main/platform/linux/gtk-dialog.test.ts b/tests/unit/main/platform/linux/gtk-dialog.test.ts index 829969e9..e7b78070 100644 --- a/tests/unit/main/platform/linux/gtk-dialog.test.ts +++ b/tests/unit/main/platform/linux/gtk-dialog.test.ts @@ -4,6 +4,7 @@ import { GASYNC_READY_CB_DEF } from '../../../../../src/main/platform/linux/gasy import { buildButtonsArray, cancelIdForButtons, + extensionPattern, mapChooseResult, settleChoose, settleFilePath, @@ -81,6 +82,14 @@ describe('cancelIdForButtons', () => { }); }); +describe('extensionPattern', () => { + it('matches an extension in any letter case (GTK globs are case-sensitive on Linux)', () => { + expect(extensionPattern('jpg')).toBe('*.[jJ][pP][gG]'); + expect(extensionPattern('Tar.gz')).toBe('*.[tT][aA][rR].[gG][zZ]'); + expect(extensionPattern('mp4')).toBe('*.[mM][pP]4'); + }); +}); + describe('settleChoose (injected finish-fn, no real dialog)', () => { it('resolves with the mapped button index from the injected finish-fn', () => { const fakeResult = 123 as unknown as Pointer; From 63573b3063aec47a2fae5dd97a408a013d611945 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:11:02 -0700 Subject: [PATCH 156/586] fix: refuse update checks while the app version is unknown --- src/main/api/auto-updater.ts | 11 ++++++++++- tests/unit/main/api/auto-updater.test.ts | 8 ++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/main/api/auto-updater.ts b/src/main/api/auto-updater.ts index 8bc3ca60..d0590c01 100644 --- a/src/main/api/auto-updater.ts +++ b/src/main/api/auto-updater.ts @@ -12,6 +12,7 @@ import { import { type Arch, currentArch as hostArch, currentPlatform } from '../../common/platform'; import { verifyArtifact } from '../../common/signature'; import { app } from './app'; +import { DEFAULT_APP_VERSION } from './app-metadata'; import { defaultInstall } from './update-installer'; /** @@ -235,6 +236,14 @@ export class AutoUpdaterImpl extends EventEmitter { async #check(): Promise { const feedURL = this.#requireFeedURL(); this.emit('checking-for-update'); + const currentVersion = this.#deps.currentVersion(); + if (currentVersion === DEFAULT_APP_VERSION) { + throw this.#emitError( + new Error( + `autoUpdater: the running app's version is unknown (${DEFAULT_APP_VERSION}), so every update would reinstall forever; set "version" in package.json`, + ), + ); + } let text: string; let manifest: UpdateManifest; try { @@ -259,7 +268,7 @@ export class AutoUpdaterImpl extends EventEmitter { ), ); } - if (!isNewerVersion(manifest.version, this.#deps.currentVersion())) { + if (!isNewerVersion(manifest.version, currentVersion)) { this.#available = undefined; this.emit('update-not-available', toUpdateInfo(manifest)); return null; diff --git a/tests/unit/main/api/auto-updater.test.ts b/tests/unit/main/api/auto-updater.test.ts index 534e9148..891a693b 100644 --- a/tests/unit/main/api/auto-updater.test.ts +++ b/tests/unit/main/api/auto-updater.test.ts @@ -135,6 +135,14 @@ describe('autoUpdater.checkForUpdates', () => { expect(h.events).toEqual(['checking-for-update', 'update-available']); }); + test('refuses to check while the running version is unknown (0.0.0), which would reinstall forever', async () => { + const h = makeUpdater({ currentVersion: () => '0.0.0' }, '2.0.0'); + h.updater.setFeedURL(FEED); + await expect(h.updater.checkForUpdates()).rejects.toThrow(/version/); + expect(h.events).not.toContain('update-available'); + expect(h.events).toContain('error'); + }); + test('emits update-not-available and returns null for an equal/older version', async () => { const h = makeUpdater({}, '1.0.0'); h.updater.setFeedURL('https://feed'); From 020159adab5bc8ea1ddd003ca14b5112a8578273 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:11:19 -0700 Subject: [PATCH 157/586] test: skip display-less Linux clipboard cases visibly --- tests/integration/linux/clipboard.test.ts | 154 +++++++++++----------- 1 file changed, 80 insertions(+), 74 deletions(-) diff --git a/tests/integration/linux/clipboard.test.ts b/tests/integration/linux/clipboard.test.ts index af4983c7..1fdb0612 100644 --- a/tests/integration/linux/clipboard.test.ts +++ b/tests/integration/linux/clipboard.test.ts @@ -23,6 +23,7 @@ import { createLinuxDrain } from '../../../src/main/platform/linux/gtk-run-loop' */ const isLinux = currentPlatform() === 'linux'; +const hasDisplay = isLinux && loadGtkFFI().symbols.gtk_init_check() !== 0; /** A valid 1x1 PNG, round-tripped as raw `image/png` bytes (no NativeImage decode). */ const PNG_1x1 = new Uint8Array( @@ -110,88 +111,93 @@ describe.skipIf(!isLinux)('Linux clipboard backend (GDK 4)', () => { // Each async test carries a 15s bun:test deadline (third arg) on TOP of the 5s // awaitWithPump budget + 20m job ceiling — so a regression fails fast at every // layer instead of hanging. - test('writeText then readText round-trips plain text in the same process', async () => { - if (loadGtkFFI().symbols.gtk_init_check() === 0) { - return; // No display; the symbol-resolution test above already proved dispatch. - } - const value = 'bunmaska-clip-roundtrip-stable'; - linuxClipboardBackend.writeText(value); - const got = await awaitWithPump(linuxClipboardBackend.readText(), 5000); - expect(got).toBe(value); - }, 15000); + test.skipIf(!hasDisplay)( + 'writeText then readText round-trips plain text in the same process', + async () => { + const value = 'bunmaska-clip-roundtrip-stable'; + linuxClipboardBackend.writeText(value); + const got = await awaitWithPump(linuxClipboardBackend.readText(), 5000); + expect(got).toBe(value); + }, + 15000, + ); - test('writeText replaces previous contents', async () => { - if (loadGtkFFI().symbols.gtk_init_check() === 0) { - return; - } - linuxClipboardBackend.writeText('bunmaska-clip-first'); - linuxClipboardBackend.writeText('bunmaska-clip-second'); - const got = await awaitWithPump(linuxClipboardBackend.readText(), 5000); - expect(got).toBe('bunmaska-clip-second'); - }, 15000); + test.skipIf(!hasDisplay)( + 'writeText replaces previous contents', + async () => { + linuxClipboardBackend.writeText('bunmaska-clip-first'); + linuxClipboardBackend.writeText('bunmaska-clip-second'); + const got = await awaitWithPump(linuxClipboardBackend.readText(), 5000); + expect(got).toBe('bunmaska-clip-second'); + }, + 15000, + ); - test('round-trips UTF-8 content', async () => { - if (loadGtkFFI().symbols.gtk_init_check() === 0) { - return; - } - const value = 'café — 日本語 — 🎉'; - linuxClipboardBackend.writeText(value); - const got = await awaitWithPump(linuxClipboardBackend.readText(), 5000); - expect(got).toBe(value); - }, 15000); + test.skipIf(!hasDisplay)( + 'round-trips UTF-8 content', + async () => { + const value = 'café — 日本語 — 🎉'; + linuxClipboardBackend.writeText(value); + const got = await awaitWithPump(linuxClipboardBackend.readText(), 5000); + expect(got).toBe(value); + }, + 15000, + ); - test('clear then readText returns empty string', async () => { - if (loadGtkFFI().symbols.gtk_init_check() === 0) { - return; - } - linuxClipboardBackend.writeText('bunmaska-clip-to-be-cleared'); - linuxClipboardBackend.clear(); - const got = await awaitWithPump(linuxClipboardBackend.readText(), 5000); - expect(got).toBe(''); - }, 15000); + test.skipIf(!hasDisplay)( + 'clear then readText returns empty string', + async () => { + linuxClipboardBackend.writeText('bunmaska-clip-to-be-cleared'); + linuxClipboardBackend.clear(); + const got = await awaitWithPump(linuxClipboardBackend.readText(), 5000); + expect(got).toBe(''); + }, + 15000, + ); - test('writeHTML then readHTML round-trips markup in the same process', async () => { - if (loadGtkFFI().symbols.gtk_init_check() === 0) { - return; - } - const markup = 'bold & italic'; - linuxClipboardBackend.writeHTML(markup); - const got = await awaitWithPump(linuxClipboardBackend.readHTML(), 5000); - expect(got).toBe(markup); - }, 15000); + test.skipIf(!hasDisplay)( + 'writeHTML then readHTML round-trips markup in the same process', + async () => { + const markup = 'bold & italic'; + linuxClipboardBackend.writeHTML(markup); + const got = await awaitWithPump(linuxClipboardBackend.readHTML(), 5000); + expect(got).toBe(markup); + }, + 15000, + ); - test('round-trips UTF-8 HTML content', async () => { - if (loadGtkFFI().symbols.gtk_init_check() === 0) { - return; - } - const markup = '

café — 日本語 — 🎉

'; - linuxClipboardBackend.writeHTML(markup); - const got = await awaitWithPump(linuxClipboardBackend.readHTML(), 5000); - expect(got).toBe(markup); - }, 15000); + test.skipIf(!hasDisplay)( + 'round-trips UTF-8 HTML content', + async () => { + const markup = '

café — 日本語 — 🎉

'; + linuxClipboardBackend.writeHTML(markup); + const got = await awaitWithPump(linuxClipboardBackend.readHTML(), 5000); + expect(got).toBe(markup); + }, + 15000, + ); - test('readHTML on a cleared clipboard returns empty string (null-stream / no-format path)', async () => { - if (loadGtkFFI().symbols.gtk_init_check() === 0) { - return; - } - linuxClipboardBackend.clear(); - const got = await awaitWithPump(linuxClipboardBackend.readHTML(), 5000); - expect(got).toBe(''); - }, 15000); + test.skipIf(!hasDisplay)( + 'readHTML on a cleared clipboard returns empty string (null-stream / no-format path)', + async () => { + linuxClipboardBackend.clear(); + const got = await awaitWithPump(linuxClipboardBackend.readHTML(), 5000); + expect(got).toBe(''); + }, + 15000, + ); - test('writeImage then readImage round-trips PNG bytes in the same process', async () => { - if (loadGtkFFI().symbols.gtk_init_check() === 0) { - return; - } - linuxClipboardBackend.writeImage(PNG_1x1); - const got = await awaitWithPump(linuxClipboardBackend.readImage(), 5000); - expect(Array.from(got)).toEqual(Array.from(PNG_1x1)); - }, 15000); + test.skipIf(!hasDisplay)( + 'writeImage then readImage round-trips PNG bytes in the same process', + async () => { + linuxClipboardBackend.writeImage(PNG_1x1); + const got = await awaitWithPump(linuxClipboardBackend.readImage(), 5000); + expect(Array.from(got)).toEqual(Array.from(PNG_1x1)); + }, + 15000, + ); - test('availableFormats reports image/png after writing an image', () => { - if (loadGtkFFI().symbols.gtk_init_check() === 0) { - return; - } + test.skipIf(!hasDisplay)('availableFormats reports image/png after writing an image', () => { linuxClipboardBackend.writeImage(PNG_1x1); expect(linuxClipboardBackend.availableFormats()).toContain('image/png'); }); From efd25ef2c485bea852ddbcc08fd4139a63dcf805 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:11:27 -0700 Subject: [PATCH 158/586] fix: throw instead of silently quitting when the install is refused --- src/main/api/update-installer.ts | 7 +------ tests/unit/main/api/update-installer.test.ts | 6 +++--- 2 files changed, 4 insertions(+), 9 deletions(-) diff --git a/src/main/api/update-installer.ts b/src/main/api/update-installer.ts index 3324f88d..9eef215e 100644 --- a/src/main/api/update-installer.ts +++ b/src/main/api/update-installer.ts @@ -8,14 +8,11 @@ import { chmodSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { basename, dirname, join } from 'node:path'; -import { createLogger } from '../../common/logger'; import type { ArtifactOs } from '../../common/manifest'; import { currentPlatform } from '../../common/platform'; import { app } from './app'; import type { StagedUpdate } from './auto-updater'; -const log = createLogger('auto-updater'); - /** * Where the running app is installed, derived from the executable path; * `undefined` means "not an installed bundle" (e.g. `bun main.ts`) and the @@ -149,12 +146,10 @@ export const installStagedUpdate = (staged: StagedUpdate, deps: InstallerDeps): const execPath = deps.execPath(); const installRoot = deriveInstallRoot(execPath, os); if (installRoot === undefined) { - log.warn( + throw new Error( `autoUpdater.quitAndInstall: ${execPath} is not an installed ${os} bundle; ` + `refusing to swap (staged tar left at ${staged.tarPath})`, ); - deps.quit(); - return; } const bundleDirName = stagedBundleDirName(staged.manifest.name, os); const pid = deps.pid(); diff --git a/tests/unit/main/api/update-installer.test.ts b/tests/unit/main/api/update-installer.test.ts index cb2651fe..e8d194af 100644 --- a/tests/unit/main/api/update-installer.test.ts +++ b/tests/unit/main/api/update-installer.test.ts @@ -184,12 +184,12 @@ const makeDeps = (execPath: string, os: 'macos' | 'linux' | 'windows'): Harness }; describe('installStagedUpdate', () => { - test('refuses to swap when the executable is not an installed bundle, and only quits', () => { + test('refuses an executable that is not an installed bundle by throwing, leaving the app running', () => { const h = makeDeps('/opt/homebrew/bin/bun', 'macos'); - installStagedUpdate(staged(), h.deps); + expect(() => installStagedUpdate(staged(), h.deps)).toThrow(/not an installed macos bundle/); expect(h.scripts).toHaveLength(0); expect(h.spawns).toHaveLength(0); - expect(h.quits).toHaveLength(1); + expect(h.quits).toHaveLength(0); }); test('macOS: writes the sh helper, spawns it detached via /bin/sh, then quits', () => { From e11863b2f84b90d53af16044c3d6356878e834ad Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:11:38 -0700 Subject: [PATCH 159/586] fix: allow empty Linux clipboard writes instead of throwing --- src/main/platform/linux/gtk-clipboard.ts | 2 +- tests/integration/linux/clipboard.test.ts | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/main/platform/linux/gtk-clipboard.ts b/src/main/platform/linux/gtk-clipboard.ts index 2b9d2c48..33e5b273 100644 --- a/src/main/platform/linux/gtk-clipboard.ts +++ b/src/main/platform/linux/gtk-clipboard.ts @@ -303,7 +303,7 @@ const writeBytes = (mime: string, bytes: Uint8Array): void => { const glib = loadGlibFFI(); const clipboard = getClipboard(); // `g_bytes_new` copies, so `bytes` need only outlive that call. - const gbytes = glib.symbols.g_bytes_new(ptr(bytes), bytes.length); + const gbytes = glib.symbols.g_bytes_new(bytes.length === 0 ? null : ptr(bytes), bytes.length); if (gbytes === null) { throw new Error('g_bytes_new() returned null'); } diff --git a/tests/integration/linux/clipboard.test.ts b/tests/integration/linux/clipboard.test.ts index 1fdb0612..5be31b32 100644 --- a/tests/integration/linux/clipboard.test.ts +++ b/tests/integration/linux/clipboard.test.ts @@ -144,6 +144,17 @@ describe.skipIf(!isLinux)('Linux clipboard backend (GDK 4)', () => { 15000, ); + test.skipIf(!hasDisplay)( + 'writeText of an empty string reads back empty (a zero-length payload is valid)', + async () => { + linuxClipboardBackend.writeText('bunmaska-clip-before-empty'); + linuxClipboardBackend.writeText(''); + const got = await awaitWithPump(linuxClipboardBackend.readText(), 5000); + expect(got).toBe(''); + }, + 15000, + ); + test.skipIf(!hasDisplay)( 'clear then readText returns empty string', async () => { From d4b33277e9c7ba21b4340601ceb680a7c80ae076 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:11:44 -0700 Subject: [PATCH 160/586] fix: give named-key menu accelerators a macOS key equivalent --- src/main/api/menu.ts | 42 +++++++++++++++++++++++++++----- tests/unit/main/api/menu.test.ts | 26 ++++++++++++++++++++ 2 files changed, 62 insertions(+), 6 deletions(-) diff --git a/src/main/api/menu.ts b/src/main/api/menu.ts index f5783987..b3efe151 100644 --- a/src/main/api/menu.ts +++ b/src/main/api/menu.ts @@ -191,10 +191,39 @@ const ROLE_NAMES = new Map( ]), ); -/** `'CmdOrCtrl+Q'` → `'q'`; `''` when the key is not a single character. */ +/** AppKit key equivalents for named keys; `\uf7xx` are NSEvent.h's function-key unicodes. */ +const MAC_NAMED_KEYS = new Map([ + ['Plus', '+'], + ['Space', ' '], + ['Tab', '\t'], + ['Return', '\r'], + ['Escape', '\u001b'], + ['Backspace', '\b'], + ['Insert', '\uf727'], + ['Delete', '\uf728'], + ['Up', '\uf700'], + ['Down', '\uf701'], + ['Left', '\uf702'], + ['Right', '\uf703'], + ['Home', '\uf729'], + ['End', '\uf72b'], + ['PageUp', '\uf72c'], + ['PageDown', '\uf72d'], +]); + +/** `'CmdOrCtrl+Q'` is `'q'`; `''` when AppKit has no key equivalent for the key. */ const acceleratorKey = (accelerator: string | undefined): string => { - const parsed = accelerator ? parseAccelerator(accelerator, 'macos') : undefined; - return parsed !== undefined && parsed.key.length === 1 ? parsed.key.toLowerCase() : ''; + const key = accelerator ? parseAccelerator(accelerator, 'macos')?.key : undefined; + if (key === undefined) { + return ''; + } + if (key.length === 1) { + return key.toLowerCase(); + } + if (/^F\d+$/.test(key)) { + return String.fromCharCode(0xf704 + Number(key.slice(1)) - 1); // NSF1FunctionKey + n - 1 + } + return MAC_NAMED_KEYS.get(key) ?? ''; }; // NSEventModifierFlags bits (macOS): only the modifier portion matters here. @@ -288,14 +317,15 @@ export const setMenuRealizerForTesting = (fake: MenuRealizer | undefined): void }; const toSpec = (item: MenuItem): NativeMenuItemSpec => { - const mask = acceleratorModifierMask(item.accelerator); + const keyEquivalent = acceleratorKey(item.accelerator); const base = { label: item.label, type: item.type, enabled: item.enabled, checked: item.checked, - keyEquivalent: acceleratorKey(item.accelerator), - ...(mask !== 0n ? { modifierMask: mask } : {}), + keyEquivalent, + // Always explicit: an absent mask makes AppKit assume Command, so `F11` would need Cmd. + ...(keyEquivalent !== '' ? { modifierMask: acceleratorModifierMask(item.accelerator) } : {}), ...(item.role !== undefined ? { role: item.role, diff --git a/tests/unit/main/api/menu.test.ts b/tests/unit/main/api/menu.test.ts index d06bfccf..baf9a603 100644 --- a/tests/unit/main/api/menu.test.ts +++ b/tests/unit/main/api/menu.test.ts @@ -313,6 +313,32 @@ describe('Menu realization spec', () => { expect(realized?.[0]?.keyEquivalent).toBe('q'); }); + test('maps named keys to AppKit key equivalents (NSEvent.h function-key unicodes)', () => { + const cases: Array<[string, string]> = [ + ['CmdOrCtrl+Plus', '+'], + ['F1', ''], + ['F11', ''], + ['Up', ''], + ['Right', ''], + ['Delete', ''], + ['Backspace', '\b'], + ['Escape', '\u001b'], + ['PageDown', ''], + ]; + Menu.buildFromTemplate(cases.map(([accelerator]) => ({ label: 'x', accelerator }))).realize(); + expect(realized?.map((spec) => spec.keyEquivalent)).toEqual(cases.map(([, key]) => key)); + }); + + test('a modifier-less accelerator sends an explicit empty mask, not AppKit Command', () => { + Menu.buildFromTemplate([{ label: 'Full Screen', accelerator: 'F11' }]).realize(); + expect(realized?.[0]?.modifierMask).toBe(0n); + }); + + test('Super lands on Command in the macOS mask', () => { + Menu.buildFromTemplate([{ label: 'x', accelerator: 'Super+K' }]).realize(); + expect(realized?.[0]?.modifierMask).toBe(1n << 20n); + }); + test('carries the click handler through to the spec', () => { const click = (): void => undefined; Menu.setApplicationMenu(Menu.buildFromTemplate([{ label: 'Go', click }])); From 26d50bc9a782df78146bb9c3b204cc36e954e468 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:11:49 -0700 Subject: [PATCH 161/586] fix: release the Linux clipboard content provider after installing it --- src/main/platform/linux/gtk-clipboard.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/platform/linux/gtk-clipboard.ts b/src/main/platform/linux/gtk-clipboard.ts index 33e5b273..c7a09389 100644 --- a/src/main/platform/linux/gtk-clipboard.ts +++ b/src/main/platform/linux/gtk-clipboard.ts @@ -308,13 +308,14 @@ const writeBytes = (mime: string, bytes: Uint8Array): void => { throw new Error('g_bytes_new() returned null'); } const provider = gdk.symbols.gdk_content_provider_new_for_bytes(cstr(mime), gbytes); - // The provider took its own ref on the GBytes; drop the local one. The provider - // itself is owned by the clipboard once set_content takes a ref. + // The provider took its own ref on the GBytes. glib.symbols.g_bytes_unref(gbytes); if (provider === null) { throw new Error('gdk_content_provider_new_for_bytes() returned null'); } + // set_content takes its own ref; drop ours or every write leaks the provider and its payload. gdk.symbols.gdk_clipboard_set_content(clipboard, provider); + loadGObjectFFI().symbols.g_object_unref(provider); }; /** Install `text` on the clipboard under `mime` (exact UTF-8 bytes, no trailing NUL). */ From 0cb69dfc50b283f3a4238bc26a0ddd151eb62f3c Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:11:51 -0700 Subject: [PATCH 162/586] fix: map a native message box Cancel to Electron's default cancelId --- src/main/platform/windows/windows-dialog.ts | 41 ++++++++++++------- .../platform/windows/windows-dialog.test.ts | 37 ++++++++++++----- 2 files changed, 54 insertions(+), 24 deletions(-) diff --git a/src/main/platform/windows/windows-dialog.ts b/src/main/platform/windows/windows-dialog.ts index 8078b067..b447f5c4 100644 --- a/src/main/platform/windows/windows-dialog.ts +++ b/src/main/platform/windows/windows-dialog.ts @@ -17,13 +17,13 @@ import { loadShell32 } from './win32-shell-ffi'; const MB_OK = 0x0; const MB_OKCANCEL = 0x1; const MB_YESNOCANCEL = 0x3; +const MB_YESNO = 0x4; const MB_ICONERROR = 0x10; const MB_ICONQUESTION = 0x20; const MB_ICONWARNING = 0x30; const MB_ICONINFORMATION = 0x40; -// MessageBoxW return ids (IDOK maps to index 0 implicitly — the "not cancel" case). +// MessageBoxW return ids; IDOK and IDYES both mean the first non-cancel button. const IDCANCEL = 2; -const IDYES = 6; const IDNO = 7; // OPENFILENAMEW flags. @@ -56,14 +56,19 @@ const BI_FLAGS_OFFSET = 32; // ulFlags const FILE_BUFFER_WCHARS = 32768; const MAX_PATH_WCHARS = 260; +/** Electron's default `cancelId` label match: the first "cancel" or "no" button, else -1. */ +const cancelLabelIndex = (buttons: ReadonlyArray): number => + buttons.findIndex((label) => ['cancel', 'no'].includes(label.toLowerCase())); + /** - * Map a message-box spec to a `MessageBoxW` `uType` (button set + icon). Electron - * allows arbitrary button labels; `MessageBoxW` only has fixed sets, so the count - * picks the closest set (1→OK, 2→OK/Cancel, 3→Yes/No/Cancel, >3→OK). Pure. + * Map a message-box spec to a `MessageBoxW` `uType`. The native labels are fixed, so the + * set is chosen to keep Esc on the app's cancel button: 2 buttons with a cancel label get + * OK/Cancel, 2 without one get Yes/No (no Esc path), 3+ get Yes/No/Cancel. Pure. */ export const messageBoxUType = (spec: MessageBoxSpec): number => { const count = spec.buttons.length; - const buttons = count === 2 ? MB_OKCANCEL : count >= 3 ? MB_YESNOCANCEL : MB_OK; + const twoButtons = cancelLabelIndex(spec.buttons) === -1 ? MB_YESNO : MB_OKCANCEL; + const buttons = count === 2 ? twoButtons : count >= 3 ? MB_YESNOCANCEL : MB_OK; const icon = spec.type === 'error' ? MB_ICONERROR @@ -77,15 +82,23 @@ export const messageBoxUType = (spec: MessageBoxSpec): number => { return buttons | icon; }; -/** Map a `MessageBoxW` return id back to the clicked button index for `buttonCount`. Pure. */ -export const messageBoxResponse = (buttonCount: number, id: number): number => { - if (buttonCount >= 3) { - return id === IDYES ? 0 : id === IDNO ? 1 : 2; // Yes / No / Cancel +/** + * Map a `MessageBoxW` return id to a button index: Cancel (and Esc) is Electron's default + * `cancelId` (the cancel label, else 0), Yes/OK and No are the remaining buttons in order. + * ponytail: labels stay OK/Yes/No/Cancel and a 4th+ button is unreachable; a WH_CBT hook + * renaming the buttons (or TaskDialogIndirect) lifts both. Pure. + */ +export const messageBoxResponse = (buttons: ReadonlyArray, id: number): number => { + const cancel = cancelLabelIndex(buttons); + if (buttons.length === 2 && cancel === -1) { + return id === IDNO ? 1 : 0; } - if (buttonCount === 2) { - return id === IDCANCEL || id === IDNO ? 1 : 0; // OK/Yes → 0, Cancel/No → 1 + const cancelId = Math.max(cancel, 0); + if (id === IDCANCEL) { + return cancelId; } - return 0; // single OK button + const others = buttons.map((_, index) => index).filter((index) => index !== cancelId); + return (id === IDNO ? others[1] : others[0]) ?? 0; }; /** @@ -221,7 +234,7 @@ export const windowsDialogBackend: DialogBackend = { ptr(captionBuffer), messageBoxUType(spec), ); - return messageBoxResponse(spec.buttons.length, id); + return messageBoxResponse(spec.buttons, id); }, showOpenDialog(spec: OpenDialogSpec): string[] { diff --git a/tests/unit/main/platform/windows/windows-dialog.test.ts b/tests/unit/main/platform/windows/windows-dialog.test.ts index 056ff98a..d127c15a 100644 --- a/tests/unit/main/platform/windows/windows-dialog.test.ts +++ b/tests/unit/main/platform/windows/windows-dialog.test.ts @@ -18,6 +18,7 @@ import { */ const MB_OK = 0x0; const MB_OKCANCEL = 0x1; +const MB_YESNO = 0x4; const MB_YESNOCANCEL = 0x3; const MB_ICONERROR = 0x10; const MB_ICONWARNING = 0x30; @@ -45,11 +46,12 @@ const spec = (buttons: string[], type?: MessageBoxSpec['type']): MessageBoxSpec }); describe('messageBoxUType', () => { - test('button count picks the closest MessageBoxW set', () => { + test('button count and a cancel label pick the MessageBoxW set', () => { expect(messageBoxUType(spec(['OK']))).toBe(MB_OK); expect(messageBoxUType(spec(['Save', 'Cancel']))).toBe(MB_OKCANCEL); + expect(messageBoxUType(spec(['Save', 'Discard']))).toBe(MB_YESNO); expect(messageBoxUType(spec(['Yes', 'No', 'Cancel']))).toBe(MB_YESNOCANCEL); - expect(messageBoxUType(spec(['a', 'b', 'c', 'd']))).toBe(MB_YESNOCANCEL); // >3 → 3-set + expect(messageBoxUType(spec(['a', 'b', 'c', 'd']))).toBe(MB_YESNOCANCEL); }); test('severity adds the icon flag', () => { @@ -62,18 +64,33 @@ describe('messageBoxUType', () => { describe('messageBoxResponse', () => { test('single OK is always index 0', () => { - expect(messageBoxResponse(1, IDOK)).toBe(0); + expect(messageBoxResponse(['OK'], IDOK)).toBe(0); }); - test('two buttons map OK/Yes→0 and Cancel/No→1', () => { - expect(messageBoxResponse(2, IDOK)).toBe(0); - expect(messageBoxResponse(2, IDCANCEL)).toBe(1); + test('native Cancel (and Esc) resolves to the cancel label, never the other button', () => { + expect(messageBoxResponse(['Cancel', 'Delete'], IDCANCEL)).toBe(0); + expect(messageBoxResponse(['Cancel', 'Delete'], IDOK)).toBe(1); + expect(messageBoxResponse(['OK', 'Cancel'], IDOK)).toBe(0); + expect(messageBoxResponse(['OK', 'Cancel'], IDCANCEL)).toBe(1); }); - test('three buttons map Yes/No/Cancel to 0/1/2', () => { - expect(messageBoxResponse(3, IDYES)).toBe(0); - expect(messageBoxResponse(3, IDNO)).toBe(1); - expect(messageBoxResponse(3, IDCANCEL)).toBe(2); + test('two buttons without a cancel label map Yes/No to 0/1', () => { + expect(messageBoxResponse(['Save', 'Discard'], IDYES)).toBe(0); + expect(messageBoxResponse(['Save', 'Discard'], IDNO)).toBe(1); + }); + + test('three buttons map Cancel to the cancel label and Yes/No to the rest in order', () => { + const buttons = ['Cancel', 'Yes, please', 'No, thanks']; + expect(messageBoxResponse(buttons, IDCANCEL)).toBe(0); + expect(messageBoxResponse(buttons, IDYES)).toBe(1); + expect(messageBoxResponse(buttons, IDNO)).toBe(2); + expect(messageBoxResponse(['Save', "Don't Save", 'Cancel'], IDCANCEL)).toBe(2); + expect(messageBoxResponse(['Save', "Don't Save", 'Cancel'], IDNO)).toBe(1); + }); + + test('without a cancel label, Cancel resolves to 0 like Electron', () => { + expect(messageBoxResponse(['a', 'b', 'c'], IDCANCEL)).toBe(0); + expect(messageBoxResponse(['a', 'b', 'c'], IDYES)).toBe(1); }); }); From 36192b01556db0b3bc2fc5e3dea4b6aa8f5b72bc Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:11:52 -0700 Subject: [PATCH 163/586] fix: refuse Windows installs outside the /.exe layout --- src/main/api/update-installer.ts | 13 +++++++++++-- tests/unit/main/api/update-installer.test.ts | 8 ++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/main/api/update-installer.ts b/src/main/api/update-installer.ts index 9eef215e..d530a9b5 100644 --- a/src/main/api/update-installer.ts +++ b/src/main/api/update-installer.ts @@ -44,9 +44,18 @@ export const deriveInstallRoot = (execPath: string, os: ArtifactOs): string | un } return rootDir; } - // build-windows layout: the portable dir holds the exe; refuse a drive root. + // build-windows layout: /.exe. Anything else (bun.exe in its + // toolchain dir, a drive root) would get moved aside and deleted by the swap. const rootDir = dirname(execPath); - return dirname(rootDir) === rootDir ? undefined : rootDir; + const exeStem = basename(execPath).replace(/\.exe$/i, ''); + if ( + dirname(rootDir) === rootDir || + /^(bun|node)$/i.test(exeStem) || + exeStem.toLowerCase() !== basename(rootDir).toLowerCase() + ) { + return undefined; + } + return rootDir; }; /** Top-level dir inside the update tar; mirrors `bunmaska build`'s bundle names. */ diff --git a/tests/unit/main/api/update-installer.test.ts b/tests/unit/main/api/update-installer.test.ts index e8d194af..adecec10 100644 --- a/tests/unit/main/api/update-installer.test.ts +++ b/tests/unit/main/api/update-installer.test.ts @@ -62,8 +62,16 @@ describe('deriveInstallRoot', () => { test('Windows: the portable dir is the executable directory, never a root', () => { expect(deriveInstallRoot('/apps/Demo/Demo.exe', 'windows')).toBe('/apps/Demo'); + expect(deriveInstallRoot('/apps/Demo/demo.EXE', 'windows')).toBe('/apps/Demo'); expect(deriveInstallRoot('/Demo.exe', 'windows')).toBeUndefined(); }); + + test('Windows: refuses a dev runner or any dir not laid out as /.exe', () => { + expect(deriveInstallRoot('C:/Users/u/.bun/bin/bun.exe', 'windows')).toBeUndefined(); + expect(deriveInstallRoot('C:/tools/bun/bun.exe', 'windows')).toBeUndefined(); + expect(deriveInstallRoot('C:/tools/node/node.exe', 'windows')).toBeUndefined(); + expect(deriveInstallRoot('C:/Users/u/Downloads/Demo.exe', 'windows')).toBeUndefined(); + }); }); describe('stagedBundleDirName', () => { From 141d3578c9d0235d2b1e70cc9e6b2a1bacc0acc0 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:12:00 -0700 Subject: [PATCH 164/586] fix: trap X errors on the shortcut display so a taken key cannot exit --- .../platform/linux/x11-global-shortcut.ts | 23 +++++++++- .../linux/x11-global-shortcut.test.ts | 42 +++++++++++++++++++ 2 files changed, 64 insertions(+), 1 deletion(-) diff --git a/src/main/platform/linux/x11-global-shortcut.ts b/src/main/platform/linux/x11-global-shortcut.ts index a55cc179..043cde82 100644 --- a/src/main/platform/linux/x11-global-shortcut.ts +++ b/src/main/platform/linux/x11-global-shortcut.ts @@ -1,4 +1,4 @@ -import { type Pointer, ptr } from 'bun:ffi'; +import { CFunction, JSCallback, type Pointer, ptr } from 'bun:ffi'; import { parseAccelerator } from '../../api/accelerator'; import type { GlobalShortcutBackend } from '../../api/global-shortcut'; import { cstr } from '../cstr'; @@ -48,6 +48,25 @@ let display: Pointer | null | undefined; let displayFailed = false; let rootWindow = 0n; const registrations: Registration[] = []; +let errorTrap: JSCallback | undefined; + +/** + * Swallow X errors on the grab display: a BadAccess for a key another client holds + * would otherwise reach Xlib's default handler, which exit(1)s the app. Errors on + * any other display chain to the previous handler. Never closed (Xlib keeps the pointer). + */ +const installErrorTrap = (x11: ReturnType): void => { + let previous: CallableFunction | undefined; + errorTrap = new JSCallback( + (dpy: Pointer | null, event: Pointer | null): number => + dpy === display || previous === undefined ? 0 : Number(previous(dpy, event)), + { args: ['ptr', 'ptr'], returns: 'i32' }, + ); + const prior = x11.symbols.XSetErrorHandler(errorTrap.ptr); + if (prior !== null) { + previous = CFunction({ ptr: prior, args: ['ptr', 'ptr'], returns: 'i32' }); + } +}; /** Open (once) the dedicated X display for grabs, or record that it is unavailable. */ const ensureDisplay = (): Pointer | null => { @@ -65,6 +84,7 @@ const ensureDisplay = (): Pointer | null => { return null; } display = dpy; + installErrorTrap(x11); rootWindow = x11.symbols.XDefaultRootWindow(dpy); x11.symbols.XSelectInput(dpy, rootWindow, KEY_PRESS_MASK); return dpy; @@ -101,6 +121,7 @@ const register = (accelerator: string, callback: () => void): boolean => { for (const lockBits of GRAB_VARIANTS) { x11.symbols.XGrabKey(dpy, keycode, modifiers | lockBits, rootWindow, 0, 1, 1); } + // ponytail: a key another client holds still returns true; XSync + a trap flag reports it once x11-ffi declares XSync. x11.symbols.XFlush(dpy); registrations.push({ keycode, modifiers, callback }); return true; diff --git a/tests/integration/linux/x11-global-shortcut.test.ts b/tests/integration/linux/x11-global-shortcut.test.ts index 606bfa51..86563bef 100644 --- a/tests/integration/linux/x11-global-shortcut.test.ts +++ b/tests/integration/linux/x11-global-shortcut.test.ts @@ -1,10 +1,13 @@ import { afterEach, describe, expect, test } from 'bun:test'; +import { dlopen, FFIType, type Pointer } from 'bun:ffi'; import { currentPlatform } from '../../../src/common/platform'; +import { cstr } from '../../../src/main/platform/cstr'; import { linuxGlobalShortcutBackend, pollX11ShortcutsOnce, } from '../../../src/main/platform/linux/x11-global-shortcut'; import { loadX11FFI } from '../../../src/main/platform/linux/x11-ffi'; +import { CONTROL_MASK, SHIFT_MASK } from '../../../src/main/platform/linux/x11-keymap'; /** * Linux-only. Exercises the REAL Xlib `XGrabKey` path. Needs an X server — under @@ -18,6 +21,29 @@ import { loadX11FFI } from '../../../src/main/platform/linux/x11-ffi'; */ const isLinux = currentPlatform() === 'linux'; +/** XSync is not in the backend's table; a second client needs it to order its grab first. */ +const xSync = (dpy: Pointer): void => { + dlopen('libX11.so.6', { + XSync: { args: [FFIType.pointer, FFIType.i32], returns: FFIType.i32 }, + }).symbols.XSync(dpy, 0); +}; + +/** Open a second X client, independent of the backend's grab connection. */ +const openOtherClient = (): Pointer => { + const dpy = loadX11FFI().symbols.XOpenDisplay(null); + if (dpy === null) { + throw new Error('XOpenDisplay failed for the second client'); + } + return dpy; +}; + +const pumpShortcuts = async (until: () => boolean): Promise => { + for (let i = 0; i < 50 && !until(); i += 1) { + pollX11ShortcutsOnce(); + await Bun.sleep(10); + } +}; + const hasDisplay = (): boolean => { if (!isLinux) { return false; @@ -66,6 +92,22 @@ describe.skipIf(!isLinux)('x11-global-shortcut (Linux)', () => { expect(() => pollX11ShortcutsOnce()).not.toThrow(); }); + test('a key another client already grabbed does not exit the process', async () => { + const x11 = loadX11FFI().symbols; + const other = openOtherClient(); + try { + const keycode = x11.XKeysymToKeycode(other, x11.XStringToKeysym(cstr('j'))); + const mods = CONTROL_MASK | SHIFT_MASK; + x11.XGrabKey(other, keycode, mods, x11.XDefaultRootWindow(other), 0, 1, 1); + xSync(other); + linuxGlobalShortcutBackend.register('Ctrl+Shift+J', () => undefined); + await pumpShortcuts(() => false); + expect(() => pollX11ShortcutsOnce()).not.toThrow(); + } finally { + x11.XCloseDisplay(other); + } + }); + test('register/unregisterAll several grabs cleanly', () => { expect(linuxGlobalShortcutBackend.register('CmdOrCtrl+1', () => undefined)).toBe(true); expect(linuxGlobalShortcutBackend.register('CmdOrCtrl+2', () => undefined)).toBe(true); From f852b519f298912b38ee5252b4e2c88b447fccdf Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:12:12 -0700 Subject: [PATCH 165/586] fix: report plain MIME names from Linux clipboard availableFormats --- src/main/platform/linux/gtk-clipboard.ts | 15 +++++++++++---- tests/integration/linux/clipboard.test.ts | 5 +++++ .../main/platform/linux/gtk-clipboard.test.ts | 12 ++++++++++++ 3 files changed, 28 insertions(+), 4 deletions(-) diff --git a/src/main/platform/linux/gtk-clipboard.ts b/src/main/platform/linux/gtk-clipboard.ts index c7a09389..07b8b595 100644 --- a/src/main/platform/linux/gtk-clipboard.ts +++ b/src/main/platform/linux/gtk-clipboard.ts @@ -394,6 +394,16 @@ const readImage = (): Promise => { }); }; +/** Electron-style MIME names from `gdk_content_formats_to_string` (GType names dropped). */ +export const formatsFromGdk = (text: string): string[] => [ + ...new Set( + text + .split(/\s+/) + .filter((token) => token.includes('/')) + .map((mime) => mime.split(';')[0] as string), + ), +]; + /** The MIME types currently advertised by the clipboard (Electron's `availableFormats`). */ const availableFormats = (): string[] => { const gdk = loadGdkFFI(); @@ -408,10 +418,7 @@ const availableFormats = (): string[] => { } const text = new CString(cstrPtr).toString(); glib.symbols.g_free(cstrPtr); - return text - .split(/\s+/) - .map((s) => s.trim()) - .filter((s) => s.length > 0); + return formatsFromGdk(text); }; const clear = (): void => { diff --git a/tests/integration/linux/clipboard.test.ts b/tests/integration/linux/clipboard.test.ts index 5be31b32..4b80d6c5 100644 --- a/tests/integration/linux/clipboard.test.ts +++ b/tests/integration/linux/clipboard.test.ts @@ -212,4 +212,9 @@ describe.skipIf(!isLinux)('Linux clipboard backend (GDK 4)', () => { linuxClipboardBackend.writeImage(PNG_1x1); expect(linuxClipboardBackend.availableFormats()).toContain('image/png'); }); + + test.skipIf(!hasDisplay)('availableFormats reports text/plain after writing text', () => { + linuxClipboardBackend.writeText('bunmaska-clip-formats'); + expect(linuxClipboardBackend.availableFormats()).toContain('text/plain'); + }); }); diff --git a/tests/unit/main/platform/linux/gtk-clipboard.test.ts b/tests/unit/main/platform/linux/gtk-clipboard.test.ts index 162597ed..87ce9362 100644 --- a/tests/unit/main/platform/linux/gtk-clipboard.test.ts +++ b/tests/unit/main/platform/linux/gtk-clipboard.test.ts @@ -4,6 +4,7 @@ import { type AsyncStreamReader, CLIPBOARD_READ_CB_DEF, drainStreamAsync, + formatsFromGdk, linuxClipboardBackend, settleReadStreamAsync, settleReadText, @@ -26,6 +27,17 @@ describe('linuxClipboardBackend shape', () => { }); }); +describe('formatsFromGdk', () => { + it('reports MIME names without parameters, drops GType names and dedupes', () => { + const gdk = 'gchararray GdkTexture text/plain;charset=utf-8 text/plain image/png'; + expect(formatsFromGdk(gdk)).toEqual(['text/plain', 'image/png']); + }); + + it('returns no formats for an empty clipboard', () => { + expect(formatsFromGdk('')).toEqual([]); + }); +}); + describe('drainStreamAsync (injected AsyncStreamReader, no real GInputStream)', () => { /** A reader resolving the given chunks in order, then EOF; records close(). */ const makeReader = ( From 452c39f197e6ff1032420b7dc619fcee119c18d7 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:12:31 -0700 Subject: [PATCH 166/586] fix: report Linux global shortcuts unsupported on Wayland sessions --- src/main/platform/linux/x11-global-shortcut.ts | 8 ++++++++ .../platform/linux/x11-global-shortcut.test.ts | 17 +++++++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 tests/unit/main/platform/linux/x11-global-shortcut.test.ts diff --git a/src/main/platform/linux/x11-global-shortcut.ts b/src/main/platform/linux/x11-global-shortcut.ts index 043cde82..0302a786 100644 --- a/src/main/platform/linux/x11-global-shortcut.ts +++ b/src/main/platform/linux/x11-global-shortcut.ts @@ -68,6 +68,10 @@ const installErrorTrap = (x11: ReturnType): void => { } }; +/** XWayland root grabs never see keys routed to native Wayland clients, so Wayland is unsupported. */ +export const isWaylandSession = (env: Readonly>): boolean => + Boolean(env['WAYLAND_DISPLAY']) || env['XDG_SESSION_TYPE'] === 'wayland'; + /** Open (once) the dedicated X display for grabs, or record that it is unavailable. */ const ensureDisplay = (): Pointer | null => { if (display !== undefined) { @@ -76,6 +80,10 @@ const ensureDisplay = (): Pointer | null => { if (displayFailed) { return null; } + if (isWaylandSession(process.env)) { + displayFailed = true; + return null; + } try { const x11 = loadX11FFI(); const dpy = x11.symbols.XOpenDisplay(null); diff --git a/tests/unit/main/platform/linux/x11-global-shortcut.test.ts b/tests/unit/main/platform/linux/x11-global-shortcut.test.ts new file mode 100644 index 00000000..9696329f --- /dev/null +++ b/tests/unit/main/platform/linux/x11-global-shortcut.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, test } from 'bun:test'; +import { isWaylandSession } from '../../../../../src/main/platform/linux/x11-global-shortcut'; + +describe('isWaylandSession', () => { + test('is true when WAYLAND_DISPLAY is set, even with an XWayland DISPLAY', () => { + expect(isWaylandSession({ WAYLAND_DISPLAY: 'wayland-0', DISPLAY: ':0' })).toBe(true); + }); + + test('is true when the session type is wayland', () => { + expect(isWaylandSession({ XDG_SESSION_TYPE: 'wayland' })).toBe(true); + }); + + test('is false for an X11 session', () => { + expect(isWaylandSession({ XDG_SESSION_TYPE: 'x11', DISPLAY: ':0' })).toBe(false); + expect(isWaylandSession({ WAYLAND_DISPLAY: '', DISPLAY: ':99' })).toBe(false); + }); +}); From 13914010b44208b15340edd7003b97881dab8fcd Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:12:31 -0700 Subject: [PATCH 167/586] fix: spawn the update helper detached so it outlives the app --- src/main/api/update-installer.ts | 11 +++--- tests/unit/main/api/update-installer.test.ts | 36 ++++++++++++++++++++ 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/src/main/api/update-installer.ts b/src/main/api/update-installer.ts index d530a9b5..f8c6ece4 100644 --- a/src/main/api/update-installer.ts +++ b/src/main/api/update-installer.ts @@ -193,10 +193,13 @@ export const installStagedUpdate = (staged: StagedUpdate, deps: InstallerDeps): deps.quit(); }; -const spawnDetachedScript = (argv: readonly string[]): void => { - // unref so app.quit() is not held open; a POSIX orphan reparents and lives on. - const proc = Bun.spawn([...argv], { stdio: ['ignore', 'ignore', 'ignore'] }); - proc.unref(); +/** + * Must be `detached`: on Windows a non-detached child sits in the app's + * kill-on-close job and dies with it (D043's TerminateProcess exit), so the swap + * never runs; on POSIX it gets its own session. `unref` keeps quit from waiting. + */ +export const spawnDetachedScript = (argv: readonly string[]): void => { + Bun.spawn([...argv], { stdio: ['ignore', 'ignore', 'ignore'], detached: true }).unref(); }; /** The production default installer behind `autoUpdater.quitAndInstall`. */ diff --git a/tests/unit/main/api/update-installer.test.ts b/tests/unit/main/api/update-installer.test.ts index adecec10..8c460c81 100644 --- a/tests/unit/main/api/update-installer.test.ts +++ b/tests/unit/main/api/update-installer.test.ts @@ -1,4 +1,7 @@ import { describe, expect, test } from 'bun:test'; +import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; import type { UpdateManifest } from '../../../../src/common/manifest'; import type { StagedUpdate } from '../../../../src/main/api/auto-updater'; import { @@ -8,6 +11,7 @@ import { installStagedUpdate, type InstallerDeps, shQuote, + spawnDetachedScript, stagedBundleDirName, } from '../../../../src/main/api/update-installer'; @@ -228,3 +232,35 @@ describe('installStagedUpdate', () => { expect(h.quits).toHaveLength(1); }); }); + +const pgidOf = (pid: number | string): string => + Bun.spawnSync(['ps', '-o', 'pgid=', '-p', String(pid)]) + .stdout.toString() + .trim(); + +describe('spawnDetachedScript', () => { + test.skipIf(process.platform === 'win32')( + 'starts the helper in its own session so it outlives the quitting app', + async () => { + const dir = mkdtempSync(join(tmpdir(), 'bunmaska-detach-')); + try { + const out = join(dir, 'pgid'); + spawnDetachedScript([ + '/bin/sh', + '-c', + `ps -o pgid= -p $$ > ${shQuote(`${out}.tmp`)}; mv ${shQuote(`${out}.tmp`)} ${shQuote(out)}`, + ]); + const deadline = Date.now() + 5000; + while (!existsSync(out)) { + if (Date.now() > deadline) { + throw new Error('the detached helper never ran'); + } + await Bun.sleep(20); + } + expect(readFileSync(out, 'utf8').trim()).not.toBe(pgidOf(process.pid)); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }, + ); +}); From 4780b6fa4ea7a08e4b0a92386c334c9510f06045 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:12:50 -0700 Subject: [PATCH 168/586] fix: surface a throwing Linux menu click instead of losing it --- src/main/platform/linux/gtk-menu.ts | 43 ++++++++++++------- .../unit/main/platform/linux/gtk-menu.test.ts | 36 ++++++++++++++++ 2 files changed, 64 insertions(+), 15 deletions(-) diff --git a/src/main/platform/linux/gtk-menu.ts b/src/main/platform/linux/gtk-menu.ts index fc5b9543..84aea04e 100644 --- a/src/main/platform/linux/gtk-menu.ts +++ b/src/main/platform/linux/gtk-menu.ts @@ -170,6 +170,31 @@ type WalkContext = { readonly dispatchRole?: ((spec: NativeMenuItemSpec) => void) | undefined; }; +/** A click handler's throw is re-thrown on a microtask; unwinding into the GLib dispatch loses it. */ +const guarded = (thunk: () => void) => (): void => { + try { + thunk(); + } catch (error) { + queueMicrotask(() => { + throw error; + }); + } +}; + +const wireAction = ( + ctx: WalkContext, + model: bigint, + label: string, + name: string, + action: bigint, + thunk: () => void, +): void => { + ctx.retained.push(ctx.b.connectActivate(action, guarded(thunk))); + ctx.b.gActionMapAddAction(ctx.group, action); + ctx.actionNames.push(name); + ctx.b.gMenuAppend(model, label, detailedAction(name)); +}; + const appendItems = ( ctx: WalkContext, root: bigint, @@ -201,33 +226,21 @@ const appendItems = ( const action = ctx.b.gSimpleActionNew(name); ctx.b.gSimpleActionSetEnabled(action, spec.enabled === false ? 0 : 1); const dispatch = ctx.dispatchRole; - const retained = ctx.b.connectActivate(action, () => dispatch(spec)); - ctx.b.gActionMapAddAction(ctx.group, action); - ctx.actionNames.push(name); - ctx.retained.push(retained); - ctx.b.gMenuAppend(model, spec.label, detailedAction(name)); + wireAction(ctx, model, spec.label, name, action, () => dispatch(spec)); continue; } if ((spec.type === 'checkbox' || spec.type === 'radio') && spec.onClick !== undefined) { const name = actionName(); const action = ctx.b.gSimpleActionNewStatefulBool(name, spec.checked ?? false); ctx.b.gSimpleActionSetEnabled(action, spec.enabled ? 1 : 0); - const retained = ctx.b.connectActivate(action, spec.onClick); - ctx.b.gActionMapAddAction(ctx.group, action); - ctx.actionNames.push(name); - ctx.retained.push(retained); - ctx.b.gMenuAppend(model, spec.label, detailedAction(name)); + wireAction(ctx, model, spec.label, name, action, spec.onClick); continue; } if (spec.type === 'normal' && spec.onClick !== undefined) { const name = actionName(); const action = ctx.b.gSimpleActionNew(name); ctx.b.gSimpleActionSetEnabled(action, spec.enabled ? 1 : 0); - const retained = ctx.b.connectActivate(action, spec.onClick); - ctx.b.gActionMapAddAction(ctx.group, action); - ctx.actionNames.push(name); - ctx.retained.push(retained); - ctx.b.gMenuAppend(model, spec.label, detailedAction(name)); + wireAction(ctx, model, spec.label, name, action, spec.onClick); continue; } // A normal item with no onClick: a static, inert label (e.g. a heading). diff --git a/tests/unit/main/platform/linux/gtk-menu.test.ts b/tests/unit/main/platform/linux/gtk-menu.test.ts index 809dcaac..a4f30c4d 100644 --- a/tests/unit/main/platform/linux/gtk-menu.test.ts +++ b/tests/unit/main/platform/linux/gtk-menu.test.ts @@ -194,6 +194,42 @@ describe('linuxMenuRealizer.realize (fake bindings)', () => { expect(fired).toEqual(['beta', 'alpha']); }); + it('re-throws a failing click on a microtask instead of into the GLib dispatch', () => { + const { bindings } = makeFakeBindings(); + setBindingsForTesting(bindings); + const boom = new Error('app bug'); + const handle = linuxMenuRealizer.realize([ + { + label: 'Bad', + type: 'normal', + enabled: true, + keyEquivalent: '', + onClick: () => { + throw boom; + }, + }, + ]); + const entry = getMenuEntry(handle); + const queued: Array<() => void> = []; + const original = globalThis.queueMicrotask; + globalThis.queueMicrotask = (cb) => { + queued.push(cb); + }; + try { + const fire = (): void => + bindings.activateAction( + entry?.group as bigint, + detailedAction(entry?.actionNames[0] as string), + null, + ); + expect(fire).not.toThrow(); + } finally { + globalThis.queueMicrotask = original; + } + expect(queued).toHaveLength(1); + expect(() => queued[0]?.()).toThrow(boom); + }); + it('honours enabled:false via g_simple_action_set_enabled(0)', () => { const { bindings, calls } = makeFakeBindings(); setBindingsForTesting(bindings); From 590dd8b677efac5d790467d0147884c2e40c4144 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:12:54 -0700 Subject: [PATCH 169/586] fix: match X11 shortcut state on the registrable modifiers only --- src/main/platform/linux/x11-keymap.ts | 9 ++++----- tests/unit/main/platform/linux/x11-keymap.test.ts | 12 ++++++++++-- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/src/main/platform/linux/x11-keymap.ts b/src/main/platform/linux/x11-keymap.ts index 6de6e443..24aaa63d 100644 --- a/src/main/platform/linux/x11-keymap.ts +++ b/src/main/platform/linux/x11-keymap.ts @@ -21,18 +21,17 @@ export const XKEY_STATE_OFFSET = 80; export const XKEY_KEYCODE_OFFSET = 84; export const XEVENT_BUFFER_SIZE = 192; -/** Lock (CapsLock) and Mod2 (NumLock) — state bits a shortcut must not care about. */ -export const IGNORED_STATE_MASK = (1 << 1) | (1 << 4); // LockMask | Mod2Mask - /** * The lock-bit grab variants: `XGrabKey(mods)` never fires while NumLock or * CapsLock is on, so every registration grabs all four combinations. */ export const GRAB_VARIANTS: readonly number[] = [0, 1 << 1, 1 << 4, (1 << 1) | (1 << 4)]; -/** Whether a KeyPress `state` matches a registered modifier mask, ignoring lock bits. Pure. */ +const REGISTRABLE_MODIFIERS = SHIFT_MASK | CONTROL_MASK | MOD1_MASK | MOD4_MASK; + +/** Compares only the registrable modifiers: `state` also carries lock, pointer-button and XKB group bits. */ export const x11StateMatches = (state: number, modifiers: number): boolean => - (state & ~IGNORED_STATE_MASK) === modifiers; + (state & REGISTRABLE_MODIFIERS) === modifiers; /** `KeyPressMask` for `XSelectInput` (`X.h`). */ export const KEY_PRESS_MASK = 1 << 0; // 1 diff --git a/tests/unit/main/platform/linux/x11-keymap.test.ts b/tests/unit/main/platform/linux/x11-keymap.test.ts index a3fa440d..ed0bc782 100644 --- a/tests/unit/main/platform/linux/x11-keymap.test.ts +++ b/tests/unit/main/platform/linux/x11-keymap.test.ts @@ -2,7 +2,6 @@ import { describe, expect, test } from 'bun:test'; import { parseAccelerator } from '../../../../../src/main/api/accelerator'; import { CONTROL_MASK, - IGNORED_STATE_MASK, MOD1_MASK, MOD4_MASK, SHIFT_MASK, @@ -114,6 +113,15 @@ describe('x11StateMatches', () => { }); test('ignores CapsLock and NumLock state bits', () => { - expect(x11StateMatches(CONTROL_MASK | IGNORED_STATE_MASK, CONTROL_MASK)).toBe(true); + const lockAndNumLock = (1 << 1) | (1 << 4); + expect(x11StateMatches(CONTROL_MASK | lockAndNumLock, CONTROL_MASK)).toBe(true); + }); + + test('ignores the XKB group bits of a second keyboard layout', () => { + expect(x11StateMatches(CONTROL_MASK | (1 << 13), CONTROL_MASK)).toBe(true); + }); + + test('ignores a held pointer button', () => { + expect(x11StateMatches(CONTROL_MASK | (1 << 8), CONTROL_MASK)).toBe(true); }); }); From 4bd3fae560d2edfa35f82c0c4083d775fe519495 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:12:54 -0700 Subject: [PATCH 170/586] fix: pass Electron's click arguments and toggle checkbox and radio items --- src/main/api/menu.ts | 61 ++++++++++++++++++++++++++------ tests/unit/main/api/menu.test.ts | 41 ++++++++++++++++++--- 2 files changed, 87 insertions(+), 15 deletions(-) diff --git a/src/main/api/menu.ts b/src/main/api/menu.ts index b3efe151..44fd764b 100644 --- a/src/main/api/menu.ts +++ b/src/main/api/menu.ts @@ -58,10 +58,17 @@ export type MenuItemOptions = { /** The key must be a SINGLE character, e.g. `'CmdOrCtrl+Q'`. */ readonly accelerator?: string; readonly role?: MenuRole | MenuMacroRole; - readonly click?: () => void; + readonly click?: MenuItemClick; readonly submenu?: Menu | ReadonlyArray; }; +/** Electron's signature; `event` fields are omitted when unknown. */ +export type MenuItemClick = ( + menuItem: MenuItem, + window: BrowserWindow | undefined, + event: { readonly triggeredByAccelerator?: boolean }, +) => void; + /** Operated on the ACTIVATING window, not a fixed one. */ export type MenuWindowAction = 'minimize' | 'close' | 'zoom' | 'togglefullscreen'; @@ -256,10 +263,10 @@ export class MenuItem { readonly type: MenuItemType; readonly id: string | undefined; readonly enabled: boolean; - readonly checked: boolean; + checked: boolean; readonly accelerator: string | undefined; readonly role: MenuRole | undefined; - readonly click: (() => void) | undefined; + readonly click: MenuItemClick | undefined; readonly submenu: Menu | undefined; constructor(options: MenuItemOptions) { @@ -316,7 +323,35 @@ export const setMenuRealizerForTesting = (fake: MenuRealizer | undefined): void realizer = fake; }; -const toSpec = (item: MenuItem): NativeMenuItemSpec => { +/** Electron groups radio items by the separators around them. */ +const radioGroup = (item: MenuItem, siblings: readonly MenuItem[]): MenuItem[] => { + let start = siblings.indexOf(item); + while (start > 0 && siblings[start - 1]?.type !== 'separator') { + start -= 1; + } + let end = start; + while (end < siblings.length - 1 && siblings[end + 1]?.type !== 'separator') { + end += 1; + } + return siblings.slice(start, end + 1).filter((other) => other.type === 'radio'); +}; + +/** Electron's click: a checkbox flips, a radio checks itself in its group, then `click` runs. */ +const activate = (item: MenuItem, siblings: readonly MenuItem[]): void => { + if (item.type === 'checkbox') { + item.checked = !item.checked; + } else if (item.type === 'radio') { + for (const other of radioGroup(item, siblings)) { + other.checked = other === item; + } + } + item.click?.(item, windowResolver?.focusedWindow?.(), {}); +}; + +const toSpecs = (items: readonly MenuItem[]): NativeMenuItemSpec[] => + items.map((item) => toSpec(item, items)); + +const toSpec = (item: MenuItem, siblings: readonly MenuItem[]): NativeMenuItemSpec => { const keyEquivalent = acceleratorKey(item.accelerator); const base = { label: item.label, @@ -341,13 +376,15 @@ const toSpec = (item: MenuItem): NativeMenuItemSpec => { : {}), }; if (item.type === 'submenu' && item.submenu !== undefined) { - return { ...base, submenu: item.submenu.items.map(toSpec) }; + return { ...base, submenu: toSpecs(item.submenu.items) }; } - // A role provides native behavior via its selector (macOS) — no JS click is - // synthesized; if both a role and a click are given, the role takes precedence. - const clickable = item.type === 'normal' || item.type === 'checkbox' || item.type === 'radio'; - if (item.role === undefined && clickable && item.click !== undefined) { - return { ...base, onClick: item.click }; + // A role wins over a click: one native item cannot run both (D035). + const checkable = item.type === 'checkbox' || item.type === 'radio'; + if ( + item.role === undefined && + (checkable || (item.type === 'normal' && item.click !== undefined)) + ) { + return { ...base, onClick: () => activate(item, siblings) }; } return base; }; @@ -376,6 +413,8 @@ export type WindowResolver = { mostRecent(): PopupTarget | undefined; /** `undefined` when `window` is not a known open window. */ resolve(window: unknown): PopupTarget | undefined; + /** The window handed to `MenuItem.click`. */ + focusedWindow?(): BrowserWindow | undefined; }; let windowResolver: WindowResolver | undefined; @@ -448,7 +487,7 @@ export class Menu { /** @internal */ realize(): bigint { - return getRealizer().realize(this.items.map(toSpec)); + return getRealizer().realize(toSpecs(this.items)); } /** `null` removes the application menu everywhere, including bars already installed. */ diff --git a/tests/unit/main/api/menu.test.ts b/tests/unit/main/api/menu.test.ts index baf9a603..317887dd 100644 --- a/tests/unit/main/api/menu.test.ts +++ b/tests/unit/main/api/menu.test.ts @@ -81,6 +81,29 @@ describe('Menu checkbox/radio items', () => { menu.realize(); expect(realized?.[0]).toMatchObject({ type: 'radio', checked: false }); }); + + test('clicking a checkbox flips checked before click sees the item', () => { + let seen: boolean | undefined; + const menu = Menu.buildFromTemplate([ + { label: 'Wrap', type: 'checkbox', checked: true, click: (item) => (seen = item.checked) }, + ]); + menu.realize(); + realized?.[0]?.onClick?.(); + expect(seen).toBe(false); + expect(menu.items[0]?.checked).toBe(false); + }); + + test('clicking a radio checks it and clears the rest of its separator-bounded group', () => { + const menu = Menu.buildFromTemplate([ + { label: 'A', type: 'radio', checked: true }, + { label: 'B', type: 'radio' }, + { type: 'separator' }, + { label: 'C', type: 'radio', checked: true }, + ]); + menu.realize(); + realized?.[1]?.onClick?.(); + expect(menu.items.map((i) => i.checked)).toEqual([false, true, false, true]); + }); }); describe('MenuItem roles', () => { @@ -339,10 +362,20 @@ describe('Menu realization spec', () => { expect(realized?.[0]?.modifierMask).toBe(1n << 20n); }); - test('carries the click handler through to the spec', () => { - const click = (): void => undefined; - Menu.setApplicationMenu(Menu.buildFromTemplate([{ label: 'Go', click }])); - expect(realized?.[0]?.onClick).toBe(click); + test('click receives the item, the focused window and an event, as in Electron', () => { + const focused = {} as BrowserWindow; + setWindowResolverForTesting({ + focused: () => undefined, + mostRecent: () => undefined, + resolve: () => undefined, + focusedWindow: () => focused, + }); + const calls: unknown[][] = []; + const menu = Menu.buildFromTemplate([{ label: 'Go', click: (...args) => calls.push(args) }]); + Menu.setApplicationMenu(menu); + realized?.[0]?.onClick?.(); + setWindowResolverForTesting(undefined); + expect(calls).toEqual([[menu.items[0], focused, {}]]); }); test('nests submenu specs', () => { From 3f9fcd57bcb3a9d197ab29073a90e4982c717d9f Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:13:21 -0700 Subject: [PATCH 171/586] fix: map punctuation accelerator keys to X11 Unicode keysyms --- src/main/platform/linux/x11-keymap.ts | 5 ++++- tests/integration/linux/x11-global-shortcut.test.ts | 4 ++++ tests/unit/main/platform/linux/x11-keymap.test.ts | 6 ++++++ 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/main/platform/linux/x11-keymap.ts b/src/main/platform/linux/x11-keymap.ts index 24aaa63d..59822e7a 100644 --- a/src/main/platform/linux/x11-keymap.ts +++ b/src/main/platform/linux/x11-keymap.ts @@ -65,7 +65,10 @@ const isFunctionKey = (key: string): boolean => /^F([1-9]|1[0-9]|2[0-4])$/.test( export const x11KeysymName = (key: string): string | undefined => { const upper = key.toUpperCase(); if (key.length === 1) { - return /[A-Z]/.test(upper) ? upper.toLowerCase() : key; + // XStringToKeysym takes names ('comma'), not characters; `U` names any character. + return /[A-Z0-9]/.test(upper) + ? upper.toLowerCase() + : `U${key.toLowerCase().charCodeAt(0).toString(16)}`; } if (isFunctionKey(upper)) { return upper; diff --git a/tests/integration/linux/x11-global-shortcut.test.ts b/tests/integration/linux/x11-global-shortcut.test.ts index 86563bef..fc38dd32 100644 --- a/tests/integration/linux/x11-global-shortcut.test.ts +++ b/tests/integration/linux/x11-global-shortcut.test.ts @@ -79,6 +79,10 @@ describe.skipIf(!isLinux)('x11-global-shortcut (Linux)', () => { expect(linuxGlobalShortcutBackend.register('CmdOrCtrl+Shift+K', () => undefined)).toBe(true); }); + test('register() grabs a punctuation key', () => { + expect(linuxGlobalShortcutBackend.register('CmdOrCtrl+,', () => undefined)).toBe(true); + }); + test('register() returns false for an unmappable key', () => { expect(linuxGlobalShortcutBackend.register('CmdOrCtrl+Bogus', () => undefined)).toBe(false); }); diff --git a/tests/unit/main/platform/linux/x11-keymap.test.ts b/tests/unit/main/platform/linux/x11-keymap.test.ts index ed0bc782..72e97939 100644 --- a/tests/unit/main/platform/linux/x11-keymap.test.ts +++ b/tests/unit/main/platform/linux/x11-keymap.test.ts @@ -26,6 +26,12 @@ describe('x11KeysymName', () => { expect(x11KeysymName('1')).toBe('1'); }); + test('maps punctuation to the Unicode keysym form XStringToKeysym accepts', () => { + expect(x11KeysymName(',')).toBe('U2c'); + expect(x11KeysymName('/')).toBe('U2f'); + expect(x11KeysymName('`')).toBe('U60'); + }); + test('maps function keys to their X names', () => { expect(x11KeysymName('F5')).toBe('F5'); }); From 39e6ca03f12a190a6c6cfcabf9904ed30608defc Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:13:36 -0700 Subject: [PATCH 172/586] fix: add Electron's default application menu for apps that set none --- src/main/api/menu.ts | 29 +++++++++++++++++++++++++++++ tests/unit/main/api/menu.test.ts | 17 +++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/src/main/api/menu.ts b/src/main/api/menu.ts index 44fd764b..8d09a463 100644 --- a/src/main/api/menu.ts +++ b/src/main/api/menu.ts @@ -492,6 +492,7 @@ export class Menu { /** `null` removes the application menu everywhere, including bars already installed. */ static setApplicationMenu(menu: Menu | null): void { + applicationMenuSet = true; applicationMenu = menu; // null must reach the native side too: it clears the menu bar (Electron // semantics on Windows/Linux; on macOS it empties the main menu). @@ -530,8 +531,36 @@ export class Menu { } let applicationMenu: Menu | null = null; +let applicationMenuSet = false; + +/** Electron's default menu, minus the roles Bunmaska lacks; skipped once the app set one, even `null`. */ +export const installDefaultApplicationMenu = (appName: string): void => { + if (applicationMenuSet) { + return; + } + Menu.setApplicationMenu( + Menu.buildFromTemplate([ + { + label: appName, + submenu: [ + { role: 'about', label: `About ${appName}` }, + { type: 'separator' }, + { role: 'hide', label: `Hide ${appName}` }, + { role: 'hideOthers' }, + { role: 'unhide' }, + { type: 'separator' }, + { role: 'quit', label: `Quit ${appName}` }, + ], + }, + { label: 'File', submenu: [{ role: 'close' }] }, + { role: 'editMenu' }, + { role: 'windowMenu' }, + ]), + ); +}; /** @internal */ export const resetApplicationMenuForTesting = (): void => { applicationMenu = null; + applicationMenuSet = false; }; diff --git a/tests/unit/main/api/menu.test.ts b/tests/unit/main/api/menu.test.ts index 317887dd..2388ea2c 100644 --- a/tests/unit/main/api/menu.test.ts +++ b/tests/unit/main/api/menu.test.ts @@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; import type { NativeMenuItemSpec } from '../../../../src/main/platform/macos/cocoa-menu'; import type { BrowserWindow } from '../../../../src/main/api/browser-window'; import { + installDefaultApplicationMenu, Menu, MenuItem, type MenuRealizer, @@ -392,6 +393,22 @@ describe('Menu realization spec', () => { }); }); +describe('installDefaultApplicationMenu', () => { + test('installs App, File, Edit and Window menus when the app set none', () => { + installDefaultApplicationMenu('Notes'); + expect(realized?.map((spec) => spec.label)).toEqual(['Notes', 'File', 'Edit', 'Window']); + expect(realized?.[0]?.submenu?.at(-1)).toMatchObject({ label: 'Quit Notes', role: 'quit' }); + expect(Menu.getApplicationMenu()).not.toBeNull(); + }); + + test('leaves an app-set menu, including null, alone', () => { + Menu.setApplicationMenu(null); + installDefaultApplicationMenu('Notes'); + expect(installed).toBe(1); + expect(Menu.getApplicationMenu()).toBeNull(); + }); +}); + describe('Menu.getApplicationMenu', () => { test('returns null before any menu is set', () => { expect(Menu.getApplicationMenu()).toBeNull(); From 4fa5dee87bd1485c989c697dd157c20c4de94702 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:14:08 -0700 Subject: [PATCH 173/586] fix: relaunch the old app when the update helper fails --- src/main/api/update-installer.ts | 32 +++-- tests/unit/main/api/update-installer.test.ts | 127 +++++++++++++------ 2 files changed, 105 insertions(+), 54 deletions(-) diff --git a/src/main/api/update-installer.ts b/src/main/api/update-installer.ts index f8c6ece4..8eb3019c 100644 --- a/src/main/api/update-installer.ts +++ b/src/main/api/update-installer.ts @@ -86,15 +86,17 @@ export const buildShInstallScript = (spec: ShInstallSpec): string => { return [ '#!/bin/sh', '# bunmaska auto-update helper: waits for the app to exit, swaps, relaunches.', + // Every failure path relaunches the old app; a failed update must not leave the user with none. + `fail() { rm -rf ${staging}; ${relaunch} & exit 1; }`, `while kill -0 ${spec.pid} 2>/dev/null; do sleep 0.5; done`, `rm -rf ${staging} ${old}`, - `mkdir -p ${staging} || exit 1`, + `mkdir -p ${staging} || fail`, // A failed extract only dirties the staging dir; the installed app is untouched. - `tar -xf ${tar} -C ${staging} || { rm -rf ${staging}; exit 1; }`, - `[ -d ${fresh} ] || { rm -rf ${staging}; exit 1; }`, + `tar -xf ${tar} -C ${staging} || fail`, + `[ -d ${fresh} ] || fail`, // The swap is two renames; a failed second rename rolls the first back. - `mv ${root} ${old} || exit 1`, - `mv ${fresh} ${root} || { mv ${old} ${root}; exit 1; }`, + `mv ${root} ${old} || fail`, + `mv ${fresh} ${root} || { mv ${old} ${root}; fail; }`, `rm -rf ${old} ${staging}`, `rm -f ${tar}`, `${relaunch} &`, @@ -115,6 +117,7 @@ export type CmdInstallSpec = { export const buildCmdInstallScript = (spec: CmdInstallSpec): string => { const staging = `${spec.installRoot}.update-staging`; const old = `${spec.installRoot}.update-old`; + const start = `start "" "${spec.installRoot}\\${spec.exeName}"`; return [ '@echo off', 'rem bunmaska auto-update helper: waits for the app to exit, swaps, relaunches.', @@ -123,19 +126,24 @@ export const buildCmdInstallScript = (spec: CmdInstallSpec): string => { 'if not errorlevel 1 (timeout /t 1 /nobreak >nul & goto wait)', `if exist "${old}" rmdir /s /q "${old}"`, `if exist "${staging}" rmdir /s /q "${staging}"`, - `mkdir "${staging}" || exit /b 1`, + `mkdir "${staging}" || goto fail`, 'rem extract from cwd, not tar -C: Windows bsdtar mangles backslash -C paths', - `cd /d "${staging}" || exit /b 1`, - `tar -xf "${spec.tarPath}" || exit /b 1`, + `cd /d "${staging}" || goto fail`, + `tar -xf "${spec.tarPath}" || goto fail`, 'cd /d "%TEMP%"', - `if not exist "${staging}\\${spec.bundleDirName}" exit /b 1`, - `move "${spec.installRoot}" "${old}" || exit /b 1`, - `move "${staging}\\${spec.bundleDirName}" "${spec.installRoot}" || (move "${old}" "${spec.installRoot}" & exit /b 1)`, + `if not exist "${staging}\\${spec.bundleDirName}" goto fail`, + `move "${spec.installRoot}" "${old}" || goto fail`, + `move "${staging}\\${spec.bundleDirName}" "${spec.installRoot}" || (move "${old}" "${spec.installRoot}" & goto fail)`, `rmdir /s /q "${old}"`, `rmdir /s /q "${staging}"`, `del /q "${spec.tarPath}"`, - `start "" "${spec.installRoot}\\${spec.exeName}"`, + start, '(goto) 2>nul & del "%~f0"', + ':fail', + 'cd /d "%TEMP%"', + `if exist "${staging}" rmdir /s /q "${staging}"`, + start, + 'exit /b 1', '', ].join('\r\n'); }; diff --git a/tests/unit/main/api/update-installer.test.ts b/tests/unit/main/api/update-installer.test.ts index 8c460c81..13f19b52 100644 --- a/tests/unit/main/api/update-installer.test.ts +++ b/tests/unit/main/api/update-installer.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from 'bun:test'; -import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import type { UpdateManifest } from '../../../../src/common/manifest'; @@ -94,34 +94,78 @@ describe('shQuote', () => { }); }); +/** Polls for a file a backgrounded helper writes; throws after 3s. */ +const waitForFile = async (path: string): Promise => { + const deadline = Date.now() + 3000; + while (!existsSync(path)) { + if (Date.now() > deadline) { + throw new Error(`${path} never appeared`); + } + await Bun.sleep(20); + } +}; + +/** Runs the real sh helper against a temp install root holding `v` = "old". */ +const runShHelper = async ( + tarContents: 'new-bundle' | 'missing-tar', +): Promise<{ root: string; relaunched: string; cleanup: () => void }> => { + const dir = mkdtempSync(join(tmpdir(), 'bunmaska-helper-')); + const root = join(dir, 'Demo'); + mkdirSync(root); + writeFileSync(join(root, 'v'), 'old'); + const tarPath = join(dir, 'up.tar'); + if (tarContents === 'new-bundle') { + mkdirSync(join(dir, 'src', 'Demo'), { recursive: true }); + writeFileSync(join(dir, 'src', 'Demo', 'v'), 'new'); + Bun.spawnSync(['tar', '-cf', tarPath, '-C', join(dir, 'src'), 'Demo']); + } + const exited = Bun.spawn(['true']); + await exited.exited; + const relaunched = join(dir, 'relaunched'); + const scriptPath = join(dir, 'install.sh'); + writeFileSync( + scriptPath, + buildShInstallScript({ + pid: exited.pid, + tarPath, + installRoot: root, + bundleDirName: 'Demo', + relaunchArgv: ['touch', relaunched], + }), + ); + Bun.spawnSync(['/bin/sh', scriptPath]); + return { root, relaunched, cleanup: () => rmSync(dir, { recursive: true, force: true }) }; +}; + describe('buildShInstallScript', () => { - test('waits for the pid, extracts to a temp sibling, rename-swaps, relaunches, self-deletes', () => { - const script = buildShInstallScript({ - pid: 4242, - tarPath: '/tmp/bunmaska-update-abc123.tar', - installRoot: '/Applications/My App.app', - bundleDirName: 'My App.app', - relaunchArgv: ['open', '/Applications/My App.app'], - }); - expect(script).toBe( - [ - '#!/bin/sh', - '# bunmaska auto-update helper: waits for the app to exit, swaps, relaunches.', - 'while kill -0 4242 2>/dev/null; do sleep 0.5; done', - "rm -rf '/Applications/My App.app.update-staging' '/Applications/My App.app.update-old'", - "mkdir -p '/Applications/My App.app.update-staging' || exit 1", - "tar -xf '/tmp/bunmaska-update-abc123.tar' -C '/Applications/My App.app.update-staging' || { rm -rf '/Applications/My App.app.update-staging'; exit 1; }", - "[ -d '/Applications/My App.app.update-staging/My App.app' ] || { rm -rf '/Applications/My App.app.update-staging'; exit 1; }", - "mv '/Applications/My App.app' '/Applications/My App.app.update-old' || exit 1", - "mv '/Applications/My App.app.update-staging/My App.app' '/Applications/My App.app' || { mv '/Applications/My App.app.update-old' '/Applications/My App.app'; exit 1; }", - "rm -rf '/Applications/My App.app.update-old' '/Applications/My App.app.update-staging'", - "rm -f '/tmp/bunmaska-update-abc123.tar'", - "'open' '/Applications/My App.app' &", - 'rm -f -- "$0"', - '', - ].join('\n'), - ); - }); + test.skipIf(process.platform === 'win32')( + 'swaps the extracted bundle into place and relaunches it', + async () => { + const run = await runShHelper('new-bundle'); + try { + await waitForFile(run.relaunched); + expect(readFileSync(join(run.root, 'v'), 'utf8')).toBe('new'); + expect(existsSync(`${run.root}.update-old`)).toBe(false); + expect(existsSync(`${run.root}.update-staging`)).toBe(false); + } finally { + run.cleanup(); + } + }, + ); + + test.skipIf(process.platform === 'win32')( + 'a failed extract leaves the installed app untouched and still relaunches it', + async () => { + const run = await runShHelper('missing-tar'); + try { + await waitForFile(run.relaunched); + expect(readFileSync(join(run.root, 'v'), 'utf8')).toBe('old'); + expect(existsSync(`${run.root}.update-staging`)).toBe(false); + } finally { + run.cleanup(); + } + }, + ); test('Linux relaunch execs the AppDir binary instead of open', () => { const script = buildShInstallScript({ @@ -137,7 +181,7 @@ describe('buildShInstallScript', () => { }); describe('buildCmdInstallScript', () => { - test('generates the wait-swap-start cmd script (live Windows path untested on this host)', () => { + test('generates the wait-swap-start cmd script whose every failure relaunches the app', () => { const script = buildCmdInstallScript({ pid: 7, tarPath: 'C:\\tmp\\up.tar', @@ -154,19 +198,24 @@ describe('buildCmdInstallScript', () => { 'if not errorlevel 1 (timeout /t 1 /nobreak >nul & goto wait)', 'if exist "C:\\Apps\\Demo.update-old" rmdir /s /q "C:\\Apps\\Demo.update-old"', 'if exist "C:\\Apps\\Demo.update-staging" rmdir /s /q "C:\\Apps\\Demo.update-staging"', - 'mkdir "C:\\Apps\\Demo.update-staging" || exit /b 1', + 'mkdir "C:\\Apps\\Demo.update-staging" || goto fail', 'rem extract from cwd, not tar -C: Windows bsdtar mangles backslash -C paths', - 'cd /d "C:\\Apps\\Demo.update-staging" || exit /b 1', - 'tar -xf "C:\\tmp\\up.tar" || exit /b 1', + 'cd /d "C:\\Apps\\Demo.update-staging" || goto fail', + 'tar -xf "C:\\tmp\\up.tar" || goto fail', 'cd /d "%TEMP%"', - 'if not exist "C:\\Apps\\Demo.update-staging\\Demo" exit /b 1', - 'move "C:\\Apps\\Demo" "C:\\Apps\\Demo.update-old" || exit /b 1', - 'move "C:\\Apps\\Demo.update-staging\\Demo" "C:\\Apps\\Demo" || (move "C:\\Apps\\Demo.update-old" "C:\\Apps\\Demo" & exit /b 1)', + 'if not exist "C:\\Apps\\Demo.update-staging\\Demo" goto fail', + 'move "C:\\Apps\\Demo" "C:\\Apps\\Demo.update-old" || goto fail', + 'move "C:\\Apps\\Demo.update-staging\\Demo" "C:\\Apps\\Demo" || (move "C:\\Apps\\Demo.update-old" "C:\\Apps\\Demo" & goto fail)', 'rmdir /s /q "C:\\Apps\\Demo.update-old"', 'rmdir /s /q "C:\\Apps\\Demo.update-staging"', 'del /q "C:\\tmp\\up.tar"', 'start "" "C:\\Apps\\Demo\\Demo.exe"', '(goto) 2>nul & del "%~f0"', + ':fail', + 'cd /d "%TEMP%"', + 'if exist "C:\\Apps\\Demo.update-staging" rmdir /s /q "C:\\Apps\\Demo.update-staging"', + 'start "" "C:\\Apps\\Demo\\Demo.exe"', + 'exit /b 1', '', ].join('\r\n'), ); @@ -250,13 +299,7 @@ describe('spawnDetachedScript', () => { '-c', `ps -o pgid= -p $$ > ${shQuote(`${out}.tmp`)}; mv ${shQuote(`${out}.tmp`)} ${shQuote(out)}`, ]); - const deadline = Date.now() + 5000; - while (!existsSync(out)) { - if (Date.now() > deadline) { - throw new Error('the detached helper never ran'); - } - await Bun.sleep(20); - } + await waitForFile(out); expect(readFileSync(out, 'utf8').trim()).not.toBe(pgidOf(process.pid)); } finally { rmSync(dir, { recursive: true, force: true }); From e42493f993158dae51b9940780dcf9a731a4b27e Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:14:16 -0700 Subject: [PATCH 174/586] refactor: drop the root key selection and per-tick X event buffer --- .../platform/linux/x11-global-shortcut.ts | 105 +++++++----------- src/main/platform/linux/x11-keymap.ts | 3 - 2 files changed, 39 insertions(+), 69 deletions(-) diff --git a/src/main/platform/linux/x11-global-shortcut.ts b/src/main/platform/linux/x11-global-shortcut.ts index 0302a786..13a89180 100644 --- a/src/main/platform/linux/x11-global-shortcut.ts +++ b/src/main/platform/linux/x11-global-shortcut.ts @@ -5,7 +5,6 @@ import { cstr } from '../cstr'; import { loadX11FFI } from './x11-ffi'; import { KEY_PRESS, - KEY_PRESS_MASK, x11KeysymName, x11ModifierMask, XEVENT_BUFFER_SIZE, @@ -38,16 +37,15 @@ import { * on. That refinement is deferred. */ -type Registration = { - readonly keycode: number; - readonly modifiers: number; - readonly callback: () => void; -}; +type Grab = { readonly keycode: number; readonly modifiers: number }; +type Registration = Grab & { readonly callback: () => void }; let display: Pointer | null | undefined; let displayFailed = false; let rootWindow = 0n; const registrations: Registration[] = []; +const eventBuffer = new Uint8Array(XEVENT_BUFFER_SIZE); +const eventView = new DataView(eventBuffer.buffer); let errorTrap: JSCallback | undefined; /** @@ -94,7 +92,6 @@ const ensureDisplay = (): Pointer | null => { display = dpy; installErrorTrap(x11); rootWindow = x11.symbols.XDefaultRootWindow(dpy); - x11.symbols.XSelectInput(dpy, rootWindow, KEY_PRESS_MASK); return dpy; } catch { displayFailed = true; @@ -102,90 +99,68 @@ const ensureDisplay = (): Pointer | null => { } }; -const register = (accelerator: string, callback: () => void): boolean => { +/** The keycode+modifier combo `accelerator` grabs, or undefined when X cannot express it. */ +const resolveGrab = (accelerator: string, dpy: Pointer): Grab | undefined => { const parsed = parseAccelerator(accelerator, 'linux'); - if (parsed === undefined) { - return false; - } - const keysymName = x11KeysymName(parsed.key); - if (keysymName === undefined) { - return false; - } - const dpy = ensureDisplay(); - if (dpy === null) { - return false; + const keysymName = parsed === undefined ? undefined : x11KeysymName(parsed.key); + if (parsed === undefined || keysymName === undefined) { + return undefined; } const x11 = loadX11FFI(); const keysym = x11.symbols.XStringToKeysym(cstr(keysymName)); - if (keysym === 0n) { - return false; + const keycode = keysym === 0n ? 0 : x11.symbols.XKeysymToKeycode(dpy, keysym); + return keycode === 0 ? undefined : { keycode, modifiers: x11ModifierMask(parsed) }; +}; + +const ungrab = (dpy: Pointer, grab: Grab): void => { + const x11 = loadX11FFI(); + for (const lockBits of GRAB_VARIANTS) { + x11.symbols.XUngrabKey(dpy, grab.keycode, grab.modifiers | lockBits, rootWindow); } - const keycode = x11.symbols.XKeysymToKeycode(dpy, keysym); - if (keycode === 0) { +}; + +const register = (accelerator: string, callback: () => void): boolean => { + const dpy = ensureDisplay(); + const grab = dpy === null ? undefined : resolveGrab(accelerator, dpy); + if (dpy === null || grab === undefined) { return false; } - const modifiers = x11ModifierMask(parsed); + const x11 = loadX11FFI(); // owner_events FALSE(0), pointer_mode/keyboard_mode GrabModeAsync(1). for (const lockBits of GRAB_VARIANTS) { - x11.symbols.XGrabKey(dpy, keycode, modifiers | lockBits, rootWindow, 0, 1, 1); + x11.symbols.XGrabKey(dpy, grab.keycode, grab.modifiers | lockBits, rootWindow, 0, 1, 1); } // ponytail: a key another client holds still returns true; XSync + a trap flag reports it once x11-ffi declares XSync. x11.symbols.XFlush(dpy); - registrations.push({ keycode, modifiers, callback }); + registrations.push({ ...grab, callback }); return true; }; -const matches = (reg: Registration, accelerator: string): boolean => { - const parsed = parseAccelerator(accelerator, 'linux'); - if (parsed === undefined) { - return false; - } - const dpy = display; - if (dpy === null || dpy === undefined) { - return false; - } - const keysymName = x11KeysymName(parsed.key); - if (keysymName === undefined) { - return false; - } - const x11 = loadX11FFI(); - const keysym = x11.symbols.XStringToKeysym(cstr(keysymName)); - const keycode = x11.symbols.XKeysymToKeycode(dpy, keysym); - return reg.keycode === keycode && reg.modifiers === x11ModifierMask(parsed); -}; - const unregister = (accelerator: string): void => { const dpy = display; - if (dpy === null || dpy === undefined) { + const grab = dpy === null || dpy === undefined ? undefined : resolveGrab(accelerator, dpy); + if (dpy === null || dpy === undefined || grab === undefined) { return; } - const x11 = loadX11FFI(); for (let i = registrations.length - 1; i >= 0; i -= 1) { const reg = registrations[i]; - if (reg !== undefined && matches(reg, accelerator)) { - for (const lockBits of GRAB_VARIANTS) { - x11.symbols.XUngrabKey(dpy, reg.keycode, reg.modifiers | lockBits, rootWindow); - } + if (reg !== undefined && reg.keycode === grab.keycode && reg.modifiers === grab.modifiers) { + ungrab(dpy, reg); registrations.splice(i, 1); } } - x11.symbols.XFlush(dpy); + loadX11FFI().symbols.XFlush(dpy); }; const unregisterAll = (): void => { const dpy = display; - if (dpy === null || dpy === undefined) { - registrations.length = 0; - return; - } - const x11 = loadX11FFI(); - for (const reg of registrations) { - for (const lockBits of GRAB_VARIANTS) { - x11.symbols.XUngrabKey(dpy, reg.keycode, reg.modifiers | lockBits, rootWindow); + if (dpy !== null && dpy !== undefined) { + for (const reg of registrations) { + ungrab(dpy, reg); } + loadX11FFI().symbols.XFlush(dpy); } registrations.length = 0; - x11.symbols.XFlush(dpy); }; /** @@ -199,17 +174,15 @@ export const pollX11ShortcutsOnce = (): void => { return; } const x11 = loadX11FFI(); - const buffer = new Uint8Array(XEVENT_BUFFER_SIZE); - const view = new DataView(buffer.buffer); let budget = 64; while (budget > 0 && x11.symbols.XPending(dpy) > 0) { budget -= 1; - x11.symbols.XNextEvent(dpy, ptr(buffer)); - if (view.getInt32(XEVENT_TYPE_OFFSET, true) !== KEY_PRESS) { + x11.symbols.XNextEvent(dpy, ptr(eventBuffer)); + if (eventView.getInt32(XEVENT_TYPE_OFFSET, true) !== KEY_PRESS) { continue; } - const keycode = view.getUint32(XKEY_KEYCODE_OFFSET, true); - const state = view.getUint32(XKEY_STATE_OFFSET, true); + const keycode = eventView.getUint32(XKEY_KEYCODE_OFFSET, true); + const state = eventView.getUint32(XKEY_STATE_OFFSET, true); for (const reg of registrations) { // Keycode alone once dispatched here, so Ctrl+K fired Ctrl+Shift+K too. if (reg.keycode === keycode && x11StateMatches(state, reg.modifiers)) { diff --git a/src/main/platform/linux/x11-keymap.ts b/src/main/platform/linux/x11-keymap.ts index 59822e7a..e891f8ee 100644 --- a/src/main/platform/linux/x11-keymap.ts +++ b/src/main/platform/linux/x11-keymap.ts @@ -33,9 +33,6 @@ const REGISTRABLE_MODIFIERS = SHIFT_MASK | CONTROL_MASK | MOD1_MASK | MOD4_MASK; export const x11StateMatches = (state: number, modifiers: number): boolean => (state & REGISTRABLE_MODIFIERS) === modifiers; -/** `KeyPressMask` for `XSelectInput` (`X.h`). */ -export const KEY_PRESS_MASK = 1 << 0; // 1 - /** Named keys → the X keysym string `XStringToKeysym` understands. */ const KEYSYM_NAMES: ReadonlyMap = new Map([ ['SPACE', 'space'], From f7022bb7ad12463a5ba71fb42336167c2736050c Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:14:23 -0700 Subject: [PATCH 175/586] fix: recycle Windows menu command ids and free the app menu's popup tree --- src/main/platform/windows/windows-menu.ts | 148 ++++++++++-------- tests/integration/windows/menu.test.ts | 9 +- .../platform/windows/windows-menu.test.ts | 104 ++++++++++-- 3 files changed, 172 insertions(+), 89 deletions(-) diff --git a/src/main/platform/windows/windows-menu.ts b/src/main/platform/windows/windows-menu.ts index 23d77768..3ec9fb4e 100644 --- a/src/main/platform/windows/windows-menu.ts +++ b/src/main/platform/windows/windows-menu.ts @@ -1,4 +1,5 @@ import { ptr } from 'bun:ffi'; +import { FFIError } from '../../../common/errors'; import type { MenuRealizer } from '../../api/menu'; import type { NativeMenuItemSpec } from '../macos/cocoa-menu'; import { wstr } from './win32'; @@ -18,6 +19,9 @@ const MF_POPUP = 0x10; const MF_CHECKED = 0x8; const MF_GRAYED = 0x1; +/** `WM_COMMAND` carries the id in LOWORD(wParam), so ids live in 1..0xFFFF. */ +const MAX_COMMAND_ID = 0xffff; + /** The AppendMenuW flags for a normal/checkbox/radio item. Pure. */ export const menuItemFlags = (enabled: boolean, checked: boolean): number => { let flags = MF_STRING; @@ -30,6 +34,12 @@ export const menuItemFlags = (enabled: boolean, checked: boolean): number => { return flags; }; +/** The user32 calls the realizer makes. */ +type MenuApi = Pick< + ReturnType['symbols'], + 'CreateMenu' | 'CreatePopupMenu' | 'AppendMenuW' | 'DestroyMenu' +>; + /** A window that can carry the application menu bar (its native `setMenuBar`). */ export type AppMenuWindow = { /** Attach an HMENU bar, or remove it with `null`. The window owns the HMENU. */ @@ -46,113 +56,113 @@ export type WindowsMenuRealizer = MenuRealizer & { unregisterAppMenuWindow(window: AppMenuWindow): void; }; -/** - * Build a Windows menu realizer. A factory (not just a singleton) so tests get an - * isolated command-id space; production uses {@link windowsMenuRealizer}. - */ -export const createWindowsMenuRealizer = (): WindowsMenuRealizer => { - const callbackByCommandId = new Map void>(); - let nextCommandId = 1; - // Windows mirroring the application menu, the current app-menu spec, and the - // last realize() result (menu.ts calls realize() then setApplicationMenu(handle) - // back-to-back, so a single slot recovers the spec from the handle leak-free). - const appMenuWindows = new Set(); +export const createWindowsMenuRealizer = ( + user32: () => MenuApi = () => loadUser32().symbols, +): WindowsMenuRealizer => { + // Every id on a menu that may still be shown, with its JS click (undefined for a role). + const commands = new Map void) | undefined>(); + let lastCommandId = 0; + const barIds = new Map(); let appMenuItems: ReadonlyArray | null = null; - let lastRealized: { handle: bigint; items: ReadonlyArray } | undefined; + // menu.ts consumes each realize() result before the next one (a popup is destroyed + // once TrackPopupMenu returns; setApplicationMenu reads it at once), so one slot + // recovers the spec from the handle and frees the previous result's ids. + let lastRealized: + | { handle: bigint; items: ReadonlyArray; ids: number[] } + | undefined; - const buildMenu = (items: ReadonlyArray): bigint => { - const user32 = loadUser32().symbols; - const hmenu = user32.CreatePopupMenu(); - for (const item of items) { - if (item.type === 'separator') { - user32.AppendMenuW(hmenu, MF_SEPARATOR, 0n, null); - continue; + const allocateId = (onClick: (() => void) | undefined): number => { + for (let tries = 0; tries < MAX_COMMAND_ID; tries += 1) { + lastCommandId = (lastCommandId % MAX_COMMAND_ID) + 1; + if (!commands.has(lastCommandId)) { + commands.set(lastCommandId, onClick); + return lastCommandId; } - const labelBuffer = wstr(item.label); // copied by AppendMenuW; alive across the call - if (item.type === 'submenu' && item.submenu !== undefined) { - const submenu = buildMenu(item.submenu); - const flags = MF_POPUP | MF_STRING | (item.enabled ? 0 : MF_GRAYED); - user32.AppendMenuW(hmenu, flags, submenu, ptr(labelBuffer)); - continue; - } - const commandId = nextCommandId; - nextCommandId += 1; - // A role's behavior is native (no JS click); a plain item fires its onClick. - if (item.role === undefined && item.onClick !== undefined) { - callbackByCommandId.set(commandId, item.onClick); - } - user32.AppendMenuW( - hmenu, - menuItemFlags(item.enabled, item.checked ?? false), - BigInt(commandId), - ptr(labelBuffer), - ); } - return hmenu; + throw new FFIError('menu: all 65535 command ids are in use'); + }; + + const release = (ids: ReadonlyArray): void => { + for (const id of ids) { + commands.delete(id); + } }; - /** Build a menu BAR (CreateMenu container) from top-level items. Each is a popup - * (submenu) or a clickable bar item; separators are skipped (meaningless in a bar). */ - const buildMenuBar = (items: ReadonlyArray): bigint => { - const user32 = loadUser32().symbols; - const bar = user32.CreateMenu(); + /** Build a menu bar (`CreateMenu`, no separators) or a popup; `ids` collects its command ids. */ + const build = (items: ReadonlyArray, bar: boolean, ids: number[]): bigint => { + const api = user32(); + const hmenu = bar ? api.CreateMenu() : api.CreatePopupMenu(); for (const item of items) { if (item.type === 'separator') { + if (!bar) { + api.AppendMenuW(hmenu, MF_SEPARATOR, 0n, null); + } continue; } - const labelBuffer = wstr(item.label); // copied by AppendMenuW; alive across the call + const labelBuffer = wstr(item.label); // AppendMenuW copies the label if (item.type === 'submenu' && item.submenu !== undefined) { - const submenu = buildMenu(item.submenu); const flags = MF_POPUP | MF_STRING | (item.enabled ? 0 : MF_GRAYED); - user32.AppendMenuW(bar, flags, submenu, ptr(labelBuffer)); + api.AppendMenuW(hmenu, flags, build(item.submenu, false, ids), ptr(labelBuffer)); continue; } - const commandId = nextCommandId; - nextCommandId += 1; - if (item.role === undefined && item.onClick !== undefined) { - callbackByCommandId.set(commandId, item.onClick); - } - user32.AppendMenuW( - bar, + // ponytail: roles are inert on Windows (no dispatch or accelerator table). + const id = allocateId(item.role === undefined ? item.onClick : undefined); + ids.push(id); + api.AppendMenuW( + hmenu, menuItemFlags(item.enabled, item.checked ?? false), - BigInt(commandId), + BigInt(id), ptr(labelBuffer), ); } - return bar; + return hmenu; + }; + + const installBar = (window: AppMenuWindow): void => { + release(barIds.get(window) ?? []); + const ids: number[] = []; + barIds.set(window, ids); + window.setMenuBar(appMenuItems === null ? null : build(appMenuItems, true, ids)); }; return { realize(items: ReadonlyArray): bigint { - const handle = buildMenu(items); - lastRealized = { handle, items }; + release(lastRealized?.ids ?? []); + const ids: number[] = []; + const handle = build(items, false, ids); + lastRealized = { handle, items, ids }; return handle; }, setApplicationMenu(menu: bigint | null): void { - // Recover the spec from the handle realize() just produced, so a FRESH bar - // (one HMENU per window) can be built for every window. null clears. - const items = - menu === null ? null : lastRealized?.handle === menu ? lastRealized.items : appMenuItems; - appMenuItems = items ?? null; - for (const window of appMenuWindows) { - window.setMenuBar(items !== null && items !== undefined ? buildMenuBar(items) : null); + if (menu === null) { + appMenuItems = null; + } else if (lastRealized?.handle === menu) { + // Each window gets its own bar, so the realized popup tree is only a key to its items. + appMenuItems = lastRealized.items; + release(lastRealized.ids); + user32().DestroyMenu(menu); + lastRealized = undefined; + } + for (const window of barIds.keys()) { + installBar(window); } }, registerAppMenuWindow(window: AppMenuWindow): void { - appMenuWindows.add(window); + barIds.set(window, []); if (appMenuItems !== null) { - window.setMenuBar(buildMenuBar(appMenuItems)); + installBar(window); } }, unregisterAppMenuWindow(window: AppMenuWindow): void { - appMenuWindows.delete(window); + release(barIds.get(window) ?? []); + barIds.delete(window); }, dispatchMenuCommand(commandId: number): void { - callbackByCommandId.get(commandId)?.(); + commands.get(commandId)?.(); }, }; }; diff --git a/tests/integration/windows/menu.test.ts b/tests/integration/windows/menu.test.ts index 711a1c00..61a1035b 100644 --- a/tests/integration/windows/menu.test.ts +++ b/tests/integration/windows/menu.test.ts @@ -50,10 +50,9 @@ if (currentPlatform() === 'windows') { loadUser32().symbols.DestroyMenu(handle); }); - test('a role item is native (no JS click stored), so its id dispatches to nothing', () => { + test('a role item stores no JS click, so its id dispatches to nothing', () => { const realizer = createWindowsMenuRealizer(); let clicks = 0; - // A role item with a stray onClick must NOT be wired (role behavior is native). const handle = realizer.realize([ item({ label: 'Copy', role: 'copy', onClick: () => clicks++ }), ]); @@ -62,11 +61,11 @@ if (currentPlatform() === 'windows') { loadUser32().symbols.DestroyMenu(handle); }); - test('setApplicationMenu is a no-op (per-window menu bar is deferred)', () => { + test('setApplicationMenu destroys the realized popup tree it read the items from', () => { const realizer = createWindowsMenuRealizer(); const handle = realizer.realize([item({ label: 'File' })]); - expect(() => realizer.setApplicationMenu(handle)).not.toThrow(); - loadUser32().symbols.DestroyMenu(handle); + realizer.setApplicationMenu(handle); + expect(loadUser32().symbols.GetMenuItemCount(handle)).toBe(-1); }); }); } diff --git a/tests/unit/main/platform/windows/windows-menu.test.ts b/tests/unit/main/platform/windows/windows-menu.test.ts index 8e54a1b3..85e6ee60 100644 --- a/tests/unit/main/platform/windows/windows-menu.test.ts +++ b/tests/unit/main/platform/windows/windows-menu.test.ts @@ -1,30 +1,104 @@ import { describe, expect, test } from 'bun:test'; -import { menuItemFlags } from '../../../../../src/main/platform/windows/windows-menu'; - -/** - * Pure AppendMenuW flag mapping for the Windows menu realizer. A disabled item is - * `MF_GRAYED`; a checked checkbox/radio is `MF_CHECKED`; both compose. (The HMENU - * build + command dispatch are integration-tested against the real Win32 menu; - * the popup itself is modal `TrackPopupMenu`, untested like macOS menu tracking.) - */ +import type { NativeMenuItemSpec } from '../../../../../src/main/platform/macos/cocoa-menu'; +import { + type AppMenuWindow, + createWindowsMenuRealizer, + menuItemFlags, +} from '../../../../../src/main/platform/windows/windows-menu'; + const MF_STRING = 0x0; const MF_GRAYED = 0x1; const MF_CHECKED = 0x8; +const MF_POPUP = 0x10; +const MF_SEPARATOR = 0x800; describe('menuItemFlags', () => { - test('an enabled, unchecked item is a plain string item', () => { + test('enabled/checked compose into MF_GRAYED and MF_CHECKED', () => { expect(menuItemFlags(true, false)).toBe(MF_STRING); + expect(menuItemFlags(false, false)).toBe(MF_GRAYED); + expect(menuItemFlags(true, true)).toBe(MF_CHECKED); + expect(menuItemFlags(false, true)).toBe(MF_GRAYED | MF_CHECKED); }); +}); - test('a disabled item is grayed', () => { - expect(menuItemFlags(false, false)).toBe(MF_GRAYED); +/** A user32 stand-in recording command ids appended and menus destroyed. */ +const fakeUser32 = () => { + let nextHandle = 100n; + const commandIds: number[] = []; + const destroyed: unknown[] = []; + const api = { + CreateMenu: () => nextHandle++, + CreatePopupMenu: () => nextHandle++, + AppendMenuW: (_menu: unknown, flags: unknown, id: unknown) => { + if ((Number(flags) & (MF_POPUP | MF_SEPARATOR)) === 0) { + commandIds.push(Number(id)); + } + return 1; + }, + DestroyMenu: (menu: unknown) => { + destroyed.push(menu); + return 1; + }, + }; + return { api, commandIds, destroyed }; +}; + +const item = (label: string, onClick?: () => void): NativeMenuItemSpec => ({ + label, + type: 'normal', + enabled: true, + keyEquivalent: '', + ...(onClick !== undefined ? { onClick } : {}), +}); + +const window = (): AppMenuWindow => ({ setMenuBar: () => undefined }); + +describe('createWindowsMenuRealizer command ids', () => { + test('stay within the 16-bit WM_COMMAND id across 70k popups and fire the newest click', () => { + const fake = fakeUser32(); + const realizer = createWindowsMenuRealizer(() => fake.api); + const fired: number[] = []; + for (let i = 0; i < 70_000; i += 1) { + realizer.realize([item('Item', () => fired.push(i))]); + } + expect(Math.max(...fake.commandIds)).toBeLessThanOrEqual(0xffff); + realizer.dispatchMenuCommand(fake.commandIds.at(-1) ?? 0); + expect(fired).toEqual([69_999]); }); - test('a checked item gets the check mark', () => { - expect(menuItemFlags(true, true)).toBe(MF_CHECKED); + test('an application menu bar item keeps its click after the ids wrap around', () => { + const fake = fakeUser32(); + const realizer = createWindowsMenuRealizer(() => fake.api); + realizer.registerAppMenuWindow(window()); + const fired: string[] = []; + realizer.setApplicationMenu(realizer.realize([item('Open', () => fired.push('open'))])); + const barId = fake.commandIds.at(-1) ?? 0; + for (let i = 0; i < 70_000; i += 1) { + realizer.realize([item('Popup', () => fired.push('popup'))]); + } + realizer.dispatchMenuCommand(barId); + expect(fired).toEqual(['open']); }); - test('disabled + checked compose', () => { - expect(menuItemFlags(false, true)).toBe(MF_GRAYED | MF_CHECKED); + test('a replaced application menu no longer holds its click handlers', () => { + const fake = fakeUser32(); + const realizer = createWindowsMenuRealizer(() => fake.api); + realizer.registerAppMenuWindow(window()); + const fired: string[] = []; + realizer.setApplicationMenu(realizer.realize([item('Old', () => fired.push('old'))])); + const oldBarId = fake.commandIds.at(-1) ?? 0; + realizer.setApplicationMenu(realizer.realize([item('New', () => fired.push('new'))])); + realizer.dispatchMenuCommand(oldBarId); + expect(fired).toEqual([]); + }); +}); + +describe('createWindowsMenuRealizer setApplicationMenu', () => { + test('destroys the realized popup tree it only reads the items from', () => { + const fake = fakeUser32(); + const realizer = createWindowsMenuRealizer(() => fake.api); + const handle = realizer.realize([item('File')]); + realizer.setApplicationMenu(handle); + expect(fake.destroyed).toEqual([handle]); }); }); From 48e901617bc1fe5c548e5df78ca20eec44654c6b Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:14:23 -0700 Subject: [PATCH 176/586] fix: accept Electron's optional window argument in dialog methods --- src/main/api/dialog.ts | 25 +++++++++++++++++++------ tests/unit/main/api/dialog.test.ts | 20 ++++++++++++++++++++ 2 files changed, 39 insertions(+), 6 deletions(-) diff --git a/src/main/api/dialog.ts b/src/main/api/dialog.ts index b375f1b6..87c5c2a6 100644 --- a/src/main/api/dialog.ts +++ b/src/main/api/dialog.ts @@ -2,6 +2,7 @@ import { selectBackend } from '../platform/index'; import { linuxDialogBackend } from '../platform/linux/gtk-dialog'; import * as cocoaDialog from '../platform/macos/cocoa-dialog'; import { windowsDialogBackend } from '../platform/windows/windows-dialog'; +import type { BrowserWindow } from './browser-window'; /** * Native system dialogs — the drop-in equivalent of Electron's `dialog`. macOS @@ -97,15 +98,25 @@ const { get: getBackend, setForTesting } = selectBackend('dialog' /** @internal */ export const setDialogBackendForTesting = setForTesting; +/** Electron's optional leading window; accepted, but dialogs are not attached as sheets. */ +type WithWindow = [window: BrowserWindow, options: T]; + export type Dialog = { - showMessageBox(options: MessageBoxOptions): Promise; - showOpenDialog(options?: OpenDialogOptions): Promise; - showSaveDialog(options?: SaveDialogOptions): Promise; + showMessageBox( + ...args: [options: MessageBoxOptions] | WithWindow + ): Promise; + showOpenDialog( + ...args: [options?: OpenDialogOptions] | WithWindow + ): Promise; + showSaveDialog( + ...args: [options?: SaveDialogOptions] | WithWindow + ): Promise; showErrorBox(title: string, content: string): void; }; export const dialog: Dialog = { - async showMessageBox(options) { + async showMessageBox(...args) { + const options = args.length === 2 ? args[1] : args[0]; const response = await getBackend().showMessageBox({ message: options.message, detail: options.detail ?? '', @@ -115,7 +126,8 @@ export const dialog: Dialog = { return { response }; }, - async showOpenDialog(options = {}) { + async showOpenDialog(...args) { + const options = (args.length === 2 ? args[1] : args[0]) ?? {}; const properties = options.properties ?? ['openFile']; const filePaths = await getBackend().showOpenDialog({ canChooseFiles: properties.includes('openFile'), @@ -128,7 +140,8 @@ export const dialog: Dialog = { return { canceled: filePaths.length === 0, filePaths }; }, - async showSaveDialog(options = {}) { + async showSaveDialog(...args) { + const options = (args.length === 2 ? args[1] : args[0]) ?? {}; const filePath = await getBackend().showSaveDialog({ defaultName: options.defaultPath ?? '', extensions: flattenFilterExtensions(options.filters), diff --git a/tests/unit/main/api/dialog.test.ts b/tests/unit/main/api/dialog.test.ts index 872c533b..f4014ed0 100644 --- a/tests/unit/main/api/dialog.test.ts +++ b/tests/unit/main/api/dialog.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; +import type { BrowserWindow } from '../../../../src/main/api/browser-window'; import { type DialogBackend, dialog, @@ -146,6 +147,25 @@ describe('dialog.showSaveDialog', () => { }); }); +describe("Electron's optional window first argument", () => { + const win = {} as BrowserWindow; + + test('showMessageBox(window, options) reads the options', async () => { + await dialog.showMessageBox(win, { message: 'Discard?', buttons: ['Discard', 'Cancel'] }); + expect(lastMessageBox).toMatchObject({ message: 'Discard?', buttons: ['Discard', 'Cancel'] }); + }); + + test('showOpenDialog(window, options) reads the options', async () => { + await dialog.showOpenDialog(win, { properties: ['openDirectory'] }); + expect(lastOpen?.canChooseDirectories).toBe(true); + }); + + test('showSaveDialog(window, options) reads the options', async () => { + await dialog.showSaveDialog(win, { defaultPath: 'notes.md' }); + expect(lastSave?.defaultName).toBe('notes.md'); + }); +}); + describe('dialog.showErrorBox', () => { test('routes the title and content through an error-styled message box', () => { dialog.showErrorBox('Boom', 'Something failed'); From 9aefa1a714fa0da81b66019de6e8bf67345c793f Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:14:24 -0700 Subject: [PATCH 177/586] fix: drop non-string script message bodies on Windows --- src/main/platform/windows/webkit2-ffi.ts | 3 ++ .../platform/windows/windows-webkit-view.ts | 26 ++++++++++---- .../windows/windows-webkit-view.test.ts | 35 +++++++++++++++++++ 3 files changed, 58 insertions(+), 6 deletions(-) create mode 100644 tests/unit/main/platform/windows/windows-webkit-view.test.ts diff --git a/src/main/platform/windows/webkit2-ffi.ts b/src/main/platform/windows/webkit2-ffi.ts index a3c79952..7af854d4 100644 --- a/src/main/platform/windows/webkit2-ffi.ts +++ b/src/main/platform/windows/webkit2-ffi.ts @@ -86,6 +86,9 @@ const WEBKIT2_SYMBOLS = { WKScriptMessageGetBody: { args: [FFIType.ptr], returns: FFIType.ptr }, // ── Strings / URLs ─────────────────────────────────────────────────────── + // WKTypeID is uint32_t. + WKGetTypeID: { args: [FFIType.ptr], returns: FFIType.u32 }, + WKStringGetTypeID: { args: [], returns: FFIType.u32 }, WKStringCreateWithUTF8CString: { args: [FFIType.cstring], returns: FFIType.ptr }, WKStringGetMaximumUTF8CStringSize: { args: [FFIType.ptr], returns: FFIType.u64 }, WKStringGetUTF8CString: { args: [FFIType.ptr, FFIType.ptr, FFIType.u64], returns: FFIType.u64 }, diff --git a/src/main/platform/windows/windows-webkit-view.ts b/src/main/platform/windows/windows-webkit-view.ts index f6589d7d..d43ed21a 100644 --- a/src/main/platform/windows/windows-webkit-view.ts +++ b/src/main/platform/windows/windows-webkit-view.ts @@ -155,6 +155,25 @@ const setupNavigationClient = ( return callbacks; }; +type ScriptMessageApi = Pick< + ReturnType['symbols'], + 'WKScriptMessageGetBody' | 'WKGetTypeID' | 'WKStringGetTypeID' +>; + +/** Forward a page-posted script message's string body to `onMessage`. */ +export const deliverScriptMessage = ( + message: Pointer, + onMessage: (body: string) => void, + wk: ScriptMessageApi = loadWebKit2().symbols, + readString: (ref: Pointer) => string = wkStringToJs, +): void => { + const body = wk.WKScriptMessageGetBody(message); + // Any page script can post a number/bool/object; reading that as a WKString faults the process. + if (body !== null && wk.WKGetTypeID(body) === wk.WKStringGetTypeID()) { + onMessage(readString(body)); + } +}; + export interface ScriptMessageHandler { readonly name: string; readonly onMessage: (body: string) => void; @@ -217,12 +236,7 @@ export class WindowsWebView { const callbacks: JSCallback[] = []; for (const handler of options.messageHandlers) { const callback = new JSCallback( - (messageRef: Pointer) => { - const bodyRef = s.WKScriptMessageGetBody(messageRef); - if (bodyRef !== null) { - handler.onMessage(wkStringToJs(bodyRef)); - } - }, + (messageRef: Pointer) => deliverScriptMessage(messageRef, handler.onMessage, s), { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr], returns: FFIType.void }, ); if (callback.ptr === null) { diff --git a/tests/unit/main/platform/windows/windows-webkit-view.test.ts b/tests/unit/main/platform/windows/windows-webkit-view.test.ts new file mode 100644 index 00000000..7164c59a --- /dev/null +++ b/tests/unit/main/platform/windows/windows-webkit-view.test.ts @@ -0,0 +1,35 @@ +import type { Pointer } from 'bun:ffi'; +import { describe, expect, test } from 'bun:test'; +import { deliverScriptMessage } from '../../../../../src/main/platform/windows/windows-webkit-view'; + +type ScriptMessageApi = NonNullable[2]>; + +const MESSAGE = 0x10 as Pointer; +const BODY = 0x20 as Pointer; +const STRING_TYPE = 7; +const DOUBLE_TYPE = 9; + +const fakeWk = (bodyType: number): ScriptMessageApi => ({ + WKScriptMessageGetBody: () => BODY, + WKGetTypeID: () => bodyType, + WKStringGetTypeID: () => STRING_TYPE, +}); + +const readBody = (ref: Pointer): string => (ref === BODY ? '{"ping":"pong"}' : 'wrong ref'); + +describe('deliverScriptMessage', () => { + test('forwards a string body to the handler', () => { + const received: string[] = []; + deliverScriptMessage(MESSAGE, (body) => received.push(body), fakeWk(STRING_TYPE), readBody); + expect(received).toEqual(['{"ping":"pong"}']); + }); + + test('drops a non-string body without reading it as a WKString', () => { + const received: string[] = []; + const readAsString = (): string => { + throw new Error('read a non-string body as a WKString'); + }; + deliverScriptMessage(MESSAGE, (body) => received.push(body), fakeWk(DOUBLE_TYPE), readAsString); + expect(received).toEqual([]); + }); +}); From ec79db4074878f27971c9dc2329cd3597244a19c Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:14:33 -0700 Subject: [PATCH 178/586] fix: refuse a second X11 grab of a combo this app already holds --- src/main/platform/linux/x11-global-shortcut.ts | 16 +++++++++------- .../linux/x11-global-shortcut.test.ts | 5 +++++ 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/src/main/platform/linux/x11-global-shortcut.ts b/src/main/platform/linux/x11-global-shortcut.ts index 13a89180..0c20a0e6 100644 --- a/src/main/platform/linux/x11-global-shortcut.ts +++ b/src/main/platform/linux/x11-global-shortcut.ts @@ -112,6 +112,9 @@ const resolveGrab = (accelerator: string, dpy: Pointer): Grab | undefined => { return keycode === 0 ? undefined : { keycode, modifiers: x11ModifierMask(parsed) }; }; +const findRegistration = (grab: Grab): number => + registrations.findIndex((r) => r.keycode === grab.keycode && r.modifiers === grab.modifiers); + const ungrab = (dpy: Pointer, grab: Grab): void => { const x11 = loadX11FFI(); for (const lockBits of GRAB_VARIANTS) { @@ -122,7 +125,7 @@ const ungrab = (dpy: Pointer, grab: Grab): void => { const register = (accelerator: string, callback: () => void): boolean => { const dpy = ensureDisplay(); const grab = dpy === null ? undefined : resolveGrab(accelerator, dpy); - if (dpy === null || grab === undefined) { + if (dpy === null || grab === undefined || findRegistration(grab) !== -1) { return false; } const x11 = loadX11FFI(); @@ -142,13 +145,12 @@ const unregister = (accelerator: string): void => { if (dpy === null || dpy === undefined || grab === undefined) { return; } - for (let i = registrations.length - 1; i >= 0; i -= 1) { - const reg = registrations[i]; - if (reg !== undefined && reg.keycode === grab.keycode && reg.modifiers === grab.modifiers) { - ungrab(dpy, reg); - registrations.splice(i, 1); - } + const index = findRegistration(grab); + if (index === -1) { + return; } + registrations.splice(index, 1); + ungrab(dpy, grab); loadX11FFI().symbols.XFlush(dpy); }; diff --git a/tests/integration/linux/x11-global-shortcut.test.ts b/tests/integration/linux/x11-global-shortcut.test.ts index fc38dd32..f125db8d 100644 --- a/tests/integration/linux/x11-global-shortcut.test.ts +++ b/tests/integration/linux/x11-global-shortcut.test.ts @@ -83,6 +83,11 @@ describe.skipIf(!isLinux)('x11-global-shortcut (Linux)', () => { expect(linuxGlobalShortcutBackend.register('CmdOrCtrl+,', () => undefined)).toBe(true); }); + test('register() refuses a second spelling of a held combo', () => { + expect(linuxGlobalShortcutBackend.register('Ctrl+K', () => undefined)).toBe(true); + expect(linuxGlobalShortcutBackend.register('Control+K', () => undefined)).toBe(false); + }); + test('register() returns false for an unmappable key', () => { expect(linuxGlobalShortcutBackend.register('CmdOrCtrl+Bogus', () => undefined)).toBe(false); }); From c71f27c0839ab4ce884bf444826694d399b0d6a3 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:14:40 -0700 Subject: [PATCH 179/586] fix: sleep without timeout.exe and call system tar in the cmd helper --- src/main/api/update-installer.ts | 6 ++++-- tests/unit/main/api/update-installer.test.ts | 4 ++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/main/api/update-installer.ts b/src/main/api/update-installer.ts index 8eb3019c..70f53f75 100644 --- a/src/main/api/update-installer.ts +++ b/src/main/api/update-installer.ts @@ -123,13 +123,15 @@ export const buildCmdInstallScript = (spec: CmdInstallSpec): string => { 'rem bunmaska auto-update helper: waits for the app to exit, swaps, relaunches.', ':wait', `tasklist /FI "PID eq ${spec.pid}" | find "${spec.pid}" >nul`, - 'if not errorlevel 1 (timeout /t 1 /nobreak >nul & goto wait)', + // timeout.exe exits at once when stdin is redirected (the helper's is), spinning this loop. + 'if not errorlevel 1 (ping -n 2 127.0.0.1 >nul & goto wait)', `if exist "${old}" rmdir /s /q "${old}"`, `if exist "${staging}" rmdir /s /q "${staging}"`, `mkdir "${staging}" || goto fail`, 'rem extract from cwd, not tar -C: Windows bsdtar mangles backslash -C paths', `cd /d "${staging}" || goto fail`, - `tar -xf "${spec.tarPath}" || goto fail`, + // System bsdtar by full path: a Git-for-Windows GNU tar on PATH reads C:\ as a remote host. + `"%SystemRoot%\\System32\\tar.exe" -xf "${spec.tarPath}" || goto fail`, 'cd /d "%TEMP%"', `if not exist "${staging}\\${spec.bundleDirName}" goto fail`, `move "${spec.installRoot}" "${old}" || goto fail`, diff --git a/tests/unit/main/api/update-installer.test.ts b/tests/unit/main/api/update-installer.test.ts index 13f19b52..9228d594 100644 --- a/tests/unit/main/api/update-installer.test.ts +++ b/tests/unit/main/api/update-installer.test.ts @@ -195,13 +195,13 @@ describe('buildCmdInstallScript', () => { 'rem bunmaska auto-update helper: waits for the app to exit, swaps, relaunches.', ':wait', 'tasklist /FI "PID eq 7" | find "7" >nul', - 'if not errorlevel 1 (timeout /t 1 /nobreak >nul & goto wait)', + 'if not errorlevel 1 (ping -n 2 127.0.0.1 >nul & goto wait)', 'if exist "C:\\Apps\\Demo.update-old" rmdir /s /q "C:\\Apps\\Demo.update-old"', 'if exist "C:\\Apps\\Demo.update-staging" rmdir /s /q "C:\\Apps\\Demo.update-staging"', 'mkdir "C:\\Apps\\Demo.update-staging" || goto fail', 'rem extract from cwd, not tar -C: Windows bsdtar mangles backslash -C paths', 'cd /d "C:\\Apps\\Demo.update-staging" || goto fail', - 'tar -xf "C:\\tmp\\up.tar" || goto fail', + '"%SystemRoot%\\System32\\tar.exe" -xf "C:\\tmp\\up.tar" || goto fail', 'cd /d "%TEMP%"', 'if not exist "C:\\Apps\\Demo.update-staging\\Demo" goto fail', 'move "C:\\Apps\\Demo" "C:\\Apps\\Demo.update-old" || goto fail', From fd3979ba96d91914ab60a20cc37fef468a555628 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:14:48 -0700 Subject: [PATCH 180/586] fix: fire powerMonitor resume once per wake on Windows --- src/main/platform/windows/windows-power-monitor.ts | 5 +++-- .../platform/windows/windows-power-monitor.test.ts | 12 +++++------- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/src/main/platform/windows/windows-power-monitor.ts b/src/main/platform/windows/windows-power-monitor.ts index 8b0790e1..887034dc 100644 --- a/src/main/platform/windows/windows-power-monitor.ts +++ b/src/main/platform/windows/windows-power-monitor.ts @@ -15,7 +15,8 @@ export const WM_WTSSESSION_CHANGE = 0x02b1; /** `WM_POWERBROADCAST` events: the system is suspending / has resumed. */ const PBT_APMSUSPEND = 0x0004; -const PBT_APMRESUMESUSPEND = 0x0007; +// Sent on every resume; a user-initiated wake also sends PBT_APMRESUMESUSPEND after +// it, which is ignored so 'resume' fires once (as Chromium does). const PBT_APMRESUMEAUTOMATIC = 0x0012; /** `WM_WTSSESSION_CHANGE` events: the session was locked / unlocked. */ @@ -34,7 +35,7 @@ export const dispatchPowerMessage = ( if (message === WM_POWERBROADCAST) { if (wParam === PBT_APMSUSPEND) { handlers.onSuspend(); - } else if (wParam === PBT_APMRESUMESUSPEND || wParam === PBT_APMRESUMEAUTOMATIC) { + } else if (wParam === PBT_APMRESUMEAUTOMATIC) { handlers.onResume(); } return; diff --git a/tests/unit/main/platform/windows/windows-power-monitor.test.ts b/tests/unit/main/platform/windows/windows-power-monitor.test.ts index 8d1ced0f..276bf7d9 100644 --- a/tests/unit/main/platform/windows/windows-power-monitor.test.ts +++ b/tests/unit/main/platform/windows/windows-power-monitor.test.ts @@ -37,13 +37,11 @@ describe('dispatchPowerMessage', () => { expect(events).toEqual(['suspend']); }); - test('both resume codes fire onResume', () => { - const a = recorder(); - dispatchPowerMessage(a.handlers, WM_POWERBROADCAST, PBT_APMRESUMEAUTOMATIC); - expect(a.events).toEqual(['resume']); - const b = recorder(); - dispatchPowerMessage(b.handlers, WM_POWERBROADCAST, PBT_APMRESUMESUSPEND); - expect(b.events).toEqual(['resume']); + test('a user-initiated wake (automatic then user-present resume) fires onResume once', () => { + const { events, handlers } = recorder(); + dispatchPowerMessage(handlers, WM_POWERBROADCAST, PBT_APMRESUMEAUTOMATIC); + dispatchPowerMessage(handlers, WM_POWERBROADCAST, PBT_APMRESUMESUSPEND); + expect(events).toEqual(['resume']); }); test('WM_WTSSESSION_CHANGE lock/unlock fire the screen handlers', () => { From a0ce5731e8cedf32acd7ebefecf12d239892eb75 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:14:49 -0700 Subject: [PATCH 181/586] fix: log a failed showErrorBox instead of leaving a rejection unhandled --- src/main/api/dialog.ts | 19 ++++++++++++------- tests/unit/main/api/dialog.test.ts | 19 +++++++++++++++++++ 2 files changed, 31 insertions(+), 7 deletions(-) diff --git a/src/main/api/dialog.ts b/src/main/api/dialog.ts index 87c5c2a6..b8baa291 100644 --- a/src/main/api/dialog.ts +++ b/src/main/api/dialog.ts @@ -1,3 +1,4 @@ +import { createLogger } from '../../common/logger'; import { selectBackend } from '../platform/index'; import { linuxDialogBackend } from '../platform/linux/gtk-dialog'; import * as cocoaDialog from '../platform/macos/cocoa-dialog'; @@ -98,6 +99,8 @@ const { get: getBackend, setForTesting } = selectBackend('dialog' /** @internal */ export const setDialogBackendForTesting = setForTesting; +const log = createLogger('dialog'); + /** Electron's optional leading window; accepted, but dialogs are not attached as sheets. */ type WithWindow = [window: BrowserWindow, options: T]; @@ -149,13 +152,15 @@ export const dialog: Dialog = { return { canceled: filePath.length === 0, filePath }; }, - // Electron's showErrorBox is sync/void, so this is fire-and-forget on Linux. + // Electron's showErrorBox is sync and void, so an async failure is logged, never thrown. showErrorBox(title, content) { - void getBackend().showMessageBox({ - message: title, - detail: content, - buttons: ['OK'], - type: 'error', - }); + Promise.resolve( + getBackend().showMessageBox({ + message: title, + detail: content, + buttons: ['OK'], + type: 'error', + }), + ).catch((error: unknown) => log.warn('showErrorBox failed', error)); }, }; diff --git a/tests/unit/main/api/dialog.test.ts b/tests/unit/main/api/dialog.test.ts index f4014ed0..76078fcf 100644 --- a/tests/unit/main/api/dialog.test.ts +++ b/tests/unit/main/api/dialog.test.ts @@ -178,6 +178,25 @@ describe('dialog.showErrorBox', () => { }); }); +describe('dialog.showErrorBox on a rejecting backend', () => { + test('leaves no unhandled rejection behind', async () => { + const unhandled: unknown[] = []; + const onUnhandled = (reason: unknown): void => { + unhandled.push(reason); + }; + process.on('unhandledRejection', onUnhandled); + setDialogBackendForTesting({ + showMessageBox: () => Promise.reject(new Error('alert failed to start')), + showOpenDialog: () => [], + showSaveDialog: () => '', + }); + dialog.showErrorBox('Boom', 'Something failed'); + await new Promise((resolve) => setTimeout(resolve, 10)); + process.off('unhandledRejection', onUnhandled); + expect(unhandled).toEqual([]); + }); +}); + describe('async DialogBackend (Promise-returning, e.g. Linux GTK)', () => { test('flattens a Promise from showMessageBox without double-wrapping', async () => { const asyncBackend: DialogBackend = { From 6a16a72017b49c05c6b353a79ed2c8ad6c497855 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:14:58 -0700 Subject: [PATCH 182/586] fix: stop retaining every decoded Linux tray icon for the process --- src/main/platform/linux/sni-tray.ts | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/main/platform/linux/sni-tray.ts b/src/main/platform/linux/sni-tray.ts index b627fca3..c68f3aa7 100644 --- a/src/main/platform/linux/sni-tray.ts +++ b/src/main/platform/linux/sni-tray.ts @@ -41,10 +41,8 @@ import { * LIFETIME (load-bearing, blind — verified by review, not CI): `register_object` COPIES the * vtable, so the live wires are the THREE JSCallbacks (the copied vtable holds their raw * fn-pointers) — they are retained FOREVER (never closed, mirroring the signal-subscription - * discipline; closing would risk the in-flight-reply / own-invocation SIGSEGV class). The - * `IconPixmap` is `g_variant_new_from_data(notify=NULL)`, so its backing ARGB `Uint8Array` - * MUST outlive every reply that references it — every icon buffer is retained for the - * process lifetime. Property getters MUST be on the pumped main thread (the THREAD INVARIANT + * discipline; closing would risk the in-flight-reply / own-invocation SIGSEGV class). + * Property getters MUST be on the pumped main thread (the THREAD INVARIANT * in linux-dbus.ts) or the host's queries dispatch to a context nothing iterates. */ @@ -81,13 +79,11 @@ export const SNI_XML = ` const liveTrayEnabled = (): boolean => process.env['BUNMASKA_ENABLE_LINUX_TRAY'] === '1'; // Process-lifetime retains (never freed — see the module note): the vtable JSCallbacks -// (the copied vtable holds their raw fn-pointers) + every icon ARGB buffer (referenced by -// from_data variants with notify=NULL) + the node infos + vtable arrays. +// (the copied vtable holds their raw fn-pointers) + the node infos + vtable arrays. const retained: { callbacks: JSCallback[]; - buffers: Uint8Array[]; misc: unknown[]; -} = { callbacks: [], buffers: [], misc: [] }; +} = { callbacks: [], misc: [] }; /** Cached `GVariantType*` per type string (allocated once, retained for the process). */ const variantTypes = new Map(); @@ -160,10 +156,14 @@ const decodeIcon = (path: string): Icon | null => { return icon; }; -/** Build a floating `a(iiay)` with the one icon frame (retains `icon.argb` for from_data). */ +/** + * Build a floating `a(iiay)` with the one icon frame. The `ay` BORROWS `icon.argb` + * (from_data, notify=NULL): the tray state owns the buffer, and GDBus serializes the reply + * inside the getter's dispatch, so a later setImage may drop the old buffer. + */ const buildIconPixmap = (icon: Icon): Pointer | null => { const g = loadGlibFFI().symbols; - retained.buffers.push(icon.argb); // referenced by from_data (notify=NULL) → must outlive the variant. + // ponytail: G_DBUS_DEBUG=message prints queued replies on the worker thread and could read a replaced buffer; copy via g_variant_new_fixed_array to close it. const builder = g.g_variant_builder_new(variantType('a(iiay)')); g.g_variant_builder_open(builder, variantType('(iiay)')); g.g_variant_builder_add_value(builder, g.g_variant_new_int32(icon.width)); @@ -349,7 +349,7 @@ const createLive = (conn: Pointer, initialImage: string): TrayInstance | null => emitSignal(conn, OBJECT_PATH, SNI_IFACE, 'NewTitle', null); }, setImage: (image) => { - state.icon = decodeIcon(image); // old argb stays retained (an in-flight reply may use it). + state.icon = decodeIcon(image); emitSignal(conn, OBJECT_PATH, SNI_IFACE, 'NewIcon', null); // argument-less; host re-fetches. }, setContextMenu: () => undefined, // deferred: dbusmenu is a follow-up (soft no-op, never throws). From dd50dd9f93d45988d67f2bcbd2e995a73e53a4f6 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:15:05 -0700 Subject: [PATCH 183/586] fix: accept Windows script messages from the main frame only --- src/main/platform/windows/webkit2-ffi.ts | 2 ++ .../platform/windows/windows-webkit-view.ts | 16 ++++++++++++---- .../windows/windows-webkit-view.test.ts | 17 ++++++++++++++++- 3 files changed, 30 insertions(+), 5 deletions(-) diff --git a/src/main/platform/windows/webkit2-ffi.ts b/src/main/platform/windows/webkit2-ffi.ts index 7af854d4..9252a737 100644 --- a/src/main/platform/windows/webkit2-ffi.ts +++ b/src/main/platform/windows/webkit2-ffi.ts @@ -84,6 +84,8 @@ const WEBKIT2_SYMBOLS = { returns: FFIType.ptr, }, WKScriptMessageGetBody: { args: [FFIType.ptr], returns: FFIType.ptr }, + WKScriptMessageGetFrameInfo: { args: [FFIType.ptr], returns: FFIType.ptr }, + WKFrameInfoGetIsMainFrame: { args: [FFIType.ptr], returns: FFIType.bool }, // ── Strings / URLs ─────────────────────────────────────────────────────── // WKTypeID is uint32_t. diff --git a/src/main/platform/windows/windows-webkit-view.ts b/src/main/platform/windows/windows-webkit-view.ts index d43ed21a..5944e5fa 100644 --- a/src/main/platform/windows/windows-webkit-view.ts +++ b/src/main/platform/windows/windows-webkit-view.ts @@ -157,16 +157,24 @@ const setupNavigationClient = ( type ScriptMessageApi = Pick< ReturnType['symbols'], - 'WKScriptMessageGetBody' | 'WKGetTypeID' | 'WKStringGetTypeID' + | 'WKScriptMessageGetBody' + | 'WKScriptMessageGetFrameInfo' + | 'WKFrameInfoGetIsMainFrame' + | 'WKGetTypeID' + | 'WKStringGetTypeID' >; -/** Forward a page-posted script message's string body to `onMessage`. */ +/** Forward a main-frame script message's string body to `onMessage`. */ export const deliverScriptMessage = ( message: Pointer, onMessage: (body: string) => void, wk: ScriptMessageApi = loadWebKit2().symbols, readString: (ref: Pointer) => string = wkStringToJs, ): void => { + // The handlers live in the page world, so any iframe could post to the bridge. + if (!wk.WKFrameInfoGetIsMainFrame(wk.WKScriptMessageGetFrameInfo(message))) { + return; + } const body = wk.WKScriptMessageGetBody(message); // Any page script can post a number/bool/object; reading that as a WKString faults the process. if (body !== null && wk.WKGetTypeID(body) === wk.WKStringGetTypeID()) { @@ -184,7 +192,7 @@ export interface WebViewOptions { readonly hwnd: bigint; readonly width: number; readonly height: number; - /** Sources injected at document-start, in order, in all frames. */ + /** Sources injected at document-start, in order, in the main frame only. */ readonly userScripts: readonly string[]; /** Renderer->main message handlers, keyed by their `messageHandlers` name. */ readonly messageHandlers: readonly ScriptMessageHandler[]; @@ -251,7 +259,7 @@ export class WindowsWebView { // Inject the preload/bridge sources at document-start, in order. for (const source of options.userScripts) { const sourceRef = wkString(source); - const userScript = s.WKUserScriptCreateWithSource(sourceRef, WK_INJECT_AT_DOCUMENT_START, 0); + const userScript = s.WKUserScriptCreateWithSource(sourceRef, WK_INJECT_AT_DOCUMENT_START, 1); wkRelease(sourceRef); if (userScript !== null) { s.WKUserContentControllerAddUserScript(controller, userScript); diff --git a/tests/unit/main/platform/windows/windows-webkit-view.test.ts b/tests/unit/main/platform/windows/windows-webkit-view.test.ts index 7164c59a..1b0e55b2 100644 --- a/tests/unit/main/platform/windows/windows-webkit-view.test.ts +++ b/tests/unit/main/platform/windows/windows-webkit-view.test.ts @@ -9,8 +9,12 @@ const BODY = 0x20 as Pointer; const STRING_TYPE = 7; const DOUBLE_TYPE = 9; -const fakeWk = (bodyType: number): ScriptMessageApi => ({ +const FRAME = 0x30 as Pointer; + +const fakeWk = (bodyType: number, isMainFrame = true): ScriptMessageApi => ({ WKScriptMessageGetBody: () => BODY, + WKScriptMessageGetFrameInfo: () => FRAME, + WKFrameInfoGetIsMainFrame: (frame) => frame === FRAME && isMainFrame, WKGetTypeID: () => bodyType, WKStringGetTypeID: () => STRING_TYPE, }); @@ -32,4 +36,15 @@ describe('deliverScriptMessage', () => { deliverScriptMessage(MESSAGE, (body) => received.push(body), fakeWk(DOUBLE_TYPE), readAsString); expect(received).toEqual([]); }); + + test('drops a message posted from a subframe', () => { + const received: string[] = []; + deliverScriptMessage( + MESSAGE, + (body) => received.push(body), + fakeWk(STRING_TYPE, false), + readBody, + ); + expect(received).toEqual([]); + }); }); From 62da52bf7d247d9b481d3945e900ab389a730b81 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:15:00 -0700 Subject: [PATCH 184/586] fix: load Linux libraries from the pinned engine when it has them --- src/main/platform/linux/gdbus-ffi.ts | 6 +-- src/main/platform/linux/gdk-ffi.ts | 6 +-- src/main/platform/linux/gdk-pixbuf-ffi.ts | 6 +-- src/main/platform/linux/gio-ffi.ts | 6 +-- src/main/platform/linux/glib-ffi.ts | 39 +++++++++++++++++-- src/main/platform/linux/gobject-ffi.ts | 6 +-- src/main/platform/linux/gtk-dialog-ffi.ts | 10 ++--- src/main/platform/linux/gtk-ffi.ts | 13 ++----- src/main/platform/linux/gtk-menu-ffi.ts | 10 ++--- src/main/platform/linux/jsc-ffi.ts | 6 +-- src/main/platform/linux/libnotify-ffi.ts | 6 +-- src/main/platform/linux/libsecret-ffi.ts | 6 +-- src/main/platform/linux/soup-ffi.ts | 9 ++--- src/main/platform/linux/webkitgtk-ffi.ts | 12 ++---- src/main/platform/linux/x11-ffi.ts | 6 +-- .../unit/main/platform/linux/glib-ffi.test.ts | 24 ++++++++++++ .../main/platform/linux/linux-ffi-abi.test.ts | 4 ++ 17 files changed, 109 insertions(+), 66 deletions(-) create mode 100644 tests/unit/main/platform/linux/glib-ffi.test.ts diff --git a/src/main/platform/linux/gdbus-ffi.ts b/src/main/platform/linux/gdbus-ffi.ts index 041c1421..bf1c3357 100644 --- a/src/main/platform/linux/gdbus-ffi.ts +++ b/src/main/platform/linux/gdbus-ffi.ts @@ -1,7 +1,7 @@ import { FFIType } from 'bun:ffi'; -import { dlopen } from '../dlopen'; import { UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; +import { dlopenLinux } from './glib-ffi'; /** * GDBus (D-Bus over GIO) symbols behind Bunmaska's deadlock-safe signal-subscription @@ -183,7 +183,7 @@ export const GDBUS_FFI_SYMBOLS = { }, } as const; -const cache: { ffi: ReturnType> | undefined } = { +const cache: { ffi: ReturnType> | undefined } = { ffi: undefined, }; @@ -202,7 +202,7 @@ export const loadGDBusFFI = () => { if (cache.ffi) { return cache.ffi; } - const ffi = dlopen(LIBGIO_PATH, GDBUS_FFI_SYMBOLS); + const ffi = dlopenLinux(LIBGIO_PATH, GDBUS_FFI_SYMBOLS); cache.ffi = ffi; return ffi; }; diff --git a/src/main/platform/linux/gdk-ffi.ts b/src/main/platform/linux/gdk-ffi.ts index 082c8d4d..47ea7a24 100644 --- a/src/main/platform/linux/gdk-ffi.ts +++ b/src/main/platform/linux/gdk-ffi.ts @@ -1,7 +1,7 @@ import { FFIType } from 'bun:ffi'; -import { dlopen } from '../dlopen'; import { UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; +import { dlopenLinux } from './glib-ffi'; /** * Loads GDK 4's display, system-beep, and clipboard symbols. @@ -101,7 +101,7 @@ export const GDK_FFI_SYMBOLS = { }, } as const; -const cache: { ffi: ReturnType> | undefined } = { +const cache: { ffi: ReturnType> | undefined } = { ffi: undefined, }; @@ -115,7 +115,7 @@ export const loadGdkFFI = () => { if (cache.ffi) { return cache.ffi; } - const ffi = dlopen(LIBGTK_PATH, GDK_FFI_SYMBOLS); + const ffi = dlopenLinux(LIBGTK_PATH, GDK_FFI_SYMBOLS); cache.ffi = ffi; return ffi; }; diff --git a/src/main/platform/linux/gdk-pixbuf-ffi.ts b/src/main/platform/linux/gdk-pixbuf-ffi.ts index 6cf224a4..e5b976cc 100644 --- a/src/main/platform/linux/gdk-pixbuf-ffi.ts +++ b/src/main/platform/linux/gdk-pixbuf-ffi.ts @@ -1,7 +1,7 @@ import { FFIType } from 'bun:ffi'; -import { dlopen } from '../dlopen'; import { UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; +import { dlopenLinux } from './glib-ffi'; /** * Loads GdkPixbuf's load/query/encode symbols — the Linux primitives behind @@ -91,7 +91,7 @@ export const GDK_PIXBUF_FFI_SYMBOLS = { }, } as const; -const cache: { ffi: ReturnType> | undefined } = { +const cache: { ffi: ReturnType> | undefined } = { ffi: undefined, }; @@ -105,7 +105,7 @@ export const loadGdkPixbufFFI = () => { if (cache.ffi) { return cache.ffi; } - const ffi = dlopen(LIBGDK_PIXBUF_PATH, GDK_PIXBUF_FFI_SYMBOLS); + const ffi = dlopenLinux(LIBGDK_PIXBUF_PATH, GDK_PIXBUF_FFI_SYMBOLS); cache.ffi = ffi; return ffi; }; diff --git a/src/main/platform/linux/gio-ffi.ts b/src/main/platform/linux/gio-ffi.ts index 601b6b3c..a3073f4e 100644 --- a/src/main/platform/linux/gio-ffi.ts +++ b/src/main/platform/linux/gio-ffi.ts @@ -1,7 +1,7 @@ import { FFIType } from 'bun:ffi'; -import { dlopen } from '../dlopen'; import { UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; +import { dlopenLinux } from './glib-ffi'; /** * Loads GIO's default-handler URI launcher plus the GFile / GListModel / stream @@ -68,7 +68,7 @@ export const GIO_FFI_SYMBOLS = { }, } as const; -const cache: { ffi: ReturnType> | undefined } = { +const cache: { ffi: ReturnType> | undefined } = { ffi: undefined, }; @@ -82,7 +82,7 @@ export const loadGioFFI = () => { if (cache.ffi) { return cache.ffi; } - const ffi = dlopen(LIBGIO_PATH, GIO_FFI_SYMBOLS); + const ffi = dlopenLinux(LIBGIO_PATH, GIO_FFI_SYMBOLS); cache.ffi = ffi; return ffi; }; diff --git a/src/main/platform/linux/glib-ffi.ts b/src/main/platform/linux/glib-ffi.ts index 38d0ab14..9a3b35ef 100644 --- a/src/main/platform/linux/glib-ffi.ts +++ b/src/main/platform/linux/glib-ffi.ts @@ -1,7 +1,14 @@ -import { FFIType } from 'bun:ffi'; -import { dlopen } from '../dlopen'; +import { type FFIFunction, FFIType } from 'bun:ffi'; +import { existsSync } from 'node:fs'; import { UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; +import { + type EngineResolution, + engineLibPath, + prepareEngineForLoad, + resolveEngine, +} from '../../engine/resolve'; +import { dlopen, type NarrowLibrary } from '../dlopen'; /** * Loads GLib's main-context iteration symbols plus `g_free`. @@ -20,6 +27,30 @@ import { currentPlatform } from '../../../common/platform'; const LIBGLIB_PATH = 'libglib-2.0.so.0'; +/** The path to dlopen for `soname`: the pinned engine's bundled copy when it has one, else the bare soname. */ +export const linuxLibPath = ( + engine: EngineResolution, + soname: string, + exists: (path: string) => boolean = existsSync, +): string => { + const bundled = engineLibPath(engine, soname); + return bundled !== soname && exists(bundled) ? bundled : soname; +}; + +/** + * `dlopen` for every Linux loader. A pinned engine must supply GLib, GTK and the rest of its + * closure to the whole process: a bare-soname load of any of them first binds the system copy, + * and the engine's GTK/WebKit then resolve their DT_NEEDED against it (mixed GLib, or two GTKs). + */ +export const dlopenLinux = >( + soname: string, + symbols: Fns, +): NarrowLibrary => { + const engine = resolveEngine(); + prepareEngineForLoad(engine, process.env, (text) => process.stderr.write(text)); + return dlopen(linuxLibPath(engine, soname), symbols); +}; + /** The GLib FFI symbol descriptor table. */ export const GLIB_FFI_SYMBOLS = { g_main_context_default: { @@ -204,7 +235,7 @@ export const GLIB_FFI_SYMBOLS = { }, } as const; -const cache: { ffi: ReturnType> | undefined } = { +const cache: { ffi: ReturnType> | undefined } = { ffi: undefined, }; @@ -218,7 +249,7 @@ export const loadGlibFFI = () => { if (cache.ffi) { return cache.ffi; } - const ffi = dlopen(LIBGLIB_PATH, GLIB_FFI_SYMBOLS); + const ffi = dlopenLinux(LIBGLIB_PATH, GLIB_FFI_SYMBOLS); cache.ffi = ffi; return ffi; }; diff --git a/src/main/platform/linux/gobject-ffi.ts b/src/main/platform/linux/gobject-ffi.ts index ab18646e..a7991175 100644 --- a/src/main/platform/linux/gobject-ffi.ts +++ b/src/main/platform/linux/gobject-ffi.ts @@ -1,7 +1,7 @@ import { FFIType } from 'bun:ffi'; -import { dlopen } from '../dlopen'; import { UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; +import { dlopenLinux } from './glib-ffi'; /** * Loads GObject's signal-connection and refcount primitives plus the @@ -69,7 +69,7 @@ export const GOBJECT_FFI_SYMBOLS = { }, } as const; -const cache: { ffi: ReturnType> | undefined } = { +const cache: { ffi: ReturnType> | undefined } = { ffi: undefined, }; @@ -83,7 +83,7 @@ export const loadGObjectFFI = () => { if (cache.ffi) { return cache.ffi; } - const ffi = dlopen(LIBGOBJECT_PATH, GOBJECT_FFI_SYMBOLS); + const ffi = dlopenLinux(LIBGOBJECT_PATH, GOBJECT_FFI_SYMBOLS); cache.ffi = ffi; return ffi; }; diff --git a/src/main/platform/linux/gtk-dialog-ffi.ts b/src/main/platform/linux/gtk-dialog-ffi.ts index 53969ad8..6f078579 100644 --- a/src/main/platform/linux/gtk-dialog-ffi.ts +++ b/src/main/platform/linux/gtk-dialog-ffi.ts @@ -1,7 +1,7 @@ import { FFIType } from 'bun:ffi'; -import { dlopen } from '../dlopen'; import { UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; +import { dlopenLinux } from './glib-ffi'; /** * Loads the GTK 4 native-dialog symbols behind Bunmaska's `dialog` API: @@ -130,8 +130,8 @@ export const GTK_DIALOG_GOBJECT_FFI_SYMBOLS = { } as const; const cache: { - gtk: ReturnType> | undefined; - gobject: ReturnType> | undefined; + gtk: ReturnType> | undefined; + gobject: ReturnType> | undefined; } = { gtk: undefined, gobject: undefined }; const requireLinux = (fn: string): void => { @@ -148,7 +148,7 @@ export const loadGtkDialogFFI = () => { if (cache.gtk) { return cache.gtk; } - const ffi = dlopen(LIBGTK_PATH, GTK_DIALOG_FFI_SYMBOLS); + const ffi = dlopenLinux(LIBGTK_PATH, GTK_DIALOG_FFI_SYMBOLS); cache.gtk = ffi; return ffi; }; @@ -158,7 +158,7 @@ export const loadGtkDialogGObjectFFI = () => { if (cache.gobject) { return cache.gobject; } - const ffi = dlopen(LIBGOBJECT_PATH, GTK_DIALOG_GOBJECT_FFI_SYMBOLS); + const ffi = dlopenLinux(LIBGOBJECT_PATH, GTK_DIALOG_GOBJECT_FFI_SYMBOLS); cache.gobject = ffi; return ffi; }; diff --git a/src/main/platform/linux/gtk-ffi.ts b/src/main/platform/linux/gtk-ffi.ts index 8ba1b743..ea82aacc 100644 --- a/src/main/platform/linux/gtk-ffi.ts +++ b/src/main/platform/linux/gtk-ffi.ts @@ -1,8 +1,7 @@ import { FFIType } from 'bun:ffi'; -import { dlopen } from '../dlopen'; import { UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; -import { engineLibPath, prepareEngineForLoad, resolveEngine } from '../../engine/resolve'; +import { dlopenLinux } from './glib-ffi'; const LIBGTK_PATH = 'libgtk-4.so.1'; @@ -127,7 +126,7 @@ export const GTK_FFI_SYMBOLS = { }, } as const; -const cache: { ffi: ReturnType> | undefined } = { +const cache: { ffi: ReturnType> | undefined } = { ffi: undefined, }; @@ -150,13 +149,7 @@ export const loadGtkFFI = () => { if (cache.ffi) { return cache.ffi; } - // Share the engine resolution with the WebKitGTK loader: in pinned mode GTK - // must come from the SAME store `lib/` as WebKit, or two GTK symbol sets land - // in one process and crash. `prepareEngineForLoad` is a one-shot no-op after - // the first loader, so whichever fires first fixes the engine for both. - const engine = resolveEngine(); - prepareEngineForLoad(engine, process.env, (text) => process.stderr.write(text)); - const ffi = dlopen(engineLibPath(engine, LIBGTK_PATH), GTK_FFI_SYMBOLS); + const ffi = dlopenLinux(LIBGTK_PATH, GTK_FFI_SYMBOLS); cache.ffi = ffi; return ffi; }; diff --git a/src/main/platform/linux/gtk-menu-ffi.ts b/src/main/platform/linux/gtk-menu-ffi.ts index d0d3fe33..f665d293 100644 --- a/src/main/platform/linux/gtk-menu-ffi.ts +++ b/src/main/platform/linux/gtk-menu-ffi.ts @@ -1,7 +1,7 @@ import { FFIType } from 'bun:ffi'; -import { dlopen } from '../dlopen'; import { UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; +import { dlopenLinux } from './glib-ffi'; /** * Loads the GIO `GMenu`/`GAction` model symbols and the GTK 4 @@ -126,8 +126,8 @@ export const GTK_MENU_FFI_SYMBOLS = { } as const; const cache: { - gio: ReturnType> | undefined; - gtk: ReturnType> | undefined; + gio: ReturnType> | undefined; + gtk: ReturnType> | undefined; } = { gio: undefined, gtk: undefined }; const requireLinux = (fn: string): void => { @@ -145,7 +145,7 @@ export const loadGMenuFFI = () => { if (cache.gio) { return cache.gio; } - const ffi = dlopen(LIBGIO_PATH, GMENU_FFI_SYMBOLS); + const ffi = dlopenLinux(LIBGIO_PATH, GMENU_FFI_SYMBOLS); cache.gio = ffi; return ffi; }; @@ -156,7 +156,7 @@ export const loadGtkMenuFFI = () => { if (cache.gtk) { return cache.gtk; } - const ffi = dlopen(LIBGTK_PATH, GTK_MENU_FFI_SYMBOLS); + const ffi = dlopenLinux(LIBGTK_PATH, GTK_MENU_FFI_SYMBOLS); cache.gtk = ffi; return ffi; }; diff --git a/src/main/platform/linux/jsc-ffi.ts b/src/main/platform/linux/jsc-ffi.ts index c64406f3..0a3d6ffb 100644 --- a/src/main/platform/linux/jsc-ffi.ts +++ b/src/main/platform/linux/jsc-ffi.ts @@ -1,7 +1,7 @@ import { FFIType } from 'bun:ffi'; -import { dlopen } from '../dlopen'; import { UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; +import { dlopenLinux } from './glib-ffi'; /** * Loads JavaScriptCoreGTK 6.0 — a SEPARATE shared object from WebKitGTK @@ -25,7 +25,7 @@ export const JSC_FFI_SYMBOLS = { }, } as const; -const cache: { ffi: ReturnType> | undefined } = { +const cache: { ffi: ReturnType> | undefined } = { ffi: undefined, }; @@ -39,7 +39,7 @@ export const loadJscFFI = () => { if (cache.ffi) { return cache.ffi; } - const ffi = dlopen(LIBJSC_PATH, JSC_FFI_SYMBOLS); + const ffi = dlopenLinux(LIBJSC_PATH, JSC_FFI_SYMBOLS); cache.ffi = ffi; return ffi; }; diff --git a/src/main/platform/linux/libnotify-ffi.ts b/src/main/platform/linux/libnotify-ffi.ts index 270556a4..633e56ab 100644 --- a/src/main/platform/linux/libnotify-ffi.ts +++ b/src/main/platform/linux/libnotify-ffi.ts @@ -1,7 +1,7 @@ import { FFIType } from 'bun:ffi'; -import { dlopen } from '../dlopen'; import { UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; +import { dlopenLinux } from './glib-ffi'; /** * Loads the libnotify symbols behind Bunmaska's `Notification` API on Linux. @@ -60,7 +60,7 @@ export const LIBNOTIFY_FFI_SYMBOLS = { }, } as const; -const cache: { ffi: ReturnType> | undefined } = { +const cache: { ffi: ReturnType> | undefined } = { ffi: undefined, }; @@ -74,7 +74,7 @@ export const loadLibnotifyFFI = () => { if (cache.ffi) { return cache.ffi; } - const ffi = dlopen(LIBNOTIFY_PATH, LIBNOTIFY_FFI_SYMBOLS); + const ffi = dlopenLinux(LIBNOTIFY_PATH, LIBNOTIFY_FFI_SYMBOLS); cache.ffi = ffi; return ffi; }; diff --git a/src/main/platform/linux/libsecret-ffi.ts b/src/main/platform/linux/libsecret-ffi.ts index dec2cb9a..07d0e967 100644 --- a/src/main/platform/linux/libsecret-ffi.ts +++ b/src/main/platform/linux/libsecret-ffi.ts @@ -1,8 +1,8 @@ import { FFIType, type Pointer } from 'bun:ffi'; -import { dlopen } from '../dlopen'; import { UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; import { cstr } from '../cstr'; +import { dlopenLinux } from './glib-ffi'; /** * libsecret symbols behind the Linux keyring backend of `safeStorage`. @@ -56,7 +56,7 @@ export const LIBSECRET_FFI_SYMBOLS = { } as const; const cache: { - ffi: ReturnType> | undefined; + ffi: ReturnType> | undefined; schema: Pointer | undefined; } = { ffi: undefined, schema: undefined }; @@ -75,7 +75,7 @@ export const loadLibsecretFFI = () => { if (cache.ffi) { return cache.ffi; } - const ffi = dlopen(LIBSECRET_PATH, LIBSECRET_FFI_SYMBOLS); + const ffi = dlopenLinux(LIBSECRET_PATH, LIBSECRET_FFI_SYMBOLS); cache.ffi = ffi; return ffi; }; diff --git a/src/main/platform/linux/soup-ffi.ts b/src/main/platform/linux/soup-ffi.ts index d13ee6e0..e7802751 100644 --- a/src/main/platform/linux/soup-ffi.ts +++ b/src/main/platform/linux/soup-ffi.ts @@ -1,8 +1,7 @@ import { FFIType } from 'bun:ffi'; -import { dlopen } from '../dlopen'; import { UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; -import { engineLibPath, prepareEngineForLoad, resolveEngine } from '../../engine/resolve'; +import { dlopenLinux } from './glib-ffi'; /** * Loads libsoup 3 - the HTTP library WebKitGTK's cookie API traffics in. @@ -67,7 +66,7 @@ export const SOUP_FFI_SYMBOLS = { }, } as const; -const cache: { ffi: ReturnType> | undefined } = { +const cache: { ffi: ReturnType> | undefined } = { ffi: undefined, }; @@ -81,9 +80,7 @@ export const loadSoupFFI = () => { if (cache.ffi) { return cache.ffi; } - const engine = resolveEngine(); - prepareEngineForLoad(engine, process.env, (text) => process.stderr.write(text)); - const ffi = dlopen(engineLibPath(engine, LIBSOUP_PATH), SOUP_FFI_SYMBOLS); + const ffi = dlopenLinux(LIBSOUP_PATH, SOUP_FFI_SYMBOLS); cache.ffi = ffi; return ffi; }; diff --git a/src/main/platform/linux/webkitgtk-ffi.ts b/src/main/platform/linux/webkitgtk-ffi.ts index dae1b9da..168e6c1b 100644 --- a/src/main/platform/linux/webkitgtk-ffi.ts +++ b/src/main/platform/linux/webkitgtk-ffi.ts @@ -1,8 +1,7 @@ import { CString, FFIType, type Pointer } from 'bun:ffi'; -import { dlopen } from '../dlopen'; import { UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; -import { engineLibPath, prepareEngineForLoad, resolveEngine } from '../../engine/resolve'; +import { dlopenLinux } from './glib-ffi'; /** * Loads WebKitGTK 6.0 — the Linux system-WebKit web view (the role @@ -279,7 +278,7 @@ export const WEBKITGTK_FFI_SYMBOLS = { }, } as const; -const cache: { ffi: ReturnType> | undefined } = { +const cache: { ffi: ReturnType> | undefined } = { ffi: undefined, }; @@ -293,12 +292,7 @@ export const loadWebKitGtkFFI = () => { if (cache.ffi) { return cache.ffi; } - // Resolve the pinned engine (if any) before dlopen, so a `bunmaska build`-baked - // engine-id loads its own WebKitGTK from the shared store instead of the - // system soname. System mode (the default) passes the bare soname through. - const engine = resolveEngine(); - prepareEngineForLoad(engine, process.env, (text) => process.stderr.write(text)); - const ffi = dlopen(engineLibPath(engine, LIBWEBKITGTK_PATH), WEBKITGTK_FFI_SYMBOLS); + const ffi = dlopenLinux(LIBWEBKITGTK_PATH, WEBKITGTK_FFI_SYMBOLS); cache.ffi = ffi; return ffi; }; diff --git a/src/main/platform/linux/x11-ffi.ts b/src/main/platform/linux/x11-ffi.ts index ee3cb88c..e0f8bedc 100644 --- a/src/main/platform/linux/x11-ffi.ts +++ b/src/main/platform/linux/x11-ffi.ts @@ -1,7 +1,7 @@ import { FFIType } from 'bun:ffi'; -import { dlopen } from '../dlopen'; import { UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; +import { dlopenLinux } from './glib-ffi'; /** * Xlib FFI for the Linux `globalShortcut` backend (`XGrabKey`). @@ -62,7 +62,7 @@ export const X11_FFI_SYMBOLS = { XSetErrorHandler: { args: [FFIType.pointer], returns: FFIType.pointer }, } as const; -const cache: { ffi: ReturnType> | undefined } = { +const cache: { ffi: ReturnType> | undefined } = { ffi: undefined, }; @@ -77,7 +77,7 @@ export const loadX11FFI = () => { if (cache.ffi) { return cache.ffi; } - const ffi = dlopen(LIBX11_PATH, X11_FFI_SYMBOLS); + const ffi = dlopenLinux(LIBX11_PATH, X11_FFI_SYMBOLS); cache.ffi = ffi; return ffi; }; diff --git a/tests/unit/main/platform/linux/glib-ffi.test.ts b/tests/unit/main/platform/linux/glib-ffi.test.ts new file mode 100644 index 00000000..2a29ab0c --- /dev/null +++ b/tests/unit/main/platform/linux/glib-ffi.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, test } from 'bun:test'; +import { join } from 'node:path'; +import type { EngineResolution } from '../../../../../src/main/engine/resolve'; +import { linuxLibPath } from '../../../../../src/main/platform/linux/glib-ffi'; + +const SONAME = 'libglib-2.0.so.0'; +const LIB_DIR = join('/store', 'engine', 'lib'); +const BUNDLED = join(LIB_DIR, SONAME); +const pinned: EngineResolution = { mode: 'pinned', libDir: LIB_DIR, warnings: [] }; +const system: EngineResolution = { mode: 'system', warnings: [] }; + +describe('linuxLibPath', () => { + test('a pinned engine that bundles the library loads the bundled copy', () => { + expect(linuxLibPath(pinned, SONAME, (path) => path === BUNDLED)).toBe(BUNDLED); + }); + + test('a pinned engine without the library falls back to the system soname', () => { + expect(linuxLibPath(pinned, SONAME, () => false)).toBe(SONAME); + }); + + test('system mode loads the system soname', () => { + expect(linuxLibPath(system, SONAME, (path) => path === BUNDLED)).toBe(SONAME); + }); +}); diff --git a/tests/unit/main/platform/linux/linux-ffi-abi.test.ts b/tests/unit/main/platform/linux/linux-ffi-abi.test.ts index 3345e0b9..c3879560 100644 --- a/tests/unit/main/platform/linux/linux-ffi-abi.test.ts +++ b/tests/unit/main/platform/linux/linux-ffi-abi.test.ts @@ -30,6 +30,7 @@ import { LIBNOTIFY_FFI_SYMBOLS, loadLibnotifyFFI, } from '../../../../../src/main/platform/linux/libnotify-ffi'; +import { loadLibsecretFFI } from '../../../../../src/main/platform/linux/libsecret-ffi'; import { loadSoupFFI, SOUP_FFI_SYMBOLS } from '../../../../../src/main/platform/linux/soup-ffi'; import { loadWebKitGtkFFI, @@ -37,6 +38,7 @@ import { WEBKIT_LOAD_FINISHED, WEBKITGTK_FFI_SYMBOLS, } from '../../../../../src/main/platform/linux/webkitgtk-ffi'; +import { loadX11FFI } from '../../../../../src/main/platform/linux/x11-ffi'; /** * The Linux FFI declarations that a reviewer would plausibly get WRONG. Restating a @@ -213,8 +215,10 @@ const LOADERS: ReadonlyArray unknown]> = [ ['loadGtkMenuFFI', loadGtkMenuFFI], ['loadJscFFI', loadJscFFI], ['loadLibnotifyFFI', loadLibnotifyFFI], + ['loadLibsecretFFI', loadLibsecretFFI], ['loadWebKitGtkFFI', loadWebKitGtkFFI], ['loadSoupFFI', loadSoupFFI], + ['loadX11FFI', loadX11FFI], ]; test.skipIf(currentPlatform() === 'linux')( From b9ca42b481d087d3e2388670787b9704691d84be Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:15:30 -0700 Subject: [PATCH 185/586] fix: clip negative-origin crop rects to the image intersection --- src/main/api/native-image.ts | 10 +++++----- tests/unit/main/api/native-image.test.ts | 8 ++++++++ 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/src/main/api/native-image.ts b/src/main/api/native-image.ts index a8e470bf..bfd09ade 100644 --- a/src/main/api/native-image.ts +++ b/src/main/api/native-image.ts @@ -73,16 +73,16 @@ export const resolveResizeDimensions = ( return { width: srcW, height: srcH }; // both omitted → unchanged size }; -/** `undefined` when the clamped rect is empty. */ +/** The rect's intersection with the image; `undefined` when empty. */ export const clampCropRect = ( imgW: number, imgH: number, rect: { x: number; y: number; width: number; height: number }, ): { x: number; y: number; width: number; height: number } | undefined => { - const x = Math.max(0, Math.min(Math.round(rect.x), imgW)); - const y = Math.max(0, Math.min(Math.round(rect.y), imgH)); - const width = Math.min(Math.round(rect.width), imgW - x); - const height = Math.min(Math.round(rect.height), imgH - y); + const x = Math.max(0, Math.round(rect.x)); + const y = Math.max(0, Math.round(rect.y)); + const width = Math.min(imgW, Math.round(rect.x) + Math.round(rect.width)) - x; + const height = Math.min(imgH, Math.round(rect.y) + Math.round(rect.height)) - y; if (width <= 0 || height <= 0) { return undefined; } diff --git a/tests/unit/main/api/native-image.test.ts b/tests/unit/main/api/native-image.test.ts index da78c474..95b44145 100644 --- a/tests/unit/main/api/native-image.test.ts +++ b/tests/unit/main/api/native-image.test.ts @@ -116,6 +116,14 @@ describe('resolveResizeDimensions / clampCropRect (pure)', () => { }); expect(clampCropRect(100, 50, { x: 200, y: 0, width: 10, height: 10 })).toBeUndefined(); }); + test('clamp: a negative origin clips to the intersection instead of shifting', () => { + expect(clampCropRect(100, 50, { x: -10, y: -5, width: 20, height: 10 })).toEqual({ + x: 0, + y: 0, + width: 10, + height: 5, + }); + }); }); describe('NativeImage.getAspectRatio', () => { From 1ca20811e1a6b761e7562c16e6de69f7e182b852 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:15:30 -0700 Subject: [PATCH 186/586] fix: refuse a bare-soname dlopen that Bun would retry from the cwd --- src/main/platform/linux/glib-ffi.ts | 13 ++++++++++++- tests/unit/main/platform/linux/glib-ffi.test.ts | 6 ++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/main/platform/linux/glib-ffi.ts b/src/main/platform/linux/glib-ffi.ts index 9a3b35ef..8b5faff1 100644 --- a/src/main/platform/linux/glib-ffi.ts +++ b/src/main/platform/linux/glib-ffi.ts @@ -1,5 +1,6 @@ import { type FFIFunction, FFIType } from 'bun:ffi'; import { existsSync } from 'node:fs'; +import { join } from 'node:path'; import { UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; import { @@ -32,9 +33,19 @@ export const linuxLibPath = ( engine: EngineResolution, soname: string, exists: (path: string) => boolean = existsSync, + cwd: string = process.cwd(), ): string => { const bundled = engineLibPath(engine, soname); - return bundled !== soname && exists(bundled) ? bundled : soname; + if (bundled !== soname && exists(bundled)) { + return bundled; + } + // Bun retries a failed bare-name dlopen as /, which would run a planted library. + if (exists(join(cwd, soname))) { + throw new Error( + `refusing to dlopen ${soname}: a file of that name is in the working directory`, + ); + } + return soname; }; /** diff --git a/tests/unit/main/platform/linux/glib-ffi.test.ts b/tests/unit/main/platform/linux/glib-ffi.test.ts index 2a29ab0c..6d22a5ce 100644 --- a/tests/unit/main/platform/linux/glib-ffi.test.ts +++ b/tests/unit/main/platform/linux/glib-ffi.test.ts @@ -6,6 +6,7 @@ import { linuxLibPath } from '../../../../../src/main/platform/linux/glib-ffi'; const SONAME = 'libglib-2.0.so.0'; const LIB_DIR = join('/store', 'engine', 'lib'); const BUNDLED = join(LIB_DIR, SONAME); +const CWD = join('/home', 'user', 'project'); const pinned: EngineResolution = { mode: 'pinned', libDir: LIB_DIR, warnings: [] }; const system: EngineResolution = { mode: 'system', warnings: [] }; @@ -21,4 +22,9 @@ describe('linuxLibPath', () => { test('system mode loads the system soname', () => { expect(linuxLibPath(system, SONAME, (path) => path === BUNDLED)).toBe(SONAME); }); + + test('a bare soname is refused when a file of that name sits in the working directory', () => { + const planted = (path: string) => path === join(CWD, SONAME); + expect(() => linuxLibPath(system, SONAME, planted, CWD)).toThrow(/working directory/); + }); }); From 30fbec3db3108a05c29ad8bc27869e79f2d84492 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:15:31 -0700 Subject: [PATCH 187/586] fix: adopt the race winner when two apps create the safeStorage key --- .../platform/windows/windows-safe-storage.ts | 40 ++++++++++++++----- .../windows/windows-safe-storage.test.ts | 39 ++++++++++++++++++ 2 files changed, 68 insertions(+), 11 deletions(-) create mode 100644 tests/unit/main/platform/windows/windows-safe-storage.test.ts diff --git a/src/main/platform/windows/windows-safe-storage.ts b/src/main/platform/windows/windows-safe-storage.ts index 932b7e06..b882ceba 100644 --- a/src/main/platform/windows/windows-safe-storage.ts +++ b/src/main/platform/windows/windows-safe-storage.ts @@ -1,6 +1,6 @@ import { type Pointer, ptr, read, toArrayBuffer } from 'bun:ffi'; import { randomBytes } from 'node:crypto'; -import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { existsSync, linkSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs'; import { homedir } from 'node:os'; import { dirname, join } from 'node:path'; import { FFIError } from '../../../common/errors'; @@ -95,18 +95,36 @@ export const dpapiUnprotect = (data: Uint8Array): Uint8Array => 'CryptUnprotectData', ); +/** + * Read the sealed key at `path`, creating it on first use. The key file is shared by every + * Bunmaska app of the user, so a first run publishes with an exclusive hard link and then + * reads back whichever key won (D036): overwriting would orphan the loser's ciphertexts. + */ +export const loadOrCreateSealedKey = ( + path: string, + seal: (key: Uint8Array) => Uint8Array, + unseal: (sealed: Uint8Array) => Uint8Array, +): Buffer => { + if (!existsSync(path)) { + mkdirSync(dirname(path), { recursive: true }); + const staged = `${path}.${process.pid}.tmp`; + writeFileSync(staged, seal(randomBytes(KEY_LENGTH))); + try { + linkSync(staged, path); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'EEXIST') { + throw error; + } + } finally { + unlinkSync(staged); + } + } + return Buffer.from(unseal(readFileSync(path))); +}; + export const windowsDpapiBackend: KeyringBackend = { // DPAPI ships with every Windows install — the key can always be sealed. isAvailable: (): boolean => true, - getOrCreateKey: (): Buffer => { - const path = keyFilePath(); - if (existsSync(path)) { - return Buffer.from(dpapiUnprotect(readFileSync(path))); - } - const key = randomBytes(KEY_LENGTH); - mkdirSync(dirname(path), { recursive: true }); - writeFileSync(path, dpapiProtect(key)); - return key; - }, + getOrCreateKey: (): Buffer => loadOrCreateSealedKey(keyFilePath(), dpapiProtect, dpapiUnprotect), }; diff --git a/tests/unit/main/platform/windows/windows-safe-storage.test.ts b/tests/unit/main/platform/windows/windows-safe-storage.test.ts new file mode 100644 index 00000000..4c19f9a7 --- /dev/null +++ b/tests/unit/main/platform/windows/windows-safe-storage.test.ts @@ -0,0 +1,39 @@ +import { afterEach, describe, expect, test } from 'bun:test'; +import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { loadOrCreateSealedKey } from '../../../../../src/main/platform/windows/windows-safe-storage'; + +const identity = (bytes: Uint8Array): Uint8Array => bytes; + +describe('loadOrCreateSealedKey', () => { + let dir: string | undefined; + + afterEach(() => { + if (dir !== undefined) { + rmSync(dir, { recursive: true, force: true }); + } + }); + + test('creates a 32-byte key on first use and reads the same key back', () => { + dir = mkdtempSync(join(tmpdir(), 'bunmaska-key-')); + const path = join(dir, 'home', 'safestorage.key'); + const first = loadOrCreateSealedKey(path, identity, identity); + expect(first).toHaveLength(32); + expect(loadOrCreateSealedKey(path, identity, identity)).toEqual(first); + }); + + test('adopts the key a concurrent first run stored, leaving no temp file behind', () => { + dir = mkdtempSync(join(tmpdir(), 'bunmaska-key-')); + const path = join(dir, 'safestorage.key'); + const winner = Buffer.alloc(32, 7); + // Another process lands its key while this one is still sealing its own. + const racingSeal = (key: Uint8Array): Uint8Array => { + writeFileSync(path, winner); + return key; + }; + expect(loadOrCreateSealedKey(path, racingSeal, identity)).toEqual(winner); + expect(readFileSync(path)).toEqual(winner); + expect(readdirSync(dir)).toEqual(['safestorage.key']); + }); +}); From 294c37328efb34c4b3b24fcb200ce4c41c4fde7c Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:15:39 -0700 Subject: [PATCH 188/586] fix: stage updates in a private temp dir instead of a guessable path --- src/main/api/auto-updater.ts | 9 +++++---- src/main/api/update-installer.ts | 5 ++--- tests/unit/main/api/auto-updater.test.ts | 20 ++++++++++++++++++++ tests/unit/main/api/update-installer.test.ts | 6 +++--- 4 files changed, 30 insertions(+), 10 deletions(-) diff --git a/src/main/api/auto-updater.ts b/src/main/api/auto-updater.ts index d0590c01..c0534eb9 100644 --- a/src/main/api/auto-updater.ts +++ b/src/main/api/auto-updater.ts @@ -1,5 +1,5 @@ import { EventEmitter } from 'node:events'; -import { writeFileSync } from 'node:fs'; +import { mkdtempSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { @@ -70,7 +70,7 @@ export type UpdateInfo = { export type StagedUpdate = { readonly manifest: UpdateManifest; - /** Path to the decompressed `.tar` on disk. */ + /** The decompressed `.tar`, alone in a private directory the default installer writes its helper into. */ readonly tarPath: string; }; @@ -120,8 +120,9 @@ const markHandled = (promise: Promise): Promise => { return promise; }; -const stageToTmp = async (tarBytes: Uint8Array, manifest: UpdateManifest): Promise => { - const tarPath = join(tmpdir(), `bunmaska-update-${manifest.hash}.tar`); +/** A fresh 0700 dir: a guessable name in a shared /tmp lets another user swap the verified tar. */ +export const stageToTmp = async (tarBytes: Uint8Array): Promise => { + const tarPath = join(mkdtempSync(join(tmpdir(), 'bunmaska-update-')), 'update.tar'); writeFileSync(tarPath, tarBytes); return tarPath; }; diff --git a/src/main/api/update-installer.ts b/src/main/api/update-installer.ts index 70f53f75..ea622cd6 100644 --- a/src/main/api/update-installer.ts +++ b/src/main/api/update-installer.ts @@ -6,7 +6,6 @@ */ import { chmodSync, writeFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; import { basename, dirname, join } from 'node:path'; import type { ArtifactOs } from '../../common/manifest'; import { currentPlatform } from '../../common/platform'; @@ -173,7 +172,7 @@ export const installStagedUpdate = (staged: StagedUpdate, deps: InstallerDeps): const bundleDirName = stagedBundleDirName(staged.manifest.name, os); const pid = deps.pid(); if (os === 'windows') { - const scriptPath = join(tmpdir(), `bunmaska-install-${staged.manifest.hash}.cmd`); + const scriptPath = join(dirname(staged.tarPath), 'install.cmd'); deps.writeScript( scriptPath, buildCmdInstallScript({ @@ -186,7 +185,7 @@ export const installStagedUpdate = (staged: StagedUpdate, deps: InstallerDeps): ); deps.spawnDetached(['cmd.exe', '/c', scriptPath]); } else { - const scriptPath = join(tmpdir(), `bunmaska-install-${staged.manifest.hash}.sh`); + const scriptPath = join(dirname(staged.tarPath), 'install.sh'); const relaunchArgv = os === 'macos' ? ['open', installRoot] : [execPath]; deps.writeScript( scriptPath, diff --git a/tests/unit/main/api/auto-updater.test.ts b/tests/unit/main/api/auto-updater.test.ts index 891a693b..9b78706d 100644 --- a/tests/unit/main/api/auto-updater.test.ts +++ b/tests/unit/main/api/auto-updater.test.ts @@ -1,4 +1,6 @@ import { describe, expect, test } from 'bun:test'; +import { readFileSync, rmSync, statSync } from 'node:fs'; +import { dirname } from 'node:path'; import { assertSizeWithin, AutoUpdaterImpl, @@ -6,6 +8,7 @@ import { MAX_COMPRESSED_ARTIFACT_BYTES, MAX_DECOMPRESSED_TAR_BYTES, type StagedUpdate, + stageToTmp, } from '../../../../src/main/api/auto-updater'; import { contentHash, @@ -330,3 +333,20 @@ describe('autoUpdater.quitAndInstall', () => { expect(h.staged[0]?.manifest.version).toBe('2.0.0'); }); }); + +describe('stageToTmp', () => { + test('writes the tar into a fresh private directory, never a guessable shared path', async () => { + const a = await stageToTmp(TAR); + const b = await stageToTmp(TAR); + try { + expect(dirname(a)).not.toBe(dirname(b)); + expect(new Uint8Array(readFileSync(a))).toEqual(TAR); + if (process.platform !== 'win32') { + expect(statSync(dirname(a)).mode & 0o777).toBe(0o700); + } + } finally { + rmSync(dirname(a), { recursive: true, force: true }); + rmSync(dirname(b), { recursive: true, force: true }); + } + }); +}); diff --git a/tests/unit/main/api/update-installer.test.ts b/tests/unit/main/api/update-installer.test.ts index 9228d594..71c1c1ba 100644 --- a/tests/unit/main/api/update-installer.test.ts +++ b/tests/unit/main/api/update-installer.test.ts @@ -28,7 +28,7 @@ const manifest = (name: string): UpdateManifest => ({ const staged = (name = 'My App'): StagedUpdate => ({ manifest: manifest(name), - tarPath: '/tmp/bunmaska-update-abc123.tar', + tarPath: '/tmp/bunmaska-update-Xy12/update.tar', }); describe('deriveInstallRoot', () => { @@ -258,7 +258,7 @@ describe('installStagedUpdate', () => { installStagedUpdate(staged(), h.deps); expect(h.scripts).toHaveLength(1); const script = h.scripts[0]; - expect(script?.path.endsWith('.sh')).toBe(true); + expect(script?.path).toBe(join('/tmp/bunmaska-update-Xy12', 'install.sh')); expect(script?.text).toContain("'open' '/Applications/My App.app' &"); expect(script?.text).toContain("mv '/Applications/My App.app'"); expect(h.spawns).toEqual([['/bin/sh', script?.path ?? '']]); @@ -276,7 +276,7 @@ describe('installStagedUpdate', () => { const h = makeDeps('/apps/My App/My App.exe', 'windows'); installStagedUpdate(staged(), h.deps); const script = h.scripts[0]; - expect(script?.path.endsWith('.cmd')).toBe(true); + expect(script?.path).toBe(join('/tmp/bunmaska-update-Xy12', 'install.cmd')); expect(h.spawns).toEqual([['cmd.exe', '/c', script?.path ?? '']]); expect(h.quits).toHaveLength(1); }); From d14512f86210542a2a12d2874054b8d8453e1749 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:15:43 -0700 Subject: [PATCH 189/586] fix: give each Linux tray its own D-Bus object path --- src/main/platform/linux/linux-dbus.ts | 6 ------ src/main/platform/linux/sni-tray.ts | 27 ++++++++++++++------------- 2 files changed, 14 insertions(+), 19 deletions(-) diff --git a/src/main/platform/linux/linux-dbus.ts b/src/main/platform/linux/linux-dbus.ts index 3dbd445d..0d18c065 100644 --- a/src/main/platform/linux/linux-dbus.ts +++ b/src/main/platform/linux/linux-dbus.ts @@ -271,12 +271,6 @@ export const unregisterObject = (conn: Pointer, registrationId: number): void => loadGDBusFFI().symbols.g_dbus_connection_unregister_object(conn, registrationId); }; -/** The connection's unique bus name (e.g. `":1.42"`), or null. */ -export const getUniqueName = (conn: Pointer): string | null => { - const name = loadGDBusFFI().symbols.g_dbus_connection_get_unique_name(conn); - return name === null ? null : name.toString(); -}; - /** * Broadcast a signal from `objectPath`/`iface`. `parameters` (a floating GVariant, or null * for an argument-less signal) is CONSUMED. diff --git a/src/main/platform/linux/sni-tray.ts b/src/main/platform/linux/sni-tray.ts index c68f3aa7..5e13a79f 100644 --- a/src/main/platform/linux/sni-tray.ts +++ b/src/main/platform/linux/sni-tray.ts @@ -14,7 +14,6 @@ import { loadGObjectFFI } from './gobject-ffi'; import { callMethodSync, emitSignal, - getUniqueName, nodeInfoLookupInterface, nodeInfoNewForXml, probeSessionBusUnchecked, @@ -46,7 +45,7 @@ import { * in linux-dbus.ts) or the host's queries dispatch to a context nothing iterates. */ -const OBJECT_PATH = '/StatusNotifierItem'; +const OBJECT_PATH_PREFIX = '/StatusNotifierItem'; const SNI_IFACE = 'org.kde.StatusNotifierItem'; const WATCHER_NAME = 'org.kde.StatusNotifierWatcher'; const WATCHER_PATH = '/StatusNotifierWatcher'; @@ -257,9 +256,13 @@ const getPropertyValue = (state: State, name: string): Pointer | null => { } }; +let trayCount = 0; + /** Build + register the live SNI object; returns a `TrayInstance`, or null on any failure. */ const createLive = (conn: Pointer, initialImage: string): TrayInstance | null => { const gdbus = loadGDBusFFI(); + // One object path per tray: a second registration at a shared path fails on one connection. + const objectPath = `${OBJECT_PATH_PREFIX}/${trayCount++}`; const node = nodeInfoNewForXml(SNI_XML); if (node === null) { return null; // malformed XML — never crash (guard the NULL deref). @@ -313,21 +316,19 @@ const createLive = (conn: Pointer, initialImage: string): TrayInstance | null => vtable[1] = BigInt(gpPtr); vtable[2] = BigInt(spPtr); - const regId = registerObject(conn, OBJECT_PATH, iface, ptr(vtable)); + const regId = registerObject(conn, objectPath, iface, ptr(vtable)); if (regId === 0) { return null; } retained.callbacks.push(methodCall, getProp, setProp); // load-bearing: the vtable copy points here. retained.misc.push(node, vtable); - // Register with the watcher via the bounded method call. The watcher reads our sender's - // unique name, so g_bus_own_name is unnecessary. Absent watcher ⇒ fast null ⇒ icon - // simply doesn't appear (no hang). - const uniqueName = getUniqueName(conn); + // Registered by object path: the watcher pairs it with our sender's unique name (the + // libappindicator form). Absent watcher => fast null => the icon simply doesn't appear. const g = loadGlibFFI().symbols; - const nameVariant = uniqueName === null ? null : g.g_variant_new_string(cstr(uniqueName)); - if (nameVariant !== null) { - const args = g.g_variant_new_tuple(ptr(new BigUint64Array([BigInt(nameVariant)])), 1n); + const pathVariant = g.g_variant_new_string(cstr(objectPath)); + if (pathVariant !== null) { + const args = g.g_variant_new_tuple(ptr(new BigUint64Array([BigInt(pathVariant)])), 1n); callMethodSync( conn, WATCHER_NAME, @@ -342,15 +343,15 @@ const createLive = (conn: Pointer, initialImage: string): TrayInstance | null => return { setToolTip: (toolTip) => { state.toolTip = toolTip; - emitSignal(conn, OBJECT_PATH, SNI_IFACE, 'NewToolTip', null); + emitSignal(conn, objectPath, SNI_IFACE, 'NewToolTip', null); }, setTitle: (title) => { state.title = title; - emitSignal(conn, OBJECT_PATH, SNI_IFACE, 'NewTitle', null); + emitSignal(conn, objectPath, SNI_IFACE, 'NewTitle', null); }, setImage: (image) => { state.icon = decodeIcon(image); - emitSignal(conn, OBJECT_PATH, SNI_IFACE, 'NewIcon', null); // argument-less; host re-fetches. + emitSignal(conn, objectPath, SNI_IFACE, 'NewIcon', null); // argument-less; host re-fetches. }, setContextMenu: () => undefined, // deferred: dbusmenu is a follow-up (soft no-op, never throws). onClick: (callback) => { From 0323db58ac5be3e11290f90cf772ec475b76097a Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:15:48 -0700 Subject: [PATCH 190/586] fix: decode percent-encoded data URLs byte-wise and allow destructuring --- src/main/api/native-image.ts | 14 ++++++++++---- tests/unit/main/api/native-image.test.ts | 16 ++++++++++++++++ 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/src/main/api/native-image.ts b/src/main/api/native-image.ts index bfd09ade..ad912a55 100644 --- a/src/main/api/native-image.ts +++ b/src/main/api/native-image.ts @@ -225,14 +225,20 @@ export const nativeImage = { createFromDataURL(dataURL: string): NativeImage { const comma = dataURL.indexOf(','); if (comma === -1 || !dataURL.startsWith('data:')) { - return this.createEmpty(); + return nativeImage.createEmpty(); } const meta = dataURL.slice('data:'.length, comma); const payload = dataURL.slice(comma + 1); + // Percent-escapes are raw bytes: decodeURIComponent throws on non-UTF-8 like `%89`. const bytes = meta.includes(';base64') - ? new Uint8Array(Buffer.from(payload, 'base64')) - : new TextEncoder().encode(decodeURIComponent(payload)); - return this.createFromBuffer(bytes); + ? Buffer.from(payload, 'base64') + : Buffer.from( + payload.replace(/%([0-9a-f]{2})/gi, (_, hex: string) => + String.fromCharCode(Number.parseInt(hex, 16)), + ), + 'latin1', + ); + return nativeImage.createFromBuffer(new Uint8Array(bytes)); }, /** No native decode is performed. */ createEmpty(): NativeImage { diff --git a/tests/unit/main/api/native-image.test.ts b/tests/unit/main/api/native-image.test.ts index 95b44145..497d661b 100644 --- a/tests/unit/main/api/native-image.test.ts +++ b/tests/unit/main/api/native-image.test.ts @@ -305,4 +305,20 @@ describe('nativeImage.createFromDataURL', () => { expect(nativeImage.createFromDataURL('not-a-data-url').isEmpty()).toBe(true); expect(decodeCalls).toHaveLength(0); }); + + test('a percent-encoded payload decodes byte-wise, including non-UTF-8 bytes', () => { + setNativeImageBackendForTesting( + makeFakeBackend({ handle: 1n, width: 1, height: 1, empty: false }, new Uint8Array([1])), + ); + nativeImage.createFromDataURL('data:image/png,%89PNG%0D%0A'); + expect(decodeCalls[0]?.source).toEqual(new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a])); + }); + + test('works when destructured off the module, as Electron code does', () => { + setNativeImageBackendForTesting( + makeFakeBackend({ handle: 1n, width: 1, height: 1, empty: false }, new Uint8Array([1])), + ); + const { createFromDataURL } = nativeImage; + expect(createFromDataURL('nope').isEmpty()).toBe(true); + }); }); From e52d6c82fedb1cfb195d6418145e17faed43b54c Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:16:01 -0700 Subject: [PATCH 191/586] fix: complete the Windows script message reply after delivery --- src/main/platform/windows/webkit2-ffi.ts | 5 +- .../platform/windows/windows-webkit-view.ts | 30 ++++++--- .../windows/windows-webkit-view.test.ts | 61 +++++++++++++------ 3 files changed, 68 insertions(+), 28 deletions(-) diff --git a/src/main/platform/windows/webkit2-ffi.ts b/src/main/platform/windows/webkit2-ffi.ts index 9252a737..6fb9bbef 100644 --- a/src/main/platform/windows/webkit2-ffi.ts +++ b/src/main/platform/windows/webkit2-ffi.ts @@ -69,7 +69,8 @@ const WEBKIT2_SYMBOLS = { returns: FFIType.void, }, WKUserContentControllerRemoveAllUserScripts: { args: [FFIType.ptr], returns: FFIType.void }, - // (ucc, WKStringRef name, WKScriptMessageHandlerCallback, const void* context) + // (ucc, WKStringRef name, callback, const void* context); the callback is + // (WKScriptMessageRef, WKCompletionListenerRef reply, const void* context). WKUserContentControllerAddScriptMessageHandler: { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.ptr], returns: FFIType.void, @@ -86,6 +87,8 @@ const WEBKIT2_SYMBOLS = { WKScriptMessageGetBody: { args: [FFIType.ptr], returns: FFIType.ptr }, WKScriptMessageGetFrameInfo: { args: [FFIType.ptr], returns: FFIType.ptr }, WKFrameInfoGetIsMainFrame: { args: [FFIType.ptr], returns: FFIType.bool }, + // (WKCompletionListenerRef, WKTypeRef reply): NULL resolves the page's postMessage promise. + WKCompletionListenerComplete: { args: [FFIType.ptr, FFIType.ptr], returns: FFIType.void }, // ── Strings / URLs ─────────────────────────────────────────────────────── // WKTypeID is uint32_t. diff --git a/src/main/platform/windows/windows-webkit-view.ts b/src/main/platform/windows/windows-webkit-view.ts index 5944e5fa..519c60b7 100644 --- a/src/main/platform/windows/windows-webkit-view.ts +++ b/src/main/platform/windows/windows-webkit-view.ts @@ -162,23 +162,32 @@ type ScriptMessageApi = Pick< | 'WKFrameInfoGetIsMainFrame' | 'WKGetTypeID' | 'WKStringGetTypeID' + | 'WKCompletionListenerComplete' >; -/** Forward a main-frame script message's string body to `onMessage`. */ +/** Forward a main-frame script message's string body to `onMessage`, then complete its reply. */ export const deliverScriptMessage = ( message: Pointer, + listener: Pointer | null, onMessage: (body: string) => void, wk: ScriptMessageApi = loadWebKit2().symbols, readString: (ref: Pointer) => string = wkStringToJs, ): void => { - // The handlers live in the page world, so any iframe could post to the bridge. - if (!wk.WKFrameInfoGetIsMainFrame(wk.WKScriptMessageGetFrameInfo(message))) { - return; - } - const body = wk.WKScriptMessageGetBody(message); - // Any page script can post a number/bool/object; reading that as a WKString faults the process. - if (body !== null && wk.WKGetTypeID(body) === wk.WKStringGetTypeID()) { - onMessage(readString(body)); + try { + // The handlers live in the page world, so any iframe could post to the bridge. + if (!wk.WKFrameInfoGetIsMainFrame(wk.WKScriptMessageGetFrameInfo(message))) { + return; + } + const body = wk.WKScriptMessageGetBody(message); + // Any page script can post a number/bool/object; reading that as a WKString faults the process. + if (body !== null && wk.WKGetTypeID(body) === wk.WKStringGetTypeID()) { + onMessage(readString(body)); + } + } finally { + // An unanswered reply pins the posting document's global object in the WebContent process. + if (listener !== null) { + wk.WKCompletionListenerComplete(listener, null); + } } }; @@ -244,7 +253,8 @@ export class WindowsWebView { const callbacks: JSCallback[] = []; for (const handler of options.messageHandlers) { const callback = new JSCallback( - (messageRef: Pointer) => deliverScriptMessage(messageRef, handler.onMessage, s), + (messageRef: Pointer, listenerRef: Pointer | null) => + deliverScriptMessage(messageRef, listenerRef, handler.onMessage, s), { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr], returns: FFIType.void }, ); if (callback.ptr === null) { diff --git a/tests/unit/main/platform/windows/windows-webkit-view.test.ts b/tests/unit/main/platform/windows/windows-webkit-view.test.ts index 1b0e55b2..e289681f 100644 --- a/tests/unit/main/platform/windows/windows-webkit-view.test.ts +++ b/tests/unit/main/platform/windows/windows-webkit-view.test.ts @@ -2,29 +2,37 @@ import type { Pointer } from 'bun:ffi'; import { describe, expect, test } from 'bun:test'; import { deliverScriptMessage } from '../../../../../src/main/platform/windows/windows-webkit-view'; -type ScriptMessageApi = NonNullable[2]>; +type ScriptMessageApi = NonNullable[3]>; const MESSAGE = 0x10 as Pointer; const BODY = 0x20 as Pointer; +const FRAME = 0x30 as Pointer; +const LISTENER = 0x40 as Pointer; const STRING_TYPE = 7; const DOUBLE_TYPE = 9; -const FRAME = 0x30 as Pointer; - -const fakeWk = (bodyType: number, isMainFrame = true): ScriptMessageApi => ({ - WKScriptMessageGetBody: () => BODY, - WKScriptMessageGetFrameInfo: () => FRAME, - WKFrameInfoGetIsMainFrame: (frame) => frame === FRAME && isMainFrame, - WKGetTypeID: () => bodyType, - WKStringGetTypeID: () => STRING_TYPE, -}); +const fakeWk = (bodyType: number, isMainFrame = true) => { + const completed: unknown[] = []; + const api: ScriptMessageApi = { + WKScriptMessageGetBody: () => BODY, + WKScriptMessageGetFrameInfo: () => FRAME, + WKFrameInfoGetIsMainFrame: (frame) => frame === FRAME && isMainFrame, + WKGetTypeID: () => bodyType, + WKStringGetTypeID: () => STRING_TYPE, + WKCompletionListenerComplete: (listener) => { + completed.push(listener); + }, + }; + return { api, completed }; +}; const readBody = (ref: Pointer): string => (ref === BODY ? '{"ping":"pong"}' : 'wrong ref'); describe('deliverScriptMessage', () => { test('forwards a string body to the handler', () => { const received: string[] = []; - deliverScriptMessage(MESSAGE, (body) => received.push(body), fakeWk(STRING_TYPE), readBody); + const { api } = fakeWk(STRING_TYPE); + deliverScriptMessage(MESSAGE, LISTENER, (body) => received.push(body), api, readBody); expect(received).toEqual(['{"ping":"pong"}']); }); @@ -33,18 +41,37 @@ describe('deliverScriptMessage', () => { const readAsString = (): string => { throw new Error('read a non-string body as a WKString'); }; - deliverScriptMessage(MESSAGE, (body) => received.push(body), fakeWk(DOUBLE_TYPE), readAsString); + const { api } = fakeWk(DOUBLE_TYPE); + deliverScriptMessage(MESSAGE, LISTENER, (body) => received.push(body), api, readAsString); expect(received).toEqual([]); }); test('drops a message posted from a subframe', () => { const received: string[] = []; - deliverScriptMessage( - MESSAGE, - (body) => received.push(body), + const { api } = fakeWk(STRING_TYPE, false); + deliverScriptMessage(MESSAGE, LISTENER, (body) => received.push(body), api, readBody); + expect(received).toEqual([]); + }); + + test('completes the reply whether the message is delivered or dropped', () => { + for (const { api, completed } of [ + fakeWk(STRING_TYPE), + fakeWk(DOUBLE_TYPE), fakeWk(STRING_TYPE, false), - readBody, + ]) { + deliverScriptMessage(MESSAGE, LISTENER, () => undefined, api, readBody); + expect(completed).toEqual([LISTENER]); + } + }); + + test('completes the reply when the handler throws', () => { + const { api, completed } = fakeWk(STRING_TYPE); + const throwing = (): void => { + throw new Error('handler failed'); + }; + expect(() => deliverScriptMessage(MESSAGE, LISTENER, throwing, api, readBody)).toThrow( + 'handler failed', ); - expect(received).toEqual([]); + expect(completed).toEqual([LISTENER]); }); }); From 0a326a18fab909137c23cdc1deaba6886c1ba768 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:16:01 -0700 Subject: [PATCH 192/586] test: drive a faked keypress through the X11 shortcut poll --- .../linux/x11-global-shortcut.test.ts | 165 +++++++++--------- 1 file changed, 87 insertions(+), 78 deletions(-) diff --git a/tests/integration/linux/x11-global-shortcut.test.ts b/tests/integration/linux/x11-global-shortcut.test.ts index f125db8d..350952d8 100644 --- a/tests/integration/linux/x11-global-shortcut.test.ts +++ b/tests/integration/linux/x11-global-shortcut.test.ts @@ -9,26 +9,32 @@ import { import { loadX11FFI } from '../../../src/main/platform/linux/x11-ffi'; import { CONTROL_MASK, SHIFT_MASK } from '../../../src/main/platform/linux/x11-keymap'; -/** - * Linux-only. Exercises the REAL Xlib `XGrabKey` path. Needs an X server — under - * `xvfb-run bun test` `XOpenDisplay` succeeds; on a host with no `$DISPLAY` the - * backend honestly reports `isSupported() === false` and every test that needs a - * display is skipped, NOT faked. - * - * Triggering a real KeyPress is not done here (it would need XTEST/XInput and a - * grabbed focus); we assert the grab lifecycle runs without throwing and that the - * poll drains cleanly. Wayland is out of scope (XGrabKey is X11-only). - */ -const isLinux = currentPlatform() === 'linux'; - -/** XSync is not in the backend's table; a second client needs it to order its grab first. */ +const hasDisplay = currentPlatform() === 'linux' && linuxGlobalShortcutBackend.isSupported(); + +/** XSync is not in the backend's table; a second client needs it to order its requests. */ const xSync = (dpy: Pointer): void => { dlopen('libX11.so.6', { XSync: { args: [FFIType.pointer, FFIType.i32], returns: FFIType.i32 }, }).symbols.XSync(dpy, 0); }; -/** Open a second X client, independent of the backend's grab connection. */ +const loadXtst = () => + dlopen('libXtst.so.6', { + XTestFakeKeyEvent: { + args: [FFIType.pointer, FFIType.u32, FFIType.i32, FFIType.u64], + returns: FFIType.i32, + }, + }).symbols; + +const xtst = ((): ReturnType | null => { + try { + return hasDisplay ? loadXtst() : null; + } catch { + return null; + } +})(); + +/** A second X client, independent of the backend's grab connection. */ const openOtherClient = (): Pointer => { const dpy = loadX11FFI().symbols.XOpenDisplay(null); if (dpy === null) { @@ -44,83 +50,86 @@ const pumpShortcuts = async (until: () => boolean): Promise => { } }; -const hasDisplay = (): boolean => { - if (!isLinux) { - return false; - } - try { - return linuxGlobalShortcutBackend.isSupported(); - } catch { - return false; - } -}; - -describe.skipIf(!isLinux)('x11-global-shortcut (Linux)', () => { +describe.skipIf(!hasDisplay)('x11-global-shortcut under an X server', () => { afterEach(() => { - if (hasDisplay()) { - linuxGlobalShortcutBackend.unregisterAll(); - } + linuxGlobalShortcutBackend.unregisterAll(); }); - test('Xlib symbols resolve', () => { - const x11 = loadX11FFI(); - expect(typeof x11.symbols.XOpenDisplay).toBe('function'); - expect(typeof x11.symbols.XGrabKey).toBe('function'); - expect(typeof x11.symbols.XUngrabKey).toBe('function'); - expect(typeof x11.symbols.XNextEvent).toBe('function'); + test('register() grabs a letter combo', () => { + expect(linuxGlobalShortcutBackend.register('CmdOrCtrl+Shift+K', () => undefined)).toBe(true); }); - test('isSupported() returns a boolean reflecting whether a display opened', () => { - expect(typeof linuxGlobalShortcutBackend.isSupported()).toBe('boolean'); + test('register() grabs a punctuation key', () => { + expect(linuxGlobalShortcutBackend.register('CmdOrCtrl+,', () => undefined)).toBe(true); }); - describe.skipIf(!hasDisplay())('with an X display (xvfb)', () => { - test('register() a valid accelerator grabs without throwing and returns true', () => { - expect(linuxGlobalShortcutBackend.register('CmdOrCtrl+Shift+K', () => undefined)).toBe(true); - }); + test('register() refuses a second spelling of a held combo', () => { + expect(linuxGlobalShortcutBackend.register('Ctrl+K', () => undefined)).toBe(true); + expect(linuxGlobalShortcutBackend.register('Control+K', () => undefined)).toBe(false); + }); - test('register() grabs a punctuation key', () => { - expect(linuxGlobalShortcutBackend.register('CmdOrCtrl+,', () => undefined)).toBe(true); - }); + test('register() returns false for an unmappable key', () => { + expect(linuxGlobalShortcutBackend.register('CmdOrCtrl+Bogus', () => undefined)).toBe(false); + }); - test('register() refuses a second spelling of a held combo', () => { - expect(linuxGlobalShortcutBackend.register('Ctrl+K', () => undefined)).toBe(true); - expect(linuxGlobalShortcutBackend.register('Control+K', () => undefined)).toBe(false); - }); + test('unregister() releases the combo so it can be registered again', () => { + expect(linuxGlobalShortcutBackend.register('CmdOrCtrl+Alt+J', () => undefined)).toBe(true); + linuxGlobalShortcutBackend.unregister('CmdOrCtrl+Alt+J'); + expect(linuxGlobalShortcutBackend.register('CmdOrCtrl+Alt+J', () => undefined)).toBe(true); + }); - test('register() returns false for an unmappable key', () => { - expect(linuxGlobalShortcutBackend.register('CmdOrCtrl+Bogus', () => undefined)).toBe(false); - }); + test('unregisterAll() releases every combo', () => { + expect(linuxGlobalShortcutBackend.register('CmdOrCtrl+1', () => undefined)).toBe(true); + expect(linuxGlobalShortcutBackend.register('CmdOrCtrl+2', () => undefined)).toBe(true); + linuxGlobalShortcutBackend.unregisterAll(); + expect(linuxGlobalShortcutBackend.register('CmdOrCtrl+1', () => undefined)).toBe(true); + }); - test('unregister() of a live grab runs clean', () => { - expect(linuxGlobalShortcutBackend.register('CmdOrCtrl+Alt+J', () => undefined)).toBe(true); - expect(() => linuxGlobalShortcutBackend.unregister('CmdOrCtrl+Alt+J')).not.toThrow(); - }); + test('pollX11ShortcutsOnce() drains cleanly with no pending events', () => { + expect(() => pollX11ShortcutsOnce()).not.toThrow(); + }); - test('pollX11ShortcutsOnce() drains cleanly with no pending events', () => { + test('a key another client already grabbed does not exit the process', async () => { + const x11 = loadX11FFI().symbols; + const other = openOtherClient(); + try { + const keycode = x11.XKeysymToKeycode(other, x11.XStringToKeysym(cstr('j'))); + const mods = CONTROL_MASK | SHIFT_MASK; + x11.XGrabKey(other, keycode, mods, x11.XDefaultRootWindow(other), 0, 1, 1); + xSync(other); + linuxGlobalShortcutBackend.register('Ctrl+Shift+J', () => undefined); + await pumpShortcuts(() => false); expect(() => pollX11ShortcutsOnce()).not.toThrow(); - }); - - test('a key another client already grabbed does not exit the process', async () => { - const x11 = loadX11FFI().symbols; - const other = openOtherClient(); - try { - const keycode = x11.XKeysymToKeycode(other, x11.XStringToKeysym(cstr('j'))); - const mods = CONTROL_MASK | SHIFT_MASK; - x11.XGrabKey(other, keycode, mods, x11.XDefaultRootWindow(other), 0, 1, 1); - xSync(other); - linuxGlobalShortcutBackend.register('Ctrl+Shift+J', () => undefined); - await pumpShortcuts(() => false); - expect(() => pollX11ShortcutsOnce()).not.toThrow(); - } finally { - x11.XCloseDisplay(other); - } - }); + } finally { + x11.XCloseDisplay(other); + } + }); - test('register/unregisterAll several grabs cleanly', () => { - expect(linuxGlobalShortcutBackend.register('CmdOrCtrl+1', () => undefined)).toBe(true); - expect(linuxGlobalShortcutBackend.register('CmdOrCtrl+2', () => undefined)).toBe(true); - expect(() => linuxGlobalShortcutBackend.unregisterAll()).not.toThrow(); - }); + test.skipIf(xtst === null)('a faked Ctrl+K fires its callback once', async () => { + let fired = 0; + expect( + linuxGlobalShortcutBackend.register('Ctrl+K', () => { + fired += 1; + }), + ).toBe(true); + const x11 = loadX11FFI().symbols; + const other = openOtherClient(); + try { + const ctrl = x11.XKeysymToKeycode(other, x11.XStringToKeysym(cstr('Control_L'))); + const k = x11.XKeysymToKeycode(other, x11.XStringToKeysym(cstr('k'))); + for (const [keycode, press] of [ + [ctrl, 1], + [k, 1], + [k, 0], + [ctrl, 0], + ] as const) { + xtst?.XTestFakeKeyEvent(other, keycode, press, 0n); + } + xSync(other); + await pumpShortcuts(() => fired > 0); + expect(fired).toBe(1); + } finally { + x11.XCloseDisplay(other); + } }); }); From c988a004e8531d74f4fb6144b9678fe543fefcf2 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:16:08 -0700 Subject: [PATCH 193/586] fix: dismiss the previous notification when show runs again --- src/main/api/notification.ts | 2 ++ tests/unit/main/api/notification.test.ts | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/api/notification.ts b/src/main/api/notification.ts index fb43bf94..9a4457f0 100644 --- a/src/main/api/notification.ts +++ b/src/main/api/notification.ts @@ -79,7 +79,9 @@ export class Notification extends EventEmitter { return getBackend().isSupported(); } + /** Dismisses a previously shown copy first, as Electron does. */ show(): void { + this.close(); const handle = getBackend().present({ title: this.title, body: this.body, diff --git a/tests/unit/main/api/notification.test.ts b/tests/unit/main/api/notification.test.ts index 37be9d4f..df9eed0e 100644 --- a/tests/unit/main/api/notification.test.ts +++ b/tests/unit/main/api/notification.test.ts @@ -96,11 +96,12 @@ describe('Notification.show', () => { expect(presented[0]?.body).toBe('body2'); }); - test('a second show presents again (re-show)', () => { + test('a second show dismisses the first before presenting again, as in Electron', () => { const n = new Notification({ title: 'T' }); n.show(); n.show(); expect(presented.length).toBe(2); + expect(closedCalls).toBe(1); }); }); From e6a06f61fc885b2ee062a914f6ecc1894c9a1bcc Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:16:10 -0700 Subject: [PATCH 194/586] fix: re-register the Linux tray when the SNI watcher restarts --- src/main/platform/linux/sni-tray.ts | 36 ++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 6 deletions(-) diff --git a/src/main/platform/linux/sni-tray.ts b/src/main/platform/linux/sni-tray.ts index 5e13a79f..a38db63c 100644 --- a/src/main/platform/linux/sni-tray.ts +++ b/src/main/platform/linux/sni-tray.ts @@ -18,6 +18,7 @@ import { nodeInfoNewForXml, probeSessionBusUnchecked, registerObject, + subscribeSignal, unregisterObject, } from './linux-dbus'; @@ -323,13 +324,17 @@ const createLive = (conn: Pointer, initialImage: string): TrayInstance | null => retained.callbacks.push(methodCall, getProp, setProp); // load-bearing: the vtable copy points here. retained.misc.push(node, vtable); + let destroyed = false; // Registered by object path: the watcher pairs it with our sender's unique name (the // libappindicator form). Absent watcher => fast null => the icon simply doesn't appear. - const g = loadGlibFFI().symbols; - const pathVariant = g.g_variant_new_string(cstr(objectPath)); - if (pathVariant !== null) { + const registerWithWatcher = (): void => { + const g = loadGlibFFI().symbols; + const pathVariant = g.g_variant_new_string(cstr(objectPath)); + if (pathVariant === null) { + return; + } const args = g.g_variant_new_tuple(ptr(new BigUint64Array([BigInt(pathVariant)])), 1n); - callMethodSync( + const reply = callMethodSync( conn, WATCHER_NAME, WATCHER_PATH, @@ -337,9 +342,28 @@ const createLive = (conn: Pointer, initialImage: string): TrayInstance | null => 'RegisterStatusNotifierItem', args, ); - } + if (reply !== null) { + g.g_variant_unref(reply); + } + }; + registerWithWatcher(); + // A watcher that starts or restarts after us has no record of this item. + subscribeSignal( + conn, + { + sender: 'org.freedesktop.DBus', + interface: 'org.freedesktop.DBus', + member: 'NameOwnerChanged', + path: '/org/freedesktop/DBus', + arg0: WATCHER_NAME, + }, + () => { + if (!destroyed) { + registerWithWatcher(); + } + }, + ); - let destroyed = false; return { setToolTip: (toolTip) => { state.toolTip = toolTip; From ebd1a991ee54a8eaa39c8d72507c86e728e5386a Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:16:12 -0700 Subject: [PATCH 195/586] test: post non-string bodies in the Windows IPC probe --- tests/integration/windows/fixtures/webkit-ipc-probe.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/integration/windows/fixtures/webkit-ipc-probe.ts b/tests/integration/windows/fixtures/webkit-ipc-probe.ts index fc168800..d7b64fde 100644 --- a/tests/integration/windows/fixtures/webkit-ipc-probe.ts +++ b/tests/integration/windows/fixtures/webkit-ipc-probe.ts @@ -24,6 +24,8 @@ const view = WindowsWebView.create({ width: 800, height: 600, userScripts: [ + // Non-string bodies first: each must be dropped, not read as a WKString. + 'const h = window.webkit.messageHandlers.bunmaska; h.postMessage(1); h.postMessage(true); h.postMessage({});', 'window.webkit.messageHandlers.bunmaska.postMessage(JSON.stringify({ ping: "pong" }));', ], messageHandlers: [ From 29033c23b8516537024c1f56eb90418b24b06808 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:16:34 -0700 Subject: [PATCH 196/586] fix: decode nativeImage paths from memory so the file stays unlocked --- .../platform/windows/win32-gdiplus-ffi.ts | 2 -- .../platform/windows/windows-native-image.ts | 17 ++++++++------- .../integration/windows/native-image.test.ts | 21 +++++++++++++++++++ 3 files changed, 31 insertions(+), 9 deletions(-) diff --git a/src/main/platform/windows/win32-gdiplus-ffi.ts b/src/main/platform/windows/win32-gdiplus-ffi.ts index 6ad0be2b..d604f99a 100644 --- a/src/main/platform/windows/win32-gdiplus-ffi.ts +++ b/src/main/platform/windows/win32-gdiplus-ffi.ts @@ -11,8 +11,6 @@ import { winLibraryAccessor } from './win32'; const GDIPLUS_SYMBOLS = { // (ULONG_PTR* token, GdiplusStartupInput* input, GdiplusStartupOutput* output) -> Status GdiplusStartup: { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr], returns: FFIType.i32 }, - // (LPCWSTR filename, GpImage** out) -> Status - GdipLoadImageFromFile: { args: [FFIType.ptr, FFIType.ptr], returns: FFIType.i32 }, // (IStream*, GpImage** out) -> Status GdipLoadImageFromStream: { args: [FFIType.u64, FFIType.ptr], returns: FFIType.i32 }, // (GpImage*, GpImage** out) -> Status — an independent copy (decouples from the source stream). diff --git a/src/main/platform/windows/windows-native-image.ts b/src/main/platform/windows/windows-native-image.ts index 32789829..017cbd57 100644 --- a/src/main/platform/windows/windows-native-image.ts +++ b/src/main/platform/windows/windows-native-image.ts @@ -1,6 +1,6 @@ import { CFunction, FFIType, type Pointer, ptr, read, toArrayBuffer } from 'bun:ffi'; +import { readFileSync } from 'node:fs'; import type { DecodedImage, NativeImageBackend, NativeImageHandle } from '../../api/native-image'; -import { wstr } from './win32'; import { loadKernel32, loadOle32 } from './win32-ffi'; import { GDIP_OK, @@ -83,16 +83,19 @@ const handleOut = (): { buffer: Uint8Array; pointer: ReturnType } => }; const decode = (source: string | Uint8Array): DecodedImage => { - ensureGdiplus(); - const gdip = loadGdiplus().symbols; - const out = handleOut(); if (typeof source === 'string') { - const nameBuffer = wstr(source); - if (gdip.GdipLoadImageFromFile(ptr(nameBuffer), out.pointer) !== GDIP_OK) { + // GdipLoadImageFromFile would share-lock the file for the image's lifetime. + let bytes: Uint8Array; + try { + bytes = readFileSync(source); + } catch { return toDecoded(0n); } - return toDecoded(read.u64(out.pointer, 0)); + return decode(bytes); } + ensureGdiplus(); + const gdip = loadGdiplus().symbols; + const out = handleOut(); if (source.length === 0) { // An empty buffer is an empty image — `ptr()` rejects zero-length views, so // short-circuit rather than fault (Electron's createFromBuffer([]) is empty). diff --git a/tests/integration/windows/native-image.test.ts b/tests/integration/windows/native-image.test.ts index ebfca577..94f63b02 100644 --- a/tests/integration/windows/native-image.test.ts +++ b/tests/integration/windows/native-image.test.ts @@ -1,4 +1,7 @@ import { describe, expect, test } from 'bun:test'; +import { mkdtempSync, rmSync, unlinkSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; import { currentPlatform } from '../../../src/common/platform'; import { nativeImage } from '../../../src/main/api/native-image'; import { windowsNativeImageBackend } from '../../../src/main/platform/windows/windows-native-image'; @@ -41,6 +44,24 @@ if (currentPlatform() === 'windows') { expect([png[0], png[1], png[2], png[3]]).toEqual([0x89, 0x50, 0x4e, 0x47]); }); + test('decode from a path does not keep the file locked', () => { + const dir = mkdtempSync(join(tmpdir(), 'bunmaska-image-')); + const path = join(dir, 'icon.png'); + writeFileSync(path, PNG_1x1); + try { + expect(windowsNativeImageBackend.decode(path).empty).toBe(false); + expect(() => unlinkSync(path)).not.toThrow(); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + test('decode of a missing path is an empty image', () => { + expect(windowsNativeImageBackend.decode('C:\\bunmaska_no_such_image_zzz.png').empty).toBe( + true, + ); + }); + test('encodeJpeg produces valid JPEG bytes', () => { const { handle } = windowsNativeImageBackend.decode(PNG_1x1); const jpeg = windowsNativeImageBackend.encodeJpeg(handle, 90); From 189c7c20d82f3118a665fdc6874fa7bb6240a69e Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:16:34 -0700 Subject: [PATCH 197/586] fix: clamp far-future Linux cookie expiry to the i32 max-age range --- src/main/platform/linux/webkit-cookies.ts | 17 +++++++++----- tests/integration/linux/cookies.test.ts | 3 ++- .../platform/linux/webkit-cookies.test.ts | 22 +++++++++++++++++++ 3 files changed, 35 insertions(+), 7 deletions(-) create mode 100644 tests/unit/main/platform/linux/webkit-cookies.test.ts diff --git a/src/main/platform/linux/webkit-cookies.ts b/src/main/platform/linux/webkit-cookies.ts index 80f175fd..2c8f857a 100644 --- a/src/main/platform/linux/webkit-cookies.ts +++ b/src/main/platform/linux/webkit-cookies.ts @@ -93,19 +93,24 @@ export const getCookies = (filter: CookieFilter): Promise => 'cookies.get', ); -/** Build a `SoupCookie*` from the normalized shape; expiration maps to max-age seconds. */ +/** + * Seconds until `expirationDate` for `soup_cookie_new`; -1 is a session cookie. Clamped to + * the i32 max: the FFI wraps a year-9999 expiry negative and libsoup drops it as expired. + */ +export const maxAgeFor = (expirationDate: number | undefined, nowSec: number): number => + expirationDate === undefined + ? -1 + : Math.min(0x7fffffff, Math.max(0, Math.round(expirationDate - nowSec))); + +/** Build a `SoupCookie*` from the normalized shape. */ const buildSoupCookie = (cookie: Cookie): Pointer => { const soup = loadSoupFFI().symbols; - const maxAge = - cookie.expirationDate === undefined - ? -1 - : Math.max(0, Math.round(cookie.expirationDate - Date.now() / 1000)); const soupCookie = soup.soup_cookie_new( cstr(cookie.name), cstr(cookie.value), cstr(cookie.domain), cstr(cookie.path), - maxAge, + maxAgeFor(cookie.expirationDate, Date.now() / 1000), ); if (soupCookie === null) { throw new InvalidArgumentError('cookies.set: soup_cookie_new rejected the cookie fields'); diff --git a/tests/integration/linux/cookies.test.ts b/tests/integration/linux/cookies.test.ts index 24678ede..02b5fe40 100644 --- a/tests/integration/linux/cookies.test.ts +++ b/tests/integration/linux/cookies.test.ts @@ -38,7 +38,8 @@ describe.skipIf(!isLinux)('session.cookies over the real WebKitGTK network sessi app.start(); const window = app.createWindow({ width: 320, height: 240, title: 'cookies', show: true }); const name = `bunmaska_it_${Date.now()}`; - const expirationDate = Math.floor(Date.now() / 1000) + 3600; + // Year 9999: past the i32 max-age range, so it proves the clamp. + const expirationDate = 253402300799; try { await settleWithPump( session.defaultSession.cookies.set({ diff --git a/tests/unit/main/platform/linux/webkit-cookies.test.ts b/tests/unit/main/platform/linux/webkit-cookies.test.ts new file mode 100644 index 00000000..6f78f086 --- /dev/null +++ b/tests/unit/main/platform/linux/webkit-cookies.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, test } from 'bun:test'; +import { maxAgeFor } from '../../../../../src/main/platform/linux/webkit-cookies'; + +describe('maxAgeFor', () => { + const now = 1_700_000_000; + + test('a session cookie has no max-age', () => { + expect(maxAgeFor(undefined, now)).toBe(-1); + }); + + test('a future expiry becomes the seconds until it', () => { + expect(maxAgeFor(now + 3600, now)).toBe(3600); + }); + + test('a past expiry becomes 0 so the cookie expires', () => { + expect(maxAgeFor(now - 10, now)).toBe(0); + }); + + test('a year-9999 expiry clamps to the i32 max instead of wrapping negative', () => { + expect(maxAgeFor(253402300799, now)).toBe(0x7fffffff); + }); +}); From 2e883d69d7350c7c53e1b48a330754a8ae59ccca Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:16:38 -0700 Subject: [PATCH 198/586] fix: hide a destroyed Linux tray icon before unexporting it --- src/main/platform/linux/sni-tray.ts | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/src/main/platform/linux/sni-tray.ts b/src/main/platform/linux/sni-tray.ts index a38db63c..a3613990 100644 --- a/src/main/platform/linux/sni-tray.ts +++ b/src/main/platform/linux/sni-tray.ts @@ -72,6 +72,7 @@ export const SNI_XML = ` + `; @@ -207,6 +208,15 @@ const buildToolTip = (title: string, text: string): Pointer | null => { return value; }; +/** A floating one-string tuple `(s)`, or null. */ +const stringTuple = (value: string): Pointer | null => { + const g = loadGlibFFI().symbols; + const child = g.g_variant_new_string(cstr(value)); + return child === null + ? null + : g.g_variant_new_tuple(ptr(new BigUint64Array([BigInt(child)])), 1n); +}; + /** A fully-inert no-op tray (gate off / no bus / export failed) — never touches the bus. */ const inertInstance = (): TrayInstance => { let destroyed = false; @@ -224,6 +234,7 @@ const inertInstance = (): TrayInstance => { }; type State = { + status: 'Active' | 'Passive'; title: string; toolTip: string; icon: Icon | null; @@ -241,7 +252,7 @@ const getPropertyValue = (state: State, name: string): Pointer | null => { case 'Title': return g.g_variant_new_string(cstr(state.title)); case 'Status': - return g.g_variant_new_string(cstr('Active')); + return g.g_variant_new_string(cstr(state.status)); case 'IconName': return g.g_variant_new_string(cstr('')); case 'IconPixmap': @@ -274,6 +285,7 @@ const createLive = (conn: Pointer, initialImage: string): TrayInstance | null => } const state: State = { + status: 'Active', title: 'Bunmaska', toolTip: '', icon: decodeIcon(initialImage), @@ -328,12 +340,10 @@ const createLive = (conn: Pointer, initialImage: string): TrayInstance | null => // Registered by object path: the watcher pairs it with our sender's unique name (the // libappindicator form). Absent watcher => fast null => the icon simply doesn't appear. const registerWithWatcher = (): void => { - const g = loadGlibFFI().symbols; - const pathVariant = g.g_variant_new_string(cstr(objectPath)); - if (pathVariant === null) { + const args = stringTuple(objectPath); + if (args === null) { return; } - const args = g.g_variant_new_tuple(ptr(new BigUint64Array([BigInt(pathVariant)])), 1n); const reply = callMethodSync( conn, WATCHER_NAME, @@ -343,7 +353,7 @@ const createLive = (conn: Pointer, initialImage: string): TrayInstance | null => args, ); if (reply !== null) { - g.g_variant_unref(reply); + loadGlibFFI().symbols.g_variant_unref(reply); } }; registerWithWatcher(); @@ -386,6 +396,12 @@ const createLive = (conn: Pointer, initialImage: string): TrayInstance | null => return; } destroyed = true; + // Hosts keep an item until our connection closes; Passive hides it (as libappindicator does). + state.status = 'Passive'; + const passive = stringTuple('Passive'); + if (passive !== null) { + emitSignal(conn, objectPath, SNI_IFACE, 'NewStatus', passive); + } unregisterObject(conn, regId); // do NOT close the callbacks (retained forever). }, isDestroyed: () => destroyed, From fc252b15bf5406f8c1d856f7c1a102734f855204 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:16:42 -0700 Subject: [PATCH 199/586] fix: export the pinned engine's env to the C environment --- src/main/platform/linux/glib-ffi.ts | 29 ++++++++++++++++++ .../linux/engine-pinned-load.test.ts | 2 +- .../linux/fixtures/pinned-load-probe.ts | Bin 880 -> 1239 bytes .../unit/main/platform/linux/glib-ffi.test.ts | 27 +++++++++++++++- 4 files changed, 56 insertions(+), 2 deletions(-) diff --git a/src/main/platform/linux/glib-ffi.ts b/src/main/platform/linux/glib-ffi.ts index 8b5faff1..b1f75492 100644 --- a/src/main/platform/linux/glib-ffi.ts +++ b/src/main/platform/linux/glib-ffi.ts @@ -1,14 +1,17 @@ import { type FFIFunction, FFIType } from 'bun:ffi'; import { existsSync } from 'node:fs'; import { join } from 'node:path'; +import type { StoreEnv } from '../../../cli/engine-store'; import { UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; import { type EngineResolution, + engineEnv, engineLibPath, prepareEngineForLoad, resolveEngine, } from '../../engine/resolve'; +import { cstr } from '../cstr'; import { dlopen, type NarrowLibrary } from '../dlopen'; /** @@ -27,6 +30,10 @@ import { dlopen, type NarrowLibrary } from '../dlopen'; */ const LIBGLIB_PATH = 'libglib-2.0.so.0'; +const LIBC_PATH = 'libc.so.6'; +const LIBC_FFI_SYMBOLS = { + setenv: { args: [FFIType.cstring, FFIType.cstring, FFIType.i32], returns: FFIType.i32 }, +} as const; /** The path to dlopen for `soname`: the pinned engine's bundled copy when it has one, else the bare soname. */ export const linuxLibPath = ( @@ -48,6 +55,22 @@ export const linuxLibPath = ( return soname; }; +/** Copy the pinned engine's env exports into the C environment: Bun's `process.env` writes never reach `getenv`. */ +export const exportEngineEnv = ( + engine: EngineResolution, + env: StoreEnv, + setenv: (name: string, value: string) => void, +): void => { + for (const name of Object.keys(engineEnv(engine, env))) { + const value = env[name]; + if (value !== undefined) { + setenv(name, value); + } + } +}; + +const nativeEnv = { exported: false }; + /** * `dlopen` for every Linux loader. A pinned engine must supply GLib, GTK and the rest of its * closure to the whole process: a bare-soname load of any of them first binds the system copy, @@ -59,6 +82,12 @@ export const dlopenLinux = >( ): NarrowLibrary => { const engine = resolveEngine(); prepareEngineForLoad(engine, process.env, (text) => process.stderr.write(text)); + if (!nativeEnv.exported) { + nativeEnv.exported = true; + exportEngineEnv(engine, process.env, (name, value) => { + dlopen(LIBC_PATH, LIBC_FFI_SYMBOLS).symbols.setenv(cstr(name), cstr(value), 1); + }); + } return dlopen(linuxLibPath(engine, soname), symbols); }; diff --git a/tests/integration/linux/engine-pinned-load.test.ts b/tests/integration/linux/engine-pinned-load.test.ts index b17e8abc..fbab9a18 100644 --- a/tests/integration/linux/engine-pinned-load.test.ts +++ b/tests/integration/linux/engine-pinned-load.test.ts @@ -64,7 +64,7 @@ describe.skipIf(!isLinux)('pinned engine load (Linux, real WebKitGTK)', () => { if (code !== 0) { throw new Error(`pinned-load probe exited ${code}: ${err}`); } - expect(out).toBe('STORE_LOADED'); + expect(out).toBe(`STORE_LOADED\nWEBKIT_EXEC_PATH=${join(store, id, 'libexec')}`); } finally { rmSync(store, { recursive: true, force: true }); } diff --git a/tests/integration/linux/fixtures/pinned-load-probe.ts b/tests/integration/linux/fixtures/pinned-load-probe.ts index 49fdc57351b939238bf352cdda31e5025fd58405..213399c2e42ae90c814e6b574fec3dfc969e0761 100644 GIT binary patch delta 330 zcmZ9H!AiqG6h%oC!7SXle~K^(gsHf2kDJnDg}?3 zl(b_-SW+YAC>7*c6vGhuDkkYpDmlF-Hf;B=oK}S*l@84IO=;ID+hO`>gJ7x>*up;y z({@d5xyEm-R4ZO7x)zyY<}&a`(}} { expect(() => linuxLibPath(system, SONAME, planted, CWD)).toThrow(/working directory/); }); }); + +describe('exportEngineEnv', () => { + const env = { + LD_LIBRARY_PATH: '/e/lib', + GIO_EXTRA_MODULES: '/e/gio', + WEBKIT_EXEC_PATH: '/e/libexec', + HOME: '/h', + }; + + test('a pinned engine pushes its env exports into the C environment', () => { + const exported: string[] = []; + exportEngineEnv(pinned, env, (name, value) => exported.push(`${name}=${value}`)); + expect(exported.sort()).toEqual([ + 'GIO_EXTRA_MODULES=/e/gio', + 'LD_LIBRARY_PATH=/e/lib', + 'WEBKIT_EXEC_PATH=/e/libexec', + ]); + }); + + test('system mode leaves the C environment alone', () => { + const exported: string[] = []; + exportEngineEnv(system, env, (name) => exported.push(name)); + expect(exported).toEqual([]); + }); +}); From 24a9ecbc1e5faf970f7d4f43dd50ec1b41a7dd11 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:16:47 -0700 Subject: [PATCH 200/586] fix: cap update feed downloads and refuse redirects off https --- src/main/api/auto-updater.ts | 40 +++++++++++++++++------- tests/unit/main/api/auto-updater.test.ts | 36 +++++++++++++++++++++ 2 files changed, 64 insertions(+), 12 deletions(-) diff --git a/src/main/api/auto-updater.ts b/src/main/api/auto-updater.ts index c0534eb9..b23f18c1 100644 --- a/src/main/api/auto-updater.ts +++ b/src/main/api/auto-updater.ts @@ -81,7 +81,8 @@ export type UpdateCheckResult = { export type AutoUpdaterDeps = { readonly fetchText: (url: string) => Promise; - readonly fetchBytes: (url: string) => Promise; + /** Rejects once the body passes `maxBytes`, without buffering the rest. */ + readonly fetchBytes: (url: string, maxBytes: number) => Promise; readonly currentVersion: () => string; readonly currentOs: () => ArtifactOs; readonly currentArch: () => Arch; @@ -98,22 +99,37 @@ const toUpdateInfo = (manifest: UpdateManifest): UpdateInfo => ({ releaseName: manifest.name, }); -const httpFetchText = async (url: string): Promise => { - const response = await fetch(url); - if (!response.ok) { - throw new Error(`autoUpdater: GET ${url} failed (${response.status})`); - } - return response.text(); -}; +/** update.json and a `.sig` are a few hundred bytes; a body past this is hostile. */ +const MAX_FEED_TEXT_BYTES = 64 * 1024; -const httpFetchBytes = async (url: string): Promise => { - const response = await fetch(url); +/** The body of a feed GET, read with a running byte cap; a redirect off https is refused. */ +export const readFeedResponse = async ( + response: Response, + url: string, + maxBytes: number, +): Promise => { if (!response.ok) { throw new Error(`autoUpdater: GET ${url} failed (${response.status})`); } - return new Uint8Array(await response.arrayBuffer()); + if (response.url !== '' && !isSecureFeedUrl(new URL(response.url))) { + throw new Error(`autoUpdater: GET ${url} was redirected to insecure ${response.url}`); + } + const chunks: Uint8Array[] = []; + let total = 0; + for await (const chunk of response.body ?? []) { + total += chunk.length; + assertSizeWithin(total, maxBytes, `GET ${url}`); + chunks.push(chunk); + } + return Buffer.concat(chunks); }; +const httpFetchText = async (url: string): Promise => + new TextDecoder().decode(await readFeedResponse(await fetch(url), url, MAX_FEED_TEXT_BYTES)); + +const httpFetchBytes = async (url: string, maxBytes: number): Promise => + readFeedResponse(await fetch(url), url, maxBytes); + /** Electron callers fire and forget, relying on the `error` event; awaiting callers still see the rejection. */ const markHandled = (promise: Promise): Promise => { promise.catch(() => undefined); @@ -310,7 +326,7 @@ export class AutoUpdaterImpl extends EventEmitter { 'update.json', ); assertSizeWithin(manifest.size, MAX_COMPRESSED_ARTIFACT_BYTES, 'compressed artifact'); - const bytes = await this.#deps.fetchBytes(joinUrl(feedURL, manifest.artifact)); + const bytes = await this.#deps.fetchBytes(joinUrl(feedURL, manifest.artifact), manifest.size); if (bytes.length !== manifest.size) { throw new Error( `autoUpdater: artifact size mismatch (expected ${manifest.size}, got ${bytes.length})`, diff --git a/tests/unit/main/api/auto-updater.test.ts b/tests/unit/main/api/auto-updater.test.ts index 9b78706d..f4f4ab89 100644 --- a/tests/unit/main/api/auto-updater.test.ts +++ b/tests/unit/main/api/auto-updater.test.ts @@ -7,6 +7,7 @@ import { type AutoUpdaterDeps, MAX_COMPRESSED_ARTIFACT_BYTES, MAX_DECOMPRESSED_TAR_BYTES, + readFeedResponse, type StagedUpdate, stageToTmp, } from '../../../../src/main/api/auto-updater'; @@ -350,3 +351,38 @@ describe('stageToTmp', () => { } }); }); + +describe('readFeedResponse', () => { + const KIB = new Uint8Array(1024); + + test('rejects a body past the cap without draining the rest of the stream', async () => { + let pulls = 0; + const body = new ReadableStream({ + pull(controller) { + pulls += 1; + if (pulls > 1000) { + controller.close(); + } else { + controller.enqueue(KIB); + } + }, + }); + await expect(readFeedResponse(new Response(body), 'https://feed/a', 4 * 1024)).rejects.toThrow( + /exceeds/, + ); + expect(pulls).toBeLessThan(10); + }); + + test('returns a body within the cap', async () => { + const bytes = await readFeedResponse(new Response(KIB), 'https://feed/a', 1024); + expect(bytes.length).toBe(1024); + }); + + test('refuses a response that was redirected off https', async () => { + const response = new Response('{}'); + Object.defineProperty(response, 'url', { value: 'http://evil.example/update.json' }); + await expect(readFeedResponse(response, 'https://feed/update.json', 1024)).rejects.toThrow( + /http:\/\/evil\.example/, + ); + }); +}); From 08cea8cc42c6e767707ea433f8ad6a969575d2d8 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:16:55 -0700 Subject: [PATCH 201/586] fix: blank a closed Windows view so its page stops running --- .../platform/windows/windows-webkit-view.ts | 30 ++++++++----------- .../windows/fixtures/window-close-probe.ts | 5 ++-- .../integration/windows/windows-close.test.ts | 4 +-- 3 files changed, 17 insertions(+), 22 deletions(-) diff --git a/src/main/platform/windows/windows-webkit-view.ts b/src/main/platform/windows/windows-webkit-view.ts index 519c60b7..7d1a2af3 100644 --- a/src/main/platform/windows/windows-webkit-view.ts +++ b/src/main/platform/windows/windows-webkit-view.ts @@ -420,30 +420,24 @@ export class WindowsWebView { } } - /** Idempotent. */ + /** + * Idempotent. The WKView is never released (D043: that re-enters a JSCallback mid-teardown), + * so blank the page to stop its scripts, media and sockets until process exit. + */ dispose(): void { if (this.#disposed) { return; } this.#disposed = true; - const wk = loadWebKit2(); - // The owning window is hidden, not destroyed (see `commitClose`), so the view - // persists until process exit. Silence it: stop loading and clear its clients - // so a closed webContents emits nothing further, and drop our controller ref - // (the shared WKContext is process-lifetime). The live WKView itself is NOT released — doing so through - // raw FFI re-enters a bun:ffi JSCallback during WebKit's multi-process - // teardown and crashes — so it and its WebProcess are reclaimed by the OS at - // exit. A clean async teardown is a documented follow-up (`.admin/WINDOWS.md`). - // Clear WebKit's clients FIRST — before any other WebKit or window operation. - // Once the window is hidden/torn down, WebKit synchronously processes those - // messages and would call our nav/message trampolines in a context that - // crashes bun:ffi; with the clients cleared it has nothing to call. (Doing any - // other WebKit call first — e.g. stop-loading — re-fires a nav callback before - // the clear and crashes.) - wk.symbols.WKPageSetPageNavigationClient(this.#page, null); - wk.symbols.WKUserContentControllerRemoveAllUserMessageHandlers(this.#retainedController); + const wk = loadWebKit2().symbols; + // Clear WebKit's clients FIRST: any earlier WebKit call (even stop-loading) re-fires a + // nav callback into a trampoline mid-teardown and crashes bun:ffi. + wk.WKPageSetPageNavigationClient(this.#page, null); + wk.WKUserContentControllerRemoveAllUserMessageHandlers(this.#retainedController); + // So the blank page runs no preload. + wk.WKUserContentControllerRemoveAllUserScripts(this.#retainedController); + this.loadURL('about:blank'); wkRelease(this.#retainedController); - // The shared WKContext is process-lifetime — never released here (it outlives this view). retainTrampolines(this.#callbacks); } } diff --git a/tests/integration/windows/fixtures/window-close-probe.ts b/tests/integration/windows/fixtures/window-close-probe.ts index 006e7d7a..cf34b361 100644 --- a/tests/integration/windows/fixtures/window-close-probe.ts +++ b/tests/integration/windows/fixtures/window-close-probe.ts @@ -3,7 +3,8 @@ * the WebKit-view teardown on window close is crash-free. The `window-all-closed` * listener keeps the app alive so this isolates the window close from app-exit * (synchronous WebKit shutdown at process exit is a separate, documented item). - * Prints `CLOSE_OK` if the process survives the close. Requires BUNMASKA_WEBKIT_PATH. + * Prints `CLOSE_OK url=` if the process survives the close. + * Requires BUNMASKA_WEBKIT_PATH. */ import { app, BrowserWindow } from '../../../../src/index'; @@ -23,7 +24,7 @@ app.whenReady().then(() => { win.webContents.once('did-finish-load', () => { win.close(); // If close tore down the live WebKit view cleanly, we get here without a crash. - setTimeout(() => finish('CLOSE_OK', 0), 600); + setTimeout(() => finish(`CLOSE_OK url=${win.webContents.getURL()}`, 0), 600); }); win.loadURL('data:text/html,bye'); }); diff --git a/tests/integration/windows/windows-close.test.ts b/tests/integration/windows/windows-close.test.ts index a72855a6..09bf82ac 100644 --- a/tests/integration/windows/windows-close.test.ts +++ b/tests/integration/windows/windows-close.test.ts @@ -11,7 +11,7 @@ import { resolveWindowsEngineDir } from '../../../src/main/platform/windows/webk const hasEngine = currentPlatform() === 'windows' && resolveWindowsEngineDir() !== undefined; describe.skipIf(!hasEngine)('Windows window close', () => { - test('closing a BrowserWindow does not crash', async () => { + test('closing a BrowserWindow does not crash and blanks its page', async () => { const fixture = `${import.meta.dir}/fixtures/window-close-probe.ts`; const proc = Bun.spawn([process.execPath, 'run', fixture], { env: { ...process.env }, @@ -20,7 +20,7 @@ describe.skipIf(!hasEngine)('Windows window close', () => { }); const stdout = await new Response(proc.stdout).text(); await proc.exited; - expect(stdout).toContain('CLOSE_OK'); + expect(stdout).toContain('CLOSE_OK url=about:blank'); }, 30000); test('app quit with a live engine exits cleanly (no teardown crash)', async () => { From 045cd567d84654a6f47ccaf82b901102c35459a0 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:16:57 -0700 Subject: [PATCH 202/586] fix: treat equivalent accelerator spellings as one global shortcut --- src/main/api/global-shortcut.ts | 26 +++++++++++++-------- tests/unit/main/api/global-shortcut.test.ts | 24 ++++++++++--------- 2 files changed, 29 insertions(+), 21 deletions(-) diff --git a/src/main/api/global-shortcut.ts b/src/main/api/global-shortcut.ts index 7443e4a2..3fc599dc 100644 --- a/src/main/api/global-shortcut.ts +++ b/src/main/api/global-shortcut.ts @@ -40,11 +40,14 @@ const { get: getBackend, setForTesting } = selectBackend( /** @internal */ export const setGlobalShortcutBackendForTesting = setForTesting; -/** Keyed by the LITERAL accelerator string, not the parsed form. */ -const registry = new Set(); +/** Canonical form to the literal the backend was given, which is what it keys its grab by. */ +const registry = new Map(); -const isParseable = (accelerator: string): boolean => - parseAccelerator(accelerator, currentPlatform()) !== undefined; +/** `CmdOrCtrl+K` and `CommandOrControl+k` share one key; `undefined` if unparseable. */ +const canonical = (accelerator: string): string | undefined => { + const p = parseAccelerator(accelerator, currentPlatform()); + return p && [p.ctrl, p.alt, p.shift, p.meta, p.super].map(Number).join('') + p.key; +}; export type GlobalShortcut = { register(accelerator: string, callback: () => void): boolean; @@ -59,12 +62,13 @@ export type GlobalShortcut = { * or already registered, and when the OS refuses the grab. */ const register = (accelerator: string, callback: () => void): boolean => { - if (!isParseable(accelerator) || registry.has(accelerator)) { + const key = canonical(accelerator); + if (key === undefined || registry.has(key)) { return false; } const ok = getBackend().register(accelerator, callback); if (ok) { - registry.add(accelerator); + registry.set(key, accelerator); } return ok; }; @@ -76,14 +80,16 @@ const registerAll = (accelerators: string[], callback: () => void): void => { } }; -const isRegistered = (accelerator: string): boolean => registry.has(accelerator); +const isRegistered = (accelerator: string): boolean => registry.has(canonical(accelerator) ?? ''); const unregister = (accelerator: string): void => { - if (!registry.has(accelerator)) { + const key = canonical(accelerator) ?? ''; + const registered = registry.get(key); + if (registered === undefined) { return; } - registry.delete(accelerator); - getBackend().unregister(accelerator); + registry.delete(key); + getBackend().unregister(registered); }; const unregisterAll = (): void => { diff --git a/tests/unit/main/api/global-shortcut.test.ts b/tests/unit/main/api/global-shortcut.test.ts index d64a19dd..15778d91 100644 --- a/tests/unit/main/api/global-shortcut.test.ts +++ b/tests/unit/main/api/global-shortcut.test.ts @@ -11,8 +11,6 @@ import { * tested with ZERO FFI. */ -type Registration = { accelerator: string; callback: () => void }; - const makeFakeBackend = () => { const registered = new Map void>(); const calls: string[] = []; @@ -36,15 +34,7 @@ const makeFakeBackend = () => { registered.get(accelerator)?.(); }; const has = (accelerator: string): boolean => registered.has(accelerator); - const last = (): Registration | undefined => { - const keys = [...registered.keys()]; - const k = keys[keys.length - 1]; - if (k === undefined) { - return undefined; - } - return { accelerator: k, callback: registered.get(k) ?? (() => undefined) }; - }; - return { backend, fire, has, last, calls }; + return { backend, fire, has, calls }; }; afterEach(() => { @@ -98,6 +88,18 @@ describe('globalShortcut.register', () => { }); }); +describe('equivalent accelerator spellings', () => { + test('are one shortcut: registered once, found and removed under any spelling', () => { + const fake = makeFakeBackend(); + setGlobalShortcutBackendForTesting(fake.backend); + expect(globalShortcut.register('CmdOrCtrl+K', () => undefined)).toBe(true); + expect(globalShortcut.register('CommandOrControl+k', () => undefined)).toBe(false); + expect(globalShortcut.isRegistered('cmdorctrl + K')).toBe(true); + globalShortcut.unregister('CommandOrControl+K'); + expect(fake.calls).toEqual(['register:CmdOrCtrl+K', 'unregister:CmdOrCtrl+K']); + }); +}); + describe('globalShortcut.registerAll', () => { test('registers every accelerator with the one shared callback', () => { const fake = makeFakeBackend(); From 709b26334e94a80540dc4e55891eaafb3e9ab68d Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:17:06 -0700 Subject: [PATCH 203/586] fix: check GDI+ startup and stream creation instead of assuming success --- src/main/platform/windows/windows-native-image.ts | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/main/platform/windows/windows-native-image.ts b/src/main/platform/windows/windows-native-image.ts index 017cbd57..747967ac 100644 --- a/src/main/platform/windows/windows-native-image.ts +++ b/src/main/platform/windows/windows-native-image.ts @@ -1,5 +1,6 @@ import { CFunction, FFIType, type Pointer, ptr, read, toArrayBuffer } from 'bun:ffi'; import { readFileSync } from 'node:fs'; +import { FFIError } from '../../../common/errors'; import type { DecodedImage, NativeImageBackend, NativeImageHandle } from '../../api/native-image'; import { loadKernel32, loadOle32 } from './win32-ffi'; import { @@ -34,7 +35,10 @@ export const ensureGdiplus = (): void => { const token = new Uint8Array(HANDLE_SIZE); const input = new Uint8Array(24); // GdiplusStartupInput new DataView(input.buffer).setUint32(0, 1, true); // GdiplusVersion = 1 - loadGdiplus().symbols.GdiplusStartup(ptr(token), ptr(input), null); + const status = loadGdiplus().symbols.GdiplusStartup(ptr(token), ptr(input), null); + if (status !== GDIP_OK) { + throw new FFIError(`nativeImage: GdiplusStartup failed (status ${status})`); + } gdiplusStarted = true; }; @@ -126,7 +130,10 @@ const encode = (handle: NativeImageHandle, encoderClsid: Uint8Array): Uint8Array const ole32 = loadOle32().symbols; const kernel32 = loadKernel32().symbols; const streamOut = handleOut(); - ole32.CreateStreamOnHGlobal(0n, 1, streamOut.pointer); // fDeleteOnRelease = TRUE + // fDeleteOnRelease = TRUE: releasing the stream frees its HGLOBAL. + if (ole32.CreateStreamOnHGlobal(0n, 1, streamOut.pointer) !== 0) { + return new Uint8Array(0); + } const stream = read.u64(streamOut.pointer, 0); if (gdip.GdipSaveImageToStream(handle, stream, ptr(encoderClsid), null) !== GDIP_OK) { releaseStream(stream); From c3748382281df2353483a077c429450133bdf350 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:17:06 -0700 Subject: [PATCH 204/586] fix: return a D-Bus error from a failed Linux tray property read --- src/main/platform/linux/sni-tray.ts | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/src/main/platform/linux/sni-tray.ts b/src/main/platform/linux/sni-tray.ts index a3613990..7caf63d0 100644 --- a/src/main/platform/linux/sni-tray.ts +++ b/src/main/platform/linux/sni-tray.ts @@ -208,6 +208,17 @@ const buildToolTip = (title: string, text: string): Pointer | null => { return value; }; +/** Fill a getter's `GError**`: GDBus g_asserts (aborts) on a NULL Get value without one. */ +const setGError = (out: Pointer | null, message: string): void => { + if (out === null) { + return; // GetAll passes NULL and skips the property. + } + const g = loadGlibFFI().symbols; + const domain = g.g_quark_from_string(cstr('bunmaska-tray')); + const gerror = g.g_error_new_literal(domain, 0, cstr(message)); + new BigUint64Array(toArrayBuffer(out, 0, 8))[0] = BigInt(gerror ?? 0); +}; + /** A floating one-string tuple `(s)`, or null. */ const stringTuple = (value: string): Pointer | null => { const g = loadGlibFFI().symbols; @@ -294,13 +305,17 @@ const createLive = (conn: Pointer, initialImage: string): TrayInstance | null => // The three vtable handlers — each wrapped so a JS throw can't cross the FFI boundary and // kill the pump. Retained FOREVER (the copied vtable holds their raw fn-pointers). - const getProp = new JSCallback((_c, _s, _p, _i, propName, _e, _u): Pointer | null => { + const getProp = new JSCallback((_c, _s, _p, _i, propName, error, _u): Pointer | null => { + let value: Pointer | null = null; try { - return getPropertyValue(state, propName === null ? '' : new CString(propName).toString()); + value = getPropertyValue(state, propName === null ? '' : new CString(propName).toString()); } catch { - // A failed getter returns null → GDBus synthesizes an error for that one property. - return null; + value = null; + } + if (value === null) { + setGError(error, 'StatusNotifierItem property unavailable'); } + return value; }, DBUS_GET_PROPERTY_CB_DEF); const methodCall = new JSCallback((_c, _s, _p, _i, method, _params, invocation, _u): void => { From 8bf92cb4fbea8520a534d7789091429b0ea6bf9a Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:17:12 -0700 Subject: [PATCH 205/586] perf: decompress and stage updates off the main thread --- src/main/api/auto-updater.ts | 11 ++++++----- tests/unit/main/api/auto-updater.test.ts | 2 +- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/main/api/auto-updater.ts b/src/main/api/auto-updater.ts index b23f18c1..531f1697 100644 --- a/src/main/api/auto-updater.ts +++ b/src/main/api/auto-updater.ts @@ -1,5 +1,5 @@ import { EventEmitter } from 'node:events'; -import { mkdtempSync, writeFileSync } from 'node:fs'; +import { mkdtempSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { @@ -86,7 +86,7 @@ export type AutoUpdaterDeps = { readonly currentVersion: () => string; readonly currentOs: () => ArtifactOs; readonly currentArch: () => Arch; - readonly decompress: (bytes: Uint8Array) => Uint8Array; + readonly decompress: (bytes: Uint8Array) => Promise; readonly stage: (tarBytes: Uint8Array, manifest: UpdateManifest) => Promise; readonly install: (staged: StagedUpdate) => void; }; @@ -139,7 +139,7 @@ const markHandled = (promise: Promise): Promise => { /** A fresh 0700 dir: a guessable name in a shared /tmp lets another user swap the verified tar. */ export const stageToTmp = async (tarBytes: Uint8Array): Promise => { const tarPath = join(mkdtempSync(join(tmpdir(), 'bunmaska-update-')), 'update.tar'); - writeFileSync(tarPath, tarBytes); + await Bun.write(tarPath, tarBytes); return tarPath; }; @@ -149,7 +149,8 @@ const productionDeps = (): AutoUpdaterDeps => ({ currentVersion: () => app.getVersion(), currentOs: currentPlatform, currentArch: hostArch, - decompress: (bytes) => new Uint8Array(Bun.zstdDecompressSync(bytes)), + // Async zstd runs on Bun's threadpool, so a large update never stalls the pumped main thread. + decompress: async (bytes) => new Uint8Array(await Bun.zstdDecompress(bytes)), stage: stageToTmp, install: defaultInstall, }); @@ -344,7 +345,7 @@ export class AutoUpdaterImpl extends EventEmitter { bytes, 'artifact', ); - const tarBytes = this.#deps.decompress(bytes); + const tarBytes = await this.#deps.decompress(bytes); assertSizeWithin(tarBytes.length, MAX_DECOMPRESSED_TAR_BYTES, 'decompressed update'); const tarPath = await this.#deps.stage(tarBytes, manifest); const staged: StagedUpdate = { manifest, tarPath }; diff --git a/tests/unit/main/api/auto-updater.test.ts b/tests/unit/main/api/auto-updater.test.ts index f4f4ab89..a729077a 100644 --- a/tests/unit/main/api/auto-updater.test.ts +++ b/tests/unit/main/api/auto-updater.test.ts @@ -67,7 +67,7 @@ const makeUpdater = (overrides: Partial, feedVersion = '2.0.0') currentVersion: () => '1.0.0', currentOs: () => 'macos', currentArch: () => 'arm64', - decompress: (bytes) => { + decompress: async (bytes) => { decompressed.push(bytes); return TAR; }, From 7564f3e92cb305f405487b1d58f9b2be627dd734 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:17:23 -0700 Subject: [PATCH 206/586] fix: warn that setWindowOpenHandler is a no-op on Windows --- .../platform/windows/windows-web-contents.ts | 4 +- .../windows/windows-web-contents.test.ts | 43 +++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) create mode 100644 tests/unit/main/platform/windows/windows-web-contents.test.ts diff --git a/src/main/platform/windows/windows-web-contents.ts b/src/main/platform/windows/windows-web-contents.ts index bbdd7ee5..477bf402 100644 --- a/src/main/platform/windows/windows-web-contents.ts +++ b/src/main/platform/windows/windows-web-contents.ts @@ -318,8 +318,8 @@ export class WindowsWebContents implements NativeWebContents { } setWindowOpenHandler(_callback: (url: string) => void): void { - // WKPageUIClient createNewPage forwarding; wired in the seam-fill phase - // (today window.open is blocked, the v1 default). + // ponytail: popups stay blocked but the URL is dropped; forward it via WKPageUIClient createNewPage. + log.warn('setWindowOpenHandler is not supported on Windows yet: the handler is never called'); } /** @internal Reject pending execs and release the view. Called on window close. */ diff --git a/tests/unit/main/platform/windows/windows-web-contents.test.ts b/tests/unit/main/platform/windows/windows-web-contents.test.ts new file mode 100644 index 00000000..13daeba7 --- /dev/null +++ b/tests/unit/main/platform/windows/windows-web-contents.test.ts @@ -0,0 +1,43 @@ +import { afterEach, describe, expect, mock, spyOn, test } from 'bun:test'; +import { type LogRecord, resetLogger, setLogSink } from '../../../../../src/common/logger'; +import { WindowsWebContents } from '../../../../../src/main/platform/windows/windows-web-contents'; +import { WindowsWebView } from '../../../../../src/main/platform/windows/windows-webkit-view'; + +/** A WindowsWebContents over a stub view (the real one needs WinCairo). */ +const createContents = () => { + const evaluated: string[] = []; + const stubView = { evaluateJavaScript: (code: string) => evaluated.push(code) }; + const create = spyOn(WindowsWebView, 'create').mockImplementation( + () => stubView as unknown as WindowsWebView, + ); + const contents = new WindowsWebContents(0n, 800, 600); + const options = create.mock.calls[0]?.[0]; + if (options === undefined) { + throw new Error('WindowsWebView.create was not called'); + } + return { contents, options, evaluated }; +}; + +const collectWarnings = (): string[] => { + const warnings: string[] = []; + setLogSink((record: LogRecord) => { + if (record.level === 'warn') { + warnings.push(record.message); + } + }); + return warnings; +}; + +afterEach(() => { + mock.restore(); + resetLogger(); +}); + +describe('WindowsWebContents', () => { + test('setWindowOpenHandler warns that the handler is never called', () => { + const warnings = collectWarnings(); + const { contents } = createContents(); + contents.setWindowOpenHandler(() => undefined); + expect(warnings).toEqual([expect.stringContaining('setWindowOpenHandler')]); + }); +}); From c80bc742eb9b2be268fb2cdab19adfa81674c06b Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:17:35 -0700 Subject: [PATCH 207/586] fix: remove the tray's temp icon directory on destroy --- src/main/api/tray.ts | 5 ++++- tests/unit/main/api/tray.test.ts | 19 ++++++++++++++++--- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/main/api/tray.ts b/src/main/api/tray.ts index 8c33eefe..73d5cbd8 100644 --- a/src/main/api/tray.ts +++ b/src/main/api/tray.ts @@ -1,6 +1,6 @@ import { EventEmitter } from 'node:events'; import { selectBackend } from '../platform/index'; -import { mkdtempSync, writeFileSync } from 'node:fs'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { linuxTrayBackend } from '../platform/linux/sni-tray'; @@ -124,6 +124,9 @@ export class Tray extends EventEmitter { } this.#destroyed = true; this.#instance.destroy(); + if (this.#iconDir !== undefined) { + rmSync(this.#iconDir, { recursive: true, force: true }); + } } isDestroyed(): boolean { diff --git a/tests/unit/main/api/tray.test.ts b/tests/unit/main/api/tray.test.ts index 79d4d3ed..591c1d63 100644 --- a/tests/unit/main/api/tray.test.ts +++ b/tests/unit/main/api/tray.test.ts @@ -93,17 +93,30 @@ describe('Tray construction', () => { const { readFileSync } = await import('node:fs'); const png = Buffer.from([0x89, 0x50, 0x4e, 0x47]); const fakeImage = { toPNG: () => png, isTemplateImage: () => false } as unknown as TrayImage; - new Tray(fakeImage); + const tray = new Tray(fakeImage); const path = created[0]?.image ?? ''; expect(path.endsWith('icon.png')).toBe(true); - expect(path).not.toBe('[object Object]'); expect(Array.from(readFileSync(path))).toEqual(Array.from(png)); + tray.destroy(); + }); + + test('destroy removes the temp icon it materialized', async () => { + const { existsSync } = await import('node:fs'); + const fakeImage = { + toPNG: () => Buffer.from([0x89]), + isTemplateImage: () => false, + } as unknown as TrayImage; + const tray = new Tray(fakeImage); + const path = created[0]?.image ?? ''; + expect(existsSync(path)).toBe(true); + tray.destroy(); + expect(existsSync(path)).toBe(false); }); test('carries a NativeImage template flag to the backend', () => { const png = Buffer.from([0x89, 0x50, 0x4e, 0x47]); const fakeImage = { toPNG: () => png, isTemplateImage: () => true } as unknown as TrayImage; - new Tray(fakeImage); + new Tray(fakeImage).destroy(); expect(createOptions[0]).toEqual({ template: true }); new Tray('/tmp/icon.png'); expect(createOptions[1]).toEqual({}); From 0130306056a62d2e2b6d6501fdd323a7d2e66334 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:17:38 -0700 Subject: [PATCH 208/586] perf: compile each COM method trampoline once instead of per call --- .../platform/windows/windows-native-image.ts | 35 +++++++++++-------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/src/main/platform/windows/windows-native-image.ts b/src/main/platform/windows/windows-native-image.ts index 747967ac..d5e6efb8 100644 --- a/src/main/platform/windows/windows-native-image.ts +++ b/src/main/platform/windows/windows-native-image.ts @@ -42,21 +42,28 @@ export const ensureGdiplus = (): void => { gdiplusStarted = true; }; -/** - * Release one COM object (an `IStream`) by walking its vtable to `IUnknown::Release` - * and calling it. The single COM vtable call in the codebase — every other Windows - * surface is flat-C. `read.u64` reads the object's vtable pointer and the function - * pointer at the Release slot; `CFunction` makes that address callable. - */ -const releaseStream = (object: bigint): void => { +const comMethods = new Map>(); + +/** Vtable `slot` of COM `object` as a callable, compiled once per method address. */ +const comMethod = ( + object: bigint, + slot: number, + args: readonly FFIType[], + returns: FFIType, +): ReturnType => { const vtable = read.u64(Number(object) as Pointer, 0); - const releaseFn = read.u64(Number(vtable) as Pointer, IUNKNOWN_RELEASE_SLOT * POINTER_SIZE); - const release = CFunction({ - ptr: Number(releaseFn) as Pointer, - args: [FFIType.u64], - returns: FFIType.u32, - }); - release(object); + const address = read.u64(Number(vtable) as Pointer, slot * POINTER_SIZE); + let method = comMethods.get(address); + if (method === undefined) { + method = CFunction({ ptr: Number(address) as Pointer, args, returns }); + comMethods.set(address, method); + } + return method; +}; + +/** Drop our reference to an `IStream`. */ +const releaseStream = (stream: bigint): void => { + comMethod(stream, IUNKNOWN_RELEASE_SLOT, [FFIType.u64], FFIType.u32)(stream); }; /** Read a GDI+ image's pixel dimensions via the scalar `GdipGetImage{Width,Height}` getters. */ From 5337e636ef48d49848202dd350094d270154715f Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:17:29 -0700 Subject: [PATCH 209/586] fix: honor toJPEG quality on Linux via gdk-pixbuf save options --- src/main/platform/linux/gdk-native-image.ts | 25 +++++++++++-------- .../linux/gdk-native-image.test.ts | 12 +++++++++ 2 files changed, 27 insertions(+), 10 deletions(-) diff --git a/src/main/platform/linux/gdk-native-image.ts b/src/main/platform/linux/gdk-native-image.ts index a3791693..8e6aa1b4 100644 --- a/src/main/platform/linux/gdk-native-image.ts +++ b/src/main/platform/linux/gdk-native-image.ts @@ -74,11 +74,8 @@ const decodeBuffer = (bytes: Uint8Array): DecodedImage => { return decodeFromPixbuf(pixbuf === null ? null : Number(pixbuf)); }; -/** - * Encode a pixbuf to `type` ("png"/"jpeg") via `gdk_pixbuf_save_to_bufferv` with - * NULL option arrays (default quality), copying the out buffer then freeing it. - */ -const encode = (handle: NativeImageHandle, type: string): Uint8Array => { +/** Encode to `type` ("png"/"jpeg"); `quality` (0-100) applies to JPEG only. */ +const encode = (handle: NativeImageHandle, type: string, quality?: number): Uint8Array => { const pixbuf = handleToPtr(handle); if (pixbuf === null) { return new Uint8Array(0); @@ -90,13 +87,22 @@ const encode = (handle: NativeImageHandle, type: string): Uint8Array => { // length, mirroring the BigInt64Array out-pointer pattern used elsewhere. const bufferOut = new BigUint64Array(1); const sizeOut = new BigUint64Array(1); + // NULL-terminated char** option lists; [NULL] alone means no options. + const key = cstr('quality'); + const value = cstr(String(Math.min(100, Math.max(0, Math.round(quality ?? 0))))); + const optionKeys = new BigUint64Array(2); + const optionValues = new BigUint64Array(2); + if (quality !== undefined) { + optionKeys[0] = BigInt(ptr(key)); + optionValues[0] = BigInt(ptr(value)); + } const ok = pixbufFFI.symbols.gdk_pixbuf_save_to_bufferv( pixbuf as Parameters[0], ptr(bufferOut), ptr(sizeOut), cstr(type), - null, - null, + ptr(optionKeys), + ptr(optionValues), null, ); if (ok !== 1) { @@ -167,9 +173,8 @@ const crop = ( export const gdkNativeImageBackend: NativeImageBackend = { decode: (source) => (typeof source === 'string' ? decodePath(source) : decodeBuffer(source)), encodePng: (handle: NativeImageHandle): Uint8Array => encode(handle, 'png'), - // Linux v1 uses GdkPixbuf's default JPEG quality (the `quality` factor is - // honored on macOS; option-key arrays for Linux are a follow-up). - encodeJpeg: (handle: NativeImageHandle): Uint8Array => encode(handle, 'jpeg'), + encodeJpeg: (handle: NativeImageHandle, quality: number): Uint8Array => + encode(handle, 'jpeg', quality), resize, crop, }; diff --git a/tests/integration/linux/gdk-native-image.test.ts b/tests/integration/linux/gdk-native-image.test.ts index 42cfb62b..54eb0bf5 100644 --- a/tests/integration/linux/gdk-native-image.test.ts +++ b/tests/integration/linux/gdk-native-image.test.ts @@ -81,6 +81,18 @@ if (currentPlatform() === 'linux') { expect(jpeg[1]).toBe(0xd8); }); + test('toJPEG(quality) reaches the encoder as its quantization table', () => { + setNativeImageBackendForTesting(undefined); + const image = nativeImage.createFromBuffer(makeTinyPng()); + /** The first luminance DC quantizer after the DQT marker: 1 at quality 100, 8 at 75. */ + const dcQuantizer = (jpeg: Uint8Array): number | undefined => { + const marker = jpeg.findIndex((byte, i) => byte === 0xff && jpeg[i + 1] === 0xdb); + return marker === -1 ? undefined : jpeg[marker + 5]; + }; + expect(dcQuantizer(image.toJPEG(100))).toBe(1); + expect(dcQuantizer(image.toJPEG(10)) ?? 0).toBeGreaterThan(8); + }); + test('a bad path decodes to an empty image (no crash)', () => { setNativeImageBackendForTesting(undefined); const image = nativeImage.createFromPath('/no/such/bunmaska/image.png'); From 80be1ae5432729c2d47328531d621bc632e7e868 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:17:50 -0700 Subject: [PATCH 210/586] fix: reject a malformed update public key in setFeedURL --- src/common/signature.ts | 9 +++++++++ src/main/api/auto-updater.ts | 7 ++++++- tests/unit/main/api/auto-updater.test.ts | 14 ++++++++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/common/signature.ts b/src/common/signature.ts index ba73db1c..c9d8adda 100644 --- a/src/common/signature.ts +++ b/src/common/signature.ts @@ -22,6 +22,15 @@ export const generateSigningKeyPair = (): SigningKeyPair => { return { publicKey, privateKey }; }; +/** Whether `pem` parses as an Ed25519 public key (a mangled PEM would otherwise fail every verify). */ +export const isEd25519PublicKey = (pem: string): boolean => { + try { + return createPublicKey(pem).asymmetricKeyType === 'ed25519'; + } catch { + return false; + } +}; + /** Sign artifact bytes with a PEM private key; returns a base64 detached signature. */ export const signArtifact = (privateKeyPem: string, message: Uint8Array): string => sign(null, message, createPrivateKey(privateKeyPem)).toString('base64'); diff --git a/src/main/api/auto-updater.ts b/src/main/api/auto-updater.ts index 531f1697..eba81cb2 100644 --- a/src/main/api/auto-updater.ts +++ b/src/main/api/auto-updater.ts @@ -10,7 +10,7 @@ import { type UpdateManifest, } from '../../common/manifest'; import { type Arch, currentArch as hostArch, currentPlatform } from '../../common/platform'; -import { verifyArtifact } from '../../common/signature'; +import { isEd25519PublicKey, verifyArtifact } from '../../common/signature'; import { app } from './app'; import { DEFAULT_APP_VERSION } from './app-metadata'; import { defaultInstall } from './update-installer'; @@ -194,6 +194,11 @@ export class AutoUpdaterImpl extends EventEmitter { `autoUpdater.setFeedURL: refusing a non-HTTPS feed url ${JSON.stringify(opts.url)} (https is required; http is allowed only for localhost)`, ); } + if (opts.publicKey !== undefined && !isEd25519PublicKey(opts.publicKey)) { + throw new Error( + 'autoUpdater.setFeedURL: publicKey is not a PEM Ed25519 public key (use the update-public-key.pem from bunmaska keygen)', + ); + } this.#feedURL = opts.url; if (opts.publicKey !== undefined) { this.#publicKey = opts.publicKey; diff --git a/tests/unit/main/api/auto-updater.test.ts b/tests/unit/main/api/auto-updater.test.ts index a729077a..60e24b96 100644 --- a/tests/unit/main/api/auto-updater.test.ts +++ b/tests/unit/main/api/auto-updater.test.ts @@ -1,4 +1,5 @@ import { describe, expect, test } from 'bun:test'; +import { generateKeyPairSync } from 'node:crypto'; import { readFileSync, rmSync, statSync } from 'node:fs'; import { dirname } from 'node:path'; import { @@ -114,6 +115,19 @@ describe('autoUpdater.setFeedURL / getFeedURL', () => { expect(() => updater.setFeedURL('not a url')).toThrow(/invalid url/i); }); + test('rejects a publicKey that is not a PEM Ed25519 public key', () => { + const { updater } = makeUpdater({}); + const ecKey = generateKeyPairSync('ec', { + namedCurve: 'P-256', + publicKeyEncoding: { type: 'spki', format: 'pem' }, + privateKeyEncoding: { type: 'pkcs8', format: 'pem' }, + }).publicKey; + for (const publicKey of ['not a pem', KEYS.publicKey.replaceAll('\n', ''), ecKey]) { + expect(() => updater.setFeedURL({ url: 'https://feed', publicKey })).toThrow(/Ed25519/); + } + expect(() => updater.setFeedURL(FEED)).not.toThrow(); + }); + test('allows http only for a localhost dev feed', () => { const { updater } = makeUpdater({}); updater.setFeedURL('http://localhost:8080/feed'); From 335b871c2a09cb3e15da6b31fc7b5052b3f797f4 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:17:51 -0700 Subject: [PATCH 211/586] fix: warn that protocol.handle schemes are unserved on Windows --- src/main/platform/windows/windows-web-contents.ts | 6 ++++++ .../platform/windows/windows-web-contents.test.ts | 15 +++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/src/main/platform/windows/windows-web-contents.ts b/src/main/platform/windows/windows-web-contents.ts index 477bf402..f690c680 100644 --- a/src/main/platform/windows/windows-web-contents.ts +++ b/src/main/platform/windows/windows-web-contents.ts @@ -1,5 +1,6 @@ import { UnsupportedPlatformError } from '../../../common/errors'; import { createLogger } from '../../../common/logger'; +import { protocol } from '../../api/protocol'; import { generateChannelId, generateIsolatedChannelSetup, @@ -114,6 +115,11 @@ export class WindowsWebContents implements NativeWebContents { readonly #windowOpCallbacks: Array<(op: string) => void> = []; constructor(hwnd: bigint, width: number, height: number, preloadScript?: string) { + const schemes = protocol.getRegisteredSchemes(); + if (schemes.length > 0) { + // ponytail: the WinCairo C API has no URL-scheme handler hook at wpewebkit-2.52.5. + log.warn(`protocol.handle schemes are not served on Windows yet: ${schemes.join(', ')}`); + } const channelId = generateChannelId(); const userScripts: string[] = [ generateIsolatedChannelSetup(channelId), diff --git a/tests/unit/main/platform/windows/windows-web-contents.test.ts b/tests/unit/main/platform/windows/windows-web-contents.test.ts index 13daeba7..b1686180 100644 --- a/tests/unit/main/platform/windows/windows-web-contents.test.ts +++ b/tests/unit/main/platform/windows/windows-web-contents.test.ts @@ -1,5 +1,6 @@ import { afterEach, describe, expect, mock, spyOn, test } from 'bun:test'; import { type LogRecord, resetLogger, setLogSink } from '../../../../../src/common/logger'; +import { protocol } from '../../../../../src/main/api/protocol'; import { WindowsWebContents } from '../../../../../src/main/platform/windows/windows-web-contents'; import { WindowsWebView } from '../../../../../src/main/platform/windows/windows-webkit-view'; @@ -31,6 +32,7 @@ const collectWarnings = (): string[] => { afterEach(() => { mock.restore(); resetLogger(); + protocol.clearForTesting(); }); describe('WindowsWebContents', () => { @@ -40,4 +42,17 @@ describe('WindowsWebContents', () => { contents.setWindowOpenHandler(() => undefined); expect(warnings).toEqual([expect.stringContaining('setWindowOpenHandler')]); }); + + test('warns when protocol.handle schemes are registered, since none are served', () => { + protocol.handle('myapp', () => ({ data: 'hi' })); + const warnings = collectWarnings(); + createContents(); + expect(warnings).toEqual([expect.stringContaining('myapp')]); + }); + + test('does not warn about schemes when none are registered', () => { + const warnings = collectWarnings(); + createContents(); + expect(warnings).toEqual([]); + }); }); From e89faf24fb846bd6d82804ccdb80c1d117cfaf4a Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:18:07 -0700 Subject: [PATCH 212/586] fix: reject non-URL strings in shell.openExternal on every platform --- src/main/api/shell.ts | 9 ++++++++- tests/unit/main/api/shell.test.ts | 7 +++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/main/api/shell.ts b/src/main/api/shell.ts index 0b699c7b..55618954 100644 --- a/src/main/api/shell.ts +++ b/src/main/api/shell.ts @@ -47,9 +47,16 @@ export type Shell = { beep(): void; }; +/** + * An absolute URL only, as Electron requires. Windows `ShellExecuteW` would otherwise run a + * bare path or program name (`C:\x\payload.exe`, `calc`), and a one-letter scheme is a drive. + */ +const isExternalUrl = (url: string): boolean => + URL.canParse(url) && new URL(url).protocol.length > 2; + export const shell: Shell = { openExternal(url) { - return Promise.resolve(getBackend().openExternal(url)); + return Promise.resolve(isExternalUrl(url) && getBackend().openExternal(url)); }, openPath(path) { const ok = getBackend().openPath(path); diff --git a/tests/unit/main/api/shell.test.ts b/tests/unit/main/api/shell.test.ts index 0ff3ead8..a84ce6cc 100644 --- a/tests/unit/main/api/shell.test.ts +++ b/tests/unit/main/api/shell.test.ts @@ -42,6 +42,13 @@ describe('shell.openExternal', () => { expect(calls).toEqual(['openExternal:https://example.com']); }); + test('resolves false for a path or program name without reaching the backend', async () => { + for (const notAUrl of ['calc', 'C:\\Users\\x\\payload.exe', 'c:/x.exe', '/etc/passwd']) { + expect(await shell.openExternal(notAUrl)).toBe(false); + } + expect(calls).toEqual([]); + }); + test('resolves false when the backend reports failure', async () => { openExternalResult = false; expect(await shell.openExternal('bad:')).toBe(false); From 75492bc9c96f768ea68ece8a8eb6f095ab9841e3 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:18:07 -0700 Subject: [PATCH 213/586] refactor: drop Linux FFI symbols nothing calls --- src/main/platform/linux/gdbus-ffi.ts | 5 ----- src/main/platform/linux/gdk-pixbuf-ffi.ts | 5 ----- src/main/platform/linux/glib-ffi.ts | 13 ------------- src/main/platform/linux/gobject-ffi.ts | 4 ---- src/main/platform/linux/gtk-dialog-ffi.ts | 4 ---- src/main/platform/linux/gtk-ffi.ts | 8 -------- src/main/platform/linux/libnotify-ffi.ts | 5 ----- src/main/platform/linux/webkitgtk-ffi.ts | 8 -------- src/main/platform/linux/x11-ffi.ts | 2 -- tests/integration/linux/glib-ffi.test.ts | 8 +------- tests/integration/linux/gobject-ffi.test.ts | 1 - tests/integration/linux/gtk-ffi.test.ts | 2 -- tests/integration/linux/notification.test.ts | 1 - tests/integration/linux/power-monitor.test.ts | 6 +----- tests/integration/linux/tray.test.ts | 1 - tests/integration/linux/webkitgtk-ffi.test.ts | 16 ++++++++++++---- .../main/platform/linux/linux-ffi-abi.test.ts | 4 +--- .../unit/main/platform/linux/x11-keymap.test.ts | 1 - 18 files changed, 15 insertions(+), 79 deletions(-) diff --git a/src/main/platform/linux/gdbus-ffi.ts b/src/main/platform/linux/gdbus-ffi.ts index bf1c3357..d7c9dc75 100644 --- a/src/main/platform/linux/gdbus-ffi.ts +++ b/src/main/platform/linux/gdbus-ffi.ts @@ -96,11 +96,6 @@ export const GDBUS_FFI_SYMBOLS = { ], returns: FFIType.u32, }, - // (connection, subscription_id:guint) -> void. - g_dbus_connection_signal_unsubscribe: { - args: [FFIType.pointer, FFIType.u32], - returns: FFIType.void, - }, // Bounded REMOTE method call. SAFE on the pumped thread: the reply is read by the // connection's PRIVATE GDBusWorker thread and call_sync awaits it on its OWN private // GMainContext (gdbusconnection.c), so it blocks only THIS thread for a bounded round diff --git a/src/main/platform/linux/gdk-pixbuf-ffi.ts b/src/main/platform/linux/gdk-pixbuf-ffi.ts index e5b976cc..cc7756e7 100644 --- a/src/main/platform/linux/gdk-pixbuf-ffi.ts +++ b/src/main/platform/linux/gdk-pixbuf-ffi.ts @@ -56,11 +56,6 @@ export const GDK_PIXBUF_FFI_SYMBOLS = { args: [FFIType.pointer], returns: FFIType.i32, }, - // (GdkPixbuf*) -> gboolean whether the pixbuf has an alpha channel. - gdk_pixbuf_get_has_alpha: { - args: [FFIType.pointer], - returns: FFIType.i32, - }, // (src, dest_width, dest_height, GdkInterpType /*BILINEAR=2*/) -> GdkPixbuf* (transfer-full) gdk_pixbuf_scale_simple: { args: [FFIType.pointer, FFIType.i32, FFIType.i32, FFIType.i32], diff --git a/src/main/platform/linux/glib-ffi.ts b/src/main/platform/linux/glib-ffi.ts index b1f75492..3fee0af1 100644 --- a/src/main/platform/linux/glib-ffi.ts +++ b/src/main/platform/linux/glib-ffi.ts @@ -93,10 +93,6 @@ export const dlopenLinux = >( /** The GLib FFI symbol descriptor table. */ export const GLIB_FFI_SYMBOLS = { - g_main_context_default: { - args: [], - returns: FFIType.pointer, - }, g_main_context_iteration: { args: [FFIType.pointer, FFIType.i32], returns: FFIType.i32, @@ -212,10 +208,6 @@ export const GLIB_FFI_SYMBOLS = { args: [FFIType.cstring], returns: FFIType.pointer, }, - g_variant_type_free: { - args: [FFIType.pointer], - returns: FFIType.void, - }, // (type:GVariantType*) -> GVariantBuilder* (heap; g_variant_builder_unref). g_variant_builder_new: { args: [FFIType.pointer], @@ -257,11 +249,6 @@ export const GLIB_FFI_SYMBOLS = { ], returns: FFIType.pointer, }, - // (value) -> GVariant*. Sinks a floating ref + adds one full ref (so we OWN the value). - g_variant_ref_sink: { - args: [FFIType.pointer], - returns: FFIType.pointer, - }, // (GList*) -> void. Frees the LIST CELLS ONLY - each node's data must already // have been freed by its owner (e.g. soup_cookie_free), or it leaks. g_list_free: { diff --git a/src/main/platform/linux/gobject-ffi.ts b/src/main/platform/linux/gobject-ffi.ts index a7991175..b7f49c35 100644 --- a/src/main/platform/linux/gobject-ffi.ts +++ b/src/main/platform/linux/gobject-ffi.ts @@ -48,10 +48,6 @@ export const GOBJECT_FFI_SYMBOLS = { args: [FFIType.pointer, FFIType.u64], returns: FFIType.void, }, - g_object_ref: { - args: [FFIType.pointer], - returns: FFIType.pointer, - }, g_object_unref: { args: [FFIType.pointer], returns: FFIType.void, diff --git a/src/main/platform/linux/gtk-dialog-ffi.ts b/src/main/platform/linux/gtk-dialog-ffi.ts index 6f078579..18f2f7a6 100644 --- a/src/main/platform/linux/gtk-dialog-ffi.ts +++ b/src/main/platform/linux/gtk-dialog-ffi.ts @@ -103,10 +103,6 @@ export const GTK_DIALOG_FFI_SYMBOLS = { args: [FFIType.pointer, FFIType.cstring], returns: FFIType.void, }, - gtk_file_filter_set_name: { - args: [FFIType.pointer, FFIType.cstring], - returns: FFIType.void, - }, gtk_file_dialog_set_default_filter: { args: [FFIType.pointer, FFIType.pointer], returns: FFIType.void, diff --git a/src/main/platform/linux/gtk-ffi.ts b/src/main/platform/linux/gtk-ffi.ts index ea82aacc..0c679570 100644 --- a/src/main/platform/linux/gtk-ffi.ts +++ b/src/main/platform/linux/gtk-ffi.ts @@ -26,10 +26,6 @@ export const GTK_FFI_SYMBOLS = { args: [FFIType.pointer, FFIType.cstring], returns: FFIType.void, }, - gtk_window_get_title: { - args: [FFIType.pointer], - returns: FFIType.pointer, - }, gtk_window_set_default_size: { args: [FFIType.pointer, FFIType.i32, FFIType.i32], returns: FFIType.void, @@ -92,10 +88,6 @@ export const GTK_FFI_SYMBOLS = { args: [FFIType.pointer], returns: FFIType.i32, }, - gtk_widget_grab_focus: { - args: [FFIType.pointer], - returns: FFIType.i32, - }, gtk_about_dialog_new: { args: [], returns: FFIType.pointer, diff --git a/src/main/platform/linux/libnotify-ffi.ts b/src/main/platform/linux/libnotify-ffi.ts index 633e56ab..296f3bcd 100644 --- a/src/main/platform/linux/libnotify-ffi.ts +++ b/src/main/platform/linux/libnotify-ffi.ts @@ -48,11 +48,6 @@ export const LIBNOTIFY_FFI_SYMBOLS = { args: [FFIType.pointer, FFIType.pointer], returns: FFIType.i32, }, - // (notification, timeout_ms) -> void; -1 = default, 0 = never expire. - notify_notification_set_timeout: { - args: [FFIType.pointer, FFIType.i32], - returns: FFIType.void, - }, // (NotifyNotification*, const char* key, GVariant* value) -> void; sinks the floating variant notify_notification_set_hint: { args: [FFIType.pointer, FFIType.cstring, FFIType.pointer], diff --git a/src/main/platform/linux/webkitgtk-ffi.ts b/src/main/platform/linux/webkitgtk-ffi.ts index 168e6c1b..2b142ca4 100644 --- a/src/main/platform/linux/webkitgtk-ffi.ts +++ b/src/main/platform/linux/webkitgtk-ffi.ts @@ -40,10 +40,6 @@ export const WEBKIT_SNAPSHOT_OPTIONS_NONE = 0; * (a real world name, e.g. `BunmaskaPreload`) — the isolated-world injection path. */ export const WEBKITGTK_FFI_SYMBOLS = { - webkit_web_view_new: { - args: [], - returns: FFIType.pointer, - }, webkit_web_view_get_type: { args: [], returns: FFIType.u64, @@ -127,10 +123,6 @@ export const WEBKITGTK_FFI_SYMBOLS = { ], returns: FFIType.void, }, - webkit_web_view_get_user_content_manager: { - args: [FFIType.pointer], - returns: FFIType.pointer, - }, webkit_web_view_get_settings: { args: [FFIType.pointer], returns: FFIType.pointer, diff --git a/src/main/platform/linux/x11-ffi.ts b/src/main/platform/linux/x11-ffi.ts index e0f8bedc..4b5b00da 100644 --- a/src/main/platform/linux/x11-ffi.ts +++ b/src/main/platform/linux/x11-ffi.ts @@ -23,8 +23,6 @@ const LIBX11_PATH = 'libX11.so.6'; export const X11_FFI_SYMBOLS = { // (const char *display_name) -> Display* (NULL = $DISPLAY) XOpenDisplay: { args: [FFIType.cstring], returns: FFIType.pointer }, - // (Display*) -> int - XCloseDisplay: { args: [FFIType.pointer], returns: FFIType.i32 }, // (Display*) -> Window (XID, unsigned long) XDefaultRootWindow: { args: [FFIType.pointer], returns: FFIType.u64 }, // (Display*, KeySym) -> KeyCode (unsigned char) diff --git a/tests/integration/linux/glib-ffi.test.ts b/tests/integration/linux/glib-ffi.test.ts index 45a1ed65..9c72096f 100644 --- a/tests/integration/linux/glib-ffi.test.ts +++ b/tests/integration/linux/glib-ffi.test.ts @@ -4,10 +4,9 @@ import { loadGlibFFI } from '../../../src/main/platform/linux/glib-ffi'; if (currentPlatform() === 'linux') { describe('GLib FFI on Linux', () => { - test('resolves the main-context, g_free, and default-context symbols', () => { + test('resolves the main-context and g_free symbols', () => { const lib = loadGlibFFI(); for (const name of [ - 'g_main_context_default', 'g_main_context_iteration', 'g_main_context_pending', 'g_free', @@ -20,10 +19,5 @@ if (currentPlatform() === 'linux') { const lib = loadGlibFFI(); expect(() => lib.symbols.g_free(null)).not.toThrow(); }); - - test('g_main_context_default returns a non-null pointer', () => { - const lib = loadGlibFFI(); - expect(lib.symbols.g_main_context_default()).not.toBeNull(); - }); }); } diff --git a/tests/integration/linux/gobject-ffi.test.ts b/tests/integration/linux/gobject-ffi.test.ts index 63b27224..41009d39 100644 --- a/tests/integration/linux/gobject-ffi.test.ts +++ b/tests/integration/linux/gobject-ffi.test.ts @@ -12,7 +12,6 @@ if (currentPlatform() === 'linux') { for (const name of [ 'g_signal_connect_data', 'g_signal_handler_disconnect', - 'g_object_ref', 'g_object_unref', 'g_object_new', ] as const) { diff --git a/tests/integration/linux/gtk-ffi.test.ts b/tests/integration/linux/gtk-ffi.test.ts index cc458291..ca5988c6 100644 --- a/tests/integration/linux/gtk-ffi.test.ts +++ b/tests/integration/linux/gtk-ffi.test.ts @@ -55,8 +55,6 @@ if (currentPlatform() === 'linux') { 'gtk_window_is_maximized', 'gtk_widget_get_width', 'gtk_widget_get_height', - 'gtk_window_get_title', - 'gtk_widget_grab_focus', ] as const) { expect(typeof lib.symbols[name]).toBe('function'); } diff --git a/tests/integration/linux/notification.test.ts b/tests/integration/linux/notification.test.ts index 1dd82bcf..dca36be2 100644 --- a/tests/integration/linux/notification.test.ts +++ b/tests/integration/linux/notification.test.ts @@ -25,7 +25,6 @@ describe.skipIf(!isLinux)('libnotify FFI + Linux notification backend (Linux)', 'notify_notification_new', 'notify_notification_show', 'notify_notification_close', - 'notify_notification_set_timeout', ] as const) { expect(typeof lib.symbols[name]).toBe('function'); } diff --git a/tests/integration/linux/power-monitor.test.ts b/tests/integration/linux/power-monitor.test.ts index 50d39854..629c6458 100644 --- a/tests/integration/linux/power-monitor.test.ts +++ b/tests/integration/linux/power-monitor.test.ts @@ -18,11 +18,7 @@ if (currentPlatform() === 'linux') { describe('Linux powerMonitor backend (GDBus/logind)', () => { test('loadGDBusFFI resolves every GDBus symbol', () => { const gdbus = loadGDBusFFI(); - for (const name of [ - 'g_bus_get_sync', - 'g_dbus_connection_signal_subscribe', - 'g_dbus_connection_signal_unsubscribe', - ] as const) { + for (const name of ['g_bus_get_sync', 'g_dbus_connection_signal_subscribe'] as const) { expect(typeof gdbus.symbols[name]).toBe('function'); } }); diff --git a/tests/integration/linux/tray.test.ts b/tests/integration/linux/tray.test.ts index 3b2a69df..8055cf84 100644 --- a/tests/integration/linux/tray.test.ts +++ b/tests/integration/linux/tray.test.ts @@ -45,7 +45,6 @@ if (currentPlatform() === 'linux') { 'gdk_pixbuf_get_pixels', 'gdk_pixbuf_get_rowstride', 'gdk_pixbuf_get_n_channels', - 'gdk_pixbuf_get_has_alpha', ] as const) { expect(typeof pix.symbols[name]).toBe('function'); } diff --git a/tests/integration/linux/webkitgtk-ffi.test.ts b/tests/integration/linux/webkitgtk-ffi.test.ts index 055f1836..a7733ba6 100644 --- a/tests/integration/linux/webkitgtk-ffi.test.ts +++ b/tests/integration/linux/webkitgtk-ffi.test.ts @@ -1,14 +1,23 @@ import { describe, expect, test } from 'bun:test'; import { currentPlatform } from '../../../src/common/platform'; import { cstr } from '../../../src/main/platform/cstr'; +import { loadGObjectFFI } from '../../../src/main/platform/linux/gobject-ffi'; import { loadGtkFFI } from '../../../src/main/platform/linux/gtk-ffi'; import { loadWebKitGtkFFI, readGetUriResult } from '../../../src/main/platform/linux/webkitgtk-ffi'; +/** A WebKitWebView with no construct properties: g_object_new(type, NULL). */ +const newWebView = () => + loadGObjectFFI().symbols.g_object_new( + loadWebKitGtkFFI().symbols.webkit_web_view_get_type(), + null, + null, + null, + ); + if (currentPlatform() === 'linux') { describe('WebKitGTK FFI on Linux', () => { test('resolves the core web-view symbols (proves the library + names are correct)', () => { const lib = loadWebKitGtkFFI(); - expect(typeof lib.symbols.webkit_web_view_new).toBe('function'); expect(typeof lib.symbols.webkit_web_view_load_uri).toBe('function'); expect(typeof lib.symbols.webkit_web_view_load_html).toBe('function'); expect(typeof lib.symbols.webkit_web_view_get_uri).toBe('function'); @@ -24,7 +33,6 @@ if (currentPlatform() === 'linux') { 'webkit_web_view_can_go_back', 'webkit_web_view_can_go_forward', 'webkit_web_view_evaluate_javascript', - 'webkit_web_view_get_user_content_manager', 'webkit_user_content_manager_new', 'webkit_user_content_manager_register_script_message_handler', 'webkit_user_content_manager_add_script', @@ -51,7 +59,7 @@ if (currentPlatform() === 'linux') { const webkit = loadWebKitGtkFFI(); // get_uri is NULL before any load -> readGetUriResult guards it to ''. - const view = webkit.symbols.webkit_web_view_new(); + const view = newWebView(); expect(view).not.toBeNull(); expect(readGetUriResult(webkit.symbols.webkit_web_view_get_uri(view))).toBe(''); @@ -93,7 +101,7 @@ if (currentPlatform() === 'linux') { return; // No display. } const webkit = loadWebKitGtkFFI(); - const view = webkit.symbols.webkit_web_view_new(); + const view = newWebView(); const settings = webkit.symbols.webkit_web_view_get_settings(view); expect(settings).not.toBeNull(); // Must resolve + not crash; the UA takes effect on the next navigation. diff --git a/tests/unit/main/platform/linux/linux-ffi-abi.test.ts b/tests/unit/main/platform/linux/linux-ffi-abi.test.ts index c3879560..8186b3ad 100644 --- a/tests/unit/main/platform/linux/linux-ffi-abi.test.ts +++ b/tests/unit/main/platform/linux/linux-ffi-abi.test.ts @@ -98,7 +98,6 @@ describe('gboolean is i32, never bool', () => { * transfer is full, hand the buffer back to g_free. */ const POINTER_GETTERS: ReadonlyArray = [ - ['gtk_window_get_title', GTK_FFI_SYMBOLS.gtk_window_get_title], ['webkit_web_view_get_uri', WEBKITGTK_FFI_SYMBOLS.webkit_web_view_get_uri], ['jsc_value_to_string', JSC_FFI_SYMBOLS.jsc_value_to_string], ['g_file_get_path', GIO_FFI_SYMBOLS.g_file_get_path], @@ -156,9 +155,8 @@ describe('width-sensitive scalars', () => { expect(GOBJECT_FFI_SYMBOLS.g_signal_handler_disconnect.args[1]).toBe(T.u64); }); - test('a D-Bus subscription id is guint (u32) on both sides', () => { + test('a D-Bus subscription id is guint (u32)', () => { expect(GDBUS_FFI_SYMBOLS.g_dbus_connection_signal_subscribe.returns).toBe(T.u32); - expect(GDBUS_FFI_SYMBOLS.g_dbus_connection_signal_unsubscribe.args[1]).toBe(T.u32); }); test('webkit_uri_scheme_request_finish takes a 64-bit stream length', () => { diff --git a/tests/unit/main/platform/linux/x11-keymap.test.ts b/tests/unit/main/platform/linux/x11-keymap.test.ts index a3fa440d..ae822330 100644 --- a/tests/unit/main/platform/linux/x11-keymap.test.ts +++ b/tests/unit/main/platform/linux/x11-keymap.test.ts @@ -82,7 +82,6 @@ describe('X11_FFI_SYMBOLS shape', () => { test('declares the grab/poll symbols the backend needs', () => { for (const name of [ 'XOpenDisplay', - 'XCloseDisplay', 'XDefaultRootWindow', 'XKeysymToKeycode', 'XStringToKeysym', From 7292d4be7cdbd0bf1e447cd1a50d03456f756687 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:18:15 -0700 Subject: [PATCH 214/586] fix: ignore a null Windows exec result instead of throwing --- src/main/platform/windows/windows-web-contents.ts | 4 ++-- .../platform/windows/windows-web-contents.test.ts | 11 +++++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/main/platform/windows/windows-web-contents.ts b/src/main/platform/windows/windows-web-contents.ts index f690c680..6c972efa 100644 --- a/src/main/platform/windows/windows-web-contents.ts +++ b/src/main/platform/windows/windows-web-contents.ts @@ -70,14 +70,14 @@ class WindowsExecResultChannel { /** Settle the pending exec for the `{ execId, ok, result?, error? }` JSON. */ deliverExecResult(json: string): void { - let outcome: { execId?: number; ok?: boolean; result?: unknown; error?: string }; + let outcome: { execId?: number; ok?: boolean; result?: unknown; error?: string } | null; try { outcome = JSON.parse(json); } catch (error) { log.warn('dropping malformed exec result', error); return; } - if (typeof outcome.execId !== 'number') { + if (typeof outcome?.execId !== 'number') { return; } const pending = this.#pending.get(outcome.execId); diff --git a/tests/unit/main/platform/windows/windows-web-contents.test.ts b/tests/unit/main/platform/windows/windows-web-contents.test.ts index b1686180..0f362403 100644 --- a/tests/unit/main/platform/windows/windows-web-contents.test.ts +++ b/tests/unit/main/platform/windows/windows-web-contents.test.ts @@ -55,4 +55,15 @@ describe('WindowsWebContents', () => { createContents(); expect(warnings).toEqual([]); }); + + test('a null or non-object exec result is ignored and later results still settle', async () => { + const { contents, options } = createContents(); + const exec = options.messageHandlers.find((handler) => handler.name === 'bunmaskaExec'); + const pending = contents.executeJavaScript('1 + 1'); + for (const body of ['null', '1', '"x"']) { + expect(() => exec?.onMessage(body)).not.toThrow(); + } + exec?.onMessage(JSON.stringify({ execId: 1, ok: true, result: 2 })); + expect(await pending).toBe(2); + }); }); From c2740239f3e7c9955afce5f7ca28f1241d114356 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:18:17 -0700 Subject: [PATCH 215/586] fix: decode only PNG and JPEG bytes in the Linux nativeImage backend --- src/main/platform/linux/gdk-native-image.ts | 23 ++++++++++++---- .../platform/linux/gdk-native-image.test.ts | 26 +++++++++++++++++++ 2 files changed, 44 insertions(+), 5 deletions(-) create mode 100644 tests/unit/main/platform/linux/gdk-native-image.test.ts diff --git a/src/main/platform/linux/gdk-native-image.ts b/src/main/platform/linux/gdk-native-image.ts index 8e6aa1b4..28903c13 100644 --- a/src/main/platform/linux/gdk-native-image.ts +++ b/src/main/platform/linux/gdk-native-image.ts @@ -1,3 +1,4 @@ +import { readFileSync } from 'node:fs'; import { ptr, toArrayBuffer } from 'bun:ffi'; import type { DecodedImage, NativeImageBackend, NativeImageHandle } from '../../api/native-image'; import { cstr } from '../cstr'; @@ -48,13 +49,17 @@ const decodeFromPixbuf = (pixbuf: number | null): DecodedImage => { return { handle: BigInt(pixbuf), width, height, empty: false }; }; -const decodePath = (path: string): DecodedImage => { - const pixbufFFI = loadGdkPixbufFFI(); - const pixbuf = pixbufFFI.symbols.gdk_pixbuf_new_from_file(cstr(path), null); - return decodeFromPixbuf(pixbuf === null ? null : Number(pixbuf)); -}; +const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47]; +const JPEG_SOI = [0xff, 0xd8, 0xff]; + +/** gdk-pixbuf sniffs and hands bytes to every installed loader (TGA, ANI, SVG, ...); only PNG/JPEG are the contract. */ +export const isPngOrJpeg = (bytes: Uint8Array): boolean => + [PNG_SIGNATURE, JPEG_SOI].some((magic) => magic.every((byte, i) => bytes[i] === byte)); const decodeBuffer = (bytes: Uint8Array): DecodedImage => { + if (!isPngOrJpeg(bytes)) { + return EMPTY; + } const pixbufFFI = loadGdkPixbufFFI(); const glib = loadGlibFFI(); const gio = loadGioFFI(); @@ -74,6 +79,14 @@ const decodeBuffer = (bytes: Uint8Array): DecodedImage => { return decodeFromPixbuf(pixbuf === null ? null : Number(pixbuf)); }; +const decodePath = (path: string): DecodedImage => { + try { + return decodeBuffer(readFileSync(path)); + } catch { + return EMPTY; + } +}; + /** Encode to `type` ("png"/"jpeg"); `quality` (0-100) applies to JPEG only. */ const encode = (handle: NativeImageHandle, type: string, quality?: number): Uint8Array => { const pixbuf = handleToPtr(handle); diff --git a/tests/unit/main/platform/linux/gdk-native-image.test.ts b/tests/unit/main/platform/linux/gdk-native-image.test.ts new file mode 100644 index 00000000..1907fe3a --- /dev/null +++ b/tests/unit/main/platform/linux/gdk-native-image.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, test } from 'bun:test'; +import { isPngOrJpeg } from '../../../../../src/main/platform/linux/gdk-native-image'; + +describe('isPngOrJpeg', () => { + test('accepts the PNG signature', () => { + expect(isPngOrJpeg(new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a]))).toBe(true); + }); + + test('accepts the JPEG SOI marker', () => { + expect(isPngOrJpeg(new Uint8Array([0xff, 0xd8, 0xff, 0xe0]))).toBe(true); + }); + + test('rejects formats gdk-pixbuf would otherwise sniff and decode', () => { + const svg = new TextEncoder().encode(''); + const ico = new Uint8Array([0x00, 0x00, 0x01, 0x00]); + const tga = new Uint8Array([0x00, 0x00, 0x02, 0x00, 0x00]); + expect(isPngOrJpeg(svg)).toBe(false); + expect(isPngOrJpeg(ico)).toBe(false); + expect(isPngOrJpeg(tga)).toBe(false); + }); + + test('rejects a truncated signature', () => { + expect(isPngOrJpeg(new Uint8Array([0x89, 0x50]))).toBe(false); + expect(isPngOrJpeg(new Uint8Array(0))).toBe(false); + }); +}); From a2ce6a51b3018c89ec196d20f4377a81da17e9f6 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:18:24 -0700 Subject: [PATCH 216/586] fix: trim encoded nativeImage bytes to the stream length --- .../platform/windows/windows-native-image.ts | 21 ++++++++++++++++++- .../integration/windows/native-image.test.ts | 6 ++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/main/platform/windows/windows-native-image.ts b/src/main/platform/windows/windows-native-image.ts index d5e6efb8..6fe6efb9 100644 --- a/src/main/platform/windows/windows-native-image.ts +++ b/src/main/platform/windows/windows-native-image.ts @@ -23,6 +23,9 @@ const HANDLE_SIZE = 8; const DWORD_SIZE = 4; /** `IUnknown` vtable slot of `Release` (QueryInterface=0, AddRef=1, Release=2). */ const IUNKNOWN_RELEASE_SLOT = 2; +/** `IStream::Seek` follows IUnknown (0-2) and ISequentialStream Read/Write (3-4). */ +const ISTREAM_SEEK_SLOT = 5; +const STREAM_SEEK_END = 2; const POINTER_SIZE = 8; let gdiplusStarted = false; @@ -66,6 +69,20 @@ const releaseStream = (stream: bigint): void => { comMethod(stream, IUNKNOWN_RELEASE_SLOT, [FFIType.u64], FFIType.u32)(stream); }; +/** The stream's logical length (a seek to its end), or `undefined` if the seek fails. */ +const streamLength = (stream: bigint): number | undefined => { + const end = handleOut(); + const seek = comMethod( + stream, + ISTREAM_SEEK_SLOT, + [FFIType.u64, FFIType.i64, FFIType.u32, FFIType.ptr], + FFIType.i32, + ); + return seek(stream, 0n, STREAM_SEEK_END, end.pointer) === 0 + ? Number(read.u64(end.pointer, 0)) + : undefined; +}; + /** Read a GDI+ image's pixel dimensions via the scalar `GdipGetImage{Width,Height}` getters. */ const dimensions = (handle: bigint): { width: number; height: number } => { const gdip = loadGdiplus().symbols; @@ -150,7 +167,9 @@ const encode = (handle: NativeImageHandle, encoderClsid: Uint8Array): Uint8Array ole32.GetHGlobalFromStream(stream, hglobalOut.pointer); const hglobal = read.u64(hglobalOut.pointer, 0); const dataPtr = kernel32.GlobalLock(hglobal); - const size = Number(kernel32.GlobalSize(hglobal)); + // GlobalSize can exceed the bytes written; the stream tracks its own length. + const allocated = Number(kernel32.GlobalSize(hglobal)); + const size = Math.min(allocated, streamLength(stream) ?? allocated); const bytes = dataPtr === null ? new Uint8Array(0) : new Uint8Array(toArrayBuffer(dataPtr, 0, size)).slice(); kernel32.GlobalUnlock(hglobal); diff --git a/tests/integration/windows/native-image.test.ts b/tests/integration/windows/native-image.test.ts index 94f63b02..6fff8041 100644 --- a/tests/integration/windows/native-image.test.ts +++ b/tests/integration/windows/native-image.test.ts @@ -62,6 +62,12 @@ if (currentPlatform() === 'windows') { ); }); + test('encodePng ends exactly at the IEND chunk (no trailing HGLOBAL bytes)', () => { + const { handle } = windowsNativeImageBackend.decode(PNG_1x1); + const png = windowsNativeImageBackend.encodePng(handle); + expect([...png.subarray(-8)]).toEqual([0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82]); + }); + test('encodeJpeg produces valid JPEG bytes', () => { const { handle } = windowsNativeImageBackend.decode(PNG_1x1); const jpeg = windowsNativeImageBackend.encodeJpeg(handle, 90); From 758e58ce935fcc4e871aff5eea1ed81fc7ae050c Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:18:24 -0700 Subject: [PATCH 217/586] refactor: drop the unread cmdOrCtrl field from parsed accelerators --- src/main/api/accelerator.ts | 3 --- tests/unit/main/api/accelerator.test.ts | 4 ---- 2 files changed, 7 deletions(-) diff --git a/src/main/api/accelerator.ts b/src/main/api/accelerator.ts index 3656680e..de813b74 100644 --- a/src/main/api/accelerator.ts +++ b/src/main/api/accelerator.ts @@ -10,8 +10,6 @@ import type { Platform } from '../../common/platform'; export type ParsedAccelerator = { /** Normalised: single letters are upper-cased. */ readonly key: string; - /** Whether the original string used the platform-relative `CmdOrCtrl` token. */ - readonly cmdOrCtrl: boolean; readonly shift: boolean; readonly alt: boolean; readonly ctrl: boolean; @@ -165,7 +163,6 @@ export const parseAccelerator = ( return { key, - cmdOrCtrl: mods.cmdOrCtrl, shift: mods.shift, alt: mods.alt, ctrl, diff --git a/tests/unit/main/api/accelerator.test.ts b/tests/unit/main/api/accelerator.test.ts index d20673ca..307dcea4 100644 --- a/tests/unit/main/api/accelerator.test.ts +++ b/tests/unit/main/api/accelerator.test.ts @@ -14,7 +14,6 @@ describe('parseAccelerator', () => { test('parses a bare single key', () => { expect(onMac('K')).toEqual({ key: 'K', - cmdOrCtrl: false, shift: false, alt: false, ctrl: false, @@ -29,14 +28,12 @@ describe('parseAccelerator', () => { test('CmdOrCtrl resolves to Cmd (meta) on macOS', () => { const parsed = onMac('CmdOrCtrl+K'); - expect(parsed?.cmdOrCtrl).toBe(true); expect(parsed?.meta).toBe(true); expect(parsed?.ctrl).toBe(false); }); test('CmdOrCtrl resolves to Ctrl on Linux', () => { const parsed = onLinux('CmdOrCtrl+K'); - expect(parsed?.cmdOrCtrl).toBe(true); expect(parsed?.ctrl).toBe(true); expect(parsed?.meta).toBe(false); }); @@ -65,7 +62,6 @@ describe('parseAccelerator', () => { const parsed = onMac('Cmd+Ctrl+Alt+Shift+Super+X'); expect(parsed).toEqual({ key: 'X', - cmdOrCtrl: false, shift: true, alt: true, ctrl: true, From 43bff058691714d46678279ac9aeb6ac1b290ca0 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:18:36 -0700 Subject: [PATCH 218/586] fix: tar update bundles from cwd so Windows GNU tar works --- src/cli/update-artifact.ts | 14 +++--- tests/unit/cli/update-artifact.test.ts | 61 ++++++++++++-------------- 2 files changed, 35 insertions(+), 40 deletions(-) diff --git a/src/cli/update-artifact.ts b/src/cli/update-artifact.ts index 313853b1..eca9d6f4 100644 --- a/src/cli/update-artifact.ts +++ b/src/cli/update-artifact.ts @@ -3,7 +3,7 @@ * plus the `update.json` manifest the runtime `autoUpdater` consumes. */ -import { readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { readFileSync, writeFileSync } from 'node:fs'; import { basename, dirname, join } from 'node:path'; import { type ArtifactOs, @@ -68,19 +68,17 @@ export type UpdateArtifactResult = { }; const tarThenZstd = async (bundlePath: string, outPath: string): Promise => { - // tar with the system tar (portable), then compress the tar bytes with Bun's - // zstd — avoids depending on `tar --zstd` being present. - const tarPath = outPath.replace(/\.zst$/, ''); - const proc = Bun.spawn(['tar', '-cf', tarPath, '-C', dirname(bundlePath), basename(bundlePath)], { - stdio: ['ignore', 'ignore', 'inherit'], + // A relative entry from cwd, never an absolute path: GNU tar on Windows reads C:\... as a remote host. + const proc = Bun.spawn(['tar', '-cf', '-', basename(bundlePath)], { + cwd: dirname(bundlePath), + stdio: ['ignore', 'pipe', 'inherit'], }); + const tarBytes = await new Response(proc.stdout).bytes(); const code = await proc.exited; if (code !== 0) { throw new Error(`update-artifact: tar exited with code ${code}`); } - const tarBytes = readFileSync(tarPath); writeFileSync(outPath, Bun.zstdCompressSync(tarBytes)); - rmSync(tarPath, { force: true }); }; const defaultDeps: UpdateArtifactDeps = { diff --git a/tests/unit/cli/update-artifact.test.ts b/tests/unit/cli/update-artifact.test.ts index b00b037c..55e525db 100644 --- a/tests/unit/cli/update-artifact.test.ts +++ b/tests/unit/cli/update-artifact.test.ts @@ -72,40 +72,37 @@ describe('emitUpdateArtifact (injected seams)', () => { }); describe('emitUpdateArtifact (real tar + zstd)', () => { - // Skipped on Windows: src spawns GNU `tar -cf C:\...` which reads the drive-letter - // path as rsh `host:path` ("Cannot connect to C: resolve failed"). The src tar - // invocation is out of scope to change here, so this real-tar path can't run. - test.skipIf(process.platform === 'win32')( - 'produces a .tar.zst + update.json whose hash verifies', - async () => { - const root = makeTmpDir(); - const bundle = join(root, 'Demo.app'); - mkdirSync(bundle, { recursive: true }); - writeFileSync(join(bundle, 'payload.txt'), 'hello bunmaska update'); - const outDir = join(root, 'out'); - mkdirSync(outDir); + test('produces a .tar.zst + update.json whose hash verifies', async () => { + const root = makeTmpDir(); + const bundle = join(root, 'Demo.app'); + mkdirSync(bundle, { recursive: true }); + writeFileSync(join(bundle, 'payload.txt'), 'hello bunmaska update'); + const outDir = join(root, 'out'); + mkdirSync(outDir); - const result = await emitUpdateArtifact({ - bundlePath: bundle, - outDir, - name: 'Demo', - version: '1.2.3', - channel: 'stable', - os: 'macos', - arch: 'arm64', - }); + const result = await emitUpdateArtifact({ + bundlePath: bundle, + outDir, + name: 'Demo', + version: '1.2.3', + channel: 'stable', + os: 'macos', + arch: 'arm64', + }); - expect(existsSync(result.artifactPath)).toBe(true); - expect(existsSync(result.manifestPath)).toBe(true); - // The on-disk artifact's hash + size match what update.json claims. - const bytes = readFileSync(result.artifactPath); - expect(result.manifest.size).toBe(bytes.length); - expect(result.manifest.hash).toBe(contentHash(bytes)); - expect(result.manifest.artifact).toBe('demo-stable-macos-arm64.tar.zst'); - // No stray uncompressed .tar left behind. - expect(existsSync(result.artifactPath.replace(/\.zst$/, ''))).toBe(false); - }, - ); + expect(existsSync(result.artifactPath)).toBe(true); + expect(existsSync(result.manifestPath)).toBe(true); + // The on-disk artifact's hash + size match what update.json claims. + const bytes = readFileSync(result.artifactPath); + expect(result.manifest.size).toBe(bytes.length); + expect(result.manifest.hash).toBe(contentHash(bytes)); + expect(result.manifest.artifact).toBe('demo-stable-macos-arm64.tar.zst'); + // No stray uncompressed .tar left behind. + expect(existsSync(result.artifactPath.replace(/\.zst$/, ''))).toBe(false); + // The installer expects the bundle dir itself as the tar's top-level entry. + const list = Bun.spawnSync(['tar', '-tf', '-'], { stdin: Bun.zstdDecompressSync(bytes) }); + expect(list.stdout.toString()).toContain('Demo.app/payload.txt'); + }); }); describe('emitUpdateArtifact signing', () => { From ca5c13fce2a68fcf88e805740fd41ca2e88719f3 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:18:46 -0700 Subject: [PATCH 219/586] fix: resolve relative paths in Linux shell.openPath via pathToFileURL --- src/main/platform/linux/gtk-shell.ts | 18 +++++++---------- tests/integration/linux/shell.test.ts | 5 ----- .../main/platform/linux/gtk-shell.test.ts | 20 ------------------- 3 files changed, 7 insertions(+), 36 deletions(-) delete mode 100644 tests/unit/main/platform/linux/gtk-shell.test.ts diff --git a/src/main/platform/linux/gtk-shell.ts b/src/main/platform/linux/gtk-shell.ts index 49d3c182..eca933e4 100644 --- a/src/main/platform/linux/gtk-shell.ts +++ b/src/main/platform/linux/gtk-shell.ts @@ -1,4 +1,5 @@ import { dirname } from 'node:path'; +import { pathToFileURL } from 'node:url'; import { cstr } from '../cstr'; import { loadGdkFFI } from './gdk-ffi'; import { loadGioFFI } from './gio-ffi'; @@ -7,22 +8,17 @@ import { loadGioFFI } from './gio-ffi'; * Desktop integration via GIO + GDK — the Linux half of Electron's `shell`. */ -/** - * Convert an absolute filesystem path to a `file://` URI, percent-encoding each - * path segment (spaces, `#`, `?`, …) while preserving the `/` separators. The - * leading slash of an absolute path yields the `file:///` triple-slash form. - */ -export const pathToFileUri = (absPath: string): string => - `file://${absPath.split('/').map(encodeURIComponent).join('/')}`; - /** Open a URL in the default application. Returns whether the OS accepted it. */ export const openExternal = (url: string): boolean => loadGioFFI().symbols.g_app_info_launch_default_for_uri(cstr(url), null, null) === 1; /** Open a file or folder path with its default application. Returns success. */ export const openPath = (path: string): boolean => - loadGioFFI().symbols.g_app_info_launch_default_for_uri(cstr(pathToFileUri(path)), null, null) === - 1; + loadGioFFI().symbols.g_app_info_launch_default_for_uri( + cstr(pathToFileURL(path).href), + null, + null, + ) === 1; /** * Reveal a file or folder by opening its containing directory in the file @@ -32,7 +28,7 @@ export const openPath = (path: string): boolean => */ export const showItemInFolder = (path: string): void => { loadGioFFI().symbols.g_app_info_launch_default_for_uri( - cstr(pathToFileUri(dirname(path))), + cstr(pathToFileURL(dirname(path)).href), null, null, ); diff --git a/tests/integration/linux/shell.test.ts b/tests/integration/linux/shell.test.ts index 5b786bd7..b7da7b4d 100644 --- a/tests/integration/linux/shell.test.ts +++ b/tests/integration/linux/shell.test.ts @@ -4,7 +4,6 @@ import { beep, openExternal, openPath, - pathToFileUri, showItemInFolder, } from '../../../src/main/platform/linux/gtk-shell'; @@ -28,10 +27,6 @@ describe.skipIf(!isLinux)('Linux shell backend', () => { expect(typeof beep).toBe('function'); }); - test('pathToFileUri builds an encoded file:// URI', () => { - expect(pathToFileUri('/tmp/a b.txt')).toBe('file:///tmp/a%20b.txt'); - }); - test('beep() runs on a real GDK display without throwing', () => { // gtk_init_check initialises GDK so gdk_display_get_default() returns a // display; under Xvfb the bell is a no-op. Skip if there is no display. diff --git a/tests/unit/main/platform/linux/gtk-shell.test.ts b/tests/unit/main/platform/linux/gtk-shell.test.ts deleted file mode 100644 index 185d9bd8..00000000 --- a/tests/unit/main/platform/linux/gtk-shell.test.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { describe, expect, it } from 'bun:test'; -import { pathToFileUri } from '../../../../../src/main/platform/linux/gtk-shell'; - -describe('pathToFileUri', () => { - it('prefixes an absolute path with file:// and keeps the leading slash', () => { - expect(pathToFileUri('/home/u/file.txt')).toBe('file:///home/u/file.txt'); - }); - - it('percent-encodes spaces', () => { - expect(pathToFileUri('/home/u/a b.txt')).toBe('file:///home/u/a%20b.txt'); - }); - - it('percent-encodes other special characters while keeping path separators', () => { - expect(pathToFileUri('/home/u/a#b?c.txt')).toBe('file:///home/u/a%23b%3Fc.txt'); - }); - - it('leaves an already-safe nested path untouched', () => { - expect(pathToFileUri('/var/log/app/out.log')).toBe('file:///var/log/app/out.log'); - }); -}); From aa2c5d8931059913ce7e8054c4daae13afe78a9e Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:18:47 -0700 Subject: [PATCH 220/586] fix: warn that openDevTools is a no-op on Windows --- src/main/platform/windows/windows-web-contents.ts | 5 +++-- .../main/platform/windows/windows-web-contents.test.ts | 7 +++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/main/platform/windows/windows-web-contents.ts b/src/main/platform/windows/windows-web-contents.ts index 6c972efa..171e1db9 100644 --- a/src/main/platform/windows/windows-web-contents.ts +++ b/src/main/platform/windows/windows-web-contents.ts @@ -283,11 +283,12 @@ export class WindowsWebContents implements NativeWebContents { } openDevTools(): void { - // WinCairo exposes a Web Inspector; wiring it is a seam-fill follow-up. + // ponytail: wire WKInspectorShow(WKPageGetInspector(page)) with developer extras enabled. + log.warn('openDevTools is not supported on Windows yet: no inspector opens'); } closeDevTools(): void { - // See openDevTools. + // No inspector ever opens (see openDevTools). } setZoomFactor(factor: number): void { diff --git a/tests/unit/main/platform/windows/windows-web-contents.test.ts b/tests/unit/main/platform/windows/windows-web-contents.test.ts index 0f362403..5ce036db 100644 --- a/tests/unit/main/platform/windows/windows-web-contents.test.ts +++ b/tests/unit/main/platform/windows/windows-web-contents.test.ts @@ -43,6 +43,13 @@ describe('WindowsWebContents', () => { expect(warnings).toEqual([expect.stringContaining('setWindowOpenHandler')]); }); + test('openDevTools warns that no inspector opens', () => { + const warnings = collectWarnings(); + const { contents } = createContents(); + contents.openDevTools(); + expect(warnings).toEqual([expect.stringContaining('openDevTools')]); + }); + test('warns when protocol.handle schemes are registered, since none are served', () => { protocol.handle('myapp', () => ({ data: 'hi' })); const warnings = collectWarnings(); From 624aab5db244f7d6c12491ea29492da2540db794 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:18:48 -0700 Subject: [PATCH 221/586] fix: ignore a pinned engine built for another os or arch --- src/cli/engine-command.ts | 91 ++++++++++++------- src/main/engine/resolve.ts | 19 +++- tests/unit/cli/engine-command.test.ts | 21 ++++- tests/unit/main/engine-resolve.test.ts | 23 ++++- .../platform/windows/webkit2-resolve.test.ts | 1 + 5 files changed, 118 insertions(+), 37 deletions(-) diff --git a/src/cli/engine-command.ts b/src/cli/engine-command.ts index bc111e79..30146b11 100644 --- a/src/cli/engine-command.ts +++ b/src/cli/engine-command.ts @@ -1,5 +1,10 @@ import { existsSync, statSync } from 'node:fs'; -import { compareEngineIds, isSystemEngine, parseEngineId } from '../common/engine-id'; +import { + compareEngineIds, + type EngineRef, + isSystemEngine, + parseEngineId, +} from '../common/engine-id'; import type { BunmaskaConfig } from '../common/config-schema'; import { currentArch, currentPlatform } from '../common/platform'; import type { EngineSubcommand } from './parse-args'; @@ -51,6 +56,25 @@ const sortIds = (ids: readonly string[]): string[] => /** The pinned engine declared by a project's config (defaults to the system sentinel). */ const configPin = (config: BunmaskaConfig): string => config.engine?.webkit ?? 'system'; +type PinState = 'system' | 'bare' | 'foreign' | 'installed' | 'missing'; + +/** How this machine treats a pin; `foreign` = built for another os/arch, never loaded here. */ +const pinState = (pin: string, root: string): PinState => { + if (isSystemEngine(pin)) { + return 'system'; + } + let ref: EngineRef; + try { + ref = parseEngineId(pin); + } catch { + return 'bare'; + } + if (ref.os !== currentPlatform() || ref.arch !== currentArch()) { + return 'foreign'; + } + return isInstalled(root, pin) ? 'installed' : 'missing'; +}; + const runList = (deps: EngineCommandDeps): number => { const installed = listInstalled(deps.root); if (installed.length === 0) { @@ -103,18 +127,22 @@ const runAvailable = async (deps: EngineCommandDeps): Promise => { const runWhich = async (target: string | undefined, deps: EngineCommandDeps): Promise => { const config = await deps.readConfig(target ?? '.'); const pin = configPin(config); - if (isSystemEngine(pin)) { - deps.out('system — uses the OS WebView (no pinned engine)'); - return 0; - } - try { - parseEngineId(pin); - const state = isInstalled(deps.root, pin) - ? 'installed' - : 'NOT installed — run `bunmaska engine install`'; - deps.out(`${pin} [${state}]`); - } catch { - deps.out(`${pin} (bare upstream — resolved to a full engine-id at build time)`); + switch (pinState(pin, deps.root)) { + case 'system': + deps.out('system — uses the OS WebView (no pinned engine)'); + break; + case 'bare': + deps.out(`${pin} (bare upstream — resolved to a full engine-id at build time)`); + break; + case 'foreign': + deps.out(`${pin} [built for another os/arch, not used on this machine]`); + break; + case 'installed': + deps.out(`${pin} [installed]`); + break; + case 'missing': + deps.out(`${pin} [NOT installed — run \`bunmaska engine install\`]`); + break; } return 0; }; @@ -301,24 +329,23 @@ export const runDoctor = async ( const config = await deps.readConfig(target ?? '.'); const pin = configPin(config); - if (isSystemEngine(pin)) { - deps.out(' project: system WebKit (no pin)'); - return 0; - } - let isFullId = true; - try { - parseEngineId(pin); - } catch { - isFullId = false; - } - if (!isFullId) { - deps.out(` project: pins ${pin} (bare upstream, resolved at build time)`); - return 0; - } - if (isInstalled(deps.root, pin)) { - deps.out(` project: pins ${pin} [installed ✓]`); - return 0; + switch (pinState(pin, deps.root)) { + case 'system': + deps.out(' project: system WebKit (no pin)'); + return 0; + case 'bare': + deps.out(` project: pins ${pin} (bare upstream, resolved at build time)`); + return 0; + case 'foreign': + deps.out(` project: pins ${pin} (built for another os/arch, not used on this machine)`); + return 0; + case 'installed': + deps.out(` project: pins ${pin} [installed ✓]`); + return 0; + case 'missing': + deps.err( + ` project: pins ${pin} [NOT installed ✗] — run \`bunmaska engine install ${pin}\``, + ); + return 1; } - deps.err(` project: pins ${pin} [NOT installed ✗] — run \`bunmaska engine install ${pin}\``); - return 1; }; diff --git a/src/main/engine/resolve.ts b/src/main/engine/resolve.ts index 149fa17f..855bb0de 100644 --- a/src/main/engine/resolve.ts +++ b/src/main/engine/resolve.ts @@ -11,7 +11,8 @@ import { existsSync, readFileSync } from 'node:fs'; import { basename, dirname, join } from 'node:path'; -import { isSystemEngine, parseEngineId } from '../../common/engine-id'; +import { type EngineRef, isSystemEngine, parseEngineId } from '../../common/engine-id'; +import { type Arch, currentArch, currentPlatform, type Platform } from '../../common/platform'; import { engineDir, enginesPath, @@ -42,6 +43,8 @@ export type ResolveDeps = { readonly readBakedId?: () => string | null; /** Override the store root (default: {@link enginesPath} of `env`). */ readonly enginesRoot?: string; + /** The machine the engine must be built for (default: this one). */ + readonly host?: { readonly os: Platform; readonly arch: Arch }; }; /** @@ -92,8 +95,9 @@ export const resolveEngineWith = (deps: ResolveDeps = {}): EngineResolution => { return { mode: 'system', warnings: [] }; } + let ref: EngineRef; try { - parseEngineId(id); // validate shape; the parsed fields are not needed here + ref = parseEngineId(id); } catch { return { mode: 'system', @@ -103,6 +107,17 @@ export const resolveEngineWith = (deps: ResolveDeps = {}): EngineResolution => { }; } + const host = deps.host ?? { os: currentPlatform(), arch: currentArch() }; + if (ref.os !== host.os || ref.arch !== host.arch) { + return { + mode: 'system', + warnings: [ + `bunmaska: pinned engine ${id} is built for ${ref.os}-${ref.arch}, not this ` + + `${host.os}-${host.arch} machine, so it is not used.`, + ], + }; + } + const root = deps.enginesRoot ?? enginesPath(env); const dir = engineDir(root, id); if (!exists(join(dir, INSTALLATION_COMPLETE))) { diff --git a/tests/unit/cli/engine-command.test.ts b/tests/unit/cli/engine-command.test.ts index bceee43f..a3b82d6d 100644 --- a/tests/unit/cli/engine-command.test.ts +++ b/tests/unit/cli/engine-command.test.ts @@ -5,9 +5,12 @@ import { join } from 'node:path'; import type { BunmaskaConfig } from '../../../src/common/config-schema'; import { runDoctor, runEngine } from '../../../src/cli/engine-command'; import { installFromDir, linkApp } from '../../../src/cli/engine-store'; +import { currentArch, currentPlatform } from '../../../src/common/platform'; -const ID = 'webkitgtk-6.0-2.52.4-bunmaska1-linux-x64'; -const ID2 = 'webkitgtk-6.0-2.46.0-bunmaska1-linux-x64'; +const HOST = `${currentPlatform()}-${currentArch()}`; +const ID = `webkitgtk-6.0-2.52.4-bunmaska1-${HOST}`; +const ID2 = `webkitgtk-6.0-2.46.0-bunmaska1-${HOST}`; +const FOREIGN = `webkit-2-2.52.4-bunmaska1-${currentPlatform() === 'windows' ? 'linux' : 'windows'}-x64`; const tmpDirs: string[] = []; const makeTmpDir = (): string => { @@ -131,6 +134,14 @@ describe('engine which', () => { expect(c.text()).toMatch(/NOT installed/); }); + test('a pin built for another machine is not reported as missing', async () => { + const c = capture(makeTmpDir(), { engine: { webkit: FOREIGN } }); + await runEngine({ action: 'which' }, c.deps); + expect(c.text()).toContain(FOREIGN); + expect(c.text()).toMatch(/not used on this machine/); + expect(c.text()).not.toMatch(/NOT installed/); + }); + test('shows installed for a present engine', async () => { const root = makeTmpDir(); await installFromDir(root, makeEngineDir(root, ID)); @@ -320,6 +331,12 @@ describe('doctor', () => { expect(c.text()).toMatch(/store:/); }); + test('exits 0 when the project pins an engine built for another machine', async () => { + const c = capture(makeTmpDir(), { engine: { webkit: FOREIGN } }); + expect(await runDoctor('.', c.deps)).toBe(0); + expect(c.text()).toMatch(/not used on this machine/); + }); + test('exits 1 when the project pins an uninstalled engine', async () => { const c = capture(makeTmpDir(), { engine: { webkit: ID } }); expect(await runDoctor('.', c.deps)).toBe(1); diff --git a/tests/unit/main/engine-resolve.test.ts b/tests/unit/main/engine-resolve.test.ts index 58b19d40..11fb343c 100644 --- a/tests/unit/main/engine-resolve.test.ts +++ b/tests/unit/main/engine-resolve.test.ts @@ -17,7 +17,13 @@ const ROOT = '/store/webkit'; const slash = (s: string): string => s.replaceAll('\\', '/'); const resolve = (deps: ResolveDeps) => - resolveEngineWith({ enginesRoot: ROOT, exists: () => true, readBakedId: () => null, ...deps }); + resolveEngineWith({ + enginesRoot: ROOT, + exists: () => true, + readBakedId: () => null, + host: { os: 'linux', arch: 'x64' }, + ...deps, + }); describe('resolveEngineWith', () => { test('BUNMASKA_WEBKIT_PATH wins — explicit pinned dir, highest precedence', () => { @@ -71,6 +77,21 @@ describe('resolveEngineWith', () => { expect(r.root).toBe(ROOT); }); + test('an installed engine built for another os -> system, with no install advice', () => { + const windows = 'webkit-2-2.52.4-bunmaska1-windows-x64'; + const r = resolve({ env: { BUNMASKA_WEBKIT_ID: windows } }); + expect(r.mode).toBe('system'); + expect(r.warnings.join(' ')).toContain('windows-x64'); + expect(r.warnings.join(' ')).not.toContain('engine install'); + }); + + test('an installed engine built for another arch -> system', () => { + const arm = 'webkitgtk-6.0-2.52.4-bunmaska1-linux-arm64'; + const r = resolve({ env: { BUNMASKA_WEBKIT_ID: arm } }); + expect(r.mode).toBe('system'); + expect(r.warnings.join(' ')).toContain('linux-arm64'); + }); + test('explicit BUNMASKA_WEBKIT_PATH pin carries no id/root (nothing to refcount)', () => { const r = resolve({ env: { BUNMASKA_WEBKIT_PATH: '/opt/webkit/lib' } }); expect(r.id).toBeUndefined(); diff --git a/tests/unit/main/platform/windows/webkit2-resolve.test.ts b/tests/unit/main/platform/windows/webkit2-resolve.test.ts index c0e851b8..b1f8ab76 100644 --- a/tests/unit/main/platform/windows/webkit2-resolve.test.ts +++ b/tests/unit/main/platform/windows/webkit2-resolve.test.ts @@ -24,6 +24,7 @@ const dir = (deps: ResolveDeps): string | undefined => enginesRoot: ROOT, exists: () => true, readBakedId: () => null, + host: { os: 'windows', arch: 'x64' }, ...deps, }); From a6ea5107a2f157b8b89b47410eb0a747cfa938b4 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:19:06 -0700 Subject: [PATCH 222/586] fix: show PNG tray icons on Windows and never destroy the shared default --- .../platform/windows/win32-gdiplus-ffi.ts | 2 + src/main/platform/windows/windows-tray.ts | 51 ++++++++++++++----- tests/integration/windows/tray.test.ts | 26 +++++++++- 3 files changed, 64 insertions(+), 15 deletions(-) diff --git a/src/main/platform/windows/win32-gdiplus-ffi.ts b/src/main/platform/windows/win32-gdiplus-ffi.ts index d604f99a..ff6d376e 100644 --- a/src/main/platform/windows/win32-gdiplus-ffi.ts +++ b/src/main/platform/windows/win32-gdiplus-ffi.ts @@ -70,6 +70,8 @@ const GDIPLUS_SYMBOLS = { }, // (GpBitmap*, BitmapData*) -> Status — release a lock taken by GdipBitmapLockBits. GdipBitmapUnlockBits: { args: [FFIType.u64, FFIType.ptr], returns: FFIType.i32 }, + // (GpBitmap*, HICON* out) -> Status; the caller owns the icon (DestroyIcon). + GdipCreateHICONFromBitmap: { args: [FFIType.u64, FFIType.ptr], returns: FFIType.i32 }, } as const; /** `Ok` GDI+ status. */ diff --git a/src/main/platform/windows/windows-tray.ts b/src/main/platform/windows/windows-tray.ts index b4e92655..c0457c1f 100644 --- a/src/main/platform/windows/windows-tray.ts +++ b/src/main/platform/windows/windows-tray.ts @@ -1,10 +1,12 @@ -import { ptr } from 'bun:ffi'; +import { ptr, read } from 'bun:ffi'; import type { Menu } from '../../api/menu'; import type { TrayBackend, TrayInstance } from '../../api/tray'; import { wstr } from './win32'; import { loadUser32 } from './win32-ffi'; +import { GDIP_OK, loadGdiplus } from './win32-gdiplus-ffi'; import { loadShell32 } from './win32-shell-ffi'; import { createMessageWindow } from './windows-message-window'; +import { windowsNativeImageBackend } from './windows-native-image'; /** * `Shell_NotifyIcon` adds/updates/removes the icon; its callback message is delivered to a @@ -53,11 +55,14 @@ export const isTrayActivation = ( uid: number, ): boolean => message === WM_TRAYICON && wParam === uid && (lParam & 0xffff) === WM_LBUTTONUP; -/** Load a `.ico` from `path`, falling back to the default application icon. */ -const loadTrayIcon = (path: string): bigint => { +/** An HICON plus whether we own it (the stock default icon is shared and never destroyed). */ +type TrayIcon = { readonly handle: bigint; readonly owned: boolean }; + +/** Load `path` as the tray icon: `.ico` natively, PNG and friends via GDI+, else the default. */ +export const loadTrayIcon = (path: string): TrayIcon => { const user32 = loadUser32().symbols; const nameBuf = wstr(path); - const icon = user32.LoadImageW( + const ico = user32.LoadImageW( 0n, ptr(nameBuf), IMAGE_ICON, @@ -65,7 +70,22 @@ const loadTrayIcon = (path: string): bigint => { 0, LR_LOADFROMFILE | LR_DEFAULTSIZE, ); - return icon !== 0n ? icon : user32.LoadIconW(0n, IDI_APPLICATION); + if (ico !== 0n) { + return { handle: ico, owned: true }; + } + const image = windowsNativeImageBackend.decode(path); + if (!image.empty) { + const gdip = loadGdiplus().symbols; + const out = new Uint8Array(8); + const outPtr = ptr(out); + const status = gdip.GdipCreateHICONFromBitmap(image.handle, outPtr); + gdip.GdipDisposeImage(image.handle); + const hIcon = status === GDIP_OK ? read.u64(outPtr, 0) : 0n; + if (hIcon !== 0n) { + return { handle: hIcon, owned: true }; + } + } + return { handle: user32.LoadIconW(0n, IDI_APPLICATION), owned: false }; }; /** Build a NOTIFYICONDATAW for `Shell_NotifyIcon`. `hIcon`/`tip` are omitted for a delete. */ @@ -83,9 +103,9 @@ const notifyIconData = (hwnd: bigint, uid: number, hIcon: bigint, tip: string): return nid; }; -const destroyIconSafely = (hIcon: bigint): void => { - if (hIcon !== 0n) { - loadUser32().symbols.DestroyIcon(hIcon); +const releaseIcon = (icon: TrayIcon): void => { + if (icon.owned) { + loadUser32().symbols.DestroyIcon(icon.handle); } }; @@ -94,7 +114,7 @@ export const windowsTrayBackend: TrayBackend = { const uid = nextUid++; const shell32 = loadShell32().symbols; let clickCallback: (() => void) | undefined; - let hIcon = loadTrayIcon(image); + let icon = loadTrayIcon(image); let toolTip = ''; let destroyed = false; @@ -105,7 +125,10 @@ export const windowsTrayBackend: TrayBackend = { }); const sync = (operation: number): void => { - shell32.Shell_NotifyIconW(operation, ptr(notifyIconData(window.hwnd, uid, hIcon, toolTip))); + shell32.Shell_NotifyIconW( + operation, + ptr(notifyIconData(window.hwnd, uid, icon.handle, toolTip)), + ); }; sync(NIM_ADD); @@ -118,10 +141,10 @@ export const windowsTrayBackend: TrayBackend = { // The Windows tray has no inline title text (a macOS NSStatusItem feature). }, setImage(path: string): void { - const previous = hIcon; - hIcon = loadTrayIcon(path); + const previous = icon; + icon = loadTrayIcon(path); sync(NIM_MODIFY); - destroyIconSafely(previous); + releaseIcon(previous); }, setContextMenu(_menu: Menu | null): void { // ponytail: deferred — needs TrackPopupMenu on the tray's message window; @@ -137,7 +160,7 @@ export const windowsTrayBackend: TrayBackend = { destroyed = true; sync(NIM_DELETE); window.destroy(); - destroyIconSafely(hIcon); + releaseIcon(icon); }, isDestroyed(): boolean { return destroyed; diff --git a/tests/integration/windows/tray.test.ts b/tests/integration/windows/tray.test.ts index a7610ae6..a8059b89 100644 --- a/tests/integration/windows/tray.test.ts +++ b/tests/integration/windows/tray.test.ts @@ -1,7 +1,11 @@ import { afterEach, describe, expect, test } from 'bun:test'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; import { currentPlatform } from '../../../src/common/platform'; import { Tray } from '../../../src/main/api/tray'; -import { windowsTrayBackend } from '../../../src/main/platform/windows/windows-tray'; +import { loadUser32 } from '../../../src/main/platform/windows/win32-ffi'; +import { loadTrayIcon, windowsTrayBackend } from '../../../src/main/platform/windows/windows-tray'; /** * Windows tray against the real Shell_NotifyIcon API. A non-existent icon path is @@ -12,6 +16,11 @@ import { windowsTrayBackend } from '../../../src/main/platform/windows/windows-t * Runs only on a Windows host; inert elsewhere. */ const BAD_ICON = 'C:\\bunmaska_no_such_icon_zzz.ico'; +/** A 1x1 PNG, the format `Tray` hands the backend for every NativeImage. */ +const PNG_1x1 = Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', + 'base64', +); if (currentPlatform() === 'windows') { describe('Windows tray backend', () => { @@ -22,6 +31,21 @@ if (currentPlatform() === 'windows') { expect(tray.isDestroyed()).toBe(true); }); + test('a PNG loads as an owned icon; a missing file falls back to the shared default', () => { + const dir = mkdtempSync(join(tmpdir(), 'bunmaska-tray-')); + const path = join(dir, 'icon.png'); + writeFileSync(path, PNG_1x1); + try { + const icon = loadTrayIcon(path); + expect(icon.owned).toBe(true); + expect(icon.handle).not.toBe(0n); + loadUser32().symbols.DestroyIcon(icon.handle); + expect(loadTrayIcon(BAD_ICON).owned).toBe(false); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + test('destroy is idempotent', () => { const tray = windowsTrayBackend.create(BAD_ICON); tray.destroy(); From ae8b4cc19052b7f31537724ea7bff74e2e860429 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:19:07 -0700 Subject: [PATCH 223/586] fix: reject Linux clipboard reads instead of throwing or hanging --- src/main/platform/linux/gtk-clipboard.ts | 31 +++++++++---------- .../main/platform/linux/gtk-clipboard.test.ts | 24 +++++++++++++- 2 files changed, 37 insertions(+), 18 deletions(-) diff --git a/src/main/platform/linux/gtk-clipboard.ts b/src/main/platform/linux/gtk-clipboard.ts index 07b8b595..4852c345 100644 --- a/src/main/platform/linux/gtk-clipboard.ts +++ b/src/main/platform/linux/gtk-clipboard.ts @@ -271,10 +271,10 @@ const realAsyncStreamReader = (stream: Pointer): AsyncStreamReader => { }; }; -const readText = (): Promise => { - const gdk = loadGdkFFI(); - const clipboard = getClipboard(); - return new Promise((resolve) => { +const readText = (): Promise => + new Promise((resolve) => { + const gdk = loadGdkFFI(); + const clipboard = getClipboard(); const callback = new JSCallback((_source: Pointer, result: Pointer, _userData: Pointer) => { const value = settleReadText({ result, @@ -295,7 +295,6 @@ const readText = (): Promise => { } gdk.symbols.gdk_clipboard_read_text_async(clipboard, null, cbPtr, null); }); -}; /** Install raw `bytes` on the clipboard under `mime` via a `GdkContentProvider`. */ const writeBytes = (mime: string, bytes: Uint8Array): void => { @@ -328,10 +327,10 @@ const writeHTML = (markup: string): void => writeBytesAs(HTML_MIME, markup); const writeImage = (png: Uint8Array): void => writeBytes(IMAGE_PNG_MIME, png); -const readHTML = (): Promise => { - const gdk = loadGdkFFI(); - const clipboard = getClipboard(); - return new Promise((resolve) => { +const readHTML = (): Promise => + new Promise((resolve, reject) => { + const gdk = loadGdkFFI(); + const clipboard = getClipboard(); // NUL-terminated array of mime-type C strings: ["text/html", NULL]. const mime = new TextEncoder().encode(`${HTML_MIME}\0`); const mimeArray = new BigUint64Array([BigInt(ptr(mime)), 0n]); @@ -342,7 +341,7 @@ const readHTML = (): Promise => { result, finish: (r) => gdk.symbols.gdk_clipboard_read_finish(clipboard, r, null, null), drain: (stream) => drainStreamAsync(realAsyncStreamReader(stream)), - }).then(resolve); + }).then(resolve, reject); setTimeout(() => { inFlight.delete(callback); retainedReadBuffers.delete(callback); @@ -359,12 +358,11 @@ const readHTML = (): Promise => { } gdk.symbols.gdk_clipboard_read_async(clipboard, ptr(mimeArray), 0, null, cbPtr, null); }); -}; -const readImage = (): Promise => { - const gdk = loadGdkFFI(); - const clipboard = getClipboard(); - return new Promise((resolve) => { +const readImage = (): Promise => + new Promise((resolve, reject) => { + const gdk = loadGdkFFI(); + const clipboard = getClipboard(); // NUL-terminated array of mime-type C strings: ["image/png", NULL]. const mime = new TextEncoder().encode(`${IMAGE_PNG_MIME}\0`); const mimeArray = new BigUint64Array([BigInt(ptr(mime)), 0n]); @@ -373,7 +371,7 @@ const readImage = (): Promise => { result, finish: (r) => gdk.symbols.gdk_clipboard_read_finish(clipboard, r, null, null), drain: (stream) => drainStreamBytesAsync(realAsyncStreamReader(stream)), - }).then(resolve); + }).then(resolve, reject); setTimeout(() => { inFlight.delete(callback); retainedReadBuffers.delete(callback); @@ -392,7 +390,6 @@ const readImage = (): Promise => { } gdk.symbols.gdk_clipboard_read_async(clipboard, ptr(mimeArray), 0, null, cbPtr, null); }); -}; /** Electron-style MIME names from `gdk_content_formats_to_string` (GType names dropped). */ export const formatsFromGdk = (text: string): string[] => [ diff --git a/tests/unit/main/platform/linux/gtk-clipboard.test.ts b/tests/unit/main/platform/linux/gtk-clipboard.test.ts index 87ce9362..b0b58565 100644 --- a/tests/unit/main/platform/linux/gtk-clipboard.test.ts +++ b/tests/unit/main/platform/linux/gtk-clipboard.test.ts @@ -1,5 +1,6 @@ import type { Pointer } from 'bun:ffi'; -import { describe, expect, it } from 'bun:test'; +import { describe, expect, it, test } from 'bun:test'; +import { currentPlatform } from '../../../../../src/common/platform'; import { type AsyncStreamReader, CLIPBOARD_READ_CB_DEF, @@ -27,6 +28,27 @@ describe('linuxClipboardBackend shape', () => { }); }); +describe('linuxClipboardBackend reads', () => { + // On Linux the shared test process may hold a real display, where a read would await a pump. + test.skipIf(currentPlatform() === 'linux')( + 'reject instead of throwing synchronously when GDK is unavailable', + async () => { + const reads = [ + linuxClipboardBackend.readText, + linuxClipboardBackend.readHTML, + linuxClipboardBackend.readImage, + ]; + for (const read of reads) { + let pending: Promise = Promise.resolve(); + expect(() => { + pending = Promise.resolve(read()); + }).not.toThrow(); + await expect(pending).rejects.toThrow(); + } + }, + ); +}); + describe('formatsFromGdk', () => { it('reports MIME names without parameters, drops GType names and dedupes', () => { const gdk = 'gchararray GdkTexture text/plain;charset=utf-8 text/plain image/png'; From 5a580d993ba3fad675cd021b10033b0969a8334e Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:19:09 -0700 Subject: [PATCH 224/586] fix: treat an empty BUNMASKA_WEBKIT_ID as unset --- src/main/engine/resolve.ts | 2 +- tests/unit/main/engine-resolve.test.ts | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/main/engine/resolve.ts b/src/main/engine/resolve.ts index 855bb0de..26bb1cb2 100644 --- a/src/main/engine/resolve.ts +++ b/src/main/engine/resolve.ts @@ -89,7 +89,7 @@ export const resolveEngineWith = (deps: ResolveDeps = {}): EngineResolution => { } const readBakedId = deps.readBakedId ?? (() => defaultReadBakedId(env)); - const id = (env['BUNMASKA_WEBKIT_ID'] ?? readBakedId() ?? 'system').trim(); + const id = env['BUNMASKA_WEBKIT_ID']?.trim() || readBakedId()?.trim() || 'system'; if (isSystemEngine(id)) { return { mode: 'system', warnings: [] }; diff --git a/tests/unit/main/engine-resolve.test.ts b/tests/unit/main/engine-resolve.test.ts index 11fb343c..16fb5864 100644 --- a/tests/unit/main/engine-resolve.test.ts +++ b/tests/unit/main/engine-resolve.test.ts @@ -65,6 +65,11 @@ describe('resolveEngineWith', () => { expect(slash(r.libDir ?? '')).toBe(`${ROOT}/${other}/lib`); }); + test('an empty BUNMASKA_WEBKIT_ID leaves the baked id in charge', () => { + const r = resolve({ env: { BUNMASKA_WEBKIT_ID: ' ' }, readBakedId: () => ID }); + expect(r.id).toBe(ID); + }); + test('a malformed id -> system fallback with a warning', () => { const r = resolve({ env: { BUNMASKA_WEBKIT_ID: 'not-an-engine-id' } }); expect(r.mode).toBe('system'); From af3d4ec3c766fe838f5e6dca7074e820d593f565 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:19:32 -0700 Subject: [PATCH 225/586] fix: keep keygen from writing the private key through a symlink --- src/cli/keygen.ts | 9 +++++---- tests/unit/cli/keygen.test.ts | 25 ++++++++++++++++++++++++- 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/src/cli/keygen.ts b/src/cli/keygen.ts index 012def60..a5e94e22 100644 --- a/src/cli/keygen.ts +++ b/src/cli/keygen.ts @@ -3,7 +3,7 @@ * `build --update-key` signs with and the runtime `autoUpdater` verifies against. */ -import { existsSync, mkdirSync, writeFileSync } from 'node:fs'; +import { lstatSync, mkdirSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { generateSigningKeyPair } from './engine-signature'; @@ -21,15 +21,16 @@ export const runKeygen = (dir: string, io: KeygenIo): number => { const privatePath = join(dir, PRIVATE_KEY_FILE); const publicPath = join(dir, PUBLIC_KEY_FILE); for (const path of [privatePath, publicPath]) { - if (existsSync(path)) { + // lstat, not exists: a dangling symlink here would receive the private key. + if (lstatSync(path, { throwIfNoEntry: false }) !== undefined) { io.err(`bunmaska keygen: refusing to overwrite ${path}`); return 1; } } const pair = generateSigningKeyPair(); mkdirSync(dir, { recursive: true }); - writeFileSync(privatePath, pair.privateKey, { mode: 0o600 }); - writeFileSync(publicPath, pair.publicKey); + writeFileSync(privatePath, pair.privateKey, { mode: 0o600, flag: 'wx' }); + writeFileSync(publicPath, pair.publicKey, { flag: 'wx' }); io.out(privatePath); io.out(publicPath); io.out( diff --git a/tests/unit/cli/keygen.test.ts b/tests/unit/cli/keygen.test.ts index 98be40a1..ca530f19 100644 --- a/tests/unit/cli/keygen.test.ts +++ b/tests/unit/cli/keygen.test.ts @@ -1,5 +1,13 @@ import { afterEach, describe, expect, test } from 'bun:test'; -import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { + existsSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + symlinkSync, + writeFileSync, +} from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { PRIVATE_KEY_FILE, PUBLIC_KEY_FILE, runKeygen } from '../../../src/cli/keygen'; @@ -53,6 +61,21 @@ describe('bunmaska keygen', () => { expect(readFileSync(join(dir, PRIVATE_KEY_FILE), 'utf8')).toBe('existing'); expect(existsSync(join(dir, PUBLIC_KEY_FILE))).toBe(false); }); + + test.skipIf(process.platform === 'win32')( + 'refuses a dangling symlink in place of either key file instead of writing through it', + () => { + for (const file of [PRIVATE_KEY_FILE, PUBLIC_KEY_FILE]) { + const dir = makeTmpDir(); + const target = join(dir, 'elsewhere.pem'); + symlinkSync(target, join(dir, file)); + const c = io(); + expect(runKeygen(dir, asIo(c))).toBe(1); + expect(existsSync(target)).toBe(false); + expect(readdirSync(dir)).toEqual([file]); + } + }, + ); }); test('creates the output directory when it does not exist', () => { From c0aedc4a090ee29746baf00737e55f2ab9addde2 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:19:34 -0700 Subject: [PATCH 226/586] fix: probe the usr/share baked engine id only under usr/bin --- src/main/engine/resolve.ts | 7 ++++--- tests/unit/main/engine-resolve.test.ts | 5 +++++ 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/main/engine/resolve.ts b/src/main/engine/resolve.ts index 26bb1cb2..0b0967c8 100644 --- a/src/main/engine/resolve.ts +++ b/src/main/engine/resolve.ts @@ -57,9 +57,10 @@ export const bakedIdCandidates = (execPath: string, env: StoreEnv): string[] => if (explicit !== undefined && explicit.length > 0) { return [explicit]; } - const dir = dirname(execPath); // .../usr/bin - const slug = basename(execPath); - return [join(dir, '..', 'share', slug, 'engine.id'), join(dir, 'engine.id')]; + const dir = dirname(execPath); + const sibling = join(dir, 'engine.id'); + const usrBin = basename(dir) === 'bin' && basename(dirname(dir)) === 'usr'; + return usrBin ? [join(dir, '..', 'share', basename(execPath), 'engine.id'), sibling] : [sibling]; }; /** Default reader for the baked `engine.id`: env override, else beside the executable. */ diff --git a/tests/unit/main/engine-resolve.test.ts b/tests/unit/main/engine-resolve.test.ts index 16fb5864..75f83740 100644 --- a/tests/unit/main/engine-resolve.test.ts +++ b/tests/unit/main/engine-resolve.test.ts @@ -111,6 +111,11 @@ describe('bakedIdCandidates', () => { expect(slash(c[1] ?? '')).toBe('/opt/app/usr/bin/engine.id'); }); + test('outside a usr/bin layout, reads only the sibling engine.id', () => { + const c = bakedIdCandidates('/home/u/Downloads/MyApp/MyApp', {}); + expect(c.map(slash)).toEqual(['/home/u/Downloads/MyApp/engine.id']); + }); + test('an explicit BUNMASKA_ENGINE_ID_FILE wins outright', () => { expect( bakedIdCandidates('/opt/app/usr/bin/my-app', { BUNMASKA_ENGINE_ID_FILE: '/x/id' }), From efa7e8a5ceaf3ceb7fb2e6cb1a055aa3971dc556 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:19:40 -0700 Subject: [PATCH 227/586] fix: release Linux dialog, filter and chosen-file GObjects --- src/main/platform/linux/gtk-dialog.ts | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/main/platform/linux/gtk-dialog.ts b/src/main/platform/linux/gtk-dialog.ts index f897aa6f..f9e371bd 100644 --- a/src/main/platform/linux/gtk-dialog.ts +++ b/src/main/platform/linux/gtk-dialog.ts @@ -4,6 +4,7 @@ import { cstr } from '../cstr'; import { runAsyncReady } from './gasync'; import { loadGioFFI } from './gio-ffi'; import { loadGlibFFI } from './glib-ffi'; +import { loadGObjectFFI } from './gobject-ffi'; import { loadGtkDialogFFI, loadGtkDialogGObjectFFI } from './gtk-dialog-ffi'; /** @@ -106,11 +107,11 @@ export const settleFilePath = (args: SettleFilePathArgs): string => { return file === null ? '' : args.readPath(file); }; -/** Read the local path out of a `GFile*`, freeing the transfer-full `char*`. */ +/** Read the local path out of a transfer-full `GFile*`, releasing the file and the `char*`. */ const readGFilePath = (file: Pointer): string => { - const gio = loadGioFFI(); const glib = loadGlibFFI(); - const pathPtr = gio.symbols.g_file_get_path(file); + const pathPtr = loadGioFFI().symbols.g_file_get_path(file); + loadGObjectFFI().symbols.g_object_unref(file); if (pathPtr === null) { return ''; } @@ -150,7 +151,7 @@ const showMessageBox = (spec: { cancelId, finish: (r) => gtk.symbols.gtk_alert_dialog_choose_finish(dialog, r, null), }), - ); + ).finally(() => loadGObjectFFI().symbols.g_object_unref(dialog)); }; /** A `*.ext` glob matching any letter case; GTK's add_pattern is case-sensitive off Windows. */ @@ -180,6 +181,7 @@ const applyExtensionFilter = ( gtk.symbols.gtk_file_filter_add_pattern(filter, cstr(extensionPattern(ext))); } gtk.symbols.gtk_file_dialog_set_default_filter(fileDialog, filter); + loadGObjectFFI().symbols.g_object_unref(filter); }; // The open spec's file/directory/multi flags are accepted for API parity but @@ -210,7 +212,7 @@ const showOpenDialog = (spec: { }); return path === '' ? [] : [path]; }, - ); + ).finally(() => loadGObjectFFI().symbols.g_object_unref(fileDialog)); }; const showSaveDialog = (spec: { @@ -236,7 +238,7 @@ const showSaveDialog = (spec: { finish: (r) => gtk.symbols.gtk_file_dialog_save_finish(fileDialog, r, null), readPath: readGFilePath, }), - ); + ).finally(() => loadGObjectFFI().symbols.g_object_unref(fileDialog)); }; /** The Linux native dialog backend (single-path open; multi-select is v2). */ From 63c1b515978d8b5383e926197dcf9894edefd42d Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:19:50 -0700 Subject: [PATCH 228/586] test: replace cannot-fail api feature unit tests with ones that can --- tests/unit/main/api/clipboard.test.ts | 52 ++---------------------- tests/unit/main/api/menu.test.ts | 4 +- tests/unit/main/api/native-image.test.ts | 14 ------- tests/unit/main/api/native-theme.test.ts | 14 ------- tests/unit/main/api/shell.test.ts | 12 ------ tests/unit/main/api/tray.test.ts | 4 +- tests/unit/main/screen.test.ts | 7 ++-- 7 files changed, 12 insertions(+), 95 deletions(-) diff --git a/tests/unit/main/api/clipboard.test.ts b/tests/unit/main/api/clipboard.test.ts index 52ae93f6..c66af3e2 100644 --- a/tests/unit/main/api/clipboard.test.ts +++ b/tests/unit/main/api/clipboard.test.ts @@ -1,12 +1,10 @@ import { afterEach, describe, expect, test } from 'bun:test'; -import { UnsupportedPlatformError } from '../../../../src/common/errors'; -import { currentPlatform } from '../../../../src/common/platform'; import { type ClipboardBackend, clipboard, setClipboardBackendForTesting, } from '../../../../src/main/api/clipboard'; -import { nativeImage } from '../../../../src/main/api/native-image'; +import type { NativeImage } from '../../../../src/main/api/native-image'; /** A backend fake with every method as a benign default; override per test. */ const makeFakeBackend = (overrides: Partial = {}): ClipboardBackend => ({ @@ -21,16 +19,6 @@ const makeFakeBackend = (overrides: Partial = {}): ClipboardBa ...overrides, }); -describe('clipboard export', () => { - test('exposes readText, writeText, readHTML, writeHTML and clear', () => { - expect(typeof clipboard.readText).toBe('function'); - expect(typeof clipboard.writeText).toBe('function'); - expect(typeof clipboard.readHTML).toBe('function'); - expect(typeof clipboard.writeHTML).toBe('function'); - expect(typeof clipboard.clear).toBe('function'); - }); -}); - describe('clipboard API with an injected backend (async readText contract)', () => { afterEach(() => { setClipboardBackendForTesting(undefined); @@ -87,13 +75,9 @@ describe('clipboard API with an injected backend (async readText contract)', () }, }), ); - const png = nativeImage.createFromDataURL( - 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', - ); - clipboard.writeImage(png); - // The API hands the backend exactly the image's PNG bytes. - expect(writes).toHaveLength(1); - expect(writes[0]).toEqual(png.toPNG()); + const image = { toPNG: () => Buffer.from([1, 2, 3]) } as unknown as NativeImage; + clipboard.writeImage(image); + expect(writes.map((bytes) => [...bytes])).toEqual([[1, 2, 3]]); }); test('readImage resolves an empty image when the clipboard holds no image', async () => { @@ -136,31 +120,3 @@ describe('clipboard API with an injected backend (async readText contract)', () expect(cleared).toBe(1); }); }); - -if ( - currentPlatform() !== 'macos' && - currentPlatform() !== 'linux' && - currentPlatform() !== 'windows' -) { - describe('clipboard on platforms without a backend', () => { - test('readText rejects with UnsupportedPlatformError', async () => { - await expect(clipboard.readText()).rejects.toBeInstanceOf(UnsupportedPlatformError); - }); - - test('writeText throws UnsupportedPlatformError', () => { - expect(() => clipboard.writeText('x')).toThrow(UnsupportedPlatformError); - }); - - test('readHTML rejects with UnsupportedPlatformError', async () => { - await expect(clipboard.readHTML()).rejects.toBeInstanceOf(UnsupportedPlatformError); - }); - - test('writeHTML throws UnsupportedPlatformError', () => { - expect(() => clipboard.writeHTML('x')).toThrow(UnsupportedPlatformError); - }); - - test('clear throws UnsupportedPlatformError', () => { - expect(() => clipboard.clear()).toThrow(UnsupportedPlatformError); - }); - }); -} diff --git a/tests/unit/main/api/menu.test.ts b/tests/unit/main/api/menu.test.ts index 2388ea2c..64c47542 100644 --- a/tests/unit/main/api/menu.test.ts +++ b/tests/unit/main/api/menu.test.ts @@ -216,7 +216,9 @@ describe('Menu.insert / getMenuItemById', () => { test('insert places an item at the given position (clamped)', () => { const menu = Menu.buildFromTemplate([{ label: 'A' }, { label: 'C' }]); menu.insert(1, new MenuItem({ label: 'B' })); - expect(menu.items.map((i) => i.label)).toEqual(['A', 'B', 'C']); + menu.insert(99, new MenuItem({ label: 'D' })); + menu.insert(-5, new MenuItem({ label: '0' })); + expect(menu.items.map((i) => i.label)).toEqual(['0', 'A', 'B', 'C', 'D']); }); test('getMenuItemById finds an item by id, including inside submenus', () => { diff --git a/tests/unit/main/api/native-image.test.ts b/tests/unit/main/api/native-image.test.ts index 497d661b..a4ac2aa5 100644 --- a/tests/unit/main/api/native-image.test.ts +++ b/tests/unit/main/api/native-image.test.ts @@ -1,7 +1,6 @@ import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; import { clampCropRect, - type NativeImage, type NativeImageBackend, type NativeImageHandle, nativeImage, @@ -254,19 +253,6 @@ describe('NativeImage.toDataURL', () => { }); }); -describe('NativeImage type', () => { - test('exposes the Electron-compatible instance surface', () => { - setNativeImageBackendForTesting( - makeFakeBackend({ handle: 1n, width: 1, height: 1, empty: false }, new Uint8Array([1])), - ); - const image: NativeImage = nativeImage.createEmpty(); - expect(typeof image.getSize).toBe('function'); - expect(typeof image.isEmpty).toBe('function'); - expect(typeof image.toPNG).toBe('function'); - expect(typeof image.toDataURL).toBe('function'); - }); -}); - describe('NativeImage.toJPEG', () => { test('encodes via the backend at the given quality', () => { setNativeImageBackendForTesting( diff --git a/tests/unit/main/api/native-theme.test.ts b/tests/unit/main/api/native-theme.test.ts index 9bda9739..3f2b4d34 100644 --- a/tests/unit/main/api/native-theme.test.ts +++ b/tests/unit/main/api/native-theme.test.ts @@ -3,14 +3,6 @@ import { describe, expect, test } from 'bun:test'; import { nativeTheme, NativeThemeImpl } from '../../../../src/main/api/native-theme'; describe('nativeTheme', () => { - test('exposes a boolean shouldUseDarkColors', () => { - expect(typeof nativeTheme.shouldUseDarkColors).toBe('boolean'); - }); - - test('exposes a boolean prefersReducedTransparency', () => { - expect(typeof nativeTheme.prefersReducedTransparency).toBe('boolean'); - }); - test('is an EventEmitter for the updated event', () => { expect(nativeTheme).toBeInstanceOf(EventEmitter); }); @@ -33,12 +25,6 @@ describe('nativeTheme.themeSource', () => { expect(t.shouldUseDarkColors).toBe(false); }); - test('themeSource "system" reads the OS appearance (a boolean)', () => { - const t = new NativeThemeImpl(); - t.themeSource = 'system'; - expect(typeof t.shouldUseDarkColors).toBe('boolean'); - }); - test('setting themeSource emits updated', () => { const t = new NativeThemeImpl(); let fired = 0; diff --git a/tests/unit/main/api/shell.test.ts b/tests/unit/main/api/shell.test.ts index a84ce6cc..72dcc189 100644 --- a/tests/unit/main/api/shell.test.ts +++ b/tests/unit/main/api/shell.test.ts @@ -65,15 +65,3 @@ describe('shell.openPath', () => { expect(await shell.openPath('/nope')).toBe('Failed to open path: /nope'); }); }); - -describe('shell.showItemInFolder and beep', () => { - test('showItemInFolder forwards the path', () => { - shell.showItemInFolder('/tmp/file'); - expect(calls).toEqual(['showItemInFolder:/tmp/file']); - }); - - test('beep calls the backend', () => { - shell.beep(); - expect(calls).toEqual(['beep']); - }); -}); diff --git a/tests/unit/main/api/tray.test.ts b/tests/unit/main/api/tray.test.ts index 591c1d63..90d04516 100644 --- a/tests/unit/main/api/tray.test.ts +++ b/tests/unit/main/api/tray.test.ts @@ -187,8 +187,6 @@ describe('Tray lifecycle', () => { expect(() => tray.setTitle('x')).not.toThrow(); expect(() => tray.setImage('/tmp/x.png')).not.toThrow(); expect(() => tray.setContextMenu(null)).not.toThrow(); - // Nothing should have been forwarded post-destroy. - expect(created[0]?.toolTips).toEqual([]); - expect(created[0]?.titles).toEqual([]); + expect(created[0]).toMatchObject({ toolTips: [], titles: [], images: [], menus: [] }); }); }); diff --git a/tests/unit/main/screen.test.ts b/tests/unit/main/screen.test.ts index 3839fe46..d3836140 100644 --- a/tests/unit/main/screen.test.ts +++ b/tests/unit/main/screen.test.ts @@ -106,10 +106,11 @@ describe('screen.getDisplayNearestPoint', () => { expect(screen.getDisplayNearestPoint({ x: -500, y: 400 }).id).toBe(1); }); - test('treats a point on the shared edge as inside one display', () => { + test('a point on a shared edge goes to the first display that contains it', () => { setScreenBackendForTesting(fakeBackend([PRIMARY, SECONDARY])); - const d = screen.getDisplayNearestPoint({ x: 1920, y: 400 }); - expect([1, 2]).toContain(d.id); + expect(screen.getDisplayNearestPoint({ x: 1920, y: 400 }).id).toBe(1); + setScreenBackendForTesting(fakeBackend([SECONDARY, PRIMARY])); + expect(screen.getDisplayNearestPoint({ x: 1920, y: 400 }).id).toBe(2); }); }); From 965710a902eaf3cf704bf58dd9eea95302328ce3 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:19:59 -0700 Subject: [PATCH 229/586] test: gate Linux FFI display tests with skipIf, drop typeof checks --- tests/integration/linux/glib-ffi.test.ts | 63 +++++++++++++---- tests/integration/linux/gobject-ffi.test.ts | 17 +---- tests/integration/linux/gtk-ffi.test.ts | 69 ++----------------- tests/integration/linux/jsc-ffi.test.ts | 13 ---- tests/integration/linux/webkitgtk-ffi.test.ts | 64 +++-------------- 5 files changed, 66 insertions(+), 160 deletions(-) delete mode 100644 tests/integration/linux/jsc-ffi.test.ts diff --git a/tests/integration/linux/glib-ffi.test.ts b/tests/integration/linux/glib-ffi.test.ts index 9c72096f..322d4ef6 100644 --- a/tests/integration/linux/glib-ffi.test.ts +++ b/tests/integration/linux/glib-ffi.test.ts @@ -1,23 +1,56 @@ import { describe, expect, test } from 'bun:test'; import { currentPlatform } from '../../../src/common/platform'; +import { loadGDBusFFI } from '../../../src/main/platform/linux/gdbus-ffi'; +import { loadGdkFFI } from '../../../src/main/platform/linux/gdk-ffi'; +import { loadGdkPixbufFFI } from '../../../src/main/platform/linux/gdk-pixbuf-ffi'; +import { loadGioFFI } from '../../../src/main/platform/linux/gio-ffi'; import { loadGlibFFI } from '../../../src/main/platform/linux/glib-ffi'; +import { loadGObjectFFI } from '../../../src/main/platform/linux/gobject-ffi'; +import { + loadGtkDialogFFI, + loadGtkDialogGObjectFFI, +} from '../../../src/main/platform/linux/gtk-dialog-ffi'; +import { loadGtkFFI } from '../../../src/main/platform/linux/gtk-ffi'; +import { loadGMenuFFI, loadGtkMenuFFI } from '../../../src/main/platform/linux/gtk-menu-ffi'; +import { loadJscFFI } from '../../../src/main/platform/linux/jsc-ffi'; +import { loadLibnotifyFFI } from '../../../src/main/platform/linux/libnotify-ffi'; +import { loadLibsecretFFI } from '../../../src/main/platform/linux/libsecret-ffi'; +import { loadSoupFFI } from '../../../src/main/platform/linux/soup-ffi'; +import { loadWebKitGtkFFI } from '../../../src/main/platform/linux/webkitgtk-ffi'; +import { loadX11FFI } from '../../../src/main/platform/linux/x11-ffi'; -if (currentPlatform() === 'linux') { - describe('GLib FFI on Linux', () => { - test('resolves the main-context and g_free symbols', () => { - const lib = loadGlibFFI(); - for (const name of [ - 'g_main_context_iteration', - 'g_main_context_pending', - 'g_free', - ] as const) { - expect(typeof lib.symbols[name]).toBe('function'); - } - }); +const LOADERS: ReadonlyArray unknown]> = [ + ['loadGDBusFFI', loadGDBusFFI], + ['loadGdkFFI', loadGdkFFI], + ['loadGdkPixbufFFI', loadGdkPixbufFFI], + ['loadGioFFI', loadGioFFI], + ['loadGlibFFI', loadGlibFFI], + ['loadGObjectFFI', loadGObjectFFI], + ['loadGtkFFI', loadGtkFFI], + ['loadGtkDialogFFI', loadGtkDialogFFI], + ['loadGtkDialogGObjectFFI', loadGtkDialogGObjectFFI], + ['loadGMenuFFI', loadGMenuFFI], + ['loadGtkMenuFFI', loadGtkMenuFFI], + ['loadJscFFI', loadJscFFI], + ['loadLibnotifyFFI', loadLibnotifyFFI], + ['loadLibsecretFFI', loadLibsecretFFI], + ['loadSoupFFI', loadSoupFFI], + ['loadWebKitGtkFFI', loadWebKitGtkFFI], + ['loadX11FFI', loadX11FFI], +]; - test('g_free is a NULL-safe no-op', () => { - const lib = loadGlibFFI(); - expect(() => lib.symbols.g_free(null)).not.toThrow(); +if (currentPlatform() === 'linux') { + describe('Linux FFI loaders', () => { + test('every loader dlopens and resolves its whole symbol table on this distro', () => { + const failures = LOADERS.flatMap(([name, load]) => { + try { + load(); + return []; + } catch (error) { + return [`${name}: ${error instanceof Error ? error.message : String(error)}`]; + } + }); + expect(failures).toEqual([]); }); }); } diff --git a/tests/integration/linux/gobject-ffi.test.ts b/tests/integration/linux/gobject-ffi.test.ts index 41009d39..55900cc7 100644 --- a/tests/integration/linux/gobject-ffi.test.ts +++ b/tests/integration/linux/gobject-ffi.test.ts @@ -6,24 +6,11 @@ import { loadGObjectFFI } from '../../../src/main/platform/linux/gobject-ffi'; import { loadGtkFFI } from '../../../src/main/platform/linux/gtk-ffi'; if (currentPlatform() === 'linux') { - describe('GObject FFI on Linux', () => { - test('resolves the signal + refcount + construct symbols', () => { - const lib = loadGObjectFFI(); - for (const name of [ - 'g_signal_connect_data', - 'g_signal_handler_disconnect', - 'g_object_unref', - 'g_object_new', - ] as const) { - expect(typeof lib.symbols[name]).toBe('function'); - } - }); + const hasDisplay = loadGtkFFI().symbols.gtk_init_check() !== 0; + describe.skipIf(!hasDisplay)('GObject FFI on a real display', () => { test('connects and disconnects a real signal handler on a GtkWindow', () => { const gtk = loadGtkFFI(); - if (gtk.symbols.gtk_init_check() === 0) { - return; // No display. - } const gobject = loadGObjectFFI(); const window = gtk.symbols.gtk_window_new(); diff --git a/tests/integration/linux/gtk-ffi.test.ts b/tests/integration/linux/gtk-ffi.test.ts index ca5988c6..b3c8c09e 100644 --- a/tests/integration/linux/gtk-ffi.test.ts +++ b/tests/integration/linux/gtk-ffi.test.ts @@ -4,79 +4,22 @@ import { cstr } from '../../../src/main/platform/cstr'; import { loadGtkFFI } from '../../../src/main/platform/linux/gtk-ffi'; if (currentPlatform() === 'linux') { - describe('GTK FFI on Linux', () => { - test('loadGtkFFI returns a library handle with gtk_init_check and gtk_window_new', () => { - const lib = loadGtkFFI(); - expect(typeof lib.symbols.gtk_init_check).toBe('function'); - expect(typeof lib.symbols.gtk_window_new).toBe('function'); - }); - - test('gtk_init_check returns a non-zero gboolean (true) on a working display', () => { - const lib = loadGtkFFI(); - const result = lib.symbols.gtk_init_check(); - // On a headless CI runner without a display, gtk_init_check may legitimately - // return 0. We assert only that the call returns a JS number — i.e. it - // didn't crash and FFI dispatch works. - expect(typeof result).toBe('number'); - }); - - test('the library exports gtk_window_set_title', () => { - const lib = loadGtkFFI(); - expect(typeof lib.symbols.gtk_window_set_title).toBe('function'); - }); - - test('the library exports gtk_window_set_default_size', () => { - const lib = loadGtkFFI(); - expect(typeof lib.symbols.gtk_window_set_default_size).toBe('function'); - }); - - test('the library exports gtk_window_present', () => { - const lib = loadGtkFFI(); - expect(typeof lib.symbols.gtk_window_present).toBe('function'); - }); - - test('gtk_about_dialog_new resolves and constructs a dialog (showAboutPanel)', () => { - const lib = loadGtkFFI(); - expect(typeof lib.symbols.gtk_about_dialog_new).toBe('function'); - lib.symbols.gtk_init_check(); - expect(lib.symbols.gtk_about_dialog_new()).not.toBeNull(); - }); + const hasDisplay = loadGtkFFI().symbols.gtk_init_check() !== 0; - test('resolves the newly added GTK4 window/widget symbols', () => { - const lib = loadGtkFFI(); - for (const name of [ - 'gtk_window_set_child', - 'gtk_widget_set_visible', - 'gtk_window_destroy', - 'gtk_window_minimize', - 'gtk_window_unminimize', - 'gtk_window_maximize', - 'gtk_window_unmaximize', - 'gtk_window_is_maximized', - 'gtk_widget_get_width', - 'gtk_widget_get_height', - ] as const) { - expect(typeof lib.symbols[name]).toBe('function'); - } + describe.skipIf(!hasDisplay)('GTK FFI on a real display', () => { + test('gtk_about_dialog_new constructs a dialog (showAboutPanel)', () => { + expect(loadGtkFFI().symbols.gtk_about_dialog_new()).not.toBeNull(); }); - test('drives the new symbols end-to-end on a real window', () => { + test('drives a real window through the GTK 4 window symbols', () => { const lib = loadGtkFFI(); - if (lib.symbols.gtk_init_check() === 0) { - return; // No display; the smoke assertions above already proved dispatch. - } const window = lib.symbols.gtk_window_new(); expect(window).not.toBeNull(); lib.symbols.gtk_window_set_title(window, cstr('Bunmaska')); lib.symbols.gtk_window_set_default_size(window, 400, 300); lib.symbols.gtk_widget_set_visible(window, 1); lib.symbols.gtk_window_present(window); - - // get_width/get_height return a JS number (0 before the window is mapped). - expect(typeof lib.symbols.gtk_widget_get_width(window)).toBe('number'); - expect(typeof lib.symbols.gtk_widget_get_height(window)).toBe('number'); - expect(typeof lib.symbols.gtk_window_is_maximized(window)).toBe('number'); - + expect(lib.symbols.gtk_window_is_maximized(window)).toBe(0); lib.symbols.gtk_window_destroy(window); }); }); diff --git a/tests/integration/linux/jsc-ffi.test.ts b/tests/integration/linux/jsc-ffi.test.ts deleted file mode 100644 index 989474ab..00000000 --- a/tests/integration/linux/jsc-ffi.test.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { currentPlatform } from '../../../src/common/platform'; -import { loadJscFFI } from '../../../src/main/platform/linux/jsc-ffi'; - -if (currentPlatform() === 'linux') { - describe('JavaScriptCoreGTK FFI on Linux', () => { - // CI-RISK: confirms libjavascriptcoregtk-6.0.so.1 resolves separately. - test('resolves jsc_value_to_string from the separate .so', () => { - const lib = loadJscFFI(); - expect(typeof lib.symbols.jsc_value_to_string).toBe('function'); - }); - }); -} diff --git a/tests/integration/linux/webkitgtk-ffi.test.ts b/tests/integration/linux/webkitgtk-ffi.test.ts index a7733ba6..34212e1e 100644 --- a/tests/integration/linux/webkitgtk-ffi.test.ts +++ b/tests/integration/linux/webkitgtk-ffi.test.ts @@ -15,47 +15,16 @@ const newWebView = () => ); if (currentPlatform() === 'linux') { - describe('WebKitGTK FFI on Linux', () => { - test('resolves the core web-view symbols (proves the library + names are correct)', () => { - const lib = loadWebKitGtkFFI(); - expect(typeof lib.symbols.webkit_web_view_load_uri).toBe('function'); - expect(typeof lib.symbols.webkit_web_view_load_html).toBe('function'); - expect(typeof lib.symbols.webkit_web_view_get_uri).toBe('function'); - }); - - test('resolves the navigation, JS-eval, and user-content symbols', () => { - const lib = loadWebKitGtkFFI(); - for (const name of [ - 'webkit_web_view_reload', - 'webkit_web_view_reload_bypass_cache', - 'webkit_web_view_go_back', - 'webkit_web_view_go_forward', - 'webkit_web_view_can_go_back', - 'webkit_web_view_can_go_forward', - 'webkit_web_view_evaluate_javascript', - 'webkit_user_content_manager_new', - 'webkit_user_content_manager_register_script_message_handler', - 'webkit_user_content_manager_add_script', - 'webkit_user_script_new', - 'webkit_web_view_get_type', - ] as const) { - expect(typeof lib.symbols[name]).toBe('function'); - } - }); + test('webkit_web_view_get_type returns a non-zero GType (BigInt)', () => { + const gtype = loadWebKitGtkFFI().symbols.webkit_web_view_get_type(); + expect(typeof gtype).toBe('bigint'); + expect(gtype).not.toBe(0n); + }); - // CI-RISK: webkit_web_view_get_type is the unverified void-arg get_type form. - test('webkit_web_view_get_type returns a non-zero GType (BigInt)', () => { - const lib = loadWebKitGtkFFI(); - const gtype = lib.symbols.webkit_web_view_get_type(); - expect(typeof gtype).toBe('bigint'); - expect(gtype).not.toBe(0n); - }); + const hasDisplay = loadGtkFFI().symbols.gtk_init_check() !== 0; + describe.skipIf(!hasDisplay)('WebKitGTK FFI on a real display', () => { test('drives navigation + user-content symbols on a real web view', () => { - const gtk = loadGtkFFI(); - if (gtk.symbols.gtk_init_check() === 0) { - return; // No display. - } const webkit = loadWebKitGtkFFI(); // get_uri is NULL before any load -> readGetUriResult guards it to ''. @@ -63,14 +32,13 @@ if (currentPlatform() === 'linux') { expect(view).not.toBeNull(); expect(readGetUriResult(webkit.symbols.webkit_web_view_get_uri(view))).toBe(''); - // load_html with a NULL base_uri (pointer 0) must not crash. + // load_html with a NULL base_uri must not crash. webkit.symbols.webkit_web_view_load_html(view, cstr('t'), null); // can_go_back/forward are gboolean (i32); false before any history. expect(webkit.symbols.webkit_web_view_can_go_back(view)).toBe(0); expect(webkit.symbols.webkit_web_view_can_go_forward(view)).toBe(0); - // user-content-manager round-trip: create, register handler, add a script. const ucm = webkit.symbols.webkit_user_content_manager_new(); expect(ucm).not.toBeNull(); webkit.symbols.webkit_user_content_manager_register_script_message_handler( @@ -96,22 +64,10 @@ if (currentPlatform() === 'linux') { }); test('sets a custom User-Agent on a real view via WebKitSettings', () => { - const gtk = loadGtkFFI(); - if (gtk.symbols.gtk_init_check() === 0) { - return; // No display. - } const webkit = loadWebKitGtkFFI(); - const view = newWebView(); - const settings = webkit.symbols.webkit_web_view_get_settings(view); + const settings = webkit.symbols.webkit_web_view_get_settings(newWebView()); expect(settings).not.toBeNull(); - // Must resolve + not crash; the UA takes effect on the next navigation. - expect(() => - webkit.symbols.webkit_settings_set_user_agent(settings, cstr('Bunmaska/1.0 (integration)')), - ).not.toThrow(); - }); - - test('readGetUriResult returns "" for a NULL pointer', () => { - expect(readGetUriResult(null)).toBe(''); + webkit.symbols.webkit_settings_set_user_agent(settings, cstr('Bunmaska/1.0 (integration)')); }); }); } From e9d33b0816acb99ee4521880749cd3d7b65781a5 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:19:59 -0700 Subject: [PATCH 230/586] fix: send scan codes and the extended bit with Windows key events --- src/main/platform/windows/windows-input.ts | 82 +++++++++++-------- .../platform/windows/windows-input.test.ts | 17 +++- 2 files changed, 64 insertions(+), 35 deletions(-) diff --git a/src/main/platform/windows/windows-input.ts b/src/main/platform/windows/windows-input.ts index c037d6d5..a3682c3f 100644 --- a/src/main/platform/windows/windows-input.ts +++ b/src/main/platform/windows/windows-input.ts @@ -25,10 +25,8 @@ const MK_LBUTTON = 0x0001; const MK_RBUTTON = 0x0002; const MK_MBUTTON = 0x0010; -/** LPARAM for a key-up: repeat count 1 + bit 30 (was down) + bit 31 (transition). */ -const KEYUP_LPARAM = 0xc0000001n; -/** LPARAM for a key-down / char: repeat count 1, key not previously down. */ -const KEYDOWN_LPARAM = 0x00000001n; +/** Key-up LPARAM flags: bit 30 (was down) + bit 31 (transition). */ +const KEYUP_FLAGS = 0xc0000000n; /** A single Win32 window message to post: `(message, wParam, lParam)`. */ export type WindowMessage = { @@ -68,34 +66,50 @@ const buttonUp = (button: MouseButton): number => { /** Named keys whose VK code IS the character they type (WM_CHAR-producing). */ const CHAR_PRODUCING_VK = new Set([0x08, 0x09, 0x0d, 0x1b, 0x20]); // BS, Tab, Enter, Esc, Space -/** Win32 virtual-key codes for the non-printable keys we map by Electron key name. */ -const NAMED_VIRTUAL_KEYS = new Map([ - ['Backspace', 0x08], - ['Tab', 0x09], - ['Enter', 0x0d], - ['Return', 0x0d], - ['Escape', 0x1b], - ['Space', 0x20], - ['PageUp', 0x21], - ['PageDown', 0x22], - ['End', 0x23], - ['Home', 0x24], - ['Left', 0x25], - ['Up', 0x26], - ['Right', 0x27], - ['Down', 0x28], - ['Delete', 0x2e], +/** Win32 virtual-key code + US-layout set-1 scan code for the keys we map by Electron key name. */ +const NAMED_KEYS = new Map([ + ['Backspace', [0x08, 0x0e]], + ['Tab', [0x09, 0x0f]], + ['Enter', [0x0d, 0x1c]], + ['Return', [0x0d, 0x1c]], + ['Escape', [0x1b, 0x01]], + ['Space', [0x20, 0x39]], + ['PageUp', [0x21, 0x49]], + ['PageDown', [0x22, 0x51]], + ['End', [0x23, 0x4f]], + ['Home', [0x24, 0x47]], + ['Left', [0x25, 0x4b]], + ['Up', [0x26, 0x48]], + ['Right', [0x27, 0x4d]], + ['Down', [0x28, 0x50]], + ['Delete', [0x2e, 0x53]], ]); -/** - * Resolve an Electron `keyCode` to a Win32 virtual-key code. Named keys come from - * {@link NAMED_VIRTUAL_KEYS}; a single ASCII letter/digit shares its codepoint with - * the VK code. Returns `undefined` for anything we do not map. - */ +/** Scan code by VK. US layout on purpose: Electron derives `event.code` from the US layout too. */ +const SCAN_CODES = new Map([ + ...NAMED_KEYS.values(), + ...( + [ + ['1234567890', 0x02], + ['QWERTYUIOP', 0x10], + ['ASDFGHJKL', 0x1e], + ['ZXCVBNM', 0x2c], + ] as const + ).flatMap(([row, first]) => [...row].map((c, i) => [c.charCodeAt(0), first + i] as const)), +]); + +/** PgUp..Down and Delete: without KF_EXTENDED WebKit reports them as numpad keys. */ +const isExtendedKey = (vk: number): boolean => (vk >= 0x21 && vk <= 0x28) || vk === 0x2e; + +/** Key-message LPARAM: repeat count 1, scan code in bits 16-23, KF_EXTENDED in bit 24. */ +const keyLParam = (vk: number, flags = 0n): bigint => + flags | 1n | (BigInt(SCAN_CODES.get(vk) ?? 0) << 16n) | (isExtendedKey(vk) ? 1n << 24n : 0n); + +/** Electron `keyCode` to Win32 VK: a named key, or an ASCII letter/digit (its codepoint is its VK). */ const virtualKey = (keyCode: string): number | undefined => { - const named = NAMED_VIRTUAL_KEYS.get(keyCode); + const named = NAMED_KEYS.get(keyCode); if (named !== undefined) { - return named; + return named[0]; } if (keyCode.length === 1) { const code = keyCode.toUpperCase().charCodeAt(0); @@ -130,7 +144,7 @@ export const inputEventToMessage = (event: NativeInputEvent): WindowMessage | un case 'char': { // A named key types its control code (Enter -> CR) or nothing (arrows); a // single character types itself. Never the first letter of a key NAME. - const named = NAMED_VIRTUAL_KEYS.get(event.keyCode); + const named = NAMED_KEYS.get(event.keyCode)?.[0]; const charCode = named !== undefined ? CHAR_PRODUCING_VK.has(named) @@ -141,19 +155,23 @@ export const inputEventToMessage = (event: NativeInputEvent): WindowMessage | un : undefined; return charCode === undefined ? undefined - : { message: WM_CHAR, wParam: BigInt(charCode), lParam: KEYDOWN_LPARAM }; + : { + message: WM_CHAR, + wParam: BigInt(charCode), + lParam: keyLParam(virtualKey(event.keyCode) ?? 0), + }; } case 'keyDown': { const vk = virtualKey(event.keyCode); return vk === undefined ? undefined - : { message: WM_KEYDOWN, wParam: BigInt(vk), lParam: KEYDOWN_LPARAM }; + : { message: WM_KEYDOWN, wParam: BigInt(vk), lParam: keyLParam(vk) }; } case 'keyUp': { const vk = virtualKey(event.keyCode); return vk === undefined ? undefined - : { message: WM_KEYUP, wParam: BigInt(vk), lParam: KEYUP_LPARAM }; + : { message: WM_KEYUP, wParam: BigInt(vk), lParam: keyLParam(vk, KEYUP_FLAGS) }; } default: return undefined; diff --git a/tests/unit/main/platform/windows/windows-input.test.ts b/tests/unit/main/platform/windows/windows-input.test.ts index cd457271..e01d3c1a 100644 --- a/tests/unit/main/platform/windows/windows-input.test.ts +++ b/tests/unit/main/platform/windows/windows-input.test.ts @@ -43,19 +43,30 @@ describe('inputEventToMessage', () => { expect(msg?.wParam).toBe(0n); }); - test('a named key maps to its virtual-key code (Escape)', () => { + test('a named key maps to its virtual-key code and scan code (Escape)', () => { expect(inputEventToMessage({ type: 'keyDown', keyCode: 'Escape' })).toEqual({ message: WM_KEYDOWN, wParam: 0x1bn, - lParam: 0x1n, + lParam: 0x00010001n, }); expect(inputEventToMessage({ type: 'keyUp', keyCode: 'Escape' })).toEqual({ message: WM_KEYUP, wParam: 0x1bn, - lParam: 0xc0000001n, + lParam: 0xc0010001n, }); }); + test('a key carries its US-layout scan code in lParam bits 16-23 (so event.code is set)', () => { + expect(inputEventToMessage({ type: 'keyDown', keyCode: 'a' })?.lParam).toBe(0x001e0001n); + expect(inputEventToMessage({ type: 'keyDown', keyCode: '1' })?.lParam).toBe(0x00020001n); + expect(inputEventToMessage({ type: 'char', keyCode: 'x' })?.lParam).toBe(0x002d0001n); + }); + + test('a navigation-cluster key sets the extended bit (not a numpad key)', () => { + expect(inputEventToMessage({ type: 'keyDown', keyCode: 'Left' })?.lParam).toBe(0x014b0001n); + expect(inputEventToMessage({ type: 'keyUp', keyCode: 'Delete' })?.lParam).toBe(0xc1530001n); + }); + test('a single letter maps to its VK code, case-insensitively', () => { const code = BigInt('A'.charCodeAt(0)); expect(inputEventToMessage({ type: 'keyDown', keyCode: 'a' })?.wParam).toBe(code); From 14d10cf09607ad6397fae277e1d3136bb6a87fac Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:20:04 -0700 Subject: [PATCH 231/586] fix: release libnotify notifications and their closed thunks --- src/main/platform/linux/gtk-notification.ts | 76 ++++++++----------- tests/integration/linux/notification.test.ts | 66 ++++------------ .../platform/linux/gtk-notification.test.ts | 38 ++-------- 3 files changed, 54 insertions(+), 126 deletions(-) diff --git a/src/main/platform/linux/gtk-notification.ts b/src/main/platform/linux/gtk-notification.ts index b85f7ac5..ae0afa1f 100644 --- a/src/main/platform/linux/gtk-notification.ts +++ b/src/main/platform/linux/gtk-notification.ts @@ -1,40 +1,23 @@ -import { JSCallback, type Pointer } from 'bun:ffi'; +import { JSCallback } from 'bun:ffi'; import type { NotificationBackend, NotificationHandle, NotificationSpec, } from '../../api/notification'; import { cstr } from '../cstr'; -import { connectSignal } from './gtk-signals'; import { loadGlibFFI } from './glib-ffi'; +import { loadGObjectFFI } from './gobject-ffi'; +import { connectSignal, deferCallbackClose } from './gtk-signals'; import { loadLibnotifyFFI } from './libnotify-ffi'; -/** - * Linux notifications via libnotify — the Linux half of Bunmaska's `Notification`. - * - * JSCallback lifecycle (a past SIGSEGV class): the `closed` handler thunk MUST - * stay reachable for the life of the connection — Bun GCs an unreferenced - * {@link JSCallback}, and the daemon would then call into freed memory. Each live - * notification therefore RETAINS its callback in the returned handle's closure, - * and {@link JSCallback.close} is deferred to a later tick (never called - * synchronously inside the handler's own invocation). - */ +/** `NotifyNotification::closed`: `(notification, user_data) -> void`. */ +const CLOSED_CB_DEF = { args: ['ptr', 'ptr'], returns: 'void' } as const; -/** ABI shape for `NotifyNotification::closed`: `(notification, user_data) -> void`. */ -export const CLOSED_CB_DEF = { args: ['ptr', 'ptr'], returns: 'void' } as const; - -/** - * Every `closed`-signal {@link JSCallback} currently wired to a live - * notification. Retained at module scope so Bun cannot GC the native thunk while - * the daemon still holds its pointer (the SIGSEGV-avoidance retain). Each entry - * is removed (and the callback closed on a later tick) when its notification - * fires `closed` or is explicitly closed. - */ +/** Keeps each `closed` thunk reachable until it fires; closed on a later tick (`deferCallbackClose`). */ const liveCallbacks = new Set(); let initialized = false; -/** Ensure `notify_init('Bunmaska')` has run once. Returns whether init succeeded. */ const ensureInit = (): boolean => { const notify = loadLibnotifyFFI(); if (initialized || notify.symbols.notify_is_initted() !== 0) { @@ -46,22 +29,22 @@ const ensureInit = (): boolean => { return ok; }; +// ponytail: libnotify's show/close are 25 s sync D-Bus calls; send Notify via linux-dbus callMethodSync (5 s bound) if a wedged daemon matters. const present = (spec: NotificationSpec): NotificationHandle => { const notify = loadLibnotifyFFI(); + const gobject = loadGObjectFFI().symbols; ensureInit(); const notification = notify.symbols.notify_notification_new( cstr(spec.title), cstr(spec.body), - // `cstring` cannot be null via the FFI binding, so an empty icon name (no - // icon) is passed instead of NULL — equivalent for our purposes. - cstr(''), + null, ); if (notification === null) { throw new Error('notify_notification_new() returned null'); } if (spec.silent) { - // The freedesktop `suppress-sound` hint; set_hint sinks the floating GVariant. + // set_hint sinks the floating GVariant. notify.symbols.notify_notification_set_hint( notification, cstr('suppress-sound'), @@ -69,27 +52,32 @@ const present = (spec: NotificationSpec): NotificationHandle => { ); } - // No daemon (headless CI) makes show return FALSE — expected, not an error. - notify.symbols.notify_notification_show(notification, null); + // No daemon (headless CI) makes show return FALSE and `closed` never fires, so release now. + if (notify.symbols.notify_notification_show(notification, null) === 0) { + gobject.g_object_unref(notification); + return { close: () => undefined, onClosed: () => undefined }; + } + + let onClosed: (() => void) | undefined; + let open = true; + const callback = new JSCallback((): void => { + open = false; + liveCallbacks.delete(callback); + gobject.g_signal_handler_disconnect(notification, connection.handlerId); + deferCallbackClose([callback, { close: () => gobject.g_object_unref(notification) }]); + onClosed?.(); + }, CLOSED_CB_DEF); + liveCallbacks.add(callback); + const connection = connectSignal(notification, 'closed', callback); return { close: () => { - notify.symbols.notify_notification_close(notification, null); + if (open) { + notify.symbols.notify_notification_close(notification, null); + } }, - // Wire the daemon's `closed` signal to `cb`. The thunk is retained in - // `liveCallbacks` until it fires; it is closed on a LATER tick (never - // synchronously inside its own invocation — that would free the trampoline - // the daemon is about to return into). onClosed: (cb) => { - const callback = new JSCallback((_notification: Pointer, _userData: Pointer): void => { - cb(); - setTimeout(() => { - liveCallbacks.delete(callback); - callback.close(); - }, 0); - }, CLOSED_CB_DEF); - liveCallbacks.add(callback); - connectSignal(notification, 'closed', callback); + onClosed = cb; }, }; }; @@ -102,7 +90,7 @@ const isSupported = (): boolean => { } }; -/** The Linux native notification backend (libnotify). */ +/** The libnotify notification backend. */ export const linuxNotificationBackend: NotificationBackend = { isSupported, present, diff --git a/tests/integration/linux/notification.test.ts b/tests/integration/linux/notification.test.ts index 1dd82bcf..2bfa6c7e 100644 --- a/tests/integration/linux/notification.test.ts +++ b/tests/integration/linux/notification.test.ts @@ -1,59 +1,25 @@ import { describe, expect, test } from 'bun:test'; import { currentPlatform } from '../../../src/common/platform'; import { linuxNotificationBackend } from '../../../src/main/platform/linux/gtk-notification'; -import { loadGtkFFI } from '../../../src/main/platform/linux/gtk-ffi'; import { loadLibnotifyFFI } from '../../../src/main/platform/linux/libnotify-ffi'; -/** - * Linux-only. Headless CI (xvfb) has NO notification daemon, so - * `notify_notification_show` returns FALSE / no-ops there — that is EXPECTED and - * NOT a failure. This test asserts only that: - * - every libnotify symbol resolves, - * - `notify_init('Bunmaska')` succeeds, - * - construct + show + close run WITHOUT THROWING. - * It deliberately does NOT assert a banner appeared. A `gtk_init_check` guard - * keeps the construct/show steps from running where there is no display at all. - */ -const isLinux = currentPlatform() === 'linux'; - -describe.skipIf(!isLinux)('libnotify FFI + Linux notification backend (Linux)', () => { - test('loadLibnotifyFFI resolves every symbol without throwing', () => { - const lib = loadLibnotifyFFI(); - for (const name of [ - 'notify_init', - 'notify_is_initted', - 'notify_notification_new', - 'notify_notification_show', - 'notify_notification_close', - 'notify_notification_set_timeout', - ] as const) { - expect(typeof lib.symbols[name]).toBe('function'); - } - }); - - test('isSupported() runs notify_init and returns a boolean', () => { - expect(typeof linuxNotificationBackend.isSupported()).toBe('boolean'); - // notify_init succeeding implies notify_is_initted is now TRUE. - const lib = loadLibnotifyFFI(); - if (linuxNotificationBackend.isSupported()) { - expect(lib.symbols.notify_is_initted()).not.toBe(0); - } +// CI has no notification daemon, so show returns FALSE there: these prove init and the +// no-daemon release path, not that a banner appeared. +describe.skipIf(currentPlatform() !== 'linux')('Linux notification backend (libnotify)', () => { + test('isSupported() initialises libnotify without a daemon', () => { + expect(linuxNotificationBackend.isSupported()).toBe(true); + expect(loadLibnotifyFFI().symbols.notify_is_initted()).not.toBe(0); }); - test('construct + show + close run without throwing (no-daemon-safe)', () => { - const gtk = loadGtkFFI(); - if (gtk.symbols.gtk_init_check() === 0) { - return; // No display; symbol-resolution + init assertions above proved dispatch. - } - expect(() => { - const handle = linuxNotificationBackend.present({ - title: 'Bunmaska test', - body: 'Integration body', - subtitle: '', - silent: false, - }); - handle.onClosed(() => undefined); - handle.close(); - }).not.toThrow(); + test('present, onClosed and a repeated close run clean without a daemon', () => { + const handle = linuxNotificationBackend.present({ + title: 'Bunmaska test', + body: 'Integration body', + subtitle: '', + silent: true, + }); + handle.onClosed(() => undefined); + handle.close(); + expect(() => handle.close()).not.toThrow(); }); }); diff --git a/tests/unit/main/platform/linux/gtk-notification.test.ts b/tests/unit/main/platform/linux/gtk-notification.test.ts index c8408bf2..cdc4a582 100644 --- a/tests/unit/main/platform/linux/gtk-notification.test.ts +++ b/tests/unit/main/platform/linux/gtk-notification.test.ts @@ -1,42 +1,16 @@ -import { describe, expect, it } from 'bun:test'; +import { describe, expect, test } from 'bun:test'; import { UnsupportedPlatformError } from '../../../../../src/common/errors'; import { currentPlatform } from '../../../../../src/common/platform'; -import { - CLOSED_CB_DEF, - linuxNotificationBackend, -} from '../../../../../src/main/platform/linux/gtk-notification'; +import { linuxNotificationBackend } from '../../../../../src/main/platform/linux/gtk-notification'; -/** - * Cross-platform-safe unit assertions for the Linux notification backend: the - * `closed`-signal callback ABI shape (pure JS) and that the backend stays - * importable on macOS, dispatching to the Linux-only loader lazily (so it throws - * only when invoked off-Linux, never at import). - */ +const isLinux = currentPlatform() === 'linux'; -describe('CLOSED_CB_DEF (NotifyNotification::closed ABI shape)', () => { - it('is (notification, user_data) -> void', () => { - expect(CLOSED_CB_DEF.args).toEqual(['ptr', 'ptr']); - expect(CLOSED_CB_DEF.returns).toBe('void'); - }); -}); - -describe('linuxNotificationBackend on a non-Linux host', () => { - it('exposes isSupported and present', () => { - expect(typeof linuxNotificationBackend.isSupported).toBe('function'); - expect(typeof linuxNotificationBackend.present).toBe('function'); - }); - - it('isSupported() returns false off-Linux instead of throwing (caught lazily)', () => { - if (currentPlatform() === 'linux') { - return; - } +describe('linuxNotificationBackend off Linux', () => { + test.skipIf(isLinux)('isSupported() returns false instead of throwing', () => { expect(linuxNotificationBackend.isSupported()).toBe(false); }); - it('present() throws UnsupportedPlatformError off-Linux (lazy loader)', () => { - if (currentPlatform() === 'linux') { - return; - } + test.skipIf(isLinux)('present() throws UnsupportedPlatformError from the lazy loader', () => { expect(() => linuxNotificationBackend.present({ title: 't', body: '', subtitle: '', silent: false }), ).toThrow(UnsupportedPlatformError); From 3d5b6f5cdad649f227b0d463ef25a419378e0bc7 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:20:05 -0700 Subject: [PATCH 232/586] test: gate update-key tests with skipIf and drop a constant check --- tests/unit/cli/dispatch-update-key.test.ts | 74 +++++++++++----------- tests/unit/main/api/auto-updater.test.ts | 5 -- 2 files changed, 36 insertions(+), 43 deletions(-) diff --git a/tests/unit/cli/dispatch-update-key.test.ts b/tests/unit/cli/dispatch-update-key.test.ts index 17972323..280bc172 100644 --- a/tests/unit/cli/dispatch-update-key.test.ts +++ b/tests/unit/cli/dispatch-update-key.test.ts @@ -5,7 +5,7 @@ import { join } from 'node:path'; import { dispatch } from '../../../src/cli/index'; import { runKeygen } from '../../../src/cli/keygen'; import { verifyArtifact } from '../../../src/common/signature'; -import { currentPlatform } from '../../../src/common/platform'; +import { currentArch, currentPlatform } from '../../../src/common/platform'; /** * `--update` routing through dispatch with the macOS builder stubbed to a REAL @@ -14,6 +14,7 @@ import { currentPlatform } from '../../../src/common/platform'; * other dispatch build tests. */ const onlyMac = currentPlatform() === 'macos'; +const ARTIFACT = `demo-stable-macos-${currentArch()}.tar.zst`; const originalCwd = process.cwd(); let dir: string | undefined; @@ -63,10 +64,7 @@ const setupProject = (): { root: string; bundle: string } => { }; describe('dispatch build --update signing', () => { - test('without --update-key it loudly warns the feed is unsigned', async () => { - if (!onlyMac) { - return; - } + test.skipIf(!onlyMac)('without --update-key it loudly warns the feed is unsigned', async () => { const { root, bundle } = setupProject(); let code = -1; const streams = await captured(async () => { @@ -83,40 +81,40 @@ describe('dispatch build --update signing', () => { const stderr = streams.err.join(''); expect(stderr).toContain('UNSIGNED'); expect(stderr).toContain('--update-key'); - expect(existsSync(join(root, 'demo-stable-macos-arm64.tar.zst.sig'))).toBe(false); + expect(existsSync(join(root, `${ARTIFACT}.sig`))).toBe(false); }); - test('with --update-key it writes a .sig the public key verifies and prints its path', async () => { - if (!onlyMac) { - return; - } - const { root, bundle } = setupProject(); - const keysDir = join(root, 'keys'); - mkdirSync(keysDir); - runKeygen(keysDir, { out: () => undefined, err: () => undefined }); - let code = -1; - const streams = await captured(async () => { - code = await dispatch( - { - kind: 'build', - entry: 'app.ts', - options: { - target: 'macos', - name: 'Demo', - update: true, - updateKey: join(keysDir, 'update-signing-key.pem'), + test.skipIf(!onlyMac)( + 'with --update-key it writes a .sig the public key verifies and prints its path', + async () => { + const { root, bundle } = setupProject(); + const keysDir = join(root, 'keys'); + mkdirSync(keysDir); + runKeygen(keysDir, { out: () => undefined, err: () => undefined }); + let code = -1; + const streams = await captured(async () => { + code = await dispatch( + { + kind: 'build', + entry: 'app.ts', + options: { + target: 'macos', + name: 'Demo', + update: true, + updateKey: join(keysDir, 'update-signing-key.pem'), + }, }, - }, - { buildMac: async () => bundle }, - ); - }); - expect(code).toBe(0); - const sigPath = join(root, 'demo-stable-macos-arm64.tar.zst.sig'); - expect(streams.out.join('')).toContain(sigPath); - expect(streams.err.join('')).not.toContain('UNSIGNED'); - const artifact = readFileSync(join(root, 'demo-stable-macos-arm64.tar.zst')); - const publicPem = readFileSync(join(keysDir, 'update-public-key.pem'), 'utf8'); - const sig = readFileSync(sigPath, 'utf8').trim(); - expect(verifyArtifact(publicPem, artifact, sig)).toBe(true); - }); + { buildMac: async () => bundle }, + ); + }); + expect(code).toBe(0); + const sigPath = join(root, `${ARTIFACT}.sig`); + expect(streams.out.join('')).toContain(sigPath); + expect(streams.err.join('')).not.toContain('UNSIGNED'); + const artifact = readFileSync(join(root, ARTIFACT)); + const publicPem = readFileSync(join(keysDir, 'update-public-key.pem'), 'utf8'); + const sig = readFileSync(sigPath, 'utf8').trim(); + expect(verifyArtifact(publicPem, artifact, sig)).toBe(true); + }, + ); }); diff --git a/tests/unit/main/api/auto-updater.test.ts b/tests/unit/main/api/auto-updater.test.ts index 60e24b96..d240424d 100644 --- a/tests/unit/main/api/auto-updater.test.ts +++ b/tests/unit/main/api/auto-updater.test.ts @@ -7,7 +7,6 @@ import { AutoUpdaterImpl, type AutoUpdaterDeps, MAX_COMPRESSED_ARTIFACT_BYTES, - MAX_DECOMPRESSED_TAR_BYTES, readFeedResponse, type StagedUpdate, stageToTmp, @@ -301,10 +300,6 @@ describe('assertSizeWithin (zip-bomb guard)', () => { expect(() => assertSizeWithin(100, 100, 'thing')).not.toThrow(); expect(() => assertSizeWithin(101, 100, 'thing')).toThrow(/exceeds/); }); - - test('the decompressed cap is larger than the compressed cap', () => { - expect(MAX_DECOMPRESSED_TAR_BYTES).toBeGreaterThan(MAX_COMPRESSED_ARTIFACT_BYTES); - }); }); describe('autoUpdater fire-and-forget calls (Electron style)', () => { From 7d9d7c64fd0f6d25ef173b2439f8c1051877143d Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:20:10 -0700 Subject: [PATCH 233/586] test: drop cannot-fail and stale Windows api feature integration tests --- tests/integration/windows/menu.test.ts | 7 ------- tests/integration/windows/native-theme.test.ts | 4 +--- tests/integration/windows/notification.test.ts | 6 ------ tests/integration/windows/shell.test.ts | 5 ----- 4 files changed, 1 insertion(+), 21 deletions(-) diff --git a/tests/integration/windows/menu.test.ts b/tests/integration/windows/menu.test.ts index 711a1c00..20a2d0ea 100644 --- a/tests/integration/windows/menu.test.ts +++ b/tests/integration/windows/menu.test.ts @@ -61,12 +61,5 @@ if (currentPlatform() === 'windows') { expect(clicks).toBe(0); loadUser32().symbols.DestroyMenu(handle); }); - - test('setApplicationMenu is a no-op (per-window menu bar is deferred)', () => { - const realizer = createWindowsMenuRealizer(); - const handle = realizer.realize([item({ label: 'File' })]); - expect(() => realizer.setApplicationMenu(handle)).not.toThrow(); - loadUser32().symbols.DestroyMenu(handle); - }); }); } diff --git a/tests/integration/windows/native-theme.test.ts b/tests/integration/windows/native-theme.test.ts index 5a6c3a6a..32886e37 100644 --- a/tests/integration/windows/native-theme.test.ts +++ b/tests/integration/windows/native-theme.test.ts @@ -19,9 +19,7 @@ if (currentPlatform() === 'windows') { describe('Windows nativeTheme (registry)', () => { test('reading AppsUseLightTheme yields 0, 1, or undefined', () => { const value = readRegistryDwordCurrentUser(PERSONALIZE, 'AppsUseLightTheme'); - if (value !== undefined) { - expect([0, 1]).toContain(value); - } + expect([0, 1, undefined]).toContain(value); }); test('a missing value reads cleanly as undefined (not a throw)', () => { diff --git a/tests/integration/windows/notification.test.ts b/tests/integration/windows/notification.test.ts index db6c768d..1b67b374 100644 --- a/tests/integration/windows/notification.test.ts +++ b/tests/integration/windows/notification.test.ts @@ -31,12 +31,6 @@ if (currentPlatform() === 'windows') { expect(() => handle.close()).not.toThrow(); }); - test('a silent notification presents without throwing', () => { - const handle = windowsNotificationBackend.present({ ...spec, silent: true }); - handle.close(); - expect(true).toBe(true); - }); - test('onClosed registers a callback without firing it eagerly', () => { const handle = windowsNotificationBackend.present(spec); let closed = 0; diff --git a/tests/integration/windows/shell.test.ts b/tests/integration/windows/shell.test.ts index c86d1de3..b9ce763f 100644 --- a/tests/integration/windows/shell.test.ts +++ b/tests/integration/windows/shell.test.ts @@ -24,11 +24,6 @@ if (currentPlatform() === 'windows') { expect(windowsShellBackend.openPath(NON_EXISTENT)).toBe(false); }); - test('exposes openExternal and showItemInFolder', () => { - expect(typeof windowsShellBackend.openExternal).toBe('function'); - expect(typeof windowsShellBackend.showItemInFolder).toBe('function'); - }); - test('the public shell.openPath surfaces the failure as an error string', async () => { const result = await shell.openPath(NON_EXISTENT); expect(result).toContain('Failed to open path'); From dd6877b53b7d29e5750a755403eb51d99af29d75 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:20:17 -0700 Subject: [PATCH 234/586] fix: stop leaking pinned-engine env into child processes --- src/main/engine/resolve.ts | 47 +++++--------------------- tests/unit/main/engine-resolve.test.ts | 44 +++++++----------------- 2 files changed, 22 insertions(+), 69 deletions(-) diff --git a/src/main/engine/resolve.ts b/src/main/engine/resolve.ts index 0b0967c8..9148f870 100644 --- a/src/main/engine/resolve.ts +++ b/src/main/engine/resolve.ts @@ -158,28 +158,6 @@ export const engineLibPath = (resolution: EngineResolution, soname: string): str ? join(resolution.libDir, soname) : soname; -/** - * Environment overrides for a pinned engine: `LD_LIBRARY_PATH` prepended so its - * bundled GTK/libsoup/ICU/GStreamer win over the distro's, `GIO_EXTRA_MODULES` for - * its gio modules, and `WEBKIT_EXEC_PATH` so WebKit spawns the engine's OWN helper - * processes (WebKitNetworkProcess/WebProcess/GPUProcess) rather than the system's. - */ -export const engineEnv = ( - resolution: EngineResolution, - env: StoreEnv, -): { LD_LIBRARY_PATH?: string; GIO_EXTRA_MODULES?: string; WEBKIT_EXEC_PATH?: string } => { - if (resolution.mode !== 'pinned' || resolution.libDir === undefined) { - return {}; - } - const prior = env['LD_LIBRARY_PATH']; - return { - LD_LIBRARY_PATH: - prior !== undefined && prior.length > 0 ? `${resolution.libDir}:${prior}` : resolution.libDir, - GIO_EXTRA_MODULES: join(resolution.libDir, 'gio', 'modules'), - WEBKIT_EXEC_PATH: join(resolution.libDir, '..', 'libexec'), - }; -}; - const prep: { done: boolean } = { done: false }; /** Injectable seams for {@link prepareEngineForLoad}'s auto-link side effect. */ @@ -191,15 +169,18 @@ export type PrepareDeps = { }; /** - * Apply a resolution before the first `dlopen`: print fallback warnings, export the - * pinned engine's env, and — for a STORE pin — register this app in the store's - * `.links` refcount so GC/prune know the engine is needed. Runs once per process: - * both Linux loaders call it, only the first takes effect, keeping them on a single - * shared engine. + * Apply a resolution before the first `dlopen`: print fallback warnings and, for a + * STORE pin, register this app in the store's `.links` refcount so prune keeps the + * engine. Runs once per process; later loaders' calls are no-ops. + * + * It exports no env: Bun's `process.env` writes never reach native `getenv` (so + * WebKit's helper spawns never see them) yet leak into every `child_process` child. + * ponytail: a pinned Linux engine's helper processes come from its build's compiled-in + * PKGLIBEXECDIR; relocating them needs a from-source build (DEVELOPER_MODE or a dladdr patch). */ export const prepareEngineForLoad = ( resolution: EngineResolution, - target: StoreEnv, + _env: StoreEnv, // ponytail: unused; drop with the gtk/webkitgtk/soup loader call sites write: (text: string) => void, deps: PrepareDeps = {}, ): void => { @@ -210,16 +191,6 @@ export const prepareEngineForLoad = ( for (const warning of resolution.warnings) { write(`${warning}\n`); } - const env = engineEnv(resolution, target); - if (env.LD_LIBRARY_PATH !== undefined) { - target['LD_LIBRARY_PATH'] = env.LD_LIBRARY_PATH; - } - if (env.GIO_EXTRA_MODULES !== undefined) { - target['GIO_EXTRA_MODULES'] = env.GIO_EXTRA_MODULES; - } - if (env.WEBKIT_EXEC_PATH !== undefined) { - target['WEBKIT_EXEC_PATH'] = env.WEBKIT_EXEC_PATH; - } // Auto-link only a STORE pin (it has an id + root); an explicit-dir pin and // system mode have nothing to refcount. if ( diff --git a/tests/unit/main/engine-resolve.test.ts b/tests/unit/main/engine-resolve.test.ts index 75f83740..c0c7471d 100644 --- a/tests/unit/main/engine-resolve.test.ts +++ b/tests/unit/main/engine-resolve.test.ts @@ -2,7 +2,6 @@ import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; import { bakedIdCandidates, type EngineResolution, - engineEnv, engineLibPath, prepareEngineForLoad, type ResolveDeps, @@ -138,44 +137,20 @@ describe('engineLibPath', () => { }); }); -describe('engineEnv', () => { - test('pinned -> sets LD_LIBRARY_PATH, GIO_EXTRA_MODULES, and WEBKIT_EXEC_PATH', () => { - const r = resolve({ env: {}, readBakedId: () => ID }); - const env = engineEnv(r, { LD_LIBRARY_PATH: '/usr/lib' }); - expect(slash(env.LD_LIBRARY_PATH ?? '')).toBe(`${ROOT}/${ID}/lib:/usr/lib`); - expect(slash(env.GIO_EXTRA_MODULES ?? '')).toBe(`${ROOT}/${ID}/lib/gio/modules`); - expect(slash(env.WEBKIT_EXEC_PATH ?? '')).toBe(`${ROOT}/${ID}/libexec`); - }); - - test('pinned with no prior LD_LIBRARY_PATH -> just the lib dir', () => { - const r = resolve({ env: {}, readBakedId: () => ID }); - const env = engineEnv(r, {}); - expect(slash(env.LD_LIBRARY_PATH ?? '')).toBe(`${ROOT}/${ID}/lib`); - }); - - test('system -> no env changes', () => { - const r = resolve({ env: {} }); - expect(engineEnv(r, { LD_LIBRARY_PATH: '/usr/lib' })).toEqual({}); - }); -}); - describe('prepareEngineForLoad', () => { // Reset BEFORE each test too: on Linux the real GTK/WebKitGTK loaders run in // the same process and set this one-shot guard, which would otherwise leak in. beforeEach(() => resetEnginePreparation()); afterEach(() => resetEnginePreparation()); - test('pinned: exports the engine env and prints warnings, exactly once', () => { + test('pinned: prints warnings exactly once', () => { const pinned: EngineResolution = { mode: 'pinned', libDir: '/store/x/lib', warnings: ['heads up'], }; - const target: Record = { LD_LIBRARY_PATH: '/usr/lib' }; const writes: string[] = []; - prepareEngineForLoad(pinned, target, (s) => writes.push(s)); - expect(slash(target['LD_LIBRARY_PATH'] ?? '')).toBe('/store/x/lib:/usr/lib'); - expect(slash(target['GIO_EXTRA_MODULES'] ?? '')).toBe('/store/x/lib/gio/modules'); + prepareEngineForLoad(pinned, {}, (s) => writes.push(s)); expect(writes).toEqual(['heads up\n']); // A second call (e.g. the other loader) is a no-op — single shared engine. @@ -183,12 +158,19 @@ describe('prepareEngineForLoad', () => { expect(writes).toEqual(['heads up\n']); }); - test('system: applies no env and prints nothing', () => { + test('pinned: leaves the env alone, so child_process children never inherit the engine libs', () => { const target: Record = { LD_LIBRARY_PATH: '/usr/lib' }; + prepareEngineForLoad( + { mode: 'pinned', libDir: '/store/x/lib', warnings: [] }, + target, + () => undefined, + ); + expect(target).toEqual({ LD_LIBRARY_PATH: '/usr/lib' }); + }); + + test('system: prints nothing', () => { const writes: string[] = []; - prepareEngineForLoad({ mode: 'system', warnings: [] }, target, (s) => writes.push(s)); - expect(target['LD_LIBRARY_PATH']).toBe('/usr/lib'); - expect(target['GIO_EXTRA_MODULES']).toBeUndefined(); + prepareEngineForLoad({ mode: 'system', warnings: [] }, {}, (s) => writes.push(s)); expect(writes).toEqual([]); }); From 50cdda97872fbcf7478e62ab19c980d1e590cb60 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:20:20 -0700 Subject: [PATCH 235/586] fix: retry a held Windows clipboard with a delay and degrade quietly --- .../platform/windows/windows-clipboard.ts | 56 ++++++++++++------- tests/integration/windows/clipboard.test.ts | 6 ++ .../windows/windows-clipboard.test.ts | 26 +++++++++ 3 files changed, 69 insertions(+), 19 deletions(-) diff --git a/src/main/platform/windows/windows-clipboard.ts b/src/main/platform/windows/windows-clipboard.ts index e6086c32..f724a0e0 100644 --- a/src/main/platform/windows/windows-clipboard.ts +++ b/src/main/platform/windows/windows-clipboard.ts @@ -1,5 +1,6 @@ import { type Pointer, ptr, read, toArrayBuffer } from 'bun:ffi'; import { FFIError } from '../../../common/errors'; +import { createLogger } from '../../../common/logger'; import type { ClipboardBackend } from '../../api/clipboard'; import { wstr } from './win32'; import { loadKernel32, loadUser32 } from './win32-ffi'; @@ -17,6 +18,8 @@ import { ensureGdiplus, windowsNativeImageBackend } from './windows-native-image * format, converted to/from PNG with the GDI+ codec the `nativeImage` backend uses. */ +const log = createLogger('windows-clipboard'); + /** `CF_UNICODETEXT` — UTF-16LE text, the modern text clipboard format. */ const CF_UNICODETEXT = 13; /** `CF_TEXT` — legacy ANSI text (read fallback only). */ @@ -80,17 +83,31 @@ export const extractCfHtmlFragment = (cfHtml: string): string => { return firstTag === -1 ? '' : cfHtml.slice(firstTag); }; -/** Run `fn` while the clipboard is open, always closing it afterward. */ -const withClipboard = (fn: () => T): T => { - const user32 = loadUser32().symbols; - // OpenClipboard can briefly fail while another process holds it; retry a bounded - // number of times rather than failing on a momentary clipboard-manager grab. - let opened = false; - for (let attempt = 0; attempt < 10 && !opened; attempt += 1) { - opened = user32.OpenClipboard(0n) !== 0; +/** Try `open` up to 10 times 5 ms apart: a clipboard manager or rdpclip holds it briefly. */ +export const openWithRetry = ( + open: () => boolean, + sleep: (ms: number) => void = Bun.sleepSync, +): boolean => { + for (let attempt = 0; attempt < 10; attempt += 1) { + if (attempt > 0) { + sleep(5); + } + if (open()) { + return true; + } } - if (!opened) { - throw new FFIError('clipboard: OpenClipboard failed (held by another process)'); + return false; +}; + +/** + * Run `fn` while the clipboard is open, always closing it afterward. A clipboard still + * held by another process yields `fallback` (like macOS and Linux, never a throw). + */ +const withClipboard = (fallback: T, fn: () => T): T => { + const user32 = loadUser32().symbols; + if (!openWithRetry(() => user32.OpenClipboard(0n) !== 0)) { + log.warn('clipboard is held by another process; skipping'); + return fallback; } try { return fn(); @@ -255,35 +272,35 @@ const bitmapToPackedDib = (handle: bigint, width: number, height: number): Uint8 export const windowsClipboardBackend: ClipboardBackend = { readText(): string { - return withClipboard(() => { + return withClipboard('', () => { const bytes = getClipboardBytes(CF_UNICODETEXT); return bytes === undefined ? '' : decodeUtf16(bytes); }); }, writeText(text: string): void { - withClipboard(() => { + withClipboard(undefined, () => { loadUser32().symbols.EmptyClipboard(); setClipboardBytes(CF_UNICODETEXT, wstr(text)); }); }, readHTML(): string { - return withClipboard(() => { + return withClipboard('', () => { const bytes = getClipboardBytes(cfHtmlFormat()); return bytes === undefined ? '' : extractCfHtmlFragment(decodeUtf8(bytes)); }); }, writeHTML(markup: string): void { - withClipboard(() => { + withClipboard(undefined, () => { loadUser32().symbols.EmptyClipboard(); setClipboardBytes(cfHtmlFormat(), new TextEncoder().encode(buildCfHtml(markup))); }); }, readImage(): Uint8Array { - const dib = withClipboard(() => getClipboardBytes(CF_DIB)); + const dib = withClipboard(undefined, () => getClipboardBytes(CF_DIB)); if (dib === undefined || dib.length < BITMAPINFOHEADER_SIZE) { return new Uint8Array(0); } @@ -312,11 +329,12 @@ export const windowsClipboardBackend: ClipboardBackend = { writeImage(bytes: Uint8Array): void { const decoded = windowsNativeImageBackend.decode(bytes); if (decoded.empty) { - throw new FFIError('clipboard: could not decode the image to write'); + log.warn('clipboard: writeImage got undecodable bytes; nothing written'); + return; } try { const dib = bitmapToPackedDib(decoded.handle, decoded.width, decoded.height); - withClipboard(() => { + withClipboard(undefined, () => { loadUser32().symbols.EmptyClipboard(); setClipboardBytes(CF_DIB, dib); }); @@ -326,7 +344,7 @@ export const windowsClipboardBackend: ClipboardBackend = { }, availableFormats(): string[] { - return withClipboard(() => { + return withClipboard([], () => { const user32 = loadUser32().symbols; const has = (format: number): boolean => user32.IsClipboardFormatAvailable(format) !== 0; const formats: string[] = []; @@ -344,7 +362,7 @@ export const windowsClipboardBackend: ClipboardBackend = { }, clear(): void { - withClipboard(() => { + withClipboard(undefined, () => { loadUser32().symbols.EmptyClipboard(); }); }, diff --git a/tests/integration/windows/clipboard.test.ts b/tests/integration/windows/clipboard.test.ts index 528f11ca..ac950a2e 100644 --- a/tests/integration/windows/clipboard.test.ts +++ b/tests/integration/windows/clipboard.test.ts @@ -66,5 +66,11 @@ if (currentPlatform() === 'windows') { windowsClipboardBackend.writeText('no image here'); expect(windowsClipboardBackend.readImage() as Uint8Array).toHaveLength(0); }); + + test('writeImage of undecodable bytes leaves the clipboard alone instead of throwing', () => { + windowsClipboardBackend.writeText('kept'); + expect(() => windowsClipboardBackend.writeImage(new Uint8Array([1, 2, 3]))).not.toThrow(); + expect(windowsClipboardBackend.readText()).toBe('kept'); + }); }); } diff --git a/tests/unit/main/platform/windows/windows-clipboard.test.ts b/tests/unit/main/platform/windows/windows-clipboard.test.ts index b0dd1d0e..7cdb1298 100644 --- a/tests/unit/main/platform/windows/windows-clipboard.test.ts +++ b/tests/unit/main/platform/windows/windows-clipboard.test.ts @@ -4,6 +4,7 @@ import { buildPackedDib, dibBitsOffset, extractCfHtmlFragment, + openWithRetry, } from '../../../../../src/main/platform/windows/windows-clipboard'; /** Construct a `BITMAPINFOHEADER` with the fields `dibBitsOffset` reads. */ @@ -159,3 +160,28 @@ describe('buildPackedDib', () => { expect([...dib.subarray(44, 48)]).toEqual([10, 11, 12, 13]); }); }); + +describe('openWithRetry', () => { + test('sleeps between attempts until the clipboard opens', () => { + const results = [false, false, true]; + const sleeps: number[] = []; + expect( + openWithRetry( + () => results.shift() ?? false, + (ms) => sleeps.push(ms), + ), + ).toBe(true); + expect(sleeps).toEqual([5, 5]); + }); + + test('gives up after a bounded wait when another process keeps it', () => { + const sleeps: number[] = []; + expect( + openWithRetry( + () => false, + (ms) => sleeps.push(ms), + ), + ).toBe(false); + expect(sleeps.reduce((total, ms) => total + ms, 0)).toBeLessThanOrEqual(50); + }); +}); From e961c587bb3b2a5749a6e36212254f076c6be59a Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:20:21 -0700 Subject: [PATCH 236/586] fix: honour & mnemonics and literal underscores in Linux menu labels --- src/main/platform/linux/gtk-menu.ts | 10 ++++--- .../unit/main/platform/linux/gtk-menu.test.ts | 27 +++++++++++++++++++ 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/src/main/platform/linux/gtk-menu.ts b/src/main/platform/linux/gtk-menu.ts index 84aea04e..2409f4bb 100644 --- a/src/main/platform/linux/gtk-menu.ts +++ b/src/main/platform/linux/gtk-menu.ts @@ -170,6 +170,10 @@ type WalkContext = { readonly dispatchRole?: ((spec: NativeMenuItemSpec) => void) | undefined; }; +/** Electron `&` mnemonics as GTK underlines (`&&` is a literal `&`); literal `_` doubled. */ +const gtkLabel = (label: string): string => + label.replace(/_/g, '__').replace(/&(&?)/g, (_match, escaped: string) => (escaped ? '&' : '_')); + /** A click handler's throw is re-thrown on a microtask; unwinding into the GLib dispatch loses it. */ const guarded = (thunk: () => void) => (): void => { try { @@ -192,7 +196,7 @@ const wireAction = ( ctx.retained.push(ctx.b.connectActivate(action, guarded(thunk))); ctx.b.gActionMapAddAction(ctx.group, action); ctx.actionNames.push(name); - ctx.b.gMenuAppend(model, label, detailedAction(name)); + ctx.b.gMenuAppend(model, gtkLabel(label), detailedAction(name)); }; const appendItems = ( @@ -211,7 +215,7 @@ const appendItems = ( if (spec.type === 'submenu' && spec.submenu !== undefined) { const child = ctx.b.gMenuNew(); appendItems(ctx, child, spec.submenu); - ctx.b.gMenuAppendSubmenu(model, spec.label, child); + ctx.b.gMenuAppendSubmenu(model, gtkLabel(spec.label), child); continue; } // A role item with a per-window dispatcher + a Linux action: wire its activate to the @@ -244,7 +248,7 @@ const appendItems = ( continue; } // A normal item with no onClick: a static, inert label (e.g. a heading). - ctx.b.gMenuAppend(model, spec.label, detailedAction(actionName())); + ctx.b.gMenuAppend(model, gtkLabel(spec.label), detailedAction(actionName())); } }; diff --git a/tests/unit/main/platform/linux/gtk-menu.test.ts b/tests/unit/main/platform/linux/gtk-menu.test.ts index a4f30c4d..e2c04615 100644 --- a/tests/unit/main/platform/linux/gtk-menu.test.ts +++ b/tests/unit/main/platform/linux/gtk-menu.test.ts @@ -230,6 +230,33 @@ describe('linuxMenuRealizer.realize (fake bindings)', () => { expect(() => queued[0]?.()).toThrow(boom); }); + it('maps Electron & mnemonics to GTK underlines and escapes literal underscores', () => { + const { bindings, calls } = makeFakeBindings(); + setBindingsForTesting(bindings); + linuxMenuRealizer.realize([ + { + label: '&File', + type: 'submenu', + enabled: true, + keyEquivalent: '', + submenu: [ + { + label: 'my_notes.txt', + type: 'normal', + enabled: true, + keyEquivalent: '', + onClick: () => undefined, + }, + { label: 'Save && Quit', type: 'normal', enabled: true, keyEquivalent: '' }, + ], + }, + ]); + const labels = calls + .filter((c) => c.fn === 'gMenuAppend' || c.fn === 'gMenuAppendSubmenu') + .map((c) => c.args[1]); + expect(labels).toEqual(['my__notes.txt', 'Save & Quit', '_File']); + }); + it('honours enabled:false via g_simple_action_set_enabled(0)', () => { const { bindings, calls } = makeFakeBindings(); setBindingsForTesting(bindings); From 46c9f1fafafe6408ad7ace54fceebee716a096ea Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:20:25 -0700 Subject: [PATCH 237/586] test: drop the g_object_new arity transcription test --- tests/unit/main/platform/linux/linux-ffi-abi.test.ts | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/tests/unit/main/platform/linux/linux-ffi-abi.test.ts b/tests/unit/main/platform/linux/linux-ffi-abi.test.ts index 8186b3ad..5afff155 100644 --- a/tests/unit/main/platform/linux/linux-ffi-abi.test.ts +++ b/tests/unit/main/platform/linux/linux-ffi-abi.test.ts @@ -19,7 +19,6 @@ import { loadGObjectFFI, } from '../../../../../src/main/platform/linux/gobject-ffi'; import { - GTK_DIALOG_GOBJECT_FFI_SYMBOLS, loadGtkDialogFFI, loadGtkDialogGObjectFFI, } from '../../../../../src/main/platform/linux/gtk-dialog-ffi'; @@ -119,11 +118,6 @@ describe('string getters return a guardable pointer, not cstring', () => { */ const PINNED_ARITY: ReadonlyArray = [ ['g_object_new (gobject-ffi, property form)', GOBJECT_FFI_SYMBOLS.g_object_new, 4], - [ - 'g_object_new (gtk-dialog-ffi, NULL-terminated form)', - GTK_DIALOG_GOBJECT_FFI_SYMBOLS.g_object_new, - 2, - ], [ 'webkit_web_view_evaluate_javascript (WK6.0)', WEBKITGTK_FFI_SYMBOLS.webkit_web_view_evaluate_javascript, @@ -141,12 +135,6 @@ describe('variadic / ABI-versioned functions are pinned to one arity', () => { test.each(PINNED_ARITY)('%s is pinned to one arity', (_name, sym, arity) => { expect(sym.args.length).toBe(arity); }); - - test('the two g_object_new declarations stay distinct arities', () => { - expect(GOBJECT_FFI_SYMBOLS.g_object_new.args.length).not.toBe( - GTK_DIALOG_GOBJECT_FFI_SYMBOLS.g_object_new.args.length, - ); - }); }); describe('width-sensitive scalars', () => { From 553d6ed7531a026afe71dbf94814f52c240741c2 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:20:31 -0700 Subject: [PATCH 238/586] refactor: delete the unused autoUpdater setDepsForTesting --- src/main/api/auto-updater.ts | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/main/api/auto-updater.ts b/src/main/api/auto-updater.ts index eba81cb2..e30ce287 100644 --- a/src/main/api/auto-updater.ts +++ b/src/main/api/auto-updater.ts @@ -156,7 +156,7 @@ const productionDeps = (): AutoUpdaterDeps => ({ }); export class AutoUpdaterImpl extends EventEmitter { - #deps: AutoUpdaterDeps; + readonly #deps: AutoUpdaterDeps; #feedURL: string | undefined; #publicKey: string | undefined; #channel: string | undefined; @@ -168,11 +168,6 @@ export class AutoUpdaterImpl extends EventEmitter { this.#deps = { ...productionDeps(), ...deps }; } - /** @internal */ - setDepsForTesting(deps: Partial): void { - this.#deps = { ...this.#deps, ...deps }; - } - /** * Base URL of the channel feed, where `update.json` + artifacts live. Must be * https (http only for localhost) so a plaintext MITM cannot serve a malicious From 631611415e9bdd7b90c1e1a9cf7f5cf4c201505a Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:20:36 -0700 Subject: [PATCH 239/586] docs: correct the WebKitGTK snapshot return type to GdkTexture --- src/main/platform/linux/webkitgtk-ffi.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/platform/linux/webkitgtk-ffi.ts b/src/main/platform/linux/webkitgtk-ffi.ts index 2b142ca4..39a1dd61 100644 --- a/src/main/platform/linux/webkitgtk-ffi.ts +++ b/src/main/platform/linux/webkitgtk-ffi.ts @@ -262,8 +262,8 @@ export const WEBKITGTK_FFI_SYMBOLS = { ], returns: FFIType.void, }, - // (view, GAsyncResult*, GError** /*null ok*/) -> cairo_surface_t* - // (transfer-FULL: cairo_surface_destroy when done; NULL on error). + // (view, GAsyncResult*, GError** /*null ok*/) -> GdkTexture* (transfer-full: g_object_unref; + // NULL on error). Never the 4.x cairo_surface_t*: cairo_surface_destroy on it aborts. webkit_web_view_get_snapshot_finish: { args: [FFIType.pointer, FFIType.pointer, FFIType.pointer], returns: FFIType.pointer, From 49aa324413fc7c0f70080c68ae0605c379ac34a1 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:20:37 -0700 Subject: [PATCH 240/586] fix: report the fractional monitor scale on GTK 4.14 and later --- src/main/platform/linux/gdk-screen.ts | 24 ++++++++++++++++++++-- tests/integration/linux/gdk-screen.test.ts | 1 + 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/main/platform/linux/gdk-screen.ts b/src/main/platform/linux/gdk-screen.ts index 896addd2..b05814d6 100644 --- a/src/main/platform/linux/gdk-screen.ts +++ b/src/main/platform/linux/gdk-screen.ts @@ -1,5 +1,6 @@ -import { type Pointer, ptr } from 'bun:ffi'; +import { FFIType, type Pointer, ptr } from 'bun:ffi'; import type { Point, RawDisplay, ScreenBackend } from '../../api/screen'; +import { dlopen } from '../dlopen'; import { loadGdkFFI } from './gdk-ffi'; import { loadGioFFI } from './gio-ffi'; import { loadGObjectFFI } from './gobject-ffi'; @@ -27,6 +28,25 @@ import { loadGObjectFFI } from './gobject-ffi'; * seat + device, which this read-only enumeration backend does not hold. */ +const loadFractionalScale = () => + dlopen('libgtk-4.so.1', { + gdk_monitor_get_scale: { args: [FFIType.pointer], returns: FFIType.f64 }, + }); + +let fractionalScale: ReturnType | null | undefined; + +/** `gdk_monitor_get_scale` (GTK 4.14+) reports fractional scaling; older GTK has only the integer ceiling. */ +const monitorScale = (monitor: Pointer, integerScale: number): number => { + if (fractionalScale === undefined) { + try { + fractionalScale = loadFractionalScale(); + } catch { + fractionalScale = null; + } + } + return fractionalScale?.symbols.gdk_monitor_get_scale(monitor) ?? integerScale; +}; + const readGeometry = ( symbols: ReturnType['symbols'], monitor: Pointer, @@ -59,7 +79,7 @@ export const getDisplays = (): readonly RawDisplay[] => { continue; } const geometry = readGeometry(gdk.symbols, monitor); - const scaleFactor = gdk.symbols.gdk_monitor_get_scale_factor(monitor); + const scaleFactor = monitorScale(monitor, gdk.symbols.gdk_monitor_get_scale_factor(monitor)); gobject.symbols.g_object_unref(monitor); const bounds = { x: geometry.x, y: geometry.y, width: geometry.width, height: geometry.height }; diff --git a/tests/integration/linux/gdk-screen.test.ts b/tests/integration/linux/gdk-screen.test.ts index b128d7cc..7c0edb39 100644 --- a/tests/integration/linux/gdk-screen.test.ts +++ b/tests/integration/linux/gdk-screen.test.ts @@ -36,6 +36,7 @@ if (currentPlatform() === 'linux') { expect(d.bounds.width).toBeGreaterThan(0); expect(d.bounds.height).toBeGreaterThan(0); expect(d.scaleFactor).toBeGreaterThanOrEqual(1); + expect(Number.isFinite(d.scaleFactor)).toBe(true); // workArea mirrors bounds on Linux v1 (no GdkMonitor work-area API). expect(d.workArea).toEqual(d.bounds); } From 64c29b8e80ce4802c394d18db7cf9b10e6c0e59d Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:20:48 -0700 Subject: [PATCH 241/586] fix: key dev-run engine links by the entry script, not bun --- src/main/engine/resolve.ts | 9 +++++++-- tests/unit/main/engine-resolve.test.ts | 16 ++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/main/engine/resolve.ts b/src/main/engine/resolve.ts index 9148f870..c4a648ab 100644 --- a/src/main/engine/resolve.ts +++ b/src/main/engine/resolve.ts @@ -158,11 +158,16 @@ export const engineLibPath = (resolution: EngineResolution, soname: string): str ? join(resolution.libDir, soname) : soname; +/** The path prune checks for this app: the entry script under the Bun CLI, else the executable. */ +export const appIdentity = (execPath: string, main: string): string => + // ponytail: same test as preload-bundle's bunCliPath; share it once that is exported + /(?:^|[\\/])bun(?:-[^\\/]*)?(?:\.exe)?$/i.test(execPath) ? main : execPath; + const prep: { done: boolean } = { done: false }; /** Injectable seams for {@link prepareEngineForLoad}'s auto-link side effect. */ export type PrepareDeps = { - /** This installed app's stable identity (default: `process.execPath`). */ + /** This app's stable identity (default: {@link appIdentity}). */ readonly appPath?: string; /** Register an app→engine refcount link (default: the store's `linkApp`). */ readonly link?: (root: string, appPath: string, engineId: string) => void; @@ -198,7 +203,7 @@ export const prepareEngineForLoad = ( resolution.id !== undefined && resolution.root !== undefined ) { - const appPath = deps.appPath ?? process.execPath; + const appPath = deps.appPath ?? appIdentity(process.execPath, Bun.main); const link = deps.link ?? linkApp; try { link(resolution.root, appPath, resolution.id); diff --git a/tests/unit/main/engine-resolve.test.ts b/tests/unit/main/engine-resolve.test.ts index c0c7471d..65617288 100644 --- a/tests/unit/main/engine-resolve.test.ts +++ b/tests/unit/main/engine-resolve.test.ts @@ -1,5 +1,6 @@ import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; import { + appIdentity, bakedIdCandidates, type EngineResolution, engineLibPath, @@ -122,6 +123,21 @@ describe('bakedIdCandidates', () => { }); }); +describe('appIdentity', () => { + test('under the Bun CLI, each project links by its own entry script', () => { + expect(appIdentity('/home/u/.bun/bin/bun', '/work/a/src/main.ts')).toBe('/work/a/src/main.ts'); + expect(appIdentity('C:\\Users\\u\\.bun\\bin\\bun.exe', 'C:\\b\\main.ts')).toBe( + 'C:\\b\\main.ts', + ); + }); + + test('a compiled app links by its executable', () => { + expect(appIdentity('/opt/MyApp/usr/bin/my-app', '/$bunfs/root/my-app')).toBe( + '/opt/MyApp/usr/bin/my-app', + ); + }); +}); + describe('engineLibPath', () => { test('pinned -> absolute path into the engine lib dir', () => { const r = resolve({ env: {}, readBakedId: () => ID }); From 174c70ee53f53ff138a396337e6f627ae758ca7b Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:20:55 -0700 Subject: [PATCH 242/586] refactor: import common/signature directly in keygen, engine-remote --- src/cli/engine-remote.ts | 2 +- src/cli/keygen.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cli/engine-remote.ts b/src/cli/engine-remote.ts index c2237568..e73b8b32 100644 --- a/src/cli/engine-remote.ts +++ b/src/cli/engine-remote.ts @@ -5,8 +5,8 @@ */ import { BunmaskaError } from '../common/errors'; +import { verifyArtifact } from '../common/signature'; import { installFromSource, type InstallResult } from './engine-store'; -import { verifyArtifact } from './engine-signature'; /** * The official feed. A self-hosted mirror overrides it via `bunmaska.config` diff --git a/src/cli/keygen.ts b/src/cli/keygen.ts index a5e94e22..2949c6b0 100644 --- a/src/cli/keygen.ts +++ b/src/cli/keygen.ts @@ -5,7 +5,7 @@ import { lstatSync, mkdirSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; -import { generateSigningKeyPair } from './engine-signature'; +import { generateSigningKeyPair } from '../common/signature'; /** Fixed file names so docs and build flags can reference them verbatim. */ export const PRIVATE_KEY_FILE = 'update-signing-key.pem'; From 15e5c1b99405952533ad995a497922bd30854f0c Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:21:05 -0700 Subject: [PATCH 243/586] refactor: drop the dead Linux tray set_property callback --- src/main/platform/linux/sni-tray.ts | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/src/main/platform/linux/sni-tray.ts b/src/main/platform/linux/sni-tray.ts index 7caf63d0..0ccc6363 100644 --- a/src/main/platform/linux/sni-tray.ts +++ b/src/main/platform/linux/sni-tray.ts @@ -4,7 +4,6 @@ import { cstr } from '../cstr'; import { DBUS_GET_PROPERTY_CB_DEF, DBUS_METHOD_CALL_CB_DEF, - DBUS_SET_PROPERTY_CB_DEF, loadGDBusFFI, VTABLE_SLOTS, } from './gdbus-ffi'; @@ -39,7 +38,7 @@ import { * instance, no bus touched, no object exported. * * LIFETIME (load-bearing, blind — verified by review, not CI): `register_object` COPIES the - * vtable, so the live wires are the THREE JSCallbacks (the copied vtable holds their raw + * vtable, so the live wires are the TWO JSCallbacks (the copied vtable holds their raw * fn-pointers) — they are retained FOREVER (never closed, mirroring the signal-subscription * discipline; closing would risk the in-flight-reply / own-invocation SIGSEGV class). * Property getters MUST be on the pumped main thread (the THREAD INVARIANT @@ -303,7 +302,7 @@ const createLive = (conn: Pointer, initialImage: string): TrayInstance | null => click: null, }; - // The three vtable handlers — each wrapped so a JS throw can't cross the FFI boundary and + // The two vtable handlers — each wrapped so a JS throw can't cross the FFI boundary and // kill the pump. Retained FOREVER (the copied vtable holds their raw fn-pointers). const getProp = new JSCallback((_c, _s, _p, _i, propName, error, _u): Pointer | null => { let value: Pointer | null = null; @@ -330,25 +329,29 @@ const createLive = (conn: Pointer, initialImage: string): TrayInstance | null => gdbus.symbols.g_dbus_method_invocation_return_value(invocation, null); }, DBUS_METHOD_CALL_CB_DEF); - const setProp = new JSCallback((): number => 0, DBUS_SET_PROPERTY_CB_DEF); // all read-only - + // Never registered, so native code holds neither: safe to close on the failure paths. + const closeCallbacks = (): null => { + methodCall.close(); + getProp.close(); + return null; + }; const mcPtr = methodCall.ptr; const gpPtr = getProp.ptr; - const spPtr = setProp.ptr; - if (mcPtr === null || gpPtr === null || spPtr === null) { - return null; + if (mcPtr === null || gpPtr === null) { + return closeCallbacks(); } - const vtable = new BigUint64Array(VTABLE_SLOTS); // [method_call, get_property, set_property, 0×8] + // [method_call, get_property, set_property = NULL, padding x8]: every property is read-only, + // so GDBus rejects a Set before it would dispatch one. + const vtable = new BigUint64Array(VTABLE_SLOTS); vtable[0] = BigInt(mcPtr); vtable[1] = BigInt(gpPtr); - vtable[2] = BigInt(spPtr); const regId = registerObject(conn, objectPath, iface, ptr(vtable)); if (regId === 0) { - return null; + return closeCallbacks(); } - retained.callbacks.push(methodCall, getProp, setProp); // load-bearing: the vtable copy points here. + retained.callbacks.push(methodCall, getProp); // load-bearing: the vtable copy points here. retained.misc.push(node, vtable); let destroyed = false; From a6335176b24bff0de71749c2e372894c925e03b8 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:21:08 -0700 Subject: [PATCH 244/586] fix: reject a clipboard DIB whose header claims more pixels than it holds --- .../platform/windows/windows-clipboard.ts | 30 ++++++++++++++- .../windows/windows-clipboard.test.ts | 37 +++++++++++++++++++ 2 files changed, 66 insertions(+), 1 deletion(-) diff --git a/src/main/platform/windows/windows-clipboard.ts b/src/main/platform/windows/windows-clipboard.ts index f724a0e0..e6a2d4cc 100644 --- a/src/main/platform/windows/windows-clipboard.ts +++ b/src/main/platform/windows/windows-clipboard.ts @@ -180,6 +180,8 @@ const decodeUtf8 = (bytes: Uint8Array): string => /** Size of a `BITMAPINFOHEADER` (the smallest DIB header). */ const BITMAPINFOHEADER_SIZE = 40; +/** `biCompression` = `BI_RGB`: uncompressed pixels. */ +const BI_RGB = 0; /** `biCompression` = `BI_BITFIELDS` — 3 trailing color-mask DWORDs after a v3 header. */ const BI_BITFIELDS = 3; /** `biCompression` = `BI_ALPHABITFIELDS` — 4 trailing color-mask DWORDs. */ @@ -211,6 +213,32 @@ export const dibBitsOffset = (header: Uint8Array): number => { return biSize + masks + paletteEntries * 4; }; +/** + * Whether a `CF_DIB` (written by any process) holds every pixel its header claims, so + * GDI+ never reads past the copied buffer. Uncompressed rows are DWORD-aligned; + * compressed pixels must fit `biSizeImage`. Pure. + */ +export const dibIsComplete = (dib: Uint8Array): boolean => { + if (dib.length < BITMAPINFOHEADER_SIZE) { + return false; + } + const view = new DataView(dib.buffer, dib.byteOffset, dib.byteLength); + const biSize = view.getUint32(0, true); + const width = view.getInt32(4, true); + const height = view.getInt32(8, true); + const biCompression = view.getUint32(16, true); + if (biSize < BITMAPINFOHEADER_SIZE || biSize > dib.length || width <= 0 || height === 0) { + return false; + } + const uncompressed = + biCompression === BI_RGB || + biCompression === BI_BITFIELDS || + biCompression === BI_ALPHABITFIELDS; + const stride = Math.floor((width * view.getUint16(14, true) + 31) / 32) * 4; + const pixelBytes = uncompressed ? stride * Math.abs(height) : view.getUint32(20, true); + return pixelBytes > 0 && dibBitsOffset(dib) + pixelBytes <= dib.length; +}; + /** * Build a packed 32bpp `BI_RGB` DIB (the `CF_DIB` clipboard format) from * top-down BGRA scanlines. DIBs are stored bottom-up, so rows are flipped; the @@ -301,7 +329,7 @@ export const windowsClipboardBackend: ClipboardBackend = { readImage(): Uint8Array { const dib = withClipboard(undefined, () => getClipboardBytes(CF_DIB)); - if (dib === undefined || dib.length < BITMAPINFOHEADER_SIZE) { + if (dib === undefined || !dibIsComplete(dib)) { return new Uint8Array(0); } ensureGdiplus(); diff --git a/tests/unit/main/platform/windows/windows-clipboard.test.ts b/tests/unit/main/platform/windows/windows-clipboard.test.ts index 7cdb1298..6e677a1a 100644 --- a/tests/unit/main/platform/windows/windows-clipboard.test.ts +++ b/tests/unit/main/platform/windows/windows-clipboard.test.ts @@ -3,6 +3,7 @@ import { buildCfHtml, buildPackedDib, dibBitsOffset, + dibIsComplete, extractCfHtmlFragment, openWithRetry, } from '../../../../../src/main/platform/windows/windows-clipboard'; @@ -131,6 +132,42 @@ describe('dibBitsOffset', () => { }); }); +describe('dibIsComplete', () => { + /** A 40-byte header claiming `width`x`height` at `bitCount`, followed by `pixelBytes`. */ + const dib = (width: number, height: number, bitCount: number, pixelBytes: number) => { + const bytes = new Uint8Array(40 + pixelBytes); + const view = new DataView(bytes.buffer); + view.setUint32(0, 40, true); + view.setInt32(4, width, true); + view.setInt32(8, height, true); + view.setUint16(14, bitCount, true); + return bytes; + }; + + test('a DIB carrying every row its header claims is complete', () => { + expect(dibIsComplete(buildPackedDib(2, 2, new Uint8Array(16), 8))).toBe(true); + expect(dibIsComplete(dib(3, -2, 24, 2 * 12))).toBe(true); // top-down, DWORD-padded rows + }); + + test('a header claiming more pixels than were copied is rejected', () => { + expect(dibIsComplete(dib(8000, 8000, 32, 1024))).toBe(false); + expect(dibIsComplete(dib(3, 2, 24, 2 * 12 - 1))).toBe(false); + }); + + test('a palette count or header size past the buffer is rejected', () => { + const hugePalette = dib(1, 1, 8, 4); + new DataView(hugePalette.buffer).setUint32(32, 0xffffffff, true); + expect(dibIsComplete(hugePalette)).toBe(false); + const hugeHeader = dib(1, 1, 32, 4); + new DataView(hugeHeader.buffer).setUint32(0, 4096, true); + expect(dibIsComplete(hugeHeader)).toBe(false); + }); + + test('a buffer shorter than the header is rejected', () => { + expect(dibIsComplete(new Uint8Array(12))).toBe(false); + }); +}); + describe('buildPackedDib', () => { test('writes a 40-byte 32bpp BI_RGB bottom-up header', () => { const dib = buildPackedDib(2, 2, new Uint8Array(2 * 2 * 4), 8); From bc57f3be00ffca3f126e0d66d68a11b1f777d0a0 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:21:14 -0700 Subject: [PATCH 245/586] fix: hold pressed buttons across synthesized Windows mouse moves --- src/main/platform/windows/windows-input.ts | 49 ++++++++++++------- .../platform/windows/windows-webkit-view.ts | 6 ++- .../platform/windows/windows-input.test.ts | 28 ++++++++++- 3 files changed, 61 insertions(+), 22 deletions(-) diff --git a/src/main/platform/windows/windows-input.ts b/src/main/platform/windows/windows-input.ts index a3682c3f..82fd367c 100644 --- a/src/main/platform/windows/windows-input.ts +++ b/src/main/platform/windows/windows-input.ts @@ -51,7 +51,7 @@ const buttonDown = (button: MouseButton): { readonly message: number; readonly m } }; -/** The *BUTTONUP message for a mouse button (WPARAM is 0 — no button still held). */ +/** The *BUTTONUP message for a mouse button. */ const buttonUp = (button: MouseButton): number => { switch (button) { case 'right': @@ -122,23 +122,37 @@ const virtualKey = (keyCode: string): number | undefined => { return undefined; }; +/** The MK_* button bits still down after `event`: mouseDown adds its button, mouseUp clears it. */ +export const heldButtonsAfter = (event: NativeInputEvent, held: number): number => { + if (event.type !== 'mouseDown' && event.type !== 'mouseUp') { + return held; + } + const { mk } = buttonDown(event.button ?? 'left'); + return event.type === 'mouseDown' ? held | mk : held & ~mk; +}; + /** * Map a synthesized {@link NativeInputEvent} to the single Win32 window message * that delivers it, or `undefined` for a key we do not map (a lenient no-op, - * matching Electron). Pure. + * matching Electron). `held` is the MK_* set down before the event. Pure. */ -export const inputEventToMessage = (event: NativeInputEvent): WindowMessage | undefined => { +export const inputEventToMessage = ( + event: NativeInputEvent, + held = 0, +): WindowMessage | undefined => { switch (event.type) { case 'mouseMove': - return { message: WM_MOUSEMOVE, wParam: 0n, lParam: mouseLParam(event.x, event.y) }; - case 'mouseDown': { - const { message, mk } = buttonDown(event.button ?? 'left'); - return { message, wParam: BigInt(mk), lParam: mouseLParam(event.x, event.y) }; - } + return { message: WM_MOUSEMOVE, wParam: BigInt(held), lParam: mouseLParam(event.x, event.y) }; + case 'mouseDown': + return { + message: buttonDown(event.button ?? 'left').message, + wParam: BigInt(heldButtonsAfter(event, held)), + lParam: mouseLParam(event.x, event.y), + }; case 'mouseUp': return { message: buttonUp(event.button ?? 'left'), - wParam: 0n, + wParam: BigInt(heldButtonsAfter(event, held)), lParam: mouseLParam(event.x, event.y), }; case 'char': { @@ -178,20 +192,17 @@ export const inputEventToMessage = (event: NativeInputEvent): WindowMessage | un } }; -/** Keyboard messages must bypass the pump's queue (see below). */ const KEYBOARD_MESSAGES = new Set([WM_KEYDOWN, WM_KEYUP, WM_CHAR]); /** - * Post a synthesized {@link NativeInputEvent} to a WKView's `hwnd` so WinCairo - * WebKit delivers it as a trusted DOM event. Unmapped keys are silently ignored. - * - * Mouse messages are POSTed (async, no focus steal). Keyboard messages are SENT - * directly to the view's native WndProc: a POSTed WM_KEYDOWN would pass through - * the pump's `TranslateMessage`, which synthesizes a SECOND, real-keyboard-state - * WM_CHAR — doubling and corrupting the typed text. SendMessageW skips the queue. + * Deliver a synthesized event to a WKView's `hwnd` as a trusted DOM event; `held` is the + * MK_* set down before it. Keyboard messages must be SENT, never POSTed: the pump's + * `TranslateMessage` would synthesize a second WM_CHAR from the real keyboard state, + * doubling the typed text. Modifier state comes from the physical keyboard, and a + * synthesized hover ends at once while the real cursor is outside the view (TME_LEAVE). */ -export const postWindowsInputEvent = (hwnd: bigint, event: NativeInputEvent): void => { - const msg = inputEventToMessage(event); +export const postWindowsInputEvent = (hwnd: bigint, event: NativeInputEvent, held = 0): void => { + const msg = inputEventToMessage(event, held); if (msg === undefined) { return; } diff --git a/src/main/platform/windows/windows-webkit-view.ts b/src/main/platform/windows/windows-webkit-view.ts index 7d1a2af3..9ced69ad 100644 --- a/src/main/platform/windows/windows-webkit-view.ts +++ b/src/main/platform/windows/windows-webkit-view.ts @@ -4,7 +4,7 @@ import type { NativeInputEvent, NativeNavigationEvent } from '../native'; import { wkRelease, wkString, wkStringToJs, wkUrl, wkUrlToJs } from './webkit-string'; import { loadWebKit2, WK_INJECT_AT_DOCUMENT_START } from './webkit2-ffi'; import { loadKernel32, loadUser32 } from './win32-ffi'; -import { postWindowsInputEvent } from './windows-input'; +import { heldButtonsAfter, postWindowsInputEvent } from './windows-input'; import { createNativeChildHost, ensureOleInitialized } from './windows-native-window'; /** @@ -217,6 +217,7 @@ export class WindowsWebView { readonly #retainedController: Pointer; readonly #callbacks: JSCallback[]; #disposed = false; + #heldButtons = 0; private constructor( view: Pointer, @@ -416,8 +417,9 @@ export class WindowsWebView { sendInputEvent(event: NativeInputEvent): void { const hwnd = loadWebKit2().symbols.WKViewGetWindow(this.#view); if (hwnd !== 0n) { - postWindowsInputEvent(hwnd, event); + postWindowsInputEvent(hwnd, event, this.#heldButtons); } + this.#heldButtons = heldButtonsAfter(event, this.#heldButtons); } /** diff --git a/tests/unit/main/platform/windows/windows-input.test.ts b/tests/unit/main/platform/windows/windows-input.test.ts index e01d3c1a..dd5ec1d2 100644 --- a/tests/unit/main/platform/windows/windows-input.test.ts +++ b/tests/unit/main/platform/windows/windows-input.test.ts @@ -1,5 +1,8 @@ import { describe, expect, test } from 'bun:test'; -import { inputEventToMessage } from '../../../../../src/main/platform/windows/windows-input'; +import { + heldButtonsAfter, + inputEventToMessage, +} from '../../../../../src/main/platform/windows/windows-input'; // Win32 message constants mirrored here for readable assertions. const WM_MOUSEMOVE = 0x0200; @@ -43,6 +46,16 @@ describe('inputEventToMessage', () => { expect(msg?.wParam).toBe(0n); }); + test('a mouse message carries every button still held (so a move after mouseDown drags)', () => { + const left = 0x0001; + const right = 0x0002; + expect(inputEventToMessage({ type: 'mouseMove', x: 1, y: 1 }, left)?.wParam).toBe(1n); + expect( + inputEventToMessage({ type: 'mouseDown', x: 1, y: 1, button: 'right' }, left)?.wParam, + ).toBe(3n); + expect(inputEventToMessage({ type: 'mouseUp', x: 1, y: 1 }, left | right)?.wParam).toBe(2n); + }); + test('a named key maps to its virtual-key code and scan code (Escape)', () => { expect(inputEventToMessage({ type: 'keyDown', keyCode: 'Escape' })).toEqual({ message: WM_KEYDOWN, @@ -99,3 +112,16 @@ describe('inputEventToMessage', () => { expect(inputEventToMessage({ type: 'keyDown', keyCode: 'F13' })).toBeUndefined(); }); }); + +describe('heldButtonsAfter', () => { + test('mouseDown adds its button, mouseUp clears it, anything else keeps the set', () => { + const afterLeft = heldButtonsAfter({ type: 'mouseDown', x: 0, y: 0 }, 0); + const afterRight = heldButtonsAfter( + { type: 'mouseDown', x: 0, y: 0, button: 'right' }, + afterLeft, + ); + expect([afterLeft, afterRight]).toEqual([0x0001, 0x0003]); + expect(heldButtonsAfter({ type: 'mouseMove', x: 0, y: 0 }, afterRight)).toBe(0x0003); + expect(heldButtonsAfter({ type: 'mouseUp', x: 0, y: 0 }, afterRight)).toBe(0x0002); + }); +}); From fddaf0d8279d0d237ab6c347c3b1d4d33a374746 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:21:28 -0700 Subject: [PATCH 246/586] refactor: drop unused Linux menu and dialog helpers --- src/main/platform/linux/gtk-dialog.ts | 6 ++---- src/main/platform/linux/gtk-menu.ts | 8 -------- tests/integration/linux/gtk-menu.test.ts | 3 +-- tests/unit/main/platform/linux/gtk-dialog.test.ts | 11 ++++------- tests/unit/main/platform/linux/gtk-menu.test.ts | 2 +- 5 files changed, 8 insertions(+), 22 deletions(-) diff --git a/src/main/platform/linux/gtk-dialog.ts b/src/main/platform/linux/gtk-dialog.ts index f9e371bd..ab55390c 100644 --- a/src/main/platform/linux/gtk-dialog.ts +++ b/src/main/platform/linux/gtk-dialog.ts @@ -52,7 +52,7 @@ export const buildButtonsArray = (labels: ReadonlyArray): ButtonsArray = * A valid (`>= 0`) index is returned as-is; the dismissal sentinel (`-1`) and * any error index fall back to `cancelId` (Electron semantics). */ -export const mapChooseResult = (index: number, _defaultId: number, cancelId: number): number => +export const mapChooseResult = (index: number, cancelId: number): number => index >= 0 ? index : cancelId; /** Electron's default cancelId: the first "cancel" or "no" button (case-insensitive), else 0. */ @@ -64,7 +64,6 @@ export const cancelIdForButtons = (buttons: ReadonlyArray): number => { /** Settle inputs for `gtk_alert_dialog_choose`, with the finish step injectable. */ export type SettleChooseArgs = { readonly result: Pointer; - readonly defaultId: number; readonly cancelId: number; /** Calls `gtk_alert_dialog_choose_finish`; may throw on the GError path. */ readonly finish: (result: Pointer) => number; @@ -81,7 +80,7 @@ export const settleChoose = (args: SettleChooseArgs): number => { } catch { index = -1; } - return mapChooseResult(index, args.defaultId, args.cancelId); + return mapChooseResult(index, args.cancelId); }; /** Settle inputs for `gtk_file_dialog_open/save`, with finish + reader injectable. */ @@ -147,7 +146,6 @@ const showMessageBox = (spec: { (result) => settleChoose({ result, - defaultId: 0, cancelId, finish: (r) => gtk.symbols.gtk_alert_dialog_choose_finish(dialog, r, null), }), diff --git a/src/main/platform/linux/gtk-menu.ts b/src/main/platform/linux/gtk-menu.ts index 2409f4bb..98f195b4 100644 --- a/src/main/platform/linux/gtk-menu.ts +++ b/src/main/platform/linux/gtk-menu.ts @@ -72,8 +72,6 @@ export type MenuEntry = { readonly actionNames: string[]; /** Retained activate thunks — kept alive for the menu's lifetime. */ readonly retained: unknown[]; - /** Count of retained thunks (one per clickable item). */ - readonly retainedCount: number; /** The spec tree this entry was realized from (so a window can re-realize it with role wiring). */ readonly specs: ReadonlyArray; }; @@ -267,7 +265,6 @@ const realizeCore = ( group, actionNames: ctx.actionNames, retained: ctx.retained, - retainedCount: ctx.retained.length, specs: items, }; menuEntries.set(model, entry); @@ -314,11 +311,6 @@ export const getMenuEntry = (handle: bigint): MenuEntry | undefined => menuEntri */ export const getCurrentAppMenu = (): CurrentAppMenu | undefined => currentAppMenu; -/** Replace the current application menu state directly. @internal */ -export const setCurrentAppMenu = (menu: CurrentAppMenu | undefined): void => { - currentAppMenu = menu; -}; - /** Clear the stored application menu. Test-only. */ export const resetCurrentAppMenuForTesting = (): void => { currentAppMenu = undefined; diff --git a/tests/integration/linux/gtk-menu.test.ts b/tests/integration/linux/gtk-menu.test.ts index d9ceac2b..7ef37ab6 100644 --- a/tests/integration/linux/gtk-menu.test.ts +++ b/tests/integration/linux/gtk-menu.test.ts @@ -7,7 +7,6 @@ import { linuxMenuRealizer, resetCurrentAppMenuForTesting, setBindingsForTesting, - setCurrentAppMenu, } from '../../../src/main/platform/linux/gtk-menu'; import { loadGMenuFFI, loadGtkMenuFFI } from '../../../src/main/platform/linux/gtk-menu-ffi'; import { loadGtkFFI } from '../../../src/main/platform/linux/gtk-ffi'; @@ -185,7 +184,7 @@ describe.skipIf(!isLinux)('GTK menu backend (Linux)', () => { if (loadGtkFFI().symbols.gtk_init_check() === 0) { return; } - setCurrentAppMenu(undefined); + resetCurrentAppMenuForTesting(); const app = createLinuxApplication(); app.start(); let window: NativeWindow | undefined; diff --git a/tests/unit/main/platform/linux/gtk-dialog.test.ts b/tests/unit/main/platform/linux/gtk-dialog.test.ts index e7b78070..0c10305b 100644 --- a/tests/unit/main/platform/linux/gtk-dialog.test.ts +++ b/tests/unit/main/platform/linux/gtk-dialog.test.ts @@ -58,16 +58,16 @@ describe('buildButtonsArray', () => { describe('mapChooseResult', () => { it('returns the clicked button index when finish yields a valid index', () => { - expect(mapChooseResult(0, 0, 1)).toBe(0); - expect(mapChooseResult(2, 0, 1)).toBe(2); + expect(mapChooseResult(0, 1)).toBe(0); + expect(mapChooseResult(2, 1)).toBe(2); }); it('maps the dismissal sentinel (-1) to the cancelId', () => { - expect(mapChooseResult(-1, 0, 3)).toBe(3); + expect(mapChooseResult(-1, 3)).toBe(3); }); it('falls back to the cancelId on any negative (error) index', () => { - expect(mapChooseResult(-5, 1, 7)).toBe(7); + expect(mapChooseResult(-5, 7)).toBe(7); }); }); @@ -95,7 +95,6 @@ describe('settleChoose (injected finish-fn, no real dialog)', () => { const fakeResult = 123 as unknown as Pointer; const value = settleChoose({ result: fakeResult, - defaultId: 0, cancelId: 1, finish: (r) => { expect(r).toBe(fakeResult); @@ -108,7 +107,6 @@ describe('settleChoose (injected finish-fn, no real dialog)', () => { it('maps a -1 dismissal from the injected finish-fn to the cancelId', () => { const value = settleChoose({ result: 0 as unknown as Pointer, - defaultId: 0, cancelId: 5, finish: () => -1, }); @@ -118,7 +116,6 @@ describe('settleChoose (injected finish-fn, no real dialog)', () => { it('maps a thrown finish (GError path) to the cancelId', () => { const value = settleChoose({ result: 0 as unknown as Pointer, - defaultId: 0, cancelId: 9, finish: () => { throw new Error('GTK_DIALOG_ERROR_DISMISSED'); diff --git a/tests/unit/main/platform/linux/gtk-menu.test.ts b/tests/unit/main/platform/linux/gtk-menu.test.ts index e2c04615..861e1177 100644 --- a/tests/unit/main/platform/linux/gtk-menu.test.ts +++ b/tests/unit/main/platform/linux/gtk-menu.test.ts @@ -336,7 +336,7 @@ describe('linuxMenuRealizer.realize (fake bindings)', () => { { label: 'A', type: 'normal', enabled: true, keyEquivalent: '', onClick: () => undefined }, { label: 'B', type: 'normal', enabled: true, keyEquivalent: '', onClick: () => undefined }, ]); - expect(getMenuEntry(handle)?.retainedCount).toBe(2); + expect(getMenuEntry(handle)?.retained).toHaveLength(2); }); }); From 8424eb23ad886d7ad45bab5f30c6cddf325668dd Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:21:35 -0700 Subject: [PATCH 247/586] test: make Linux display gates visible skips and assert the theme flip --- tests/integration/linux/capture-page.test.ts | 7 +-- tests/integration/linux/cookies.test.ts | 7 +-- tests/integration/linux/gdk-screen.test.ts | 52 ++++++++++---------- tests/integration/linux/native-theme.test.ts | 45 ++++++++++++----- tests/integration/linux/shell.test.ts | 35 ++----------- 5 files changed, 68 insertions(+), 78 deletions(-) diff --git a/tests/integration/linux/capture-page.test.ts b/tests/integration/linux/capture-page.test.ts index e23b4466..f320c617 100644 --- a/tests/integration/linux/capture-page.test.ts +++ b/tests/integration/linux/capture-page.test.ts @@ -8,7 +8,7 @@ import { createLinuxApplication } from '../../../src/main/platform/linux/linux-b * `xvfb-run -a`; inert elsewhere via `describe.skipIf`. */ -const isLinux = process.platform === 'linux'; +const hasDisplay = process.platform === 'linux' && loadGtkFFI().symbols.gtk_init_check() !== 0; const pump = (ms: number): Promise => new Promise((resolve) => setTimeout(resolve, ms)); @@ -19,11 +19,8 @@ const pumpUntil = async (predicate: () => boolean, budgetMs: number): Promise { +describe.skipIf(!hasDisplay)('capturePage over a real WebKitGTK webview', () => { test('resolves non-empty bytes starting with the PNG signature', async () => { - if (loadGtkFFI().symbols.gtk_init_check() === 0) { - return; - } const app = createLinuxApplication(); app.start(); const window = app.createWindow({ width: 400, height: 300, title: 'capture', show: true }); diff --git a/tests/integration/linux/cookies.test.ts b/tests/integration/linux/cookies.test.ts index 02b5fe40..cc410dd1 100644 --- a/tests/integration/linux/cookies.test.ts +++ b/tests/integration/linux/cookies.test.ts @@ -10,7 +10,7 @@ import { createLinuxApplication } from '../../../src/main/platform/linux/linux-b * ubuntu under `xvfb-run -a`; inert elsewhere via `describe.skipIf`. */ -const isLinux = process.platform === 'linux'; +const hasDisplay = process.platform === 'linux' && loadGtkFFI().symbols.gtk_init_check() !== 0; const pump = (ms: number): Promise => new Promise((resolve) => setTimeout(resolve, ms)); @@ -29,11 +29,8 @@ const settleWithPump = async (promise: Promise, budgetMs: number): Promise return promise; }; -describe.skipIf(!isLinux)('session.cookies over the real WebKitGTK network session', () => { +describe.skipIf(!hasDisplay)('session.cookies over the real WebKitGTK network session', () => { test('set -> get roundtrip -> remove -> gone', async () => { - if (loadGtkFFI().symbols.gtk_init_check() === 0) { - return; - } const app = createLinuxApplication(); app.start(); const window = app.createWindow({ width: 320, height: 240, title: 'cookies', show: true }); diff --git a/tests/integration/linux/gdk-screen.test.ts b/tests/integration/linux/gdk-screen.test.ts index 7c0edb39..d8646323 100644 --- a/tests/integration/linux/gdk-screen.test.ts +++ b/tests/integration/linux/gdk-screen.test.ts @@ -5,31 +5,31 @@ import { getDisplays } from '../../../src/main/platform/linux/gdk-screen'; import { loadGioFFI } from '../../../src/main/platform/linux/gio-ffi'; import { loadGtkFFI } from '../../../src/main/platform/linux/gtk-ffi'; -if (currentPlatform() === 'linux') { - describe('GDK/GIO screen FFI on Linux', () => { - test('gdk-ffi resolves the new GdkMonitor symbols', () => { - const gdk = loadGdkFFI(); - for (const name of [ - 'gdk_display_get_monitors', - 'gdk_monitor_get_geometry', - 'gdk_monitor_get_scale_factor', - ] as const) { - expect(typeof gdk.symbols[name]).toBe('function'); - } - }); +const isLinux = currentPlatform() === 'linux'; +const hasDisplay = isLinux && loadGtkFFI().symbols.gtk_init_check() !== 0; - test('gio-ffi resolves the new GListModel symbols', () => { - const gio = loadGioFFI(); - for (const name of ['g_list_model_get_n_items', 'g_list_model_get_item'] as const) { - expect(typeof gio.symbols[name]).toBe('function'); - } - }); +describe.skipIf(!isLinux)('GDK/GIO screen FFI on Linux', () => { + test('gdk-ffi resolves the new GdkMonitor symbols', () => { + const gdk = loadGdkFFI(); + for (const name of [ + 'gdk_display_get_monitors', + 'gdk_monitor_get_geometry', + 'gdk_monitor_get_scale_factor', + ] as const) { + expect(typeof gdk.symbols[name]).toBe('function'); + } + }); - test('getDisplays returns at least one monitor with positive geometry under a display', () => { - const gtk = loadGtkFFI(); - if (gtk.symbols.gtk_init_check() === 0) { - return; // No display (no Xvfb); the symbol-resolution tests above stand. - } + test('gio-ffi resolves the new GListModel symbols', () => { + const gio = loadGioFFI(); + for (const name of ['g_list_model_get_n_items', 'g_list_model_get_item'] as const) { + expect(typeof gio.symbols[name]).toBe('function'); + } + }); + + test.skipIf(!hasDisplay)( + 'getDisplays returns at least one monitor with positive geometry', + () => { const displays = getDisplays(); expect(displays.length).toBeGreaterThanOrEqual(1); for (const d of displays) { @@ -42,6 +42,6 @@ if (currentPlatform() === 'linux') { } // Exactly one display is flagged primary (index 0). expect(displays.filter((d) => d.primary).length).toBe(1); - }); - }); -} + }, + ); +}); diff --git a/tests/integration/linux/native-theme.test.ts b/tests/integration/linux/native-theme.test.ts index 07d74bed..31065c9b 100644 --- a/tests/integration/linux/native-theme.test.ts +++ b/tests/integration/linux/native-theme.test.ts @@ -1,23 +1,44 @@ import { describe, expect, test } from 'bun:test'; +import { dlopen, FFIType } from 'bun:ffi'; import { currentPlatform } from '../../../src/common/platform'; +import { cstr } from '../../../src/main/platform/cstr'; import { loadGtkFFI } from '../../../src/main/platform/linux/gtk-ffi'; import { observeAppearanceChange, shouldUseDarkColors, } from '../../../src/main/platform/linux/gtk-native-theme'; -// Exercises the real `gtk_settings_get_default` + `g_object_get` read and the -// `notify::gtk-application-prefer-dark-theme` observer registration on Linux. -if (currentPlatform() === 'linux') { - describe('gtk-native-theme', () => { - test('shouldUseDarkColors reads a boolean from GtkSettings', () => { - loadGtkFFI().symbols.gtk_init_check(); - expect(typeof shouldUseDarkColors()).toBe('boolean'); - }); +const hasDisplay = currentPlatform() === 'linux' && loadGtkFFI().symbols.gtk_init_check() !== 0; + +/** g_object_set pinned to one gboolean property (the backend only reads it). */ +const setPreferDark = (value: 0 | 1): void => { + const settings = loadGtkFFI().symbols.gtk_settings_get_default(); + if (settings === null) { + throw new Error('gtk_settings_get_default returned null'); + } + dlopen('libgobject-2.0.so.0', { + g_object_set: { + args: [FFIType.pointer, FFIType.cstring, FFIType.i32, FFIType.pointer], + returns: FFIType.void, + }, + }).symbols.g_object_set(settings, cstr('gtk-application-prefer-dark-theme'), value, null); +}; - test('observeAppearanceChange connects to GtkSettings without throwing', () => { - loadGtkFFI().symbols.gtk_init_check(); - expect(() => observeAppearanceChange(() => undefined)).not.toThrow(); +describe.skipIf(!hasDisplay)('gtk-native-theme', () => { + test('shouldUseDarkColors follows prefer-dark and the observer fires on the flip', () => { + setPreferDark(0); + let notified = 0; + observeAppearanceChange(() => { + notified += 1; }); + try { + setPreferDark(1); + expect(shouldUseDarkColors()).toBe(true); + expect(notified).toBeGreaterThan(0); + setPreferDark(0); + expect(shouldUseDarkColors()).toBe(false); + } finally { + setPreferDark(0); + } }); -} +}); diff --git a/tests/integration/linux/shell.test.ts b/tests/integration/linux/shell.test.ts index b7da7b4d..24b00dcf 100644 --- a/tests/integration/linux/shell.test.ts +++ b/tests/integration/linux/shell.test.ts @@ -1,38 +1,13 @@ import { describe, expect, test } from 'bun:test'; +import { currentPlatform } from '../../../src/common/platform'; import { loadGtkFFI } from '../../../src/main/platform/linux/gtk-ffi'; -import { - beep, - openExternal, - openPath, - showItemInFolder, -} from '../../../src/main/platform/linux/gtk-shell'; +import { beep } from '../../../src/main/platform/linux/gtk-shell'; -/** - * Linux `shell` backend smoke test against a real GTK4/GDK display. - * - * Goal: the GIO/GDK symbols resolve and `beep()` runs on a live display - * without crashing. We deliberately do NOT call `openExternal`/`openPath`/ - * `showItemInFolder`, which would actually launch a browser or file manager and - * could hang or fail in CI. Runs only in CI ubuntu under `xvfb-run -a`; inert on - * macOS via `describe.skipIf`. - */ - -const isLinux = process.platform === 'linux'; - -describe.skipIf(!isLinux)('Linux shell backend', () => { - test('exposes the ShellBackend-shaped methods', () => { - expect(typeof openExternal).toBe('function'); - expect(typeof openPath).toBe('function'); - expect(typeof showItemInFolder).toBe('function'); - expect(typeof beep).toBe('function'); - }); +// openExternal/openPath/showItemInFolder would launch a real browser or file manager, so CI skips them. +const hasDisplay = currentPlatform() === 'linux' && loadGtkFFI().symbols.gtk_init_check() !== 0; +describe.skipIf(!hasDisplay)('Linux shell backend', () => { test('beep() runs on a real GDK display without throwing', () => { - // gtk_init_check initialises GDK so gdk_display_get_default() returns a - // display; under Xvfb the bell is a no-op. Skip if there is no display. - if (loadGtkFFI().symbols.gtk_init_check() === 0) { - return; - } expect(() => beep()).not.toThrow(); }); }); From 8c9d92479f23cc2fb82dcbd9c819bc09967851c0 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:21:35 -0700 Subject: [PATCH 248/586] fix: skip index entries this client cannot parse --- src/cli/engine-index.ts | 17 +++++++++++++---- tests/unit/cli/engine-index.test.ts | 26 +++++++++++++++++++------- 2 files changed, 32 insertions(+), 11 deletions(-) diff --git a/src/cli/engine-index.ts b/src/cli/engine-index.ts index 63ca68d8..115ae9e4 100644 --- a/src/cli/engine-index.ts +++ b/src/cli/engine-index.ts @@ -31,7 +31,8 @@ const err = (message: string): never => { throw new BunmaskaError(message, { code: 'ERR_ENGINE_INDEX' }); }; -export const parseEngineIndex = (text: string): EngineIndexEntry[] => { +/** The index's stored entries, structurally checked; ids are kept verbatim. */ +const readStoredEntries = (text: string): StoredEntry[] => { let raw: unknown; try { raw = JSON.parse(text); @@ -50,9 +51,7 @@ export const parseEngineIndex = (text: string): EngineIndexEntry[] => { if (typeof record['id'] !== 'string') { return err('engine index: every entry needs a string "id"'); } - const ref = parseEngineId(record['id']); // throws on a malformed id return { - ...ref, id: record['id'], ...(typeof record['size'] === 'number' ? { size: record['size'] } : {}), ...(typeof record['hash'] === 'string' ? { hash: record['hash'] } : {}), @@ -61,6 +60,16 @@ export const parseEngineIndex = (text: string): EngineIndexEntry[] => { }); }; +/** The entries this client understands; an id it cannot parse (newer family, os, arch) is skipped. */ +export const parseEngineIndex = (text: string): EngineIndexEntry[] => + readStoredEntries(text).flatMap((entry) => { + try { + return [{ ...parseEngineId(entry.id), ...entry }]; + } catch { + return []; + } + }); + /** Serialize entries to the pretty, newline-terminated `index.json` a feed serves. */ export const buildEngineIndex = (entries: readonly StoredEntry[]): string => { const engines = entries.map((e) => ({ @@ -86,7 +95,7 @@ export const mergeEngineIndex = ( indexText: string | undefined, manifest: RemoteManifest, ): string => { - const existing = indexText === undefined ? [] : parseEngineIndex(indexText); + const existing = indexText === undefined ? [] : readStoredEntries(indexText); parseEngineId(manifest.id); // reject a malformed id before it enters the index const entries = [ ...existing.filter((e) => e.id !== manifest.id), diff --git a/tests/unit/cli/engine-index.test.ts b/tests/unit/cli/engine-index.test.ts index 2733add2..eeff321f 100644 --- a/tests/unit/cli/engine-index.test.ts +++ b/tests/unit/cli/engine-index.test.ts @@ -10,6 +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'; describe('engineFeedIndexUrl', () => { test('maps a feed base to /index.json (official by default, trailing slash ok)', () => { @@ -47,10 +48,17 @@ describe('parseEngineIndex', () => { expect(() => parseEngineIndex('not json')).toThrow(BunmaskaError); }); - test('rejects an entry whose id is not a valid engine-id', () => { - expect(() => - parseEngineIndex(JSON.stringify({ version: 1, engines: [{ id: 'nope' }] })), - ).toThrow(BunmaskaError); + 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' }] }), + ); + expect(entries.map((e) => e.id)).toEqual([ID]); + }); + + test('rejects an entry without a string id', () => { + expect(() => parseEngineIndex(JSON.stringify({ version: 1, engines: [{ id: 7 }] }))).toThrow( + BunmaskaError, + ); }); test('rejects a non-object / missing engines array', () => { @@ -97,19 +105,23 @@ describe('mergeEngineIndex', () => { expect(parsed[0]).toMatchObject({ id: ID, hash: 'abc', size: 10 }); }); - test('replaces the same-id entry and keeps the others, sorted by id', () => { + test('adds the entry and keeps the others, sorted by id', () => { const existing = buildEngineIndex([ - { id: ID, size: 1, hash: 'old', soname: 'WebKit2.dll' }, { id: LINUX_ID, size: 2, hash: 'keep', soname: 'libwebkitgtk-6.0.so.4' }, ]); const json = mergeEngineIndex(existing, { id: ID, hash: 'new', size: 99 }); const parsed = parseEngineIndex(json); - expect(parsed).toHaveLength(2); expect(parsed.map((e) => e.id)).toEqual([ID, LINUX_ID].sort()); expect(parsed.find((e) => e.id === ID)).toMatchObject({ hash: 'new', size: 99 }); expect(parsed.find((e) => e.id === LINUX_ID)).toMatchObject({ hash: 'keep' }); }); + test('keeps entries this client cannot parse', () => { + const existing = buildEngineIndex([{ id: CEF_ID, hash: 'blink' }]); + const json = mergeEngineIndex(existing, { id: ID, hash: 'new' }); + expect(JSON.parse(json).engines.map((e: { id: string }) => e.id)).toEqual([CEF_ID, ID].sort()); + }); + test('rejects a malformed engine id before it enters the index', () => { expect(() => mergeEngineIndex(undefined, { id: '../evil', hash: 'x' })).toThrow(); }); From 1826c7fcd3391d78ede1374fdbdbadd357d498e4 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:21:38 -0700 Subject: [PATCH 249/586] fix: keep Windows strings with a lone surrogate instead of emptying them --- src/main/platform/windows/webkit-string.ts | 4 +++- src/main/platform/windows/webkit2-ffi.ts | 6 +++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/main/platform/windows/webkit-string.ts b/src/main/platform/windows/webkit-string.ts index 5cc2c77c..9aa45c61 100644 --- a/src/main/platform/windows/webkit-string.ts +++ b/src/main/platform/windows/webkit-string.ts @@ -26,7 +26,9 @@ export const wkStringToJs = (ref: Pointer): string => { } const buffer = new Uint8Array(size); // Returns the byte count written INCLUDING the trailing NUL. - const written = Number(wk.symbols.WKStringGetUTF8CString(ref, ptr(buffer), BigInt(size))); + const written = Number( + wk.symbols.WKStringGetUTF8CStringNonStrict(ref, ptr(buffer), BigInt(size)), + ); const length = written > 0 ? written - 1 : 0; return new TextDecoder().decode(buffer.subarray(0, length)); }; diff --git a/src/main/platform/windows/webkit2-ffi.ts b/src/main/platform/windows/webkit2-ffi.ts index 6fb9bbef..9b13f3da 100644 --- a/src/main/platform/windows/webkit2-ffi.ts +++ b/src/main/platform/windows/webkit2-ffi.ts @@ -96,7 +96,11 @@ const WEBKIT2_SYMBOLS = { WKStringGetTypeID: { args: [], returns: FFIType.u32 }, WKStringCreateWithUTF8CString: { args: [FFIType.cstring], returns: FFIType.ptr }, WKStringGetMaximumUTF8CStringSize: { args: [FFIType.ptr], returns: FFIType.u64 }, - WKStringGetUTF8CString: { args: [FFIType.ptr, FFIType.ptr, FFIType.u64], returns: FFIType.u64 }, + // NonStrict replaces a lone surrogate; the strict variant returns 0 and drops the whole string. + WKStringGetUTF8CStringNonStrict: { + args: [FFIType.ptr, FFIType.ptr, FFIType.u64], + returns: FFIType.u64, + }, WKURLCreateWithUTF8CString: { args: [FFIType.cstring], returns: FFIType.ptr }, WKURLCopyString: { args: [FFIType.ptr], returns: FFIType.ptr }, From a94bf90b150da6e43edb5adc06b19bd20c279e59 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:21:51 -0700 Subject: [PATCH 250/586] test: drop X11 keymap transcription tests that cannot fail --- .../main/platform/linux/x11-keymap.test.ts | 43 ++----------------- 1 file changed, 4 insertions(+), 39 deletions(-) diff --git a/tests/unit/main/platform/linux/x11-keymap.test.ts b/tests/unit/main/platform/linux/x11-keymap.test.ts index 72e97939..aff02e1c 100644 --- a/tests/unit/main/platform/linux/x11-keymap.test.ts +++ b/tests/unit/main/platform/linux/x11-keymap.test.ts @@ -9,12 +9,6 @@ import { x11ModifierMask, x11StateMatches, } from '../../../../../src/main/platform/linux/x11-keymap'; -import { X11_FFI_SYMBOLS } from '../../../../../src/main/platform/linux/x11-ffi'; - -/** - * Pure X11 keysym-name + modifier-mask mapping, plus an FFI SHAPE check for the - * Xlib symbol table. No dlopen here (we are on macOS) — shape only. - */ describe('x11KeysymName', () => { test('lowercases single ASCII letters', () => { @@ -44,20 +38,16 @@ describe('x11KeysymName', () => { expect(x11KeysymName('Backspace')).toBe('BackSpace'); }); - test('returns undefined for an unmappable key', () => { + test('maps the Plus key name to its keysym', () => { expect(x11KeysymName('Plus')).toBe('plus'); + }); + + test('returns undefined for an unmappable key', () => { expect(x11KeysymName('Bogus')).toBeUndefined(); }); }); describe('x11ModifierMask', () => { - test('exposes the X.h mask constants', () => { - expect(SHIFT_MASK).toBe(1); - expect(CONTROL_MASK).toBe(4); - expect(MOD1_MASK).toBe(8); - expect(MOD4_MASK).toBe(64); - }); - test('CmdOrCtrl on Linux yields ControlMask', () => { const parsed = parseAccelerator('CmdOrCtrl+K', 'linux'); if (parsed === undefined) { @@ -83,37 +73,12 @@ describe('x11ModifierMask', () => { }); }); -describe('X11_FFI_SYMBOLS shape', () => { - test('declares the grab/poll symbols the backend needs', () => { - for (const name of [ - 'XOpenDisplay', - 'XCloseDisplay', - 'XDefaultRootWindow', - 'XKeysymToKeycode', - 'XStringToKeysym', - 'XGrabKey', - 'XUngrabKey', - 'XSelectInput', - 'XPending', - 'XNextEvent', - 'XFlush', - ]) { - expect(X11_FFI_SYMBOLS).toHaveProperty(name); - } - }); - - test('XGrabKey has the 7-argument Xlib signature', () => { - expect(X11_FFI_SYMBOLS.XGrabKey.args).toHaveLength(7); - }); -}); - describe('x11StateMatches', () => { test('matches the exact registered modifiers', () => { expect(x11StateMatches(CONTROL_MASK | SHIFT_MASK, CONTROL_MASK | SHIFT_MASK)).toBe(true); }); test('rejects a subset or superset of the registered modifiers', () => { - // The old dispatch matched on keycode alone, so Ctrl+K fired Ctrl+Shift+K too. expect(x11StateMatches(CONTROL_MASK, CONTROL_MASK | SHIFT_MASK)).toBe(false); expect(x11StateMatches(CONTROL_MASK | SHIFT_MASK, CONTROL_MASK)).toBe(false); }); From 64d322bd7b3e99700055af2864bc9de07fa699ad Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:21:53 -0700 Subject: [PATCH 251/586] fix: keep the clipboard DIB reachable while GDI+ reads its pixels --- .../platform/windows/windows-clipboard.ts | 20 ++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/src/main/platform/windows/windows-clipboard.ts b/src/main/platform/windows/windows-clipboard.ts index e6a2d4cc..f172229a 100644 --- a/src/main/platform/windows/windows-clipboard.ts +++ b/src/main/platform/windows/windows-clipboard.ts @@ -298,6 +298,13 @@ const bitmapToPackedDib = (handle: bigint, width: number, height: number): Uint8 return buildPackedDib(width, height, pixels, stride); }; +/** + * DIBs a live GDI+ bitmap reads in place (GdipCreateBitmapFromGdiDib does not copy the + * pixels). A local's last use is the create call, so an optimised frame could let GC free + * it mid-encode; membership here keeps it reachable until GdipDisposeImage. + */ +const pinnedDibs = new Set(); + export const windowsClipboardBackend: ClipboardBackend = { readText(): string { return withClipboard('', () => { @@ -336,21 +343,20 @@ export const windowsClipboardBackend: ClipboardBackend = { const gdip = loadGdiplus().symbols; const out = new Uint8Array(8); const outPtr = ptr(out); - // GdiplusCreateBitmapFromGdiDib may reference (not copy) the pixels, so `dib` - // must stay live until encodePng — it does, being referenced through the call. + pinnedDibs.add(dib); const status = gdip.GdipCreateBitmapFromGdiDib( ptr(dib), ptr(dib.subarray(dibBitsOffset(dib))), outPtr, ); - if (status !== GDIP_OK) { - return new Uint8Array(0); - } - const handle = read.u64(outPtr, 0); + const handle = status === GDIP_OK ? read.u64(outPtr, 0) : 0n; try { return windowsNativeImageBackend.encodePng(handle); } finally { - gdip.GdipDisposeImage(handle); + if (handle !== 0n) { + gdip.GdipDisposeImage(handle); + } + pinnedDibs.delete(dib); } }, From 6d62f7a0d95c9329fe2bc9ba57ae2d3af3120a88 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:22:02 -0700 Subject: [PATCH 252/586] refactor: merge the Linux clipboard stream settle helpers --- src/main/platform/linux/gtk-clipboard.ts | 57 ++++++------------- .../main/platform/linux/gtk-clipboard.test.ts | 21 +++---- 2 files changed, 26 insertions(+), 52 deletions(-) diff --git a/src/main/platform/linux/gtk-clipboard.ts b/src/main/platform/linux/gtk-clipboard.ts index 4852c345..9dc51926 100644 --- a/src/main/platform/linux/gtk-clipboard.ts +++ b/src/main/platform/linux/gtk-clipboard.ts @@ -1,6 +1,7 @@ import { CString, JSCallback, type Pointer, ptr, toArrayBuffer } from 'bun:ffi'; import type { ClipboardBackend } from '../../api/clipboard'; import { cstr } from '../cstr'; +import { GASYNC_READY_CB_DEF } from './gasync'; import { loadGdkFFI } from './gdk-ffi'; import { loadGioFFI } from './gio-ffi'; import { loadGlibFFI } from './glib-ffi'; @@ -47,9 +48,6 @@ import { loadGObjectFFI } from './gobject-ffi'; * there is never more than one in flight per stream — no `G_IO_ERROR_PENDING`). */ -/** ABI shape for `GAsyncReadyCallback`: `(source, result, user_data) -> void`. */ -export const CLIPBOARD_READ_CB_DEF = { args: ['ptr', 'ptr', 'ptr'], returns: 'void' } as const; - /** The MIME type GDK uses for UTF-8 plain text on the clipboard. */ const TEXT_MIME = 'text/plain;charset=utf-8'; /** The MIME type for HTML markup on the clipboard. */ @@ -158,46 +156,25 @@ export const drainStreamAsync = async (reader: AsyncStreamReader): Promise = { readonly result: Pointer; /** Calls `gdk_clipboard_read_finish`; returns a `GInputStream*` or null; may throw. */ readonly finish: (result: Pointer) => Pointer | null; - /** Drains a non-null `GInputStream*` to a string. */ - readonly drain: (stream: Pointer) => Promise; -}; - -/** - * Produce the clipboard payload from a `GAsyncResult`. A null stream (no matching - * format) or a thrown `finish` (GError path) yields `''`. - */ -export const settleReadStreamAsync = async (args: SettleReadStreamArgs): Promise => { - let stream: Pointer | null; - try { - stream = args.finish(args.result); - } catch { - return ''; - } - return stream === null ? '' : args.drain(stream); -}; - -/** Settle inputs for a binary `gdk_clipboard_read_finish`, draining to raw bytes. */ -export type SettleReadStreamBytesArgs = { - readonly result: Pointer; - readonly finish: (result: Pointer) => Pointer | null; - readonly drain: (stream: Pointer) => Promise; + /** Drains a non-null `GInputStream*`. */ + readonly drain: (stream: Pointer) => Promise; + /** The payload when there is no stream. */ + readonly empty: T; }; -/** Like {@link settleReadStreamAsync} but yields raw bytes (empty on no-match/error). */ -export const settleReadStreamBytesAsync = async ( - args: SettleReadStreamBytesArgs, -): Promise => { +/** The clipboard payload from a `GAsyncResult`; `empty` for a null stream or a throwing finish. */ +export const settleReadStream = async (args: SettleReadStreamArgs): Promise => { let stream: Pointer | null; try { stream = args.finish(args.result); } catch { - return new Uint8Array(0); + return args.empty; } - return stream === null ? new Uint8Array(0) : args.drain(stream); + return stream === null ? args.empty : args.drain(stream); }; /** @@ -250,7 +227,7 @@ const realAsyncStreamReader = (stream: Pointer): AsyncStreamReader => { inFlight.delete(cb); cb.close(); }, 0); - }, CLIPBOARD_READ_CB_DEF); + }, GASYNC_READY_CB_DEF); inFlight.add(cb); const cbPtr = cb.ptr; if (cbPtr === null) { @@ -286,7 +263,7 @@ const readText = (): Promise => inFlight.delete(callback); callback.close(); }, 0); - }, CLIPBOARD_READ_CB_DEF); + }, GASYNC_READY_CB_DEF); inFlight.add(callback); const cbPtr = callback.ptr; if (cbPtr === null) { @@ -337,17 +314,18 @@ const readHTML = (): Promise => const callback = new JSCallback((_source: Pointer, result: Pointer, _userData: Pointer) => { // The drain is async (yields to the pump between chunks); resolve when it // settles. This kickoff callback's own work is done synchronously here. - void settleReadStreamAsync({ + void settleReadStream({ result, finish: (r) => gdk.symbols.gdk_clipboard_read_finish(clipboard, r, null, null), drain: (stream) => drainStreamAsync(realAsyncStreamReader(stream)), + empty: '', }).then(resolve, reject); setTimeout(() => { inFlight.delete(callback); retainedReadBuffers.delete(callback); callback.close(); }, 0); - }, CLIPBOARD_READ_CB_DEF); + }, GASYNC_READY_CB_DEF); inFlight.add(callback); retainedReadBuffers.set(callback, { mime, mimeArray }); const cbPtr = callback.ptr; @@ -367,17 +345,18 @@ const readImage = (): Promise => const mime = new TextEncoder().encode(`${IMAGE_PNG_MIME}\0`); const mimeArray = new BigUint64Array([BigInt(ptr(mime)), 0n]); const callback = new JSCallback((_source: Pointer, result: Pointer, _userData: Pointer) => { - void settleReadStreamBytesAsync({ + void settleReadStream({ result, finish: (r) => gdk.symbols.gdk_clipboard_read_finish(clipboard, r, null, null), drain: (stream) => drainStreamBytesAsync(realAsyncStreamReader(stream)), + empty: new Uint8Array(0), }).then(resolve, reject); setTimeout(() => { inFlight.delete(callback); retainedReadBuffers.delete(callback); callback.close(); }, 0); - }, CLIPBOARD_READ_CB_DEF); + }, GASYNC_READY_CB_DEF); inFlight.add(callback); retainedReadBuffers.set(callback, { mime, mimeArray }); const cbPtr = callback.ptr; diff --git a/tests/unit/main/platform/linux/gtk-clipboard.test.ts b/tests/unit/main/platform/linux/gtk-clipboard.test.ts index b0b58565..a9c9f916 100644 --- a/tests/unit/main/platform/linux/gtk-clipboard.test.ts +++ b/tests/unit/main/platform/linux/gtk-clipboard.test.ts @@ -3,21 +3,13 @@ import { describe, expect, it, test } from 'bun:test'; import { currentPlatform } from '../../../../../src/common/platform'; import { type AsyncStreamReader, - CLIPBOARD_READ_CB_DEF, drainStreamAsync, formatsFromGdk, linuxClipboardBackend, - settleReadStreamAsync, + settleReadStream, settleReadText, } from '../../../../../src/main/platform/linux/gtk-clipboard'; -describe('CLIPBOARD_READ_CB_DEF (GAsyncReadyCallback ABI, shape-only)', () => { - it('is (source, result, user_data) -> void', () => { - expect(CLIPBOARD_READ_CB_DEF.args).toEqual(['ptr', 'ptr', 'ptr']); - expect(CLIPBOARD_READ_CB_DEF.returns).toBe('void'); - }); -}); - describe('linuxClipboardBackend shape', () => { it('exposes readText, writeText, readHTML, writeHTML and clear', () => { expect(typeof linuxClipboardBackend.readText).toBe('function'); @@ -111,9 +103,10 @@ describe('drainStreamAsync (injected AsyncStreamReader, no real GInputStream)', }); }); -describe('settleReadStreamAsync (injected finish + async drain, no real clipboard)', () => { +describe('settleReadStream (injected finish + async drain, no real clipboard)', () => { it('drains the stream when finish yields a non-null GInputStream*', async () => { - const value = await settleReadStreamAsync({ + const value = await settleReadStream({ + empty: '', result: 1 as unknown as Pointer, finish: () => 42 as unknown as Pointer, drain: (stream) => { @@ -125,7 +118,8 @@ describe('settleReadStreamAsync (injected finish + async drain, no real clipboar }); it('returns empty string when finish yields null (no matching format)', async () => { - const value = await settleReadStreamAsync({ + const value = await settleReadStream({ + empty: '', result: 0 as unknown as Pointer, finish: () => null, drain: () => { @@ -136,7 +130,8 @@ describe('settleReadStreamAsync (injected finish + async drain, no real clipboar }); it('returns empty string when finish throws (GError path)', async () => { - const value = await settleReadStreamAsync({ + const value = await settleReadStream({ + empty: '', result: 0 as unknown as Pointer, finish: () => { throw new Error('read failed'); From e6c80438d6f6d22f7a9b651897eb620d09c67648 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:22:08 -0700 Subject: [PATCH 253/586] fix: NUL-terminate the CF_HTML clipboard block --- src/main/platform/windows/windows-clipboard.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/platform/windows/windows-clipboard.ts b/src/main/platform/windows/windows-clipboard.ts index f172229a..f25d520f 100644 --- a/src/main/platform/windows/windows-clipboard.ts +++ b/src/main/platform/windows/windows-clipboard.ts @@ -330,7 +330,8 @@ export const windowsClipboardBackend: ClipboardBackend = { writeHTML(markup: string): void { withClipboard(undefined, () => { loadUser32().symbols.EmptyClipboard(); - setClipboardBytes(cfHtmlFormat(), new TextEncoder().encode(buildCfHtml(markup))); + // NUL-terminated for readers that treat the block as a C string; EndHTML precedes it. + setClipboardBytes(cfHtmlFormat(), new TextEncoder().encode(`${buildCfHtml(markup)}\0`)); }); }, From fb896f8a5783751a436cf315340e7c1d21007991 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:22:11 -0700 Subject: [PATCH 254/586] test: cover the bundled-engine fallback in the Windows resolver --- src/main/platform/windows/webkit2-ffi.ts | 6 ++++-- .../platform/windows/webkit2-resolve.test.ts | 16 +++++++++++++--- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/src/main/platform/windows/webkit2-ffi.ts b/src/main/platform/windows/webkit2-ffi.ts index 9b13f3da..b06921d1 100644 --- a/src/main/platform/windows/webkit2-ffi.ts +++ b/src/main/platform/windows/webkit2-ffi.ts @@ -154,12 +154,14 @@ export const bundledEngineDir = ( * `lib/`, or the verbatim `BUNMASKA_WEBKIT_PATH`), then a {@link bundledEngineDir} * shipped next to the executable. `deps` is a test seam. */ -export const resolveWindowsEngineDir = (deps: ResolveDeps = {}): string | undefined => { +export const resolveWindowsEngineDir = ( + deps: ResolveDeps & { readonly execPath?: string } = {}, +): string | undefined => { const resolution = resolveEngineWith(deps); if (resolution.mode === 'pinned') { return resolution.libDir; } - return bundledEngineDir(process.execPath, existsSync); + return bundledEngineDir(deps.execPath ?? process.execPath, deps.exists ?? existsSync); }; /** diff --git a/tests/unit/main/platform/windows/webkit2-resolve.test.ts b/tests/unit/main/platform/windows/webkit2-resolve.test.ts index c0e851b8..35d3d7b5 100644 --- a/tests/unit/main/platform/windows/webkit2-resolve.test.ts +++ b/tests/unit/main/platform/windows/webkit2-resolve.test.ts @@ -17,12 +17,14 @@ import { */ const ID = 'webkit-2-2.52.4-bunmaska1-windows-x64'; const ROOT = 'C:\\store\\webkit'; +const APP_DIR = 'C:\\Program Files\\My App'; -/** Inject deterministic seams (no ambient env / fs) into the resolver. */ -const dir = (deps: ResolveDeps): string | undefined => +/** Inject deterministic seams (no ambient env / fs); only a bundled WebKit2.dll is absent. */ +const dir = (deps: ResolveDeps & { readonly execPath?: string }): string | undefined => resolveWindowsEngineDir({ enginesRoot: ROOT, - exists: () => true, + execPath: join(APP_DIR, 'My App.exe'), + exists: (path) => !path.endsWith('WebKit2.dll'), readBakedId: () => null, ...deps, }); @@ -60,6 +62,14 @@ describe('resolveWindowsEngineDir', () => { test('a malformed pin -> undefined', () => { expect(dir({ env: { BUNMASKA_WEBKIT_ID: 'not-an-engine-id' } })).toBeUndefined(); }); + + test('no pin -> the engine bundled next to the executable', () => { + expect(dir({ env: {}, exists: () => true })).toBe(join(APP_DIR, 'webkit')); + }); + + test('a pin wins over a bundled engine', () => { + expect(dir({ env: {}, readBakedId: () => ID, exists: () => true })).toBe(join(ROOT, ID, 'lib')); + }); }); describe('bundledEngineDir', () => { From 257a87414506b6f716ae968ea6178a70a7b0fd8b Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:22:18 -0700 Subject: [PATCH 255/586] fix: refuse to republish an engine id already in the feed index --- src/cli/engine-index.ts | 12 ++++--- tests/unit/cli/engine-index.test.ts | 5 +++ tools/engine/publish-engine-r2.ts | 54 ++++++++++++++--------------- 3 files changed, 40 insertions(+), 31 deletions(-) diff --git a/src/cli/engine-index.ts b/src/cli/engine-index.ts index 115ae9e4..0287a2f9 100644 --- a/src/cli/engine-index.ts +++ b/src/cli/engine-index.ts @@ -88,17 +88,21 @@ export const fetchEngineIndex = async ( parseEngineIndex(new TextDecoder().decode(await fetch(engineFeedIndexUrl(feedBase)))); /** - * Same-id entry replaced, everything else kept, output sorted by id. - * `indexText` undefined means "no index published yet" and starts one. + * Add one engine, keep every other entry, sort by id. `indexText` undefined means + * no index is published yet. Throws on a malformed id or an id already published: + * clients cache and pin by id, so an id's bytes never change (bump the rev instead). */ export const mergeEngineIndex = ( indexText: string | undefined, manifest: RemoteManifest, ): string => { const existing = indexText === undefined ? [] : readStoredEntries(indexText); - parseEngineId(manifest.id); // reject a malformed id before it enters the index + parseEngineId(manifest.id); + if (existing.some((e) => e.id === manifest.id)) { + return err(`engine index: ${manifest.id} is already published; bump the rev to republish`); + } const entries = [ - ...existing.filter((e) => e.id !== manifest.id), + ...existing, { id: manifest.id, ...(manifest.size !== undefined ? { size: manifest.size } : {}), diff --git a/tests/unit/cli/engine-index.test.ts b/tests/unit/cli/engine-index.test.ts index eeff321f..a78e71d3 100644 --- a/tests/unit/cli/engine-index.test.ts +++ b/tests/unit/cli/engine-index.test.ts @@ -122,6 +122,11 @@ describe('mergeEngineIndex', () => { expect(JSON.parse(json).engines.map((e: { id: string }) => e.id)).toEqual([CEF_ID, ID].sort()); }); + test('refuses to republish an id already in the index (ids are immutable)', () => { + const existing = buildEngineIndex([{ id: ID, hash: 'old' }]); + expect(() => mergeEngineIndex(existing, { id: ID, hash: 'new' })).toThrow(/already published/); + }); + test('rejects a malformed engine id before it enters the index', () => { expect(() => mergeEngineIndex(undefined, { id: '../evil', hash: 'x' })).toThrow(); }); diff --git a/tools/engine/publish-engine-r2.ts b/tools/engine/publish-engine-r2.ts index f238a057..6bbf3db9 100644 --- a/tools/engine/publish-engine-r2.ts +++ b/tools/engine/publish-engine-r2.ts @@ -1,16 +1,13 @@ /** - * Publish a packed engine feed directory (the 3 files produced by - * `pack-engine.ts`: `.tar.zst` + `.json` + `.sig`) to a Cloudflare R2 bucket - * via wrangler, then refresh the bucket's `index.json` (fetched from R2 itself, - * merged, re-uploaded) so `bunmaska engine available` lists the new engine. The - * bucket is served at the feed base (`engines.bunmaska.org`), so this is the - * entire "go live" step — the client (`bunmaska engine install `) then - * fetches + verifies them. + * Publish a packed engine feed dir (`.tar.zst` + `.json` + `.sig` from + * `pack-engine.ts`) to the R2 bucket behind engines.bunmaska.org and add it to + * the bucket's `index.json`. The index merge runs before any upload, so a + * republished or malformed id uploads nothing. * * bun tools/engine/publish-engine-r2.ts [--bucket ] * * Requires wrangler auth in the environment (CLOUDFLARE_API_TOKEN + - * CLOUDFLARE_ACCOUNT_ID with R2 write on the bucket). Idempotent per object. + * CLOUDFLARE_ACCOUNT_ID with R2 write on the bucket). */ import { existsSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; @@ -31,6 +28,11 @@ if (!feedDir || !engineId) { process.exit(2); } +const fail = (message: string): never => { + process.stderr.write(`${message}\n`); + process.exit(1); +}; + const wrangler = (...cmd: string[]): number => Bun.spawnSync(['bunx', 'wrangler@4', 'r2', 'object', ...cmd, '--remote'], { stdout: 'inherit', @@ -39,40 +41,38 @@ const wrangler = (...cmd: string[]): number => const files = [`${engineId}.tar.zst`, `${engineId}.tar.zst.json`, `${engineId}.tar.zst.sig`]; for (const name of files) { - const path = join(feedDir, name); - if (!existsSync(path)) { - process.stderr.write(`missing feed file: ${path}\n`); - process.exit(1); + if (!existsSync(join(feedDir, name))) { + fail(`missing feed file: ${join(feedDir, name)}`); } } -for (const name of files) { - const path = join(feedDir, name); - process.stdout.write(`uploading ${name} -> r2://${bucket}/${name}\n`); - if (wrangler('put', `${bucket}/${name}`, '--file', path) !== 0) { - process.stderr.write(`wrangler put failed for ${name}\n`); - process.exit(1); - } +const manifest = parseRemoteManifest( + readFileSync(join(feedDir, `${engineId}.tar.zst.json`), 'utf8'), +); +if (manifest.id !== engineId) { + fail(`manifest id ${manifest.id} does not match ${engineId}`); } -// Refresh index.json: read the CURRENT one from the bucket (not the CDN — no -// cache staleness, works for any bucket), merge this engine in, upload back. -// A missing index (first publish) just starts a new one. +// Read the CURRENT index from the bucket (not the CDN), so the merge sees every engine. const work = mkdtempSync(join(tmpdir(), 'bunmaska-index-')); const current = join(work, 'index-current.json'); const merged = join(work, 'index.json'); const hadIndex = wrangler('get', `${bucket}/index.json`, '--file', current) === 0; -const manifest = parseRemoteManifest( - readFileSync(join(feedDir, `${engineId}.tar.zst.json`), 'utf8'), -); writeFileSync( merged, mergeEngineIndex(hadIndex ? readFileSync(current, 'utf8') : undefined, manifest), ); + +for (const name of files) { + process.stdout.write(`uploading ${name} -> r2://${bucket}/${name}\n`); + if (wrangler('put', `${bucket}/${name}`, '--file', join(feedDir, name)) !== 0) { + fail(`wrangler put failed for ${name}`); + } +} + process.stdout.write(`updating index.json (${hadIndex ? 'merged into existing' : 'new index'})\n`); if (wrangler('put', `${bucket}/index.json`, '--file', merged) !== 0) { - process.stderr.write('wrangler put failed for index.json\n'); - process.exit(1); + fail('wrangler put failed for index.json'); } process.stdout.write( From b8eedbdd5ce5a05886fa1cf4de774fa1f20c2e5d Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:22:23 -0700 Subject: [PATCH 256/586] fix: fail fast when a Windows WebKit configuration is NULL --- src/main/platform/windows/windows-webkit-view.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/main/platform/windows/windows-webkit-view.ts b/src/main/platform/windows/windows-webkit-view.ts index 9ced69ad..b89bf089 100644 --- a/src/main/platform/windows/windows-webkit-view.ts +++ b/src/main/platform/windows/windows-webkit-view.ts @@ -63,6 +63,9 @@ const sharedWebKitContext = (): Pointer => { } const s = loadWebKit2().symbols; const contextConfig = s.WKContextConfigurationCreate(); + if (contextConfig === null) { + throw new FFIError('WKContextConfigurationCreate returned NULL'); + } const context = s.WKContextCreateWithConfiguration(contextConfig); wkRelease(contextConfig); if (context === null) { @@ -279,6 +282,9 @@ export class WindowsWebView { } const pageConfig = s.WKPageConfigurationCreate(); + if (pageConfig === null) { + throw new FFIError('WKPageConfigurationCreate returned NULL'); + } s.WKPageConfigurationSetContext(pageConfig, context); s.WKPageConfigurationSetUserContentController(pageConfig, controller); const preferences = s.WKPageConfigurationGetPreferences(pageConfig); From a386ef7e150bdd3e96fd3b750dd4c1c60b431e68 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:22:32 -0700 Subject: [PATCH 257/586] fix: abort an engine publish when the live index cannot be read --- tools/engine/publish-engine-r2.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/tools/engine/publish-engine-r2.ts b/tools/engine/publish-engine-r2.ts index 6bbf3db9..8cabdbe9 100644 --- a/tools/engine/publish-engine-r2.ts +++ b/tools/engine/publish-engine-r2.ts @@ -4,7 +4,7 @@ * the bucket's `index.json`. The index merge runs before any upload, so a * republished or malformed id uploads nothing. * - * bun tools/engine/publish-engine-r2.ts [--bucket ] + * bun tools/engine/publish-engine-r2.ts [--bucket ] [--new-index] * * Requires wrangler auth in the environment (CLOUDFLARE_API_TOKEN + * CLOUDFLARE_ACCOUNT_ID with R2 write on the bucket). @@ -20,10 +20,11 @@ const feedDir = args[0]; const engineId = args[1]; const bucketFlag = args.indexOf('--bucket'); const bucket = bucketFlag >= 0 ? args[bucketFlag + 1] : 'bunmaska-engines'; +const newIndex = args.includes('--new-index'); if (!feedDir || !engineId) { process.stderr.write( - 'usage: bun tools/engine/publish-engine-r2.ts [--bucket ]\n', + 'usage: bun tools/engine/publish-engine-r2.ts [--bucket ] [--new-index]\n', ); process.exit(2); } @@ -58,6 +59,10 @@ const work = mkdtempSync(join(tmpdir(), 'bunmaska-index-')); const current = join(work, 'index-current.json'); const merged = join(work, 'index.json'); const hadIndex = wrangler('get', `${bucket}/index.json`, '--file', current) === 0; +if (!hadIndex && !newIndex) { + // Any failure (auth, 5xx, network) must not replace the live index with one entry. + fail(`could not read ${bucket}/index.json; pass --new-index only for a bucket with no index`); +} writeFileSync( merged, mergeEngineIndex(hadIndex ? readFileSync(current, 'utf8') : undefined, manifest), From 6e4daa41a6d12fb6ff1a77c723197097c1118c0d Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:22:32 -0700 Subject: [PATCH 258/586] chore: trim X11 shortcut comments to the comment rules --- .../platform/linux/x11-global-shortcut.ts | 33 ++----------------- src/main/platform/linux/x11-keymap.ts | 26 ++++----------- 2 files changed, 10 insertions(+), 49 deletions(-) diff --git a/src/main/platform/linux/x11-global-shortcut.ts b/src/main/platform/linux/x11-global-shortcut.ts index 0c20a0e6..a7c457b9 100644 --- a/src/main/platform/linux/x11-global-shortcut.ts +++ b/src/main/platform/linux/x11-global-shortcut.ts @@ -15,27 +15,8 @@ import { XKEY_STATE_OFFSET, } from './x11-keymap'; -/** - * Linux `globalShortcut` backend via Xlib `XGrabKey` (X11 only, BEST-EFFORT). - * - * On X11 we open a DEDICATED display connection, grab each accelerator's - * keycode+modifier on the root window, and poll that connection for `KeyPress` - * events from {@link pollX11ShortcutsOnce} (wired into the Linux cooperative - * pump's drain). A fired `KeyPress` is matched back to its registration by - * keycode+modifier and the JS callback is dispatched. - * - * HONEST LIMITS: - * - WAYLAND IS UNSUPPORTED in v1. `XGrabKey` only governs the X server; under a - * Wayland compositor (even via XWayland) a global grab does not see keys routed - * to native Wayland clients. True global shortcuts on Wayland require the - * `org.freedesktop.portal.GlobalShortcuts` portal — a separate, deferred path. - * - If `XOpenDisplay` fails (no X server / headless without xvfb), the backend - * reports `isSupported() === false` and `register` returns `false` — it does - * NOT fake success. - * - `XGrabKey` here grabs ONLY the exact modifier combo; it does not add the - * Lock/NumLock variants, so a shortcut may not fire while CapsLock/NumLock is - * on. That refinement is deferred. - */ +// X11 only: grabs live on a dedicated display that gtk-run-loop polls; Wayland sessions report +// unsupported. ponytail: Wayland needs the org.freedesktop.portal.GlobalShortcuts portal. type Grab = { readonly keycode: number; readonly modifiers: number }; type Registration = Grab & { readonly callback: () => void }; @@ -70,7 +51,6 @@ const installErrorTrap = (x11: ReturnType): void => { export const isWaylandSession = (env: Readonly>): boolean => Boolean(env['WAYLAND_DISPLAY']) || env['XDG_SESSION_TYPE'] === 'wayland'; -/** Open (once) the dedicated X display for grabs, or record that it is unavailable. */ const ensureDisplay = (): Pointer | null => { if (display !== undefined) { return display; @@ -165,11 +145,7 @@ const unregisterAll = (): void => { registrations.length = 0; }; -/** - * Drain pending `KeyPress` events from the dedicated grab connection and fire the - * matching callbacks. Wired into the Linux cooperative pump so registered hot - * keys dispatch without blocking. No-op when no display is open. - */ +/** Dispatch pending grab `KeyPress` events; called from the gtk-run-loop drain. */ export const pollX11ShortcutsOnce = (): void => { const dpy = display; if (dpy === null || dpy === undefined) { @@ -186,7 +162,6 @@ export const pollX11ShortcutsOnce = (): void => { const keycode = eventView.getUint32(XKEY_KEYCODE_OFFSET, true); const state = eventView.getUint32(XKEY_STATE_OFFSET, true); for (const reg of registrations) { - // Keycode alone once dispatched here, so Ctrl+K fired Ctrl+Shift+K too. if (reg.keycode === keycode && x11StateMatches(state, reg.modifiers)) { reg.callback(); } @@ -194,10 +169,8 @@ export const pollX11ShortcutsOnce = (): void => { } }; -/** Linux is supported only when a real X display connection can be opened. */ const isSupported = (): boolean => ensureDisplay() !== null; -/** The Linux X11 global-shortcut backend (X11 only; Wayland deferred). */ export const linuxGlobalShortcutBackend: GlobalShortcutBackend = { isSupported, register, diff --git a/src/main/platform/linux/x11-keymap.ts b/src/main/platform/linux/x11-keymap.ts index e891f8ee..199e9d1a 100644 --- a/src/main/platform/linux/x11-keymap.ts +++ b/src/main/platform/linux/x11-keymap.ts @@ -1,17 +1,10 @@ import type { ParsedAccelerator } from '../../api/accelerator'; -/** - * Pure X11 keysym-name + modifier-mask mapping for the Linux global-shortcut - * backend. No FFI here — these map a parsed accelerator onto the X keysym NAME - * (resolved to a real keysym via `XStringToKeysym` at registration time) and the - * X modifier mask. - */ - /** X11 modifier mask bits (`X.h`). */ -export const SHIFT_MASK = 1 << 0; // 1 -export const CONTROL_MASK = 1 << 2; // 4 -export const MOD1_MASK = 1 << 3; // 8 (Alt) -export const MOD4_MASK = 1 << 6; // 64 (Super) +export const SHIFT_MASK = 1 << 0; +export const CONTROL_MASK = 1 << 2; +export const MOD1_MASK = 1 << 3; // Alt +export const MOD4_MASK = 1 << 6; // Super /** `KeyPress` event type and the XEvent byte offsets we read (64-bit ABI). */ export const KEY_PRESS = 2; @@ -33,7 +26,7 @@ const REGISTRABLE_MODIFIERS = SHIFT_MASK | CONTROL_MASK | MOD1_MASK | MOD4_MASK; export const x11StateMatches = (state: number, modifiers: number): boolean => (state & REGISTRABLE_MODIFIERS) === modifiers; -/** Named keys → the X keysym string `XStringToKeysym` understands. */ +/** Accelerator key names to `XStringToKeysym` names. */ const KEYSYM_NAMES: ReadonlyMap = new Map([ ['SPACE', 'space'], ['TAB', 'Tab'], @@ -54,11 +47,7 @@ const KEYSYM_NAMES: ReadonlyMap = new Map([ const isFunctionKey = (key: string): boolean => /^F([1-9]|1[0-9]|2[0-4])$/.test(key); -/** - * Map a parsed accelerator key to the X keysym NAME string for - * `XStringToKeysym`, or `undefined` if it cannot be expressed. Single letters - * become their lowercase form (`'K'` → `'k'`); digits stay as-is. - */ +/** The keysym NAME for `XStringToKeysym`, or `undefined` when X cannot express the key. */ export const x11KeysymName = (key: string): string | undefined => { const upper = key.toUpperCase(); if (key.length === 1) { @@ -73,7 +62,6 @@ export const x11KeysymName = (key: string): string | undefined => { return KEYSYM_NAMES.get(upper); }; -/** Build the X modifier mask for a parsed accelerator (CmdOrCtrl already resolved). */ export const x11ModifierMask = (parsed: ParsedAccelerator): number => { let mask = 0; if (parsed.shift) { @@ -85,7 +73,7 @@ export const x11ModifierMask = (parsed: ParsedAccelerator): number => { if (parsed.alt) { mask |= MOD1_MASK; } - // On Linux, Super (and Cmd-as-meta, which CmdOrCtrl never sets here) maps to Mod4. + // Super and Cmd both map to Mod4. if (parsed.super || parsed.meta) { mask |= MOD4_MASK; } From 90aaa995e287ef25c63a77f2f687b92e5da7dd2b Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:22:39 -0700 Subject: [PATCH 259/586] refactor: drop unused WebKit2 symbols and view accessors --- src/main/platform/windows/webkit2-ffi.ts | 6 ------ src/main/platform/windows/windows-webkit-view.ts | 14 -------------- 2 files changed, 20 deletions(-) diff --git a/src/main/platform/windows/webkit2-ffi.ts b/src/main/platform/windows/webkit2-ffi.ts index b06921d1..7e666dc8 100644 --- a/src/main/platform/windows/webkit2-ffi.ts +++ b/src/main/platform/windows/webkit2-ffi.ts @@ -23,8 +23,6 @@ const WEBKIT2_SYMBOLS = { args: [FFIType.ptr, FFIType.ptr], returns: FFIType.void, }, - WKPageConfigurationGetPreferences: { args: [FFIType.ptr], returns: FFIType.ptr }, - WKPreferencesSetJavaScriptEnabled: { args: [FFIType.ptr, FFIType.u8], returns: FFIType.void }, // ── View (hosted in an HWND) ───────────────────────────────────────────── // WKViewCreate(RECT rect, WKPageConfigurationRef, HWND parent): RECT is 16 @@ -33,7 +31,6 @@ const WEBKIT2_SYMBOLS = { WKViewGetPage: { args: [FFIType.ptr], returns: FFIType.ptr }, WKViewGetWindow: { args: [FFIType.ptr], returns: FFIType.u64 }, WKViewSetIsInWindow: { args: [FFIType.ptr, FFIType.u8], returns: FFIType.void }, - WKViewSetParentWindow: { args: [FFIType.ptr, FFIType.u64], returns: FFIType.void }, // ── Navigation + history ───────────────────────────────────────────────── WKPageLoadURL: { args: [FFIType.ptr, FFIType.ptr], returns: FFIType.void }, @@ -121,14 +118,11 @@ const WEBKIT2_SYMBOLS = { }, // ── Reference counting ─────────────────────────────────────────────────── - WKRetain: { args: [FFIType.ptr], returns: FFIType.ptr }, WKRelease: { args: [FFIType.ptr], returns: FFIType.void }, } as const; /** `_WKUserScriptInjectionTime`: inject before the page's own scripts run. */ export const WK_INJECT_AT_DOCUMENT_START = 0; -/** `_WKUserScriptInjectionTime`: inject after the document has parsed. */ -export const WK_INJECT_AT_DOCUMENT_END = 1; /** The subdir an embedded engine is bundled into (must match `build-windows.ts`). */ const BUNDLED_ENGINE_DIRNAME = 'webkit'; diff --git a/src/main/platform/windows/windows-webkit-view.ts b/src/main/platform/windows/windows-webkit-view.ts index b89bf089..2cda55be 100644 --- a/src/main/platform/windows/windows-webkit-view.ts +++ b/src/main/platform/windows/windows-webkit-view.ts @@ -287,10 +287,6 @@ export class WindowsWebView { } s.WKPageConfigurationSetContext(pageConfig, context); s.WKPageConfigurationSetUserContentController(pageConfig, controller); - const preferences = s.WKPageConfigurationGetPreferences(pageConfig); - if (preferences !== null) { - s.WKPreferencesSetJavaScriptEnabled(preferences, 1); - } const hostWindow = createNativeChildHost(options.hwnd, options.width, options.height); @@ -315,16 +311,6 @@ export class WindowsWebView { return new WindowsWebView(view, page, hostWindow, controller, callbacks); } - /** The underlying `WKPageRef`. */ - page(): Pointer { - return this.#page; - } - - /** The underlying `WKViewRef`. */ - view(): Pointer { - return this.#view; - } - /** Navigate to a URL (http/https/file/about). */ loadURL(url: string): void { const urlRef = wkUrl(url); From 621bf92d4252c035f31e1d9dd3fea06eb1297c41 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:22:44 -0700 Subject: [PATCH 260/586] fix: serve the engine feed index uncached --- tools/engine/feed-worker/serve-engines.js | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/tools/engine/feed-worker/serve-engines.js b/tools/engine/feed-worker/serve-engines.js index 459345b9..304f3feb 100644 --- a/tools/engine/feed-worker/serve-engines.js +++ b/tools/engine/feed-worker/serve-engines.js @@ -1,5 +1,5 @@ -// Serves the signed Bunmaska engine feed from the bunmaska-engines R2 bucket. -// Read-only, public, long-cache (engine ids are content-addressed + immutable). +// Serves the signed Bunmaska engine feed from the bunmaska-engines R2 bucket. Read-only, public. +// Engine objects are immutable per id (publish refuses a republish); index.json changes. export default { async fetch(request, env) { if (request.method !== 'GET' && request.method !== 'HEAD') { @@ -12,7 +12,10 @@ export default { const headers = new Headers(); obj.writeHttpMetadata(headers); headers.set('etag', obj.httpEtag); - headers.set('cache-control', 'public, max-age=31536000, immutable'); + headers.set( + 'cache-control', + key === 'index.json' ? 'no-cache' : 'public, max-age=31536000, immutable', + ); headers.set('access-control-allow-origin', '*'); return new Response(request.method === 'HEAD' ? null : obj.body, { headers }); }, From 7a6bb1430c55260381c82cdd5b738d06481ebb9c Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:22:49 -0700 Subject: [PATCH 261/586] test: drop the WebKit2 symbol test that cannot fail --- tests/integration/windows/webkit2-ffi.test.ts | 8 -------- 1 file changed, 8 deletions(-) diff --git a/tests/integration/windows/webkit2-ffi.test.ts b/tests/integration/windows/webkit2-ffi.test.ts index 6ccb026f..5cf01b21 100644 --- a/tests/integration/windows/webkit2-ffi.test.ts +++ b/tests/integration/windows/webkit2-ffi.test.ts @@ -20,14 +20,6 @@ import { const hasEngine = currentPlatform() === 'windows' && resolveWindowsEngineDir() !== undefined; describe.skipIf(!hasEngine)('WinCairo WebKit2 FFI', () => { - test('loads WebKit2.dll and resolves the core WK2 symbols', () => { - const wk = loadWebKit2(); - expect(typeof wk.symbols.WKViewCreate).toBe('function'); - expect(typeof wk.symbols.WKPageLoadURL).toBe('function'); - expect(typeof wk.symbols.WKUserContentControllerAddScriptMessageHandler).toBe('function'); - expect(typeof wk.symbols.WKUserScriptCreateWithSource).toBe('function'); - }); - test('loadWebKit2 is idempotent (same library handle)', () => { expect(loadWebKit2()).toBe(loadWebKit2()); }); From f17f462a7c02d94f847ba59ad729299ff3cee608 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:22:55 -0700 Subject: [PATCH 262/586] test: drop transcription tests from the Linux desktop unit suites --- src/main/platform/linux/gtk-menu.ts | 2 +- .../main/platform/linux/gtk-clipboard.test.ts | 36 +++++--------- .../main/platform/linux/gtk-dialog.test.ts | 42 +++++++--------- .../unit/main/platform/linux/gtk-menu.test.ts | 46 +++++++---------- .../unit/main/platform/linux/sni-tray.test.ts | 49 ++++--------------- 5 files changed, 59 insertions(+), 116 deletions(-) diff --git a/src/main/platform/linux/gtk-menu.ts b/src/main/platform/linux/gtk-menu.ts index 98f195b4..4c07ec55 100644 --- a/src/main/platform/linux/gtk-menu.ts +++ b/src/main/platform/linux/gtk-menu.ts @@ -28,7 +28,7 @@ import { loadGMenuFFI } from './gtk-menu-ffi'; */ /** ABI shape for `GSimpleAction::activate`: `(action, parameter, user_data) -> void`. */ -export const ACTION_ACTIVATE_CB_DEF = { args: ['ptr', 'ptr', 'ptr'], returns: 'void' } as const; +const ACTION_ACTIVATE_CB_DEF = { args: ['ptr', 'ptr', 'ptr'], returns: 'void' } as const; /** The action-group namespace prefix inserted into the window. */ const ACTION_GROUP_PREFIX = 'bunmaska'; diff --git a/tests/unit/main/platform/linux/gtk-clipboard.test.ts b/tests/unit/main/platform/linux/gtk-clipboard.test.ts index a9c9f916..893ca183 100644 --- a/tests/unit/main/platform/linux/gtk-clipboard.test.ts +++ b/tests/unit/main/platform/linux/gtk-clipboard.test.ts @@ -1,5 +1,5 @@ import type { Pointer } from 'bun:ffi'; -import { describe, expect, it, test } from 'bun:test'; +import { describe, expect, test } from 'bun:test'; import { currentPlatform } from '../../../../../src/common/platform'; import { type AsyncStreamReader, @@ -10,16 +10,6 @@ import { settleReadText, } from '../../../../../src/main/platform/linux/gtk-clipboard'; -describe('linuxClipboardBackend shape', () => { - it('exposes readText, writeText, readHTML, writeHTML and clear', () => { - expect(typeof linuxClipboardBackend.readText).toBe('function'); - expect(typeof linuxClipboardBackend.writeText).toBe('function'); - expect(typeof linuxClipboardBackend.readHTML).toBe('function'); - expect(typeof linuxClipboardBackend.writeHTML).toBe('function'); - expect(typeof linuxClipboardBackend.clear).toBe('function'); - }); -}); - describe('linuxClipboardBackend reads', () => { // On Linux the shared test process may hold a real display, where a read would await a pump. test.skipIf(currentPlatform() === 'linux')( @@ -42,12 +32,12 @@ describe('linuxClipboardBackend reads', () => { }); describe('formatsFromGdk', () => { - it('reports MIME names without parameters, drops GType names and dedupes', () => { + test('reports MIME names without parameters, drops GType names and dedupes', () => { const gdk = 'gchararray GdkTexture text/plain;charset=utf-8 text/plain image/png'; expect(formatsFromGdk(gdk)).toEqual(['text/plain', 'image/png']); }); - it('returns no formats for an empty clipboard', () => { + test('returns no formats for an empty clipboard', () => { expect(formatsFromGdk('')).toEqual([]); }); }); @@ -70,27 +60,27 @@ describe('drainStreamAsync (injected AsyncStreamReader, no real GInputStream)', }; }; - it('concatenates multi-chunk reads and UTF-8 decodes them', async () => { + test('concatenates multi-chunk reads and UTF-8 decodes them', async () => { const enc = new TextEncoder(); const { reader, closed } = makeReader([enc.encode('café'), enc.encode(' & co')]); expect(await drainStreamAsync(reader)).toBe('café & co'); expect(closed()).toBe(1); }); - it('decodes a multibyte char split across a chunk boundary (bytes joined before decode)', async () => { + test('decodes a multibyte char split across a chunk boundary (bytes joined before decode)', async () => { // '🎉' is 4 UTF-8 bytes (F0 9F 8E 89); split it 2/2 across two chunks. const party = new TextEncoder().encode('🎉'); // length 4 const { reader } = makeReader([party.slice(0, 2), party.slice(2, 4)]); expect(await drainStreamAsync(reader)).toBe('🎉'); }); - it('returns empty string and still closes when the stream is immediately EOF', async () => { + test('returns empty string and still closes when the stream is immediately EOF', async () => { const { reader, closed } = makeReader([]); expect(await drainStreamAsync(reader)).toBe(''); expect(closed()).toBe(1); }); - it('still closes the stream when a read rejects (finally path)', async () => { + test('still closes the stream when a read rejects (finally path)', async () => { let closed = 0; const reader: AsyncStreamReader = { read: () => Promise.reject(new Error('boom')), @@ -104,7 +94,7 @@ describe('drainStreamAsync (injected AsyncStreamReader, no real GInputStream)', }); describe('settleReadStream (injected finish + async drain, no real clipboard)', () => { - it('drains the stream when finish yields a non-null GInputStream*', async () => { + test('drains the stream when finish yields a non-null GInputStream*', async () => { const value = await settleReadStream({ empty: '', result: 1 as unknown as Pointer, @@ -117,7 +107,7 @@ describe('settleReadStream (injected finish + async drain, no real clipboard)', expect(value).toBe('

html

'); }); - it('returns empty string when finish yields null (no matching format)', async () => { + test('returns empty string when finish yields null (no matching format)', async () => { const value = await settleReadStream({ empty: '', result: 0 as unknown as Pointer, @@ -129,7 +119,7 @@ describe('settleReadStream (injected finish + async drain, no real clipboard)', expect(value).toBe(''); }); - it('returns empty string when finish throws (GError path)', async () => { + test('returns empty string when finish throws (GError path)', async () => { const value = await settleReadStream({ empty: '', result: 0 as unknown as Pointer, @@ -143,7 +133,7 @@ describe('settleReadStream (injected finish + async drain, no real clipboard)', }); describe('settleReadText (injected finish-fn, no real clipboard)', () => { - it('returns the read string when the injected finish-fn yields a non-null char*', () => { + test('returns the read string when the injected finish-fn yields a non-null char*', () => { const fakeResult = 7 as unknown as Pointer; const value = settleReadText({ result: fakeResult, @@ -159,7 +149,7 @@ describe('settleReadText (injected finish-fn, no real clipboard)', () => { expect(value).toBe('clipboard text'); }); - it('returns empty string when the injected finish-fn yields null (empty/none)', () => { + test('returns empty string when the injected finish-fn yields null (empty/none)', () => { const value = settleReadText({ result: 0 as unknown as Pointer, finish: () => null, @@ -170,7 +160,7 @@ describe('settleReadText (injected finish-fn, no real clipboard)', () => { expect(value).toBe(''); }); - it('returns empty string when finish throws (GError path)', () => { + test('returns empty string when finish throws (GError path)', () => { const value = settleReadText({ result: 0 as unknown as Pointer, finish: () => { diff --git a/tests/unit/main/platform/linux/gtk-dialog.test.ts b/tests/unit/main/platform/linux/gtk-dialog.test.ts index 0c10305b..46f2a03d 100644 --- a/tests/unit/main/platform/linux/gtk-dialog.test.ts +++ b/tests/unit/main/platform/linux/gtk-dialog.test.ts @@ -1,6 +1,5 @@ import { type Pointer, ptr, read } from 'bun:ffi'; -import { describe, expect, it } from 'bun:test'; -import { GASYNC_READY_CB_DEF } from '../../../../../src/main/platform/linux/gasync'; +import { describe, expect, test } from 'bun:test'; import { buildButtonsArray, cancelIdForButtons, @@ -10,15 +9,8 @@ import { settleFilePath, } from '../../../../../src/main/platform/linux/gtk-dialog'; -describe('GASYNC_READY_CB_DEF (GAsyncReadyCallback ABI, shape-only)', () => { - it('is (source, result, user_data) -> void', () => { - expect(GASYNC_READY_CB_DEF.args).toEqual(['ptr', 'ptr', 'ptr']); - expect(GASYNC_READY_CB_DEF.returns).toBe('void'); - }); -}); - describe('buildButtonsArray', () => { - it('produces a NULL-terminated array of one pointer per label plus a trailing 0n', () => { + test('produces a NULL-terminated array of one pointer per label plus a trailing 0n', () => { const built = buildButtonsArray(['Yes', 'No', 'Cancel']); // 3 labels + 1 NULL terminator. expect(built.array.length).toBe(4); @@ -31,7 +23,7 @@ describe('buildButtonsArray', () => { expect(built.buffers.length).toBe(3); }); - it('encodes each label as a readable NUL-terminated UTF-8 cstr', () => { + test('encodes each label as a readable NUL-terminated UTF-8 cstr', () => { const built = buildButtonsArray(['OK']); // Read the bytes back through the pointer to prove it points at "OK\0". const base = Number(built.array[0]) as unknown as Pointer; @@ -43,47 +35,47 @@ describe('buildButtonsArray', () => { expect(b2).toBe(0); }); - it('yields just a NULL terminator for an empty label list', () => { + test('yields just a NULL terminator for an empty label list', () => { const built = buildButtonsArray([]); expect(built.array.length).toBe(1); expect(built.array[0]).toBe(0n); expect(built.buffers.length).toBe(0); }); - it('exposes a non-null pointer to the underlying array for passing to GTK', () => { + test('exposes a non-null pointer to the underlying array for passing to GTK', () => { const built = buildButtonsArray(['A']); expect(ptr(built.array.buffer)).not.toBe(0); }); }); describe('mapChooseResult', () => { - it('returns the clicked button index when finish yields a valid index', () => { + test('returns the clicked button index when finish yields a valid index', () => { expect(mapChooseResult(0, 1)).toBe(0); expect(mapChooseResult(2, 1)).toBe(2); }); - it('maps the dismissal sentinel (-1) to the cancelId', () => { + test('maps the dismissal sentinel (-1) to the cancelId', () => { expect(mapChooseResult(-1, 3)).toBe(3); }); - it('falls back to the cancelId on any negative (error) index', () => { + test('falls back to the cancelId on any negative (error) index', () => { expect(mapChooseResult(-5, 7)).toBe(7); }); }); describe('cancelIdForButtons', () => { - it('picks the first button labelled cancel or no, case-insensitively (Electron default)', () => { + test('picks the first button labelled cancel or no, case-insensitively (Electron default)', () => { expect(cancelIdForButtons(['Yes', 'No'])).toBe(1); expect(cancelIdForButtons(['Save', 'CANCEL', 'No'])).toBe(1); }); - it('falls back to 0 when no button is a cancel label', () => { + test('falls back to 0 when no button is a cancel label', () => { expect(cancelIdForButtons(['OK', 'Retry'])).toBe(0); }); }); describe('extensionPattern', () => { - it('matches an extension in any letter case (GTK globs are case-sensitive on Linux)', () => { + test('matches an extension in any letter case (GTK globs are case-sensitive on Linux)', () => { expect(extensionPattern('jpg')).toBe('*.[jJ][pP][gG]'); expect(extensionPattern('Tar.gz')).toBe('*.[tT][aA][rR].[gG][zZ]'); expect(extensionPattern('mp4')).toBe('*.[mM][pP]4'); @@ -91,7 +83,7 @@ describe('extensionPattern', () => { }); describe('settleChoose (injected finish-fn, no real dialog)', () => { - it('resolves with the mapped button index from the injected finish-fn', () => { + test('resolves with the mapped button index from the injected finish-fn', () => { const fakeResult = 123 as unknown as Pointer; const value = settleChoose({ result: fakeResult, @@ -104,7 +96,7 @@ describe('settleChoose (injected finish-fn, no real dialog)', () => { expect(value).toBe(2); }); - it('maps a -1 dismissal from the injected finish-fn to the cancelId', () => { + test('maps a -1 dismissal from the injected finish-fn to the cancelId', () => { const value = settleChoose({ result: 0 as unknown as Pointer, cancelId: 5, @@ -113,7 +105,7 @@ describe('settleChoose (injected finish-fn, no real dialog)', () => { expect(value).toBe(5); }); - it('maps a thrown finish (GError path) to the cancelId', () => { + test('maps a thrown finish (GError path) to the cancelId', () => { const value = settleChoose({ result: 0 as unknown as Pointer, cancelId: 9, @@ -126,7 +118,7 @@ describe('settleChoose (injected finish-fn, no real dialog)', () => { }); describe('settleFilePath (injected finish + reader, no real dialog)', () => { - it('returns the read path when the injected finish-fn yields a non-null GFile*', () => { + test('returns the read path when the injected finish-fn yields a non-null GFile*', () => { const fakeFile = 42 as unknown as Pointer; const path = settleFilePath({ result: 0 as unknown as Pointer, @@ -139,7 +131,7 @@ describe('settleFilePath (injected finish + reader, no real dialog)', () => { expect(path).toBe('/home/user/notes.md'); }); - it('returns empty string when the injected finish-fn yields null (cancel)', () => { + test('returns empty string when the injected finish-fn yields null (cancel)', () => { const path = settleFilePath({ result: 0 as unknown as Pointer, finish: () => null, @@ -150,7 +142,7 @@ describe('settleFilePath (injected finish + reader, no real dialog)', () => { expect(path).toBe(''); }); - it('returns empty string when finish throws (GError / dismissal)', () => { + test('returns empty string when finish throws (GError / dismissal)', () => { const path = settleFilePath({ result: 0 as unknown as Pointer, finish: () => { diff --git a/tests/unit/main/platform/linux/gtk-menu.test.ts b/tests/unit/main/platform/linux/gtk-menu.test.ts index 861e1177..8765dcc9 100644 --- a/tests/unit/main/platform/linux/gtk-menu.test.ts +++ b/tests/unit/main/platform/linux/gtk-menu.test.ts @@ -1,7 +1,6 @@ -import { afterEach, describe, expect, it } from 'bun:test'; +import { afterEach, describe, expect, test } from 'bun:test'; import type { NativeMenuItemSpec } from '../../../../../src/main/platform/macos/cocoa-menu'; import { - ACTION_ACTIVATE_CB_DEF, actionName, type Bindings, detailedAction, @@ -102,15 +101,8 @@ afterEach(() => { resetCurrentAppMenuForTesting(); }); -describe('ACTION_ACTIVATE_CB_DEF (GSimpleAction::activate ABI, shape-only)', () => { - it('is (action, parameter, user_data) -> void', () => { - expect(ACTION_ACTIVATE_CB_DEF.args).toEqual(['ptr', 'ptr', 'ptr']); - expect(ACTION_ACTIVATE_CB_DEF.returns).toBe('void'); - }); -}); - describe('action-name helpers', () => { - it('actionName produces a unique monotonic menu- per call', () => { + test('actionName produces a unique monotonic menu- per call', () => { const a = actionName(); const b = actionName(); expect(a).not.toBe(b); @@ -118,13 +110,13 @@ describe('action-name helpers', () => { expect(b).toMatch(/^menu-\d+$/); }); - it('detailedAction prefixes the action group namespace', () => { + test('detailedAction prefixes the action group namespace', () => { expect(detailedAction('menu-7')).toBe('bunmaska.menu-7'); }); }); describe('linuxMenuRealizer.realize (fake bindings)', () => { - it('appends one model entry per normal item and wires its action', () => { + test('appends one model entry per normal item and wires its action', () => { const { bindings, calls } = makeFakeBindings(); setBindingsForTesting(bindings); const items: NativeMenuItemSpec[] = [ @@ -144,7 +136,7 @@ describe('linuxMenuRealizer.realize (fake bindings)', () => { expect(calls.filter((c) => c.fn === 'connectActivate')).toHaveLength(2); }); - it('creates a stateful boolean action for a checkbox item carrying its checked state', () => { + test('creates a stateful boolean action for a checkbox item carrying its checked state', () => { const { bindings, calls } = makeFakeBindings(); setBindingsForTesting(bindings); linuxMenuRealizer.realize([ @@ -164,7 +156,7 @@ describe('linuxMenuRealizer.realize (fake bindings)', () => { expect(calls.filter((c) => c.fn === 'connectActivate')).toHaveLength(1); }); - it('routes activate to the matching onClick via the action group', () => { + test('routes activate to the matching onClick via the action group', () => { const { bindings } = makeFakeBindings(); setBindingsForTesting(bindings); const fired: string[] = []; @@ -194,7 +186,7 @@ describe('linuxMenuRealizer.realize (fake bindings)', () => { expect(fired).toEqual(['beta', 'alpha']); }); - it('re-throws a failing click on a microtask instead of into the GLib dispatch', () => { + test('re-throws a failing click on a microtask instead of into the GLib dispatch', () => { const { bindings } = makeFakeBindings(); setBindingsForTesting(bindings); const boom = new Error('app bug'); @@ -230,7 +222,7 @@ describe('linuxMenuRealizer.realize (fake bindings)', () => { expect(() => queued[0]?.()).toThrow(boom); }); - it('maps Electron & mnemonics to GTK underlines and escapes literal underscores', () => { + test('maps Electron & mnemonics to GTK underlines and escapes literal underscores', () => { const { bindings, calls } = makeFakeBindings(); setBindingsForTesting(bindings); linuxMenuRealizer.realize([ @@ -257,7 +249,7 @@ describe('linuxMenuRealizer.realize (fake bindings)', () => { expect(labels).toEqual(['my__notes.txt', 'Save & Quit', '_File']); }); - it('honours enabled:false via g_simple_action_set_enabled(0)', () => { + test('honours enabled:false via g_simple_action_set_enabled(0)', () => { const { bindings, calls } = makeFakeBindings(); setBindingsForTesting(bindings); linuxMenuRealizer.realize([ @@ -268,7 +260,7 @@ describe('linuxMenuRealizer.realize (fake bindings)', () => { expect(enabledCalls[0]?.args[1]).toBe(0); }); - it('does not create an action for an item without onClick', () => { + test('does not create an action for an item without onClick', () => { const { bindings, calls } = makeFakeBindings(); setBindingsForTesting(bindings); linuxMenuRealizer.realize([ @@ -279,7 +271,7 @@ describe('linuxMenuRealizer.realize (fake bindings)', () => { expect(calls.filter((c) => c.fn === 'gMenuAppend')).toHaveLength(1); }); - it('puts the items after a separator into a new section (GTK draws no empty section)', () => { + test('puts the items after a separator into a new section (GTK draws no empty section)', () => { const { bindings, calls } = makeFakeBindings(); setBindingsForTesting(bindings); const handle = linuxMenuRealizer.realize([ @@ -296,7 +288,7 @@ describe('linuxMenuRealizer.realize (fake bindings)', () => { expect(appendedTo('B')).toBe(sections[0]?.args[1]); }); - it('realizes a submenu into a child model sharing the same action group', () => { + test('realizes a submenu into a child model sharing the same action group', () => { const { bindings, calls } = makeFakeBindings(); setBindingsForTesting(bindings); const fired: string[] = []; @@ -329,7 +321,7 @@ describe('linuxMenuRealizer.realize (fake bindings)', () => { expect(fired).toEqual(['new']); }); - it('retains one JSCallback-equivalent thunk per clickable item', () => { + test('retains one JSCallback-equivalent thunk per clickable item', () => { const { bindings } = makeFakeBindings(); setBindingsForTesting(bindings); const handle = linuxMenuRealizer.realize([ @@ -349,7 +341,7 @@ describe('realizeForWindow (per-window role wiring)', () => { ...extra, }); - it('wires a role item with a Linux action to dispatchRole, fired on activate', () => { + test('wires a role item with a Linux action to dispatchRole, fired on activate', () => { const { bindings, calls } = makeFakeBindings(); setBindingsForTesting(bindings); const dispatched: NativeMenuItemSpec[] = []; @@ -361,14 +353,14 @@ describe('realizeForWindow (per-window role wiring)', () => { expect(dispatched).toEqual([copy]); }); - it('leaves a role with no Linux action (quit) inert — no action wired', () => { + test('leaves a role with no Linux action (quit) inert — no action wired', () => { const { bindings, calls } = makeFakeBindings(); setBindingsForTesting(bindings); realizeForWindow([role('Quit', { role: 'quit' })], () => undefined); expect(calls.filter((c) => c.fn === 'connectActivate')).toHaveLength(0); }); - it('the shared realize() (no dispatcher) leaves role items inert', () => { + test('the shared realize() (no dispatcher) leaves role items inert', () => { const { bindings, calls } = makeFakeBindings(); setBindingsForTesting(bindings); linuxMenuRealizer.realize([role('Copy', { role: 'copy', editingCommand: 'Copy' })]); @@ -377,11 +369,11 @@ describe('realizeForWindow (per-window role wiring)', () => { }); describe('shared app-menu state', () => { - it('is undefined before any setApplicationMenu', () => { + test('is undefined before any setApplicationMenu', () => { expect(getCurrentAppMenu()).toBeUndefined(); }); - it('setApplicationMenu stores the realized model + group as the current menu', () => { + test('setApplicationMenu stores the realized model + group as the current menu', () => { const { bindings } = makeFakeBindings(); setBindingsForTesting(bindings); const handle = linuxMenuRealizer.realize([ @@ -394,7 +386,7 @@ describe('shared app-menu state', () => { expect(current?.group).toBe(entry?.group as bigint); }); - it('throws if setApplicationMenu is given an unknown handle', () => { + test('throws if setApplicationMenu is given an unknown handle', () => { const { bindings } = makeFakeBindings(); setBindingsForTesting(bindings); expect(() => linuxMenuRealizer.setApplicationMenu(999999n)).toThrow(); diff --git a/tests/unit/main/platform/linux/sni-tray.test.ts b/tests/unit/main/platform/linux/sni-tray.test.ts index 84c0d57d..8acc61c5 100644 --- a/tests/unit/main/platform/linux/sni-tray.test.ts +++ b/tests/unit/main/platform/linux/sni-tray.test.ts @@ -1,37 +1,26 @@ -import { describe, expect, it } from 'bun:test'; -import { - DBUS_GET_PROPERTY_CB_DEF, - DBUS_METHOD_CALL_CB_DEF, - DBUS_SET_PROPERTY_CB_DEF, - VTABLE_SLOTS, -} from '../../../../../src/main/platform/linux/gdbus-ffi'; -import { rgbaToArgb32Network, SNI_XML } from '../../../../../src/main/platform/linux/sni-tray'; - -/** - * Pure unit tests for the SNI tray — the FFI-free core: the RGBA→ARGB32-network pixel swap - * (the riskiest blind piece, exercised exhaustively here), the vtable/callback ABI shapes, - * and the embedded introspection XML. No `dlopen`, runs on any host. - */ +import { describe, expect, test } from 'bun:test'; +import { VTABLE_SLOTS } from '../../../../../src/main/platform/linux/gdbus-ffi'; +import { rgbaToArgb32Network } from '../../../../../src/main/platform/linux/sni-tray'; describe('rgbaToArgb32Network', () => { - it('swaps a single RGBA pixel to A,R,G,B network order', () => { + test('swaps a single RGBA pixel to A,R,G,B network order', () => { const out = rgbaToArgb32Network(new Uint8Array([10, 20, 30, 40]), 1, 1, 4, 4); expect(Array.from(out)).toEqual([40, 10, 20, 30]); }); - it('synthesizes A=0xFF for a 3-channel (no-alpha) source', () => { + test('synthesizes A=0xFF for a 3-channel (no-alpha) source', () => { const out = rgbaToArgb32Network(new Uint8Array([10, 20, 30]), 1, 1, 3, 3); expect(Array.from(out)).toEqual([0xff, 10, 20, 30]); }); - it('strips row padding using rowstride (not width*channels)', () => { + test('strips row padding using rowstride (not width*channels)', () => { // 2×1 RGBA with a 4-byte row pad (rowstride 12 > 2*4=8). const row = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0]); const out = rgbaToArgb32Network(row, 2, 1, 12, 4); expect(Array.from(out)).toEqual([4, 1, 2, 3, 8, 5, 6, 7]); // [A,R,G,B] per pixel, pad ignored }); - it('reads each row at its rowstride offset for height > 1', () => { + test('reads each row at its rowstride offset for height > 1', () => { // 1×2 RGBA, rowstride 8 (4 data + 4 pad per row). const px = new Uint8Array([10, 11, 12, 13, 0, 0, 0, 0, 20, 21, 22, 23, 0, 0, 0, 0]); const out = rgbaToArgb32Network(px, 1, 2, 8, 4); @@ -39,28 +28,8 @@ describe('rgbaToArgb32Network', () => { }); }); -describe('SNI vtable + callback ABI shapes', () => { - it('the vtable has 11 slots (3 fn-ptrs + gpointer padding[8])', () => { +describe('GDBusInterfaceVTable', () => { + test('spans the 3 fn-ptrs plus the gpointer padding[8] GDBus copies with the vtable', () => { expect(VTABLE_SLOTS).toBe(11); }); - - it('method_call is 8 ptr -> void; get_property is 7 ptr -> ptr; set_property is 8 ptr -> i32', () => { - expect(DBUS_METHOD_CALL_CB_DEF.args).toHaveLength(8); - expect(DBUS_METHOD_CALL_CB_DEF.returns).toBe('void'); - expect(DBUS_GET_PROPERTY_CB_DEF.args).toHaveLength(7); - expect(DBUS_GET_PROPERTY_CB_DEF.returns).toBe('ptr'); - expect(DBUS_SET_PROPERTY_CB_DEF.args).toHaveLength(8); - expect(DBUS_SET_PROPERTY_CB_DEF.returns).toBe('i32'); - }); -}); - -describe('SNI introspection XML', () => { - it('declares the StatusNotifierItem interface with the served properties + Activate', () => { - expect(SNI_XML).toContain('name="org.kde.StatusNotifierItem"'); - for (const prop of ['Category', 'Id', 'Title', 'Status', 'IconPixmap', 'ToolTip', 'Menu']) { - expect(SNI_XML).toContain(`name="${prop}"`); - } - expect(SNI_XML).toContain('name="Activate"'); - expect(SNI_XML).toContain('name="NewIcon"'); - }); }); From 349cd1b7f72eb56ac4286de9f3f11b0ddea81172 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:23:01 -0700 Subject: [PATCH 263/586] fix: reject a malformed engine id before packing and signing --- src/cli/engine-pack.ts | 2 ++ tests/unit/cli/engine-pack.test.ts | 13 +++++++++++++ 2 files changed, 15 insertions(+) diff --git a/src/cli/engine-pack.ts b/src/cli/engine-pack.ts index 9a46a13c..233a847b 100644 --- a/src/cli/engine-pack.ts +++ b/src/cli/engine-pack.ts @@ -4,6 +4,7 @@ * a plain object upload. */ +import { parseEngineId } from '../common/engine-id'; import { BunmaskaError } from '../common/errors'; import { contentHash } from '../common/manifest'; import { signArtifact } from './engine-signature'; @@ -51,6 +52,7 @@ export const packEngineDir = async ( deps: PackDeps = {}, ): Promise => { const manifest = readEngineManifest(engineDir); + parseEngineId(manifest.id); const compress = deps.compress ?? zstdTarCompress; const artifact = await compress(engineDir); const hash = contentHash(artifact); diff --git a/tests/unit/cli/engine-pack.test.ts b/tests/unit/cli/engine-pack.test.ts index 314935fb..28845bf2 100644 --- a/tests/unit/cli/engine-pack.test.ts +++ b/tests/unit/cli/engine-pack.test.ts @@ -71,6 +71,19 @@ describe('packEngineDir', () => { await expect(packEngineDir(empty, privateKey)).rejects.toThrow(/engine\.json/i); }); + test('rejects an engine.json id that is not a valid engine-id, before signing', async () => { + const { privateKey } = generateSigningKeyPair(); + const dir = makeEngineDir(); + writeFileSync(join(dir, 'engine.json'), JSON.stringify({ id: 'webkit-local', soname: 'x' })); + let compressed = false; + const compress = async () => { + compressed = true; + return new Uint8Array(); + }; + await expect(packEngineDir(dir, privateKey, { compress })).rejects.toThrow(/engine-id/); + expect(compressed).toBe(false); + }); + test('does not ship the store-local INSTALLATION_COMPLETE marker inside the artifact', async () => { const { privateKey } = generateSigningKeyPair(); const dir = makeEngineDir(); From 4e829c53c9907f16f868525e9e6f65b98de10a30 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:23:11 -0700 Subject: [PATCH 264/586] chore: trim updater, signing and safeStorage comments to the rules --- src/cli/engine-remote.ts | 7 ++-- src/cli/engine-signature.ts | 24 ++--------- src/cli/update-artifact.ts | 7 +--- src/common/manifest.ts | 11 +---- src/common/signature.ts | 11 ++--- src/main/api/auto-updater.ts | 52 ++++++------------------ src/main/api/safe-storage.ts | 27 +++--------- src/main/api/update-installer.ts | 16 +++----- tests/unit/cli/engine-remote.test.ts | 2 +- tests/unit/main/api/safe-storage.test.ts | 4 +- 10 files changed, 39 insertions(+), 122 deletions(-) diff --git a/src/cli/engine-remote.ts b/src/cli/engine-remote.ts index e73b8b32..dde4559a 100644 --- a/src/cli/engine-remote.ts +++ b/src/cli/engine-remote.ts @@ -1,7 +1,6 @@ /** - * The Ed25519 signature is verified against the release public key BEFORE the - * bytes reach the store. Artifact layout at a feed: `` (the `.tar.zst`), - * `.json`, `.sig`. + * The Ed25519 signature is verified against the resolved feed key BEFORE the bytes reach + * the store. Feed layout: `` (the `.tar.zst`), `.json`, `.sig`. */ import { BunmaskaError } from '../common/errors'; @@ -53,7 +52,7 @@ export const parseRemoteManifest = (text: string): RemoteManifest => { export const zstdTarExtract = async (bytes: Uint8Array, destDir: string): Promise => { const tarBytes = Bun.zstdDecompressSync(bytes); - // extract via cwd, not `-C
` — Windows bsdtar mangles backslash paths + // extract via cwd, not `-C `: Windows bsdtar mangles backslash paths const proc = Bun.spawn(['tar', '-xf', '-'], { cwd: destDir, stdin: tarBytes, diff --git a/src/cli/engine-signature.ts b/src/cli/engine-signature.ts index 37433ae1..e1a5f416 100644 --- a/src/cli/engine-signature.ts +++ b/src/cli/engine-signature.ts @@ -1,9 +1,3 @@ -/** - * The engine-feed trust layer: the signature primitive lives in - * `common/signature.ts` (shared with the auto-updater), so this module owns only - * how the ENGINE public key is resolved. - */ - export { generateSigningKeyPair, signArtifact, @@ -11,23 +5,11 @@ export { type SigningKeyPair, } from '../common/signature'; -/** - * The Bunmaska release engine-signing public key — the **baked-in trust anchor** - * (D041). It is public (not a secret) and is verified automatically, with no - * user knob. The matching private key lives only in the release owner's secret - * store and signs every engine on the official feed. - */ +/** The baked release trust anchor for the official engine feed (D042); public, never a user knob. */ export const RELEASE_ENGINE_PUBKEY = '-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEA9YGBi1+rnrTL0i7pap8uxxhMqNxJFucR7+qbOxe192w=\n-----END PUBLIC KEY-----\n'; -/** - * Resolve the public key to verify an engine artifact, in priority order: - * a self-hosted feed key from `bunmaska.config` (`engine.feed.publicKey`) → the - * baked release anchor → a dev/test `BUNMASKA_ENGINE_PUBKEY` env fallback. The - * explicit self-hosted key wins so a private mirror uses its own key; otherwise - * the baked anchor verifies the official feed. The env path is a dev-only last - * resort that CANNOT override the anchor (D041). - */ +/** A self-hosted `engine.feed.publicKey` wins, else the baked anchor (D042). */ export const resolveEnginePublicKey = (opts: { readonly feedPublicKey?: string | undefined; readonly env?: Record; @@ -38,7 +20,7 @@ export const resolveEnginePublicKey = (opts: { if (RELEASE_ENGINE_PUBKEY.length > 0) { return RELEASE_ENGINE_PUBKEY; } - const env = opts.env ?? process.env; + const env = opts.env ?? process.env; // ponytail: dead while the anchor is baked; drop with engine-command's env const envKey = env['BUNMASKA_ENGINE_PUBKEY']; return envKey !== undefined && envKey.length > 0 ? envKey : undefined; }; diff --git a/src/cli/update-artifact.ts b/src/cli/update-artifact.ts index eca9d6f4..2cc63585 100644 --- a/src/cli/update-artifact.ts +++ b/src/cli/update-artifact.ts @@ -1,7 +1,4 @@ -/** - * Emits the auto-update feed for a built bundle: a `.tar.zst` of the `.app`/AppDir - * plus the `update.json` manifest the runtime `autoUpdater` consumes. - */ +/** `build --update`: the feed's `.tar.zst` and `update.json`, plus a `.sig` for each when signing. */ import { readFileSync, writeFileSync } from 'node:fs'; import { basename, dirname, join } from 'node:path'; @@ -26,7 +23,7 @@ export type UpdateArtifactSpec = { readonly channel: string; readonly os: ArtifactOs; readonly arch: Arch; - /** PEM Ed25519 private key; when set, a detached `.sig` is written beside the artifact. */ + /** PEM Ed25519 private key; when set, `.sig`s are written beside the artifact and `update.json`. */ readonly signingKeyPem?: string; }; diff --git a/src/common/manifest.ts b/src/common/manifest.ts index 485689f7..9b25071a 100644 --- a/src/common/manifest.ts +++ b/src/common/manifest.ts @@ -1,8 +1,4 @@ -/** - * The distributable artifact naming + update-manifest contract, shared by the - * `bunmaska build` packager (which writes `version.json` beside each artifact) and - * the runtime `autoUpdater` (which reads a channel feed's `update.json`). - */ +/** Artifact naming and the `update.json` contract shared by `build --update` and `autoUpdater`. */ import type { Arch } from './platform'; @@ -22,10 +18,7 @@ export type ArtifactSpec = { readonly arch: Arch; }; -/** - * The manifest written to `version.json` beside a build's artifact, and served as - * a channel's `update.json` feed. - */ +/** A channel's `update.json`; `update.json.sig` authenticates all of it before any download. */ export type UpdateManifest = { readonly name: string; readonly version: string; diff --git a/src/common/signature.ts b/src/common/signature.ts index c9d8adda..0fa97207 100644 --- a/src/common/signature.ts +++ b/src/common/signature.ts @@ -1,8 +1,6 @@ /** - * Detached Ed25519 signatures over artifact bytes — the shared trust primitive for - * both the engine feed and the app auto-updater, verified against a baked/configured - * public key. The signature is what makes an artifact authentic; the content hash - * (wyhash) is only a corruption check. + * Detached Ed25519 signatures: the only authenticity check on engine and app-update feeds. + * The wyhash content hash beside them is a corruption check, never trust. */ import { createPrivateKey, createPublicKey, generateKeyPairSync, sign, verify } from 'node:crypto'; @@ -35,10 +33,7 @@ export const isEd25519PublicKey = (pem: string): boolean => { export const signArtifact = (privateKeyPem: string, message: Uint8Array): string => sign(null, message, createPrivateKey(privateKeyPem)).toString('base64'); -/** - * Verify a base64 Ed25519 signature over `message` against a PEM public key. - * Returns false (never throws) on any bad key, malformed signature, or mismatch. - */ +/** Verify a base64 signature over `message`; false (never a throw) for a bad key, sig or mismatch. */ export const verifyArtifact = ( publicKeyPem: string, message: Uint8Array, diff --git a/src/main/api/auto-updater.ts b/src/main/api/auto-updater.ts index e30ce287..ef3e7b67 100644 --- a/src/main/api/auto-updater.ts +++ b/src/main/api/auto-updater.ts @@ -15,49 +15,29 @@ import { app } from './app'; import { DEFAULT_APP_VERSION } from './app-metadata'; import { defaultInstall } from './update-installer'; -/** - * Application self-update — a drop-in subset of Electron's `autoUpdater`, built - * on the same `version.json` contract `bunmaska build` emits. - * - * An {@link EventEmitter} (D023) emitting Electron's event names: - * `checking-for-update`, `update-available`, `update-not-available`, - * `update-downloaded` and `error`. The feed must be https. The default installer - * swaps the bundle via a detached helper script (see `update-installer.ts`); - * its script generators are unit-tested, but the live swap is the one step the - * suite does not exercise end to end. - */ - export type FeedURLOptions = { readonly url: string; /** - * PEM Ed25519 public key that every downloaded artifact's detached `.sig` must - * verify against. Required to download — unsigned updates are refused. This is - * the app publisher's own release key (baked into the app), not a Bunmaska key. + * PEM Ed25519 key that `update.json.sig` and `.sig` must verify against; + * required to download. The publisher's own release key, not a Bunmaska key. */ readonly publicKey?: string; /** If set, a manifest whose `channel` differs is rejected (channel confusion). */ readonly channel?: string; }; -/** - * Caps guarding the decompression step against a zip bomb: a tiny signed-looking - * artifact that expands to gigabytes and OOMs the process. The compressed cap is - * checked against the declared size before any fetch; the decompressed cap after. - */ +/** Sanity bounds on publisher-signed input; the download itself is capped at the signed size. */ export const MAX_COMPRESSED_ARTIFACT_BYTES = 512 * 1024 * 1024; export const MAX_DECOMPRESSED_TAR_BYTES = 2 * 1024 * 1024 * 1024; -/** The zip-bomb guard: throws if a byte length exceeds `max`. */ export const assertSizeWithin = (length: number, max: number, what: string): void => { if (length > max) { throw new Error(`autoUpdater: ${what} exceeds the ${max}-byte limit (got ${length})`); } }; -/** http is refused for any host but these — dev feeds served from localhost. */ const LOCAL_FEED_HOSTS: ReadonlySet = new Set(['localhost', '127.0.0.1', '[::1]']); -/** Transport-secure: https anywhere, http only on localhost. */ const isSecureFeedUrl = (parsed: URL): boolean => parsed.protocol === 'https:' || (parsed.protocol === 'http:' && LOCAL_FEED_HOSTS.has(parsed.hostname)); @@ -70,7 +50,7 @@ export type UpdateInfo = { export type StagedUpdate = { readonly manifest: UpdateManifest; - /** The decompressed `.tar`, alone in a private directory the default installer writes its helper into. */ + /** The decompressed `.tar`, alone in a private dir the default installer also writes into. */ readonly tarPath: string; }; @@ -130,7 +110,7 @@ const httpFetchText = async (url: string): Promise => const httpFetchBytes = async (url: string, maxBytes: number): Promise => readFeedResponse(await fetch(url), url, maxBytes); -/** Electron callers fire and forget, relying on the `error` event; awaiting callers still see the rejection. */ +/** Fire-and-forget callers (Electron's pattern) get failures via `error`; awaiters still reject. */ const markHandled = (promise: Promise): Promise => { promise.catch(() => undefined); return promise; @@ -149,7 +129,7 @@ const productionDeps = (): AutoUpdaterDeps => ({ currentVersion: () => app.getVersion(), currentOs: currentPlatform, currentArch: hostArch, - // Async zstd runs on Bun's threadpool, so a large update never stalls the pumped main thread. + // Async zstd runs on Bun's threadpool; a sync decompress would freeze the pumped main thread. decompress: async (bytes) => new Uint8Array(await Bun.zstdDecompress(bytes)), stage: stageToTmp, install: defaultInstall, @@ -168,11 +148,7 @@ export class AutoUpdaterImpl extends EventEmitter { this.#deps = { ...productionDeps(), ...deps }; } - /** - * Base URL of the channel feed, where `update.json` + artifacts live. Must be - * https (http only for localhost) so a plaintext MITM cannot serve a malicious - * feed. - */ + /** Base URL of the channel feed; https only, except http on localhost for dev. */ setFeedURL(options: FeedURLOptions | string): void { const opts = typeof options === 'string' ? { url: options } : options; if (typeof opts.url !== 'string' || opts.url.length === 0) { @@ -218,7 +194,7 @@ export class AutoUpdaterImpl extends EventEmitter { #requirePublicKey(): string { if (this.#publicKey === undefined || this.#publicKey.length === 0) { throw new Error( - 'autoUpdater: no update public key configured; pass { publicKey } to setFeedURL — unsigned updates are refused', + 'autoUpdater: no update public key configured; pass { publicKey } to setFeedURL (unsigned updates are refused)', ); } return this.#publicKey; @@ -297,12 +273,8 @@ export class AutoUpdaterImpl extends EventEmitter { } /** - * Download, verify and stage the update found by the most recent - * {@link checkForUpdates}. - * - * The signature — not the wyhash — is what makes an update trustworthy: a - * feed/MITM controls the manifest, so its size + hash are self-referential; - * only the publisher's key can produce a valid `.sig`. + * Download, verify and stage the update from the last {@link checkForUpdates}. + * Trust comes only from the two signatures, never the wyhash (see `common/signature.ts`). */ downloadUpdate(): Promise { return markHandled(this.#download()); @@ -357,7 +329,7 @@ export class AutoUpdaterImpl extends EventEmitter { } } - /** Throws if no update has been downloaded. See `update-installer.ts` for the default installer. */ + /** Throws if nothing is downloaded, or if the installer refuses this app's layout. */ quitAndInstall(): void { if (this.#staged === undefined) { throw new Error( @@ -368,6 +340,6 @@ export class AutoUpdaterImpl extends EventEmitter { } } -/** The application updater singleton — Electron's `autoUpdater`. */ +/** Electron's `autoUpdater` singleton. */ export const autoUpdater = new AutoUpdaterImpl(); export type AutoUpdater = AutoUpdaterImpl; diff --git a/src/main/api/safe-storage.ts b/src/main/api/safe-storage.ts index 48c73838..83381cd3 100644 --- a/src/main/api/safe-storage.ts +++ b/src/main/api/safe-storage.ts @@ -7,15 +7,8 @@ import { macosKeychainBackend } from '../platform/macos/cocoa-safe-storage'; import { windowsDpapiBackend } from '../platform/windows/windows-safe-storage'; /** - * Encryption of strings tied to an OS-protected key — the drop-in equivalent of - * Electron's `safeStorage`. The key is a random 32 bytes kept in the OS keyring - * and never written to disk by Bunmaska; strings are sealed with AES-256-GCM. - * - * DIVERGENCE FROM ELECTRON, deliberate: Electron falls back to a `basic_text` - * scheme (an obfuscated, effectively-plaintext key) when no OS keyring exists. - * Bunmaska does NOT — a key sitting next to the ciphertext is not protection. - * With no keyring, `isEncryptionAvailable()` is `false` and encrypt/decrypt - * throw. Blobs are NOT Electron-compatible: the format is native and versioned. + * AES-256-GCM under a keyring-held key (a DPAPI-sealed file on Windows), with no plaintext + * fallback when there is no keyring (D036). Blobs are Bunmaska's own format, not Electron's. */ export type SafeStorage = { @@ -23,7 +16,7 @@ export type SafeStorage = { isEncryptionAvailable(): boolean; /** `plainText` is UTF-8. Throws when encryption is unavailable. */ encryptString(plainText: string): Buffer; - /** Throws on tamper, bad format, or unavailability — never returns garbage. */ + /** Throws on tamper, bad format or unavailability; never returns garbage. */ decryptString(encrypted: Buffer): string; }; @@ -40,13 +33,9 @@ const IV_LENGTH = 12; const TAG_LENGTH = 16; /** Bumped when the layout changes, so a future format can co-exist. */ const VERSION = 0x01; -/** Version + IV + zero-length ciphertext + tag. */ const MIN_BLOB_LENGTH = 1 + IV_LENGTH + TAG_LENGTH; -/** - * Blob layout: `[version:1][iv:12][ciphertext:N][tag:16]`. A random IV per - * encryption (never reused) + the GCM tag make the blob tamper-evident. - */ +/** Blob layout `[version:1][iv:12][ciphertext:N][tag:16]`; a fresh random IV every time. */ const encryptWithKey = (key: Buffer, plainText: string): Buffer => { const iv = randomBytes(IV_LENGTH); const cipher = createCipheriv('aes-256-gcm', key, iv); @@ -69,8 +58,7 @@ const decryptWithKey = (key: Buffer, blob: Buffer): string => { const ciphertext = blob.subarray(1 + IV_LENGTH, blob.length - TAG_LENGTH); const decipher = createDecipheriv('aes-256-gcm', key, iv); decipher.setAuthTag(tag); - // GCM auth failure (tamper / wrong key) makes final() THROW — surface it loudly, - // never return garbage plaintext. + // GCM final() throws on tamper or a wrong key: never return unauthenticated plaintext. return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8'); }; @@ -98,10 +86,7 @@ const isAvailable = (): boolean => { return cachedAvailable; }; -/** - * Read the keyring ONCE per process: only the first op pays the round-trip — on - * Linux, the one blocking D-Bus call. - */ +/** Read the keyring once per process: on Linux it is the one blocking D-Bus call. */ const getKey = (): Buffer => { if (cachedKey === undefined) { const key = getBackend().getOrCreateKey(); diff --git a/src/main/api/update-installer.ts b/src/main/api/update-installer.ts index ea622cd6..e9cb3742 100644 --- a/src/main/api/update-installer.ts +++ b/src/main/api/update-installer.ts @@ -1,8 +1,6 @@ /** - * The default `quitAndInstall` installer: a detached helper script waits for the - * app to exit, extracts the staged tar into a TEMP SIBLING of the install root, - * rename-swaps it into place (a half-extract can never brick the installed - * app), relaunches, and deletes itself. + * The default `quitAndInstall`: a detached helper extracts into a sibling of the install + * root and rename-swaps it in, so a half-finished extract can never brick the installed app. */ import { chmodSync, writeFileSync } from 'node:fs'; @@ -12,11 +10,7 @@ import { currentPlatform } from '../../common/platform'; import { app } from './app'; import type { StagedUpdate } from './auto-updater'; -/** - * Where the running app is installed, derived from the executable path; - * `undefined` means "not an installed bundle" (e.g. `bun main.ts`) and the - * installer must refuse rather than swap a guessed directory. - */ +/** The bundle root around `execPath`, or `undefined` (e.g. `bun main.ts`): never swap a guessed dir. */ export const deriveInstallRoot = (execPath: string, os: ArtifactOs): string | undefined => { if (os === 'macos') { // build-macos layout: .app/Contents/MacOS/ @@ -85,7 +79,7 @@ export const buildShInstallScript = (spec: ShInstallSpec): string => { return [ '#!/bin/sh', '# bunmaska auto-update helper: waits for the app to exit, swaps, relaunches.', - // Every failure path relaunches the old app; a failed update must not leave the user with none. + // Every failure relaunches the old app; a failed update must not leave the user with none. `fail() { rm -rf ${staging}; ${relaunch} & exit 1; }`, `while kill -0 ${spec.pid} 2>/dev/null; do sleep 0.5; done`, `rm -rf ${staging} ${old}`, @@ -158,7 +152,7 @@ export type InstallerDeps = { readonly quit: () => void; }; -/** Write + spawn the helper for a staged update, then quit; refuses un-bundled layouts. */ +/** Writes and spawns the helper, then quits; throws, without quitting, for an unswappable layout. */ export const installStagedUpdate = (staged: StagedUpdate, deps: InstallerDeps): void => { const os = deps.os(); const execPath = deps.execPath(); diff --git a/tests/unit/cli/engine-remote.test.ts b/tests/unit/cli/engine-remote.test.ts index ac5090f5..f2b2f682 100644 --- a/tests/unit/cli/engine-remote.test.ts +++ b/tests/unit/cli/engine-remote.test.ts @@ -127,7 +127,7 @@ describe('installFromUrl', () => { expect(existsSync(engineDir(root, ID))).toBe(false); }); - // The .sig covers the artifact bytes, NOT the .json — so a hostile feed can pair + // The .sig covers the artifact bytes, NOT the .json, so a hostile feed can pair // a validly-signed artifact with a traversal id. The store guard must still refuse. test('rejects a path-traversal id even when the signature is valid', async () => { const root = makeTmpDir(); diff --git a/tests/unit/main/api/safe-storage.test.ts b/tests/unit/main/api/safe-storage.test.ts index abe4ad48..7661cd48 100644 --- a/tests/unit/main/api/safe-storage.test.ts +++ b/tests/unit/main/api/safe-storage.test.ts @@ -7,7 +7,7 @@ import { setSafeStorageBackendForTesting, } from '../../../../src/main/api/safe-storage'; -/** A fake keyring holding a fixed in-memory key — no FFI, no real keyring. */ +/** A fake keyring holding a fixed in-memory key: no FFI, no real keyring. */ const makeFakeBackend = ( key: Buffer = randomBytes(32), ): KeyringBackend & { keyCalls: () => number } => { @@ -36,7 +36,7 @@ afterEach(() => { describe('safeStorage crypto round-trip', () => { test('round-trips ASCII, Unicode, empty, and a long string', () => { setSafeStorageBackendForTesting(makeFakeBackend()); - for (const s of ['hello', 'café — 日本語 — 🎉', '', 'x'.repeat(100_000)]) { + for (const s of ['hello', 'café - 日本語 - 🎉', '', 'x'.repeat(100_000)]) { expect(safeStorage.decryptString(safeStorage.encryptString(s))).toBe(s); } }); From 517759ae1b7543ddc4b5814843e985e948bf1c36 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:23:12 -0700 Subject: [PATCH 265/586] chore: trim GdkPixbuf and GdkMonitor comments to the comment rules --- src/main/platform/linux/gdk-native-image.ts | 38 ++++----------------- src/main/platform/linux/gdk-screen.ts | 30 +++------------- 2 files changed, 10 insertions(+), 58 deletions(-) diff --git a/src/main/platform/linux/gdk-native-image.ts b/src/main/platform/linux/gdk-native-image.ts index 28903c13..e47bb6e4 100644 --- a/src/main/platform/linux/gdk-native-image.ts +++ b/src/main/platform/linux/gdk-native-image.ts @@ -7,29 +7,8 @@ import { loadGioFFI } from './gio-ffi'; import { loadGlibFFI } from './glib-ffi'; import { loadGObjectFFI } from './gobject-ffi'; -/** - * Linux image backend for `nativeImage`, via GdkPixbuf. - * - * DECODE — `gdk_pixbuf_new_from_file` for a path; for a buffer the bytes are - * copied into a refcounted `GBytes` (`g_bytes_new`), wrapped as a - * `GMemoryInputStream` (`g_memory_input_stream_new_from_bytes`), and decoded - * with `gdk_pixbuf_new_from_stream`. A NULL pixbuf (bad path / undecodable - * bytes) is reported empty — no placeholder is fabricated. - * - * SIZE WITHOUT A STRUCT — `gdk_pixbuf_get_width` / `gdk_pixbuf_get_height` are - * plain `int` SCALARS, so `getSize` needs no struct return (the Linux mirror of - * the macOS `pixelsWide`/`pixelsHigh` scalar path). - * - * ENCODE — `gdk_pixbuf_save_to_bufferv(pixbuf, &buffer, &size, "png", NULL, - * NULL, &error)` writes an out `guint8*` and out `gsize`; we copy the buffer out - * with `toArrayBuffer` then `g_free` it. - * - * The decoded handle carries the live `GdkPixbuf*` (as a bigint). We do NOT - * unref it here — its lifetime is the JS `NativeImage`'s, and Bunmaska has no - * finalizer hook yet, so the pixbuf is intentionally leaked for the image's - * lifetime (documented; matches how other Linux handles are retained). The - * transient `GBytes` and `GInputStream` of the buffer path ARE freed. - */ +// ponytail: decoded, resized and cropped GdkPixbufs are never unref'd (one per image for the process +// lifetime); fix with a NativeImageBackend.release driven by a FinalizationRegistry in api/native-image.ts. const handleToPtr = (handle: NativeImageHandle) => (handle === 0n ? null : Number(handle)); @@ -52,7 +31,7 @@ const decodeFromPixbuf = (pixbuf: number | null): DecodedImage => { const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47]; const JPEG_SOI = [0xff, 0xd8, 0xff]; -/** gdk-pixbuf sniffs and hands bytes to every installed loader (TGA, ANI, SVG, ...); only PNG/JPEG are the contract. */ +/** gdk-pixbuf sniffs bytes into every installed loader (TGA, ANI, SVG, ...); the contract is PNG/JPEG only. */ export const isPngOrJpeg = (bytes: Uint8Array): boolean => [PNG_SIGNATURE, JPEG_SOI].some((magic) => magic.every((byte, i) => bytes[i] === byte)); @@ -96,8 +75,6 @@ const encode = (handle: NativeImageHandle, type: string, quality?: number): Uint const pixbufFFI = loadGdkPixbufFFI(); const glib = loadGlibFFI(); - // Out-params: a gchar** slot for the buffer pointer and a gsize* slot for its - // length, mirroring the BigInt64Array out-pointer pattern used elsewhere. const bufferOut = new BigUint64Array(1); const sizeOut = new BigUint64Array(1); // NULL-terminated char** option lists; [NULL] alone means no options. @@ -129,11 +106,12 @@ const encode = (handle: NativeImageHandle, type: string, quality?: number): Uint const copy = new Uint8Array( toArrayBuffer(Number(outPtr) as Parameters[0], 0, size).slice(0), ); + // The out buffer is g_malloc'd: copy, then g_free. glib.symbols.g_free(Number(outPtr) as Parameters[0]); return copy; }; -/** `GdkInterpType` BILINEAR — good quality/speed balance for resampling. */ +/** `GdkInterpType` BILINEAR. */ const GDK_INTERP_BILINEAR = 2; const resize = (handle: NativeImageHandle, width: number, height: number): DecodedImage => { @@ -148,8 +126,6 @@ const resize = (handle: NativeImageHandle, width: number, height: number): Decod height, GDK_INTERP_BILINEAR, ); - // transfer-full: the new pixbuf is the result image's handle, leaked for its lifetime - // exactly like a decoded pixbuf (no finalizer yet — documented above). return decodeFromPixbuf(out === null ? null : Number(out)); }; @@ -175,14 +151,12 @@ const crop = ( if (sub === null) { return EMPTY; } - // new_subpixbuf SHARES the parent's pixels + refs it; copy to a fully independent pixbuf, - // then unref the transient sub (which releases its parent ref). + // A subpixbuf shares (and refs) the parent's pixels: copy it out, then unref the sub. const copy = pixbufFFI.symbols.gdk_pixbuf_copy(sub); loadGObjectFFI().symbols.g_object_unref(sub); return decodeFromPixbuf(copy === null ? null : Number(copy)); }; -/** Linux implementation of {@link NativeImageBackend}. */ export const gdkNativeImageBackend: NativeImageBackend = { decode: (source) => (typeof source === 'string' ? decodePath(source) : decodeBuffer(source)), encodePng: (handle: NativeImageHandle): Uint8Array => encode(handle, 'png'), diff --git a/src/main/platform/linux/gdk-screen.ts b/src/main/platform/linux/gdk-screen.ts index b05814d6..004d6d2f 100644 --- a/src/main/platform/linux/gdk-screen.ts +++ b/src/main/platform/linux/gdk-screen.ts @@ -5,29 +5,6 @@ import { loadGdkFFI } from './gdk-ffi'; import { loadGioFFI } from './gio-ffi'; import { loadGObjectFFI } from './gobject-ffi'; -/** - * Linux display enumeration via GTK4's GdkMonitor model. - * - * `gdk_display_get_monitors(default)` returns a `GListModel*` of `GdkMonitor` - * (owned by GDK — NOT unref'd). `g_list_model_get_n_items` gives the count and - * `g_list_model_get_item(model, i)` returns a transfer-full `GdkMonitor*` that - * MUST be `g_object_unref`'d after reading. Per monitor: - * `gdk_monitor_get_geometry(monitor, GdkRectangle* out)` fills a 4 x i32 - * `[x, y, width, height]` buffer (allocated here as an `Int32Array(4)`), and - * `gdk_monitor_get_scale_factor` gives the integer device-pixel scale. - * - * v1 LIMITATIONS (all documented): - * - workArea == bounds: GTK4's GdkMonitor has no work-area / strut API, so the - * panel/dock inset is not excluded. - * - id == index: GdkMonitor has no stable numeric id; the list index is used. - * - primary == index 0: GTK4 removed the primary-monitor concept; the first - * enumerated monitor is treated as primary. - * - rotation == 0, internal == false: GdkMonitor exposes neither a rotation - * angle nor a built-in-panel flag through a simple scalar getter. - * - getCursorScreenPoint == {0,0}: the GTK4 pointer position needs a surface + - * seat + device, which this read-only enumeration backend does not hold. - */ - const loadFractionalScale = () => dlopen('libgtk-4.so.1', { gdk_monitor_get_scale: { args: [FFIType.pointer], returns: FFIType.f64 }, @@ -56,7 +33,7 @@ const readGeometry = ( return { x: rect[0] ?? 0, y: rect[1] ?? 0, width: rect[2] ?? 0, height: rect[3] ?? 0 }; }; -/** Enumerate connected monitors via the GdkMonitor GListModel. */ +// ponytail: workArea = bounds, id = index, primary = index 0, rotation 0, internal false; GTK4 has no API for them. export const getDisplays = (): readonly RawDisplay[] => { const gdk = loadGdkFFI(); const gio = loadGioFFI(); @@ -66,6 +43,7 @@ export const getDisplays = (): readonly RawDisplay[] => { if (display === null) { return []; } + // GDK owns the model: never unref it. const model = gdk.symbols.gdk_display_get_monitors(display); if (model === null) { return []; @@ -74,6 +52,7 @@ export const getDisplays = (): readonly RawDisplay[] => { const displays: RawDisplay[] = []; for (let i = 0; i < count; i++) { + // transfer-full: unref after reading. const monitor = gio.symbols.g_list_model_get_item(model, i); if (monitor === null) { continue; @@ -96,10 +75,9 @@ export const getDisplays = (): readonly RawDisplay[] => { return displays; }; -/** GTK4 cursor position needs a seat/device; v1 returns {0,0} (documented). */ +// ponytail: always {0,0}; the GTK4 pointer position needs a surface, seat and device. export const getCursorScreenPoint = (): Point => ({ x: 0, y: 0 }); -/** The Linux screen backend the public `screen` API delegates to. */ export const gdkScreenBackend: ScreenBackend = { getDisplays, getCursorScreenPoint, From 306544baf3b6b6c1b3240990f74ab65305bb9c24 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:23:13 -0700 Subject: [PATCH 266/586] fix: honour defaultPath and openDirectory in the Windows open dialog --- src/main/platform/windows/windows-dialog.ts | 22 ++++++++++++++++--- .../platform/windows/windows-dialog.test.ts | 18 +++++++++++++++ 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/src/main/platform/windows/windows-dialog.ts b/src/main/platform/windows/windows-dialog.ts index b447f5c4..2a2466ea 100644 --- a/src/main/platform/windows/windows-dialog.ts +++ b/src/main/platform/windows/windows-dialog.ts @@ -1,5 +1,6 @@ import { type Pointer, ptr, read } from 'bun:ffi'; -import { join } from 'node:path'; +import { statSync } from 'node:fs'; +import { dirname, join } from 'node:path'; import type { DialogBackend } from '../../api/dialog'; import type { MessageBoxSpec, OpenDialogSpec, SaveDialogSpec } from '../macos/cocoa-dialog'; import { wstr } from './win32'; @@ -45,6 +46,7 @@ const OFN_FILTER_OFFSET = 24; // lpstrFilter const OFN_FILTER_INDEX_OFFSET = 44; // nFilterIndex const OFN_FILE_OFFSET = 48; // lpstrFile (output buffer) const OFN_MAX_FILE_OFFSET = 56; // nMaxFile (in WCHARs) +const OFN_INITIAL_DIR_OFFSET = 80; // lpstrInitialDir const OFN_FLAGS_OFFSET = 96; // Flags /** `sizeof(BROWSEINFOW)` (x64) and the field offsets used below. */ const BI_SIZE = 64; @@ -128,6 +130,12 @@ export const parseSelectedPaths = (decoded: string): string[] => { return names.map((name) => join(directory ?? '', name)); }; +/** The folder an open dialog starts in: `defaultPath` itself, or its parent for a file. */ +export const initialDirectory = (defaultPath: string): string => + defaultPath.length === 0 || statSync(defaultPath, { throwIfNoEntry: false })?.isDirectory() + ? defaultPath + : dirname(defaultPath); + /** Read a NUL-separated wide-string list from native memory up to its double-NUL. */ const readResultString = (bufferPtr: ReturnType, maxWchars: number): string => { const units: number[] = []; @@ -176,8 +184,10 @@ const runFileDialog = ( extensions: ReadonlyArray, flags: number, defaultName: string, + initialDir: string, ): string[] => { const filterBuffer = wstr(buildFileFilter(extensions)); + const initialDirBuffer = wstr(initialDir); const fileBuffer = new Uint8Array(FILE_BUFFER_WCHARS * 2); if (defaultName.length > 0) { const name = wstr(defaultName); @@ -192,6 +202,9 @@ const runFileDialog = ( view.setBigUint64(OFN_FILE_OFFSET, BigInt(fileBufferPtr), true); view.setUint32(OFN_MAX_FILE_OFFSET, FILE_BUFFER_WCHARS, true); view.setUint32(OFN_FLAGS_OFFSET, flags, true); + if (initialDir.length > 0) { + view.setBigUint64(OFN_INITIAL_DIR_OFFSET, BigInt(ptr(initialDirBuffer)), true); + } if (call(ptr(ofn)) === 0) { return []; // the user cancelled } @@ -238,8 +251,9 @@ export const windowsDialogBackend: DialogBackend = { }, showOpenDialog(spec: OpenDialogSpec): string[] { - if (spec.canChooseDirectories && !spec.canChooseFiles) { - return runFolderDialog(); + // Electron: an open dialog cannot pick both on Windows, so openDirectory wins. + if (spec.canChooseDirectories) { + return runFolderDialog(); // ponytail: ignores defaultPath (needs a BFFM_SETSELECTION callback) } const flags = OFN_EXPLORER | @@ -253,6 +267,7 @@ export const windowsDialogBackend: DialogBackend = { spec.extensions, flags, '', + initialDirectory(spec.defaultPath), ); }, @@ -264,6 +279,7 @@ export const windowsDialogBackend: DialogBackend = { spec.extensions, flags, spec.defaultName, + '', ); return path ?? ''; }, diff --git a/tests/unit/main/platform/windows/windows-dialog.test.ts b/tests/unit/main/platform/windows/windows-dialog.test.ts index d127c15a..ded1fa38 100644 --- a/tests/unit/main/platform/windows/windows-dialog.test.ts +++ b/tests/unit/main/platform/windows/windows-dialog.test.ts @@ -1,9 +1,12 @@ import { describe, expect, test } from 'bun:test'; import { ptr } from 'bun:ffi'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; import { join } from 'node:path'; import type { MessageBoxSpec } from '../../../../../src/main/platform/macos/cocoa-dialog'; import { buildFileFilter, + initialDirectory, messageBoxResponse, messageBoxUType, parseSelectedPaths, @@ -145,3 +148,18 @@ describe('readFileDialogResult', () => { ]); }); }); + +describe('initialDirectory', () => { + test('a folder opens as itself, a file at its parent, and no path at the system default', () => { + const dir = mkdtempSync(join(tmpdir(), 'bunmaska-dialog-')); + try { + const file = join(dir, 'notes.txt'); + writeFileSync(file, ''); + expect(initialDirectory(dir)).toBe(dir); + expect(initialDirectory(file)).toBe(dir); + expect(initialDirectory('')).toBe(''); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); From 732be7b563d84e00ed4fba43c5ff62e1fb618e15 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:23:27 -0700 Subject: [PATCH 267/586] fix: stop retained Windows trampolines pinning closed windows --- .../platform/windows/windows-webkit-view.ts | 30 ++++++++++++++----- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/src/main/platform/windows/windows-webkit-view.ts b/src/main/platform/windows/windows-webkit-view.ts index 2cda55be..8af38a3b 100644 --- a/src/main/platform/windows/windows-webkit-view.ts +++ b/src/main/platform/windows/windows-webkit-view.ts @@ -212,6 +212,12 @@ export interface WebViewOptions { readonly onNavigationEvent?: (event: NativeNavigationEvent) => void; } +/** What the process-lifetime trampolines call; dispose empties it so they pin no closed window. */ +type TrampolineSinks = { + readonly messages: Map void>; + navigation: ((event: NativeNavigationEvent) => void) | undefined; +}; + /** A live WebKit view + its retained FFI resources. */ export class WindowsWebView { readonly #view: Pointer; @@ -219,6 +225,7 @@ export class WindowsWebView { readonly #hostWindow: bigint; readonly #retainedController: Pointer; readonly #callbacks: JSCallback[]; + readonly #sinks: TrampolineSinks; #disposed = false; #heldButtons = 0; @@ -228,12 +235,14 @@ export class WindowsWebView { hostWindow: bigint, controller: Pointer, callbacks: JSCallback[], + sinks: TrampolineSinks, ) { this.#view = view; this.#page = page; this.#hostWindow = hostWindow; this.#retainedController = controller; this.#callbacks = callbacks; + this.#sinks = sinks; } /** Build a wired WebKit view hosted in a native child of `options.hwnd`. */ @@ -252,19 +261,22 @@ export class WindowsWebView { throw new FFIError('WKUserContentControllerCreate returned NULL'); } - // Register the renderer->main message handlers. Each callback is retained for - // the view's lifetime; the OS invokes it synchronously during the message pump. + const sinks: TrampolineSinks = { + messages: new Map(options.messageHandlers.map(({ name, onMessage }) => [name, onMessage])), + navigation: options.onNavigationEvent, + }; const callbacks: JSCallback[] = []; - for (const handler of options.messageHandlers) { + for (const { name } of options.messageHandlers) { + const onMessage = (body: string): void => sinks.messages.get(name)?.(body); const callback = new JSCallback( (messageRef: Pointer, listenerRef: Pointer | null) => - deliverScriptMessage(messageRef, listenerRef, handler.onMessage, s), + deliverScriptMessage(messageRef, listenerRef, onMessage, s), { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr], returns: FFIType.void }, ); if (callback.ptr === null) { - throw new FFIError(`failed to allocate the '${handler.name}' message-handler trampoline`); + throw new FFIError(`failed to allocate the '${name}' message-handler trampoline`); } - const nameRef = wkString(handler.name); + const nameRef = wkString(name); s.WKUserContentControllerAddScriptMessageHandler(controller, nameRef, callback.ptr, null); wkRelease(nameRef); callbacks.push(callback); @@ -305,10 +317,10 @@ export class WindowsWebView { } if (options.onNavigationEvent !== undefined) { - callbacks.push(...setupNavigationClient(page, options.onNavigationEvent)); + callbacks.push(...setupNavigationClient(page, (event) => sinks.navigation?.(event))); } - return new WindowsWebView(view, page, hostWindow, controller, callbacks); + return new WindowsWebView(view, page, hostWindow, controller, callbacks, sinks); } /** Navigate to a URL (http/https/file/about). */ @@ -432,6 +444,8 @@ export class WindowsWebView { wk.WKUserContentControllerRemoveAllUserScripts(this.#retainedController); this.loadURL('about:blank'); wkRelease(this.#retainedController); + this.#sinks.messages.clear(); + this.#sinks.navigation = undefined; retainTrampolines(this.#callbacks); } } From 37ed75fc529e3edbad9052460cb475c778e41fb5 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:23:29 -0700 Subject: [PATCH 268/586] test: gate Linux menu, dialog and tray cases with visible skips --- tests/integration/linux/dialog.test.ts | 59 ++++---- tests/integration/linux/gtk-menu.test.ts | 169 ++++++++++++----------- tests/integration/linux/tray.test.ts | 110 ++++++++------- 3 files changed, 169 insertions(+), 169 deletions(-) diff --git a/tests/integration/linux/dialog.test.ts b/tests/integration/linux/dialog.test.ts index 2a9531da..03b23d09 100644 --- a/tests/integration/linux/dialog.test.ts +++ b/tests/integration/linux/dialog.test.ts @@ -19,6 +19,7 @@ import { loadGtkFFI } from '../../../src/main/platform/linux/gtk-ffi'; * construction + setter dispatch; it CANNOT verify a real click/pick round-trip. */ const isLinux = currentPlatform() === 'linux'; +const hasDisplay = isLinux && loadGtkFFI().symbols.gtk_init_check() !== 0; describe.skipIf(!isLinux)('GTK dialog FFI + construction (Linux)', () => { test('loadGtkDialogFFI resolves every dialog symbol without throwing', () => { @@ -49,35 +50,33 @@ describe.skipIf(!isLinux)('GTK dialog FFI + construction (Linux)', () => { expect(typeof gobject.symbols.g_object_new).toBe('function'); }); - test('constructs a GtkAlertDialog and calls every setter without crashing', () => { - const gtk = loadGtkFFI(); - if (gtk.symbols.gtk_init_check() === 0) { - return; // No display; symbol-resolution assertions above already proved dispatch. - } - const dialogLib = loadGtkDialogFFI(); - const gobject = loadGtkDialogGObjectFFI(); - const dialog = gobject.symbols.g_object_new( - dialogLib.symbols.gtk_alert_dialog_get_type(), - null, - ); - expect(dialog).not.toBeNull(); - dialogLib.symbols.gtk_alert_dialog_set_message(dialog, cstr('Hello')); - dialogLib.symbols.gtk_alert_dialog_set_detail(dialog, cstr('Details here')); - dialogLib.symbols.gtk_alert_dialog_set_modal(dialog, 1); - const buttons = buildButtonsArray(['OK', 'Cancel']); - dialogLib.symbols.gtk_alert_dialog_set_buttons(dialog, ptr(buttons.array.buffer)); - }); + test.skipIf(!hasDisplay)( + 'constructs a GtkAlertDialog and calls every setter without crashing', + () => { + const dialogLib = loadGtkDialogFFI(); + const gobject = loadGtkDialogGObjectFFI(); + const dialog = gobject.symbols.g_object_new( + dialogLib.symbols.gtk_alert_dialog_get_type(), + null, + ); + expect(dialog).not.toBeNull(); + dialogLib.symbols.gtk_alert_dialog_set_message(dialog, cstr('Hello')); + dialogLib.symbols.gtk_alert_dialog_set_detail(dialog, cstr('Details here')); + dialogLib.symbols.gtk_alert_dialog_set_modal(dialog, 1); + const buttons = buildButtonsArray(['OK', 'Cancel']); + dialogLib.symbols.gtk_alert_dialog_set_buttons(dialog, ptr(buttons.array.buffer)); + }, + ); - test('constructs a GtkFileDialog and calls set_title/set_modal/set_initial_name', () => { - const gtk = loadGtkFFI(); - if (gtk.symbols.gtk_init_check() === 0) { - return; - } - const dialogLib = loadGtkDialogFFI(); - const fileDialog = dialogLib.symbols.gtk_file_dialog_new(); - expect(fileDialog).not.toBeNull(); - dialogLib.symbols.gtk_file_dialog_set_title(fileDialog, cstr('Open')); - dialogLib.symbols.gtk_file_dialog_set_modal(fileDialog, 1); - dialogLib.symbols.gtk_file_dialog_set_initial_name(fileDialog, cstr('untitled.txt')); - }); + test.skipIf(!hasDisplay)( + 'constructs a GtkFileDialog and calls set_title/set_modal/set_initial_name', + () => { + const dialogLib = loadGtkDialogFFI(); + const fileDialog = dialogLib.symbols.gtk_file_dialog_new(); + expect(fileDialog).not.toBeNull(); + dialogLib.symbols.gtk_file_dialog_set_title(fileDialog, cstr('Open')); + dialogLib.symbols.gtk_file_dialog_set_modal(fileDialog, 1); + dialogLib.symbols.gtk_file_dialog_set_initial_name(fileDialog, cstr('untitled.txt')); + }, + ); }); diff --git a/tests/integration/linux/gtk-menu.test.ts b/tests/integration/linux/gtk-menu.test.ts index 7ef37ab6..7b38c331 100644 --- a/tests/integration/linux/gtk-menu.test.ts +++ b/tests/integration/linux/gtk-menu.test.ts @@ -35,6 +35,7 @@ import type { NativeWindow } from '../../../src/main/platform/native'; */ const isLinux = currentPlatform() === 'linux'; +const hasDisplay = isLinux && loadGtkFFI().symbols.gtk_init_check() !== 0; const pump = async (ms: number): Promise => { await new Promise((resolve) => setTimeout(resolve, ms)); @@ -109,90 +110,92 @@ describe.skipIf(!isLinux)('GTK menu backend (Linux)', () => { expect(firedOther).toBe(1); }); - test('constructs a GtkPopoverMenuBar + box from a model without crashing', () => { - if (loadGtkFFI().symbols.gtk_init_check() === 0) { - return; // No display; symbol-resolution + activate routing above proved dispatch. - } - setBindingsForTesting(undefined); - const handle = linuxMenuRealizer.realize([ - { - label: 'File', - type: 'submenu', - enabled: true, - keyEquivalent: '', - submenu: [ - { - label: 'New', - type: 'normal', - enabled: true, - keyEquivalent: 'n', - onClick: () => undefined, - }, - ], - }, - ]); - const entry = getMenuEntry(handle); - const gtk = loadGtkMenuFFI(); - const asPtr = (h: bigint): import('bun:ffi').Pointer => - Number(h) as unknown as import('bun:ffi').Pointer; - const menuBar = gtk.symbols.gtk_popover_menu_bar_new_from_model(asPtr(entry?.model as bigint)); - expect(menuBar).not.toBeNull(); - const box = gtk.symbols.gtk_box_new(1 /* GTK_ORIENTATION_VERTICAL */, 0); - expect(box).not.toBeNull(); - gtk.symbols.gtk_box_append(box, menuBar); - }); + test.skipIf(!hasDisplay)( + 'constructs a GtkPopoverMenuBar + box from a model without crashing', + () => { + setBindingsForTesting(undefined); + const handle = linuxMenuRealizer.realize([ + { + label: 'File', + type: 'submenu', + enabled: true, + keyEquivalent: '', + submenu: [ + { + label: 'New', + type: 'normal', + enabled: true, + keyEquivalent: 'n', + onClick: () => undefined, + }, + ], + }, + ]); + const entry = getMenuEntry(handle); + const gtk = loadGtkMenuFFI(); + const asPtr = (h: bigint): import('bun:ffi').Pointer => + Number(h) as unknown as import('bun:ffi').Pointer; + const menuBar = gtk.symbols.gtk_popover_menu_bar_new_from_model( + asPtr(entry?.model as bigint), + ); + expect(menuBar).not.toBeNull(); + const box = gtk.symbols.gtk_box_new(1 /* GTK_ORIENTATION_VERTICAL */, 0); + expect(box).not.toBeNull(); + gtk.symbols.gtk_box_append(box, menuBar); + }, + ); - test('a window created AFTER setApplicationMenu builds without throwing (menu-bar path)', async () => { - if (loadGtkFFI().symbols.gtk_init_check() === 0) { - return; - } - setBindingsForTesting(undefined); - resetCurrentAppMenuForTesting(); - const handle = linuxMenuRealizer.realize([ - { - label: 'App', - type: 'submenu', - enabled: true, - keyEquivalent: '', - submenu: [ - { - label: 'Quit', - type: 'normal', - enabled: true, - keyEquivalent: 'q', - onClick: () => undefined, - }, - ], - }, - ]); - linuxMenuRealizer.setApplicationMenu(handle); - expect(getCurrentAppMenu()).toBeDefined(); + test.skipIf(!hasDisplay)( + 'a window created AFTER setApplicationMenu builds without throwing (menu-bar path)', + async () => { + setBindingsForTesting(undefined); + resetCurrentAppMenuForTesting(); + const handle = linuxMenuRealizer.realize([ + { + label: 'App', + type: 'submenu', + enabled: true, + keyEquivalent: '', + submenu: [ + { + label: 'Quit', + type: 'normal', + enabled: true, + keyEquivalent: 'q', + onClick: () => undefined, + }, + ], + }, + ]); + linuxMenuRealizer.setApplicationMenu(handle); + expect(getCurrentAppMenu()).toBeDefined(); - const app = createLinuxApplication(); - app.start(); - let window: NativeWindow | undefined; - expect(() => { - window = app.createWindow({ width: 320, height: 240, title: 'MenuBar', show: true }); - }).not.toThrow(); - await pump(100); - window?.close(); - app.quit(); - resetCurrentAppMenuForTesting(); - }); + const app = createLinuxApplication(); + app.start(); + let window: NativeWindow | undefined; + expect(() => { + window = app.createWindow({ width: 320, height: 240, title: 'MenuBar', show: true }); + }).not.toThrow(); + await pump(100); + window?.close(); + app.quit(); + resetCurrentAppMenuForTesting(); + }, + ); - test('the default (no app menu) window path still builds without throwing', async () => { - if (loadGtkFFI().symbols.gtk_init_check() === 0) { - return; - } - resetCurrentAppMenuForTesting(); - const app = createLinuxApplication(); - app.start(); - let window: NativeWindow | undefined; - expect(() => { - window = app.createWindow({ width: 320, height: 240, title: 'NoMenu', show: true }); - }).not.toThrow(); - await pump(100); - window?.close(); - app.quit(); - }); + test.skipIf(!hasDisplay)( + 'the default (no app menu) window path still builds without throwing', + async () => { + resetCurrentAppMenuForTesting(); + const app = createLinuxApplication(); + app.start(); + let window: NativeWindow | undefined; + expect(() => { + window = app.createWindow({ width: 320, height: 240, title: 'NoMenu', show: true }); + }).not.toThrow(); + await pump(100); + window?.close(); + app.quit(); + }, + ); }); diff --git a/tests/integration/linux/tray.test.ts b/tests/integration/linux/tray.test.ts index 3b2a69df..2c6be08c 100644 --- a/tests/integration/linux/tray.test.ts +++ b/tests/integration/linux/tray.test.ts @@ -13,62 +13,60 @@ import { linuxTrayBackend, SNI_XML } from '../../../src/main/platform/linux/sni- // it), so create() is a fast inert no-op here. CI CAN verify: the object-export + GVariant // + pixbuf-accessor symbols resolve, and that the embedded introspection XML actually parses // + the interface resolves (node-info parsing is local — no bus needed). -if (currentPlatform() === 'linux') { - describe('Linux Tray backend (StatusNotifierItem)', () => { - test('the object-export + GVariant-builder + pixbuf symbols resolve', () => { - const gdbus = loadGDBusFFI(); - for (const name of [ - 'g_dbus_connection_register_object', - 'g_dbus_connection_unregister_object', - 'g_dbus_node_info_new_for_xml', - 'g_dbus_node_info_lookup_interface', - 'g_dbus_connection_emit_signal', - 'g_dbus_connection_get_unique_name', - 'g_dbus_method_invocation_return_value', - ] as const) { - expect(typeof gdbus.symbols[name]).toBe('function'); - } - const glib = loadGlibFFI(); - for (const name of [ - 'g_variant_type_new', - 'g_variant_builder_new', - 'g_variant_builder_add_value', - 'g_variant_builder_end', - 'g_variant_new_from_data', - 'g_variant_new_int32', - 'g_variant_new_object_path', - ] as const) { - expect(typeof glib.symbols[name]).toBe('function'); - } - const pix = loadGdkPixbufFFI(); - for (const name of [ - 'gdk_pixbuf_get_pixels', - 'gdk_pixbuf_get_rowstride', - 'gdk_pixbuf_get_n_channels', - 'gdk_pixbuf_get_has_alpha', - ] as const) { - expect(typeof pix.symbols[name]).toBe('function'); - } - }); +describe.skipIf(currentPlatform() !== 'linux')('Linux Tray backend (StatusNotifierItem)', () => { + test('the object-export + GVariant-builder + pixbuf symbols resolve', () => { + const gdbus = loadGDBusFFI(); + for (const name of [ + 'g_dbus_connection_register_object', + 'g_dbus_connection_unregister_object', + 'g_dbus_node_info_new_for_xml', + 'g_dbus_node_info_lookup_interface', + 'g_dbus_connection_emit_signal', + 'g_dbus_connection_get_unique_name', + 'g_dbus_method_invocation_return_value', + ] as const) { + expect(typeof gdbus.symbols[name]).toBe('function'); + } + const glib = loadGlibFFI(); + for (const name of [ + 'g_variant_type_new', + 'g_variant_builder_new', + 'g_variant_builder_add_value', + 'g_variant_builder_end', + 'g_variant_new_from_data', + 'g_variant_new_int32', + 'g_variant_new_object_path', + ] as const) { + expect(typeof glib.symbols[name]).toBe('function'); + } + const pix = loadGdkPixbufFFI(); + for (const name of [ + 'gdk_pixbuf_get_pixels', + 'gdk_pixbuf_get_rowstride', + 'gdk_pixbuf_get_n_channels', + 'gdk_pixbuf_get_has_alpha', + ] as const) { + expect(typeof pix.symbols[name]).toBe('function'); + } + }); - test('the embedded SNI introspection XML parses and the interface resolves', () => { - const node = nodeInfoNewForXml(SNI_XML); - expect(node).not.toBeNull(); - const iface = nodeInfoLookupInterface(node as never, 'org.kde.StatusNotifierItem'); - expect(iface).not.toBeNull(); - }); + test('the embedded SNI introspection XML parses and the interface resolves', () => { + const node = nodeInfoNewForXml(SNI_XML); + expect(node).not.toBeNull(); + const iface = nodeInfoLookupInterface(node as never, 'org.kde.StatusNotifierItem'); + expect(iface).not.toBeNull(); + }); - test('create() is a fast inert no-op when the gate is off', () => { - expect(process.env['BUNMASKA_ENABLE_LINUX_TRAY']).not.toBe('1'); - const start = performance.now(); - const tray = linuxTrayBackend.create('/tmp/nonexistent-icon.png'); - expect(() => { - tray.setToolTip('hi'); - tray.setImage('/tmp/other.png'); - tray.destroy(); - }).not.toThrow(); - expect(performance.now() - start).toBeLessThan(1000); - expect(tray.isDestroyed()).toBe(true); - }); + test('create() is a fast inert no-op when the gate is off', () => { + expect(process.env['BUNMASKA_ENABLE_LINUX_TRAY']).not.toBe('1'); + const start = performance.now(); + const tray = linuxTrayBackend.create('/tmp/nonexistent-icon.png'); + expect(() => { + tray.setToolTip('hi'); + tray.setImage('/tmp/other.png'); + tray.destroy(); + }).not.toThrow(); + expect(performance.now() - start).toBeLessThan(1000); + expect(tray.isDestroyed()).toBe(true); }); -} +}); From 87b8c5f3f885b47f7c78c24f96ec688978eaecbe Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:23:44 -0700 Subject: [PATCH 269/586] chore: trim GTK theme, shell and notification comments to the rules --- src/main/platform/linux/gtk-native-theme.ts | 14 +++----------- src/main/platform/linux/gtk-notification.ts | 3 ++- src/main/platform/linux/gtk-shell.ts | 13 +------------ 3 files changed, 6 insertions(+), 24 deletions(-) diff --git a/src/main/platform/linux/gtk-native-theme.ts b/src/main/platform/linux/gtk-native-theme.ts index bd5c50c3..0b909f7a 100644 --- a/src/main/platform/linux/gtk-native-theme.ts +++ b/src/main/platform/linux/gtk-native-theme.ts @@ -4,17 +4,11 @@ import { loadGObjectFFI } from './gobject-ffi'; import { loadGtkFFI } from './gtk-ffi'; import { connectSignal, makeNotifyCallback } from './gtk-signals'; -/** - * Linux appearance query + change observer. - * - * Reads the `gtk-application-prefer-dark-theme` boolean off the default - * `GtkSettings` via `g_object_get` into a caller-allocated `gboolean` buffer — - * the in-process GTK signal of the user's dark-mode preference. Pure read, no UI. - */ +// Reads GtkSettings' app-level prefer-dark hint (settings.ini, KDE); GNOME keeps its dark style in the +// portal color-scheme. ponytail: read org.freedesktop.appearance color-scheme first (needs a session bus). const PREFER_DARK = 'gtk-application-prefer-dark-theme'; -/** Whether the GTK desktop currently prefers a dark theme. */ export const shouldUseDarkColors = (): boolean => { const settings = loadGtkFFI().symbols.gtk_settings_get_default(); if (settings === null) { @@ -25,11 +19,9 @@ export const shouldUseDarkColors = (): boolean => { return out[0] !== 0; }; -// The settings object outlives the app, so the connection is permanent and its -// callback must stay reachable (else GObject jumps into a freed thunk). +// The settings object outlives the app: its callbacks stay reachable forever, or GObject calls a freed thunk. const retainedThemeCallbacks: JSCallback[] = []; -/** Fire `onChange` whenever the GTK desktop's dark-theme preference flips. */ export const observeAppearanceChange = (onChange: () => void): void => { const settings = loadGtkFFI().symbols.gtk_settings_get_default(); if (settings === null) { diff --git a/src/main/platform/linux/gtk-notification.ts b/src/main/platform/linux/gtk-notification.ts index ae0afa1f..367fd335 100644 --- a/src/main/platform/linux/gtk-notification.ts +++ b/src/main/platform/linux/gtk-notification.ts @@ -24,12 +24,13 @@ const ensureInit = (): boolean => { initialized = true; return true; } + // ponytail: every app notifies as 'Bunmaska'; needs app.getName() passed down from api/notification.ts. const ok = notify.symbols.notify_init(cstr('Bunmaska')) !== 0; initialized = ok; return ok; }; -// ponytail: libnotify's show/close are 25 s sync D-Bus calls; send Notify via linux-dbus callMethodSync (5 s bound) if a wedged daemon matters. +// ponytail: show/close are libnotify's 25 s sync D-Bus calls; bound them via linux-dbus callMethodSync (5 s). const present = (spec: NotificationSpec): NotificationHandle => { const notify = loadLibnotifyFFI(); const gobject = loadGObjectFFI().symbols; diff --git a/src/main/platform/linux/gtk-shell.ts b/src/main/platform/linux/gtk-shell.ts index eca933e4..fc60bb78 100644 --- a/src/main/platform/linux/gtk-shell.ts +++ b/src/main/platform/linux/gtk-shell.ts @@ -4,15 +4,9 @@ import { cstr } from '../cstr'; import { loadGdkFFI } from './gdk-ffi'; import { loadGioFFI } from './gio-ffi'; -/** - * Desktop integration via GIO + GDK — the Linux half of Electron's `shell`. - */ - -/** Open a URL in the default application. Returns whether the OS accepted it. */ export const openExternal = (url: string): boolean => loadGioFFI().symbols.g_app_info_launch_default_for_uri(cstr(url), null, null) === 1; -/** Open a file or folder path with its default application. Returns success. */ export const openPath = (path: string): boolean => loadGioFFI().symbols.g_app_info_launch_default_for_uri( cstr(pathToFileURL(path).href), @@ -20,12 +14,7 @@ export const openPath = (path: string): boolean => null, ) === 1; -/** - * Reveal a file or folder by opening its containing directory in the file - * manager. Approximation: opens the parent folder; it does NOT select the item - * (selecting requires the `org.freedesktop.FileManager1` DBus interface, out of - * scope). - */ +// ponytail: opens the parent folder without selecting the item; selecting needs FileManager1.ShowItems over D-Bus. export const showItemInFolder = (path: string): void => { loadGioFFI().symbols.g_app_info_launch_default_for_uri( cstr(pathToFileURL(dirname(path)).href), From a4c520bf6d0f5d3f5dbe199d5cf50cbd205b5e43 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:23:49 -0700 Subject: [PATCH 270/586] fix: emit error when an update call runs before setFeedURL --- src/main/api/auto-updater.ts | 2 +- tests/unit/main/api/auto-updater.test.ts | 8 +++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/main/api/auto-updater.ts b/src/main/api/auto-updater.ts index ef3e7b67..a2e96c90 100644 --- a/src/main/api/auto-updater.ts +++ b/src/main/api/auto-updater.ts @@ -186,7 +186,7 @@ export class AutoUpdaterImpl extends EventEmitter { #requireFeedURL(): string { if (this.#feedURL === undefined) { - throw new Error('autoUpdater: feed URL is not set; call setFeedURL first'); + throw this.#emitError(new Error('autoUpdater: feed URL is not set; call setFeedURL first')); } return this.#feedURL; } diff --git a/tests/unit/main/api/auto-updater.test.ts b/tests/unit/main/api/auto-updater.test.ts index d240424d..81bade94 100644 --- a/tests/unit/main/api/auto-updater.test.ts +++ b/tests/unit/main/api/auto-updater.test.ts @@ -139,9 +139,11 @@ describe('autoUpdater.setFeedURL / getFeedURL', () => { }); describe('autoUpdater.checkForUpdates', () => { - test('throws when the feed URL is not set', () => { - const { updater } = makeUpdater({}); - expect(updater.checkForUpdates()).rejects.toThrow(/feed URL is not set/); + test('rejects and emits error when the feed URL is not set', async () => { + const h = makeUpdater({}); + await expect(h.updater.checkForUpdates()).rejects.toThrow(/feed URL is not set/); + await expect(h.updater.downloadUpdate()).rejects.toThrow(/feed URL is not set/); + expect(h.events.filter((e) => e === 'error')).toHaveLength(2); }); test('emits update-available and returns the result for a newer version', async () => { From f33d8b8b0261fa3e654cf8e39aff229ef1dafc19 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:24:04 -0700 Subject: [PATCH 271/586] chore: trim WebKitGTK cookie comments to the comment rules --- src/main/platform/linux/webkit-cookies.ts | 18 +++--------------- 1 file changed, 3 insertions(+), 15 deletions(-) diff --git a/src/main/platform/linux/webkit-cookies.ts b/src/main/platform/linux/webkit-cookies.ts index 2c8f857a..d7d82de0 100644 --- a/src/main/platform/linux/webkit-cookies.ts +++ b/src/main/platform/linux/webkit-cookies.ts @@ -12,10 +12,7 @@ import { loadGlibFFI } from './glib-ffi'; import { loadSoupFFI } from './soup-ffi'; import { loadWebKitGtkFFI } from './webkitgtk-ffi'; -/** - * `session.cookies` on Linux (WebKitGTK 6.0) via the default network session's - * `WebKitCookieManager`. Async settles follow the gasync.ts callback rules. - */ +// Async settles follow the gasync.ts callback rules. const COOKIE_TIMEOUT_MS = 15_000; @@ -52,11 +49,7 @@ const readSoupCookie = (cookie: Pointer): Cookie => { }; }; -/** - * Drain a transfer-full `GList` of `SoupCookie*` into JS cookies: each node's - * data is `soup_cookie_free`d and the cells `g_list_free`d (the finish - * contract - anything less leaks per call). - */ +/** Takes a transfer-full `GList` of `SoupCookie*`: every node is `soup_cookie_free`d and the list `g_list_free`d, or each call leaks. */ const drainCookieList = (list: Pointer | null): Cookie[] => { const soup = loadSoupFFI().symbols; const glib = loadGlibFFI().symbols; @@ -102,7 +95,6 @@ export const maxAgeFor = (expirationDate: number | undefined, nowSec: number): n ? -1 : Math.min(0x7fffffff, Math.max(0, Math.round(expirationDate - nowSec))); -/** Build a `SoupCookie*` from the normalized shape. */ const buildSoupCookie = (cookie: Cookie): Pointer => { const soup = loadSoupFFI().symbols; const soupCookie = soup.soup_cookie_new( @@ -142,11 +134,7 @@ export const setCookie = (cookie: Cookie): Promise => { ); }; -/** - * Delete one stored cookie. The match goes through soup_cookie_equal, which - * compares the VALUE too - blanking it made every delete a silent no-op (a CI - * catch), so the cookie is rebuilt verbatim from the read-back fields. - */ +/** soup_cookie_equal compares the VALUE too: rebuild the cookie verbatim, or the delete is a silent no-op. */ const deleteOne = (target: Cookie): Promise => { const wk = loadWebKitGtkFFI().symbols; const soup = loadSoupFFI().symbols; From 3bc4a69b10cc7c5d0e196a46d14bea2457cbae15 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:24:28 -0700 Subject: [PATCH 272/586] chore: trim Linux menu comments to the comment rules --- src/main/platform/linux/gtk-menu.ts | 82 +++++++++-------------------- 1 file changed, 25 insertions(+), 57 deletions(-) diff --git a/src/main/platform/linux/gtk-menu.ts b/src/main/platform/linux/gtk-menu.ts index 4c07ec55..6cc46ebd 100644 --- a/src/main/platform/linux/gtk-menu.ts +++ b/src/main/platform/linux/gtk-menu.ts @@ -6,45 +6,24 @@ import { G_CONNECT_DEFAULT, loadGObjectFFI } from './gobject-ffi'; import { loadGMenuFFI } from './gtk-menu-ffi'; /** - * Builds native GTK 4 application menus from the backend-neutral menu spec and - * routes item clicks back to JS — the Linux equivalent of `cocoa-menu.ts`. - * - * A GTK menu is a `GMenu` *model* paired with a `GSimpleActionGroup`. Each - * clickable item is given a uniquely named `GSimpleAction` (e.g. `menu-0`); the - * model entry references it as `"bunmaska.menu-0"`. Activating the action — by a - * click, an accelerator, or `g_action_group_activate_action` — emits the - * action's `activate` signal, which fires the item's JS `onClick`. This mirrors - * the macOS `bunmaskaMenuAction:` registry pattern. - * - * One action group is shared by the whole tree (submenus add their actions to - * the SAME group), so a single `gtk_widget_insert_action_group(window, - * "bunmaska", group)` makes every item live. - * - * JSCallback lifecycle: the `activate` thunks are LONG-LIVED — they must stay - * reachable for the menu's lifetime or GObject jumps into freed memory on the - * next click (a past SIGSEGV class). Every thunk is therefore retained in the - * per-menu {@link MenuEntry} (held by {@link menuEntries}) and NEVER closed - * synchronously inside its own invocation. In v1 they are not closed at all. + * GMenu models plus one GSimpleActionGroup per realization, inserted as `bunmaska` (D039). + * Activate thunks stay retained for the menu's lifetime and are never closed: GObject jumps + * into a freed trampoline on the next click (a past SIGSEGV). No accelerators are installed (D035). */ -/** ABI shape for `GSimpleAction::activate`: `(action, parameter, user_data) -> void`. */ +/** `GSimpleAction::activate(action, parameter, user_data)`. */ const ACTION_ACTIVATE_CB_DEF = { args: ['ptr', 'ptr', 'ptr'], returns: 'void' } as const; -/** The action-group namespace prefix inserted into the window. */ const ACTION_GROUP_PREFIX = 'bunmaska'; let actionCounter = 0; -/** A fresh, process-unique action name like `menu-0`, `menu-1`, … */ +/** Process-unique, e.g. `menu-0`. */ export const actionName = (): string => `menu-${actionCounter++}`; -/** Namespace an action name for a `GMenu` `detailed_action` (e.g. `bunmaska.menu-0`). */ +/** The `detailed_action` a GMenu item references, e.g. `bunmaska.menu-0`. */ export const detailedAction = (name: string): string => `${ACTION_GROUP_PREFIX}.${name}`; -/** - * The native operations the realizer needs. Handles are `bigint` here; the real - * binding casts to/from `Pointer`. - */ export type Bindings = { gMenuNew(): bigint; gMenuAppend(menu: bigint, label: string, detailed: string): void; @@ -56,23 +35,22 @@ export type Bindings = { gSimpleActionNewStatefulBool(name: string, state: boolean): bigint; gSimpleActionSetEnabled(action: bigint, enabled: number): void; gActionMapAddAction(group: bigint, action: bigint): void; - /** Connect a retained `activate` handler to `action`; returns the retained thunk. */ + /** Returns the thunk, which the caller must retain. */ connectActivate(action: bigint, thunk: () => void): unknown; - /** Programmatically fire `detailed` on `group` (the testing/verification path). */ + /** Fire `detailed` on `group` without a click (tests). */ activateAction(group: bigint, detailed: string, parameter: bigint | null): void; }; -/** The realized native artefacts for one top-level menu, kept in {@link menuEntries}. */ export type MenuEntry = { - /** The top-level `GMenu` model pointer (also the realizer's bigint handle). */ + /** Also the realizer's handle. */ readonly model: bigint; - /** The `GSimpleActionGroup` shared by the whole tree. */ + /** Shared by the whole tree, submenus included. */ readonly group: bigint; - /** Action names (e.g. `menu-0`) in realization order, for lookup/verification. */ + /** In realization order. */ readonly actionNames: string[]; - /** Retained activate thunks — kept alive for the menu's lifetime. */ + /** Activate thunks; must outlive the menu. */ readonly retained: unknown[]; - /** The spec tree this entry was realized from (so a window can re-realize it with role wiring). */ + /** Kept so a window can re-realize the tree with role wiring. */ readonly specs: ReadonlyArray; }; @@ -97,7 +75,6 @@ export const onAppMenuCleared = (listener: () => void): (() => void) => { let injectedBindings: Bindings | undefined; -/** The real GIO/GObject-backed bindings (constructed lazily on Linux). */ const realBindings = (): Bindings => { const gio = loadGMenuFFI(); const gobject = loadGObjectFFI(); @@ -172,7 +149,7 @@ type WalkContext = { const gtkLabel = (label: string): string => label.replace(/_/g, '__').replace(/&(&?)/g, (_match, escaped: string) => (escaped ? '&' : '_')); -/** A click handler's throw is re-thrown on a microtask; unwinding into the GLib dispatch loses it. */ +/** Re-throw a click's error on a microtask: unwinding into the GLib dispatch loses it. */ const guarded = (thunk: () => void) => (): void => { try { thunk(); @@ -216,9 +193,8 @@ const appendItems = ( ctx.b.gMenuAppendSubmenu(model, gtkLabel(spec.label), child); continue; } - // A role item with a per-window dispatcher + a Linux action: wire its activate to the - // dispatcher (which runs the editing command / window op on THIS window). Roles without a - // Linux action (quit/about/…) or without a dispatcher fall through to the inert-label path. + // Role items act on THIS window via dispatchRole. Roles with no Linux action (quit, about) + // or realized without a dispatcher fall through to an inert label (D039). if ( spec.role !== undefined && ctx.dispatchRole !== undefined && @@ -245,12 +221,12 @@ const appendItems = ( wireAction(ctx, model, spec.label, name, action, spec.onClick); continue; } - // A normal item with no onClick: a static, inert label (e.g. a heading). + // No onClick: an inert label. ctx.b.gMenuAppend(model, gtkLabel(spec.label), detailedAction(actionName())); } }; -/** Build a `GMenu` model + `GSimpleActionGroup` for `items` (optionally role-wired); stores + returns the entry. */ +/** Realize `items` (role-wired when `dispatchRole` is given) and store the entry. */ const realizeCore = ( items: ReadonlyArray, dispatchRole?: (spec: NativeMenuItemSpec) => void, @@ -271,24 +247,20 @@ const realizeCore = ( return entry; }; -/** Build a shared model + group for `items` (no role wiring); returns the model handle. */ +/** Realize without role wiring; returns the model handle. */ const realize = (items: ReadonlyArray): bigint => realizeCore(items).model; -/** - * Realize a PER-WINDOW model + group from `items`, wiring role items live to `dispatchRole` - * (so their clicks act on that window's own web view / window). Returns the fresh entry. - */ +/** A per-window realization whose role items dispatch to that window (D039). */ export const realizeForWindow = ( items: ReadonlyArray, dispatchRole: (spec: NativeMenuItemSpec) => void, ): MenuEntry => realizeCore(items, dispatchRole); -/** Install `menuHandle` as the current application menu (applied to future windows). */ +/** `null` also removes the bars of live windows. */ const setApplicationMenu = (menuHandle: bigint | null): void => { + // ponytail: a non-null menu reaches only windows created later; live ones need a bar swap. if (menuHandle === null) { currentAppMenu = undefined; - // Live bars come down too; a later setApplicationMenu(menu) still only - // applies to windows created after it. for (const listener of [...clearListeners]) { listener(); } @@ -302,21 +274,17 @@ const setApplicationMenu = (menuHandle: bigint | null): void => { currentAppMenu = { model: entry.model, group: entry.group, specs: entry.specs }; }; -/** The realized artefacts for a handle, or `undefined`. Used by tests + verification. */ +/** `undefined` for an unknown handle. */ export const getMenuEntry = (handle: bigint): MenuEntry | undefined => menuEntries.get(handle); -/** - * The model + action group of the current application menu, or `undefined` if - * none is set. Read by {@link LinuxWindow} construction to attach a menu bar. - */ +/** Read when a LinuxWindow is constructed, to attach its menu bar. */ export const getCurrentAppMenu = (): CurrentAppMenu | undefined => currentAppMenu; -/** Clear the stored application menu. Test-only. */ +/** Test-only. */ export const resetCurrentAppMenuForTesting = (): void => { currentAppMenu = undefined; }; -/** The Linux native menu realizer (GMenu + GSimpleActionGroup + GtkPopoverMenuBar). */ export const linuxMenuRealizer: MenuRealizer = { realize, setApplicationMenu, From f492e35f7f16278110e4a4f5cb2d428280a3bda1 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:24:06 -0700 Subject: [PATCH 273/586] fix: reuse freed global shortcut ids on Windows --- .../windows/windows-global-shortcut.ts | 26 +++++++++++++------ .../windows/windows-global-shortcut.test.ts | 20 +++++++++++++- 2 files changed, 37 insertions(+), 9 deletions(-) diff --git a/src/main/platform/windows/windows-global-shortcut.ts b/src/main/platform/windows/windows-global-shortcut.ts index 112c6c5d..1298ed53 100644 --- a/src/main/platform/windows/windows-global-shortcut.ts +++ b/src/main/platform/windows/windows-global-shortcut.ts @@ -113,14 +113,21 @@ export type WindowsGlobalShortcutBackend = GlobalShortcutBackend & { dispatchHotkeyMessage(message: number, wParam: bigint): boolean; }; +/** The user32 calls the backend makes. */ +type HotkeyApi = Pick< + ReturnType['symbols'], + 'RegisterHotKey' | 'UnregisterHotKey' +>; + /** * Build a Windows globalShortcut backend. A factory (not just a singleton) so * tests get an isolated id space; production uses {@link windowsGlobalShortcutBackend}. */ -export const createWindowsGlobalShortcutBackend = (): WindowsGlobalShortcutBackend => { +export const createWindowsGlobalShortcutBackend = ( + user32: () => HotkeyApi = () => loadUser32().symbols, +): WindowsGlobalShortcutBackend => { const idByAccelerator = new Map(); const callbackById = new Map void>(); - let nextId = 1; return { isSupported: (): boolean => true, @@ -130,11 +137,14 @@ export const createWindowsGlobalShortcutBackend = (): WindowsGlobalShortcutBacke if (hotkey === undefined) { return false; } - const id = nextId; - if (loadUser32().symbols.RegisterHotKey(0n, id, hotkey.modifiers, hotkey.vk) === 0) { + // The lowest free id keeps ids inside RegisterHotKey's app range (0x0000-0xBFFF). + let id = 1; + while (callbackById.has(id)) { + id += 1; + } + if (user32().RegisterHotKey(0n, id, hotkey.modifiers, hotkey.vk) === 0) { return false; // the OS refused the grab (reserved/already taken) } - nextId += 1; idByAccelerator.set(accelerator, id); callbackById.set(id, callback); return true; @@ -145,15 +155,15 @@ export const createWindowsGlobalShortcutBackend = (): WindowsGlobalShortcutBacke if (id === undefined) { return; } - loadUser32().symbols.UnregisterHotKey(0n, id); + user32().UnregisterHotKey(0n, id); idByAccelerator.delete(accelerator); callbackById.delete(id); }, unregisterAll(): void { - const user32 = loadUser32().symbols; + const api = user32(); for (const id of callbackById.keys()) { - user32.UnregisterHotKey(0n, id); + api.UnregisterHotKey(0n, id); } idByAccelerator.clear(); callbackById.clear(); diff --git a/tests/unit/main/platform/windows/windows-global-shortcut.test.ts b/tests/unit/main/platform/windows/windows-global-shortcut.test.ts index 42228038..580d1083 100644 --- a/tests/unit/main/platform/windows/windows-global-shortcut.test.ts +++ b/tests/unit/main/platform/windows/windows-global-shortcut.test.ts @@ -1,5 +1,8 @@ import { describe, expect, test } from 'bun:test'; -import { acceleratorToHotkey } from '../../../../../src/main/platform/windows/windows-global-shortcut'; +import { + acceleratorToHotkey, + createWindowsGlobalShortcutBackend, +} from '../../../../../src/main/platform/windows/windows-global-shortcut'; /** * Pure accelerator → Windows hot key translation (virtual-key code + RegisterHotKey @@ -64,3 +67,18 @@ describe('acceleratorToHotkey', () => { expect(acceleratorToHotkey('CmdOrCtrl+£')).toBeUndefined(); }); }); + +describe('createWindowsGlobalShortcutBackend', () => { + test('reuses a freed hot-key id, so a register/unregister cycle stays in the app id range', () => { + const ids: number[] = []; + const backend = createWindowsGlobalShortcutBackend(() => ({ + RegisterHotKey: (_hwnd: unknown, id: unknown) => ids.push(Number(id)), + UnregisterHotKey: () => 1, + })); + for (let i = 0; i < 3; i += 1) { + backend.register('Ctrl+Alt+K', () => undefined); + backend.unregister('Ctrl+Alt+K'); + } + expect(ids).toEqual([1, 1, 1]); + }); +}); From 8ba9ef64e87cdf28a78c4cacb2bc409e9e5b74e0 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:25:04 -0700 Subject: [PATCH 274/586] chore: trim Linux dialog comments to the comment rules --- src/main/platform/linux/gtk-dialog.ts | 61 ++++++--------------------- 1 file changed, 13 insertions(+), 48 deletions(-) diff --git a/src/main/platform/linux/gtk-dialog.ts b/src/main/platform/linux/gtk-dialog.ts index ab55390c..2cc6e7de 100644 --- a/src/main/platform/linux/gtk-dialog.ts +++ b/src/main/platform/linux/gtk-dialog.ts @@ -7,33 +7,14 @@ import { loadGlibFFI } from './glib-ffi'; import { loadGObjectFFI } from './gobject-ffi'; import { loadGtkDialogFFI, loadGtkDialogGObjectFFI } from './gtk-dialog-ffi'; -/** - * Native dialogs for the Linux backend — the GTK 4 equivalent of the macOS - * `cocoa-dialog` module. `GtkAlertDialog` powers `showMessageBox`; - * `GtkFileDialog` powers `showOpenDialog`/`showSaveDialog` (both added 4.10, - * always present on the CI runner's GTK 4.12+). - * - * Unlike Cocoa's blocking `runModal`, GTK's dialogs are asynchronous: each - * `gtk_*_choose/open/save` call kicks off the modal dialog and invokes a - * `GAsyncReadyCallback` when the user settles it; the matching `*_finish` reads - * the value. The backend methods therefore return Promises (the `dialog` API's - * `await` flattens them). Callback lifetime rules live in gasync.ts. - */ +// GtkAlertDialog and GtkFileDialog (GTK 4.10+). Callback lifetime rules live in gasync.ts. /** - * The NULL-terminated `const char* const*` button-label array for - * `gtk_alert_dialog_set_buttons`, plus the backing cstr buffers. - * - * GTK reads the array (and each string) only during the synchronous - * `set_buttons` call, but Bun may GC a `Uint8Array` whose pointer was taken via - * `ptr()` the moment it falls out of scope — so the caller MUST keep BOTH the - * returned `array` and every entry of `buffers` referenced until that call - * returns. + * The NULL-terminated `const char* const*` for `gtk_alert_dialog_set_buttons`. Keep `array` + * AND `buffers` referenced until that call returns: Bun may GC a buffer whose `ptr()` was taken. */ export type ButtonsArray = { - /** `BigUint64Array` of cstr pointers, NULL-terminated with a trailing `0n`. */ readonly array: BigUint64Array; - /** One retained NUL-terminated UTF-8 buffer per label. */ readonly buffers: ReadonlyArray; }; @@ -47,11 +28,7 @@ export const buildButtonsArray = (labels: ReadonlyArray): ButtonsArray = return { array, buffers }; }; -/** - * Map the raw `gtk_alert_dialog_choose_finish` button index to the response. - * A valid (`>= 0`) index is returned as-is; the dismissal sentinel (`-1`) and - * any error index fall back to `cancelId` (Electron semantics). - */ +/** A negative `choose_finish` index (Escape or an error) is the `cancelId` response. */ export const mapChooseResult = (index: number, cancelId: number): number => index >= 0 ? index : cancelId; @@ -61,18 +38,14 @@ export const cancelIdForButtons = (buttons: ReadonlyArray): number => { return idx >= 0 ? idx : 0; }; -/** Settle inputs for `gtk_alert_dialog_choose`, with the finish step injectable. */ export type SettleChooseArgs = { readonly result: Pointer; readonly cancelId: number; - /** Calls `gtk_alert_dialog_choose_finish`; may throw on the GError path. */ + /** Calls `gtk_alert_dialog_choose_finish`. */ readonly finish: (result: Pointer) => number; }; -/** - * Produce the message-box response from a `GAsyncResult`. A thrown `finish` - * (the `GError` dismissal path) maps to `cancelId`. - */ +/** The message-box response; a throwing `finish` counts as a dismissal. */ export const settleChoose = (args: SettleChooseArgs): number => { let index: number; try { @@ -83,19 +56,15 @@ export const settleChoose = (args: SettleChooseArgs): number => { return mapChooseResult(index, args.cancelId); }; -/** Settle inputs for `gtk_file_dialog_open/save`, with finish + reader injectable. */ export type SettleFilePathArgs = { readonly result: Pointer; - /** Calls `gtk_file_dialog_*_finish`; returns a `GFile*` or null; may throw. */ + /** Calls `gtk_file_dialog_*_finish`; null on cancel. */ readonly finish: (result: Pointer) => Pointer | null; - /** Reads (and frees) the path out of a non-null `GFile*`. */ + /** Reads the path out of, and releases, a non-null `GFile*`. */ readonly readPath: (file: Pointer) => string; }; -/** - * Produce a file path from a `GAsyncResult`. A null `GFile*` (cancel) or a - * thrown `finish` (dismissal) yields `''`. - */ +/** The chosen path; `''` on cancel or a throwing `finish`. */ export const settleFilePath = (args: SettleFilePathArgs): string => { let file: Pointer | null; try { @@ -136,8 +105,7 @@ const showMessageBox = (spec: { gtk.symbols.gtk_alert_dialog_set_detail(dialog, cstr(spec.detail)); gtk.symbols.gtk_alert_dialog_set_modal(dialog, 1); const labels = spec.buttons.length > 0 ? spec.buttons : ['OK']; - // `set_buttons` copies the labels internally, so the buffers need only outlive - // this synchronous call (not the async choose() round-trip). + // set_buttons copies the labels, so the buffers need only outlive this synchronous call. const buttons = buildButtonsArray(labels); gtk.symbols.gtk_alert_dialog_set_buttons(dialog, ptr(buttons.array.buffer)); const cancelId = cancelIdForButtons(labels); @@ -162,7 +130,7 @@ export const extensionPattern = (ext: string): string => { return `*.${chars.join('')}`; }; -/** Set a default `GtkFileFilter` of `*.ext` patterns, when any extension is given. */ +/** No filter when `extensions` is empty. */ const applyExtensionFilter = ( gtk: ReturnType, fileDialog: Pointer, @@ -182,10 +150,8 @@ const applyExtensionFilter = ( loadGObjectFFI().symbols.g_object_unref(filter); }; -// The open spec's file/directory/multi flags are accepted for API parity but -// not yet applied: v1 always presents a single-file open. Directory selection -// (gtk_file_dialog_select_folder) and multi-select (gtk_file_dialog_open_multiple) -// are out of scope. +// ponytail: single-file open only; openDirectory, multiSelections and defaultPath need +// gtk_file_dialog_select_folder, _open_multiple and _set_initial_folder in gtk-dialog-ffi. const showOpenDialog = (spec: { readonly canChooseFiles: boolean; readonly canChooseDirectories: boolean; @@ -239,7 +205,6 @@ const showSaveDialog = (spec: { ).finally(() => loadGObjectFFI().symbols.g_object_unref(fileDialog)); }; -/** The Linux native dialog backend (single-path open; multi-select is v2). */ export const linuxDialogBackend: DialogBackend = { showMessageBox, showOpenDialog, From feecbe2b904e9492eb267e04cc7413e01e820cdf Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:25:07 -0700 Subject: [PATCH 275/586] chore: trim api feature comments to the comment rules --- src/main/api/accelerator.ts | 22 ++++------ src/main/api/clipboard.ts | 10 +---- src/main/api/dialog.ts | 27 +++++------- src/main/api/global-shortcut.ts | 24 ++--------- src/main/api/menu.ts | 66 ++++++++---------------------- src/main/api/native-image.ts | 36 ++++------------ src/main/api/native-theme.ts | 16 ++------ src/main/api/notification.ts | 18 +------- src/main/api/power-monitor.ts | 15 +++---- src/main/api/power-save-blocker.ts | 27 ++---------- src/main/api/screen.ts | 24 +++-------- src/main/api/shell.ts | 7 +--- src/main/api/tray.ts | 29 ++++--------- 13 files changed, 78 insertions(+), 243 deletions(-) diff --git a/src/main/api/accelerator.ts b/src/main/api/accelerator.ts index de813b74..97b393d2 100644 --- a/src/main/api/accelerator.ts +++ b/src/main/api/accelerator.ts @@ -1,21 +1,14 @@ import type { Platform } from '../../common/platform'; -/** - * Accelerator parsing: Electron's `'CmdOrCtrl+Shift+K'` — zero or more modifier - * tokens and EXACTLY ONE final key, joined by `+`. `CmdOrCtrl` resolves to - * Command (meta) on macOS, Control everywhere else. Empty, keyless, two-key and - * unknown-token accelerators parse to `undefined` so callers can reject them. - */ - export type ParsedAccelerator = { /** Normalised: single letters are upper-cased. */ readonly key: string; readonly shift: boolean; readonly alt: boolean; readonly ctrl: boolean; - /** The Command key on macOS — from a `Cmd`/`Command` token. */ + /** Command: a `Cmd`/`Command` token, or `CmdOrCtrl` on macOS. */ readonly meta: boolean; - /** The Super/Windows key — from a `Super`/`Meta` token. */ + /** A `Super`/`Meta` token: the Windows key, and Command on macOS (Electron). */ readonly super: boolean; }; @@ -114,8 +107,8 @@ const applyModifier = (token: string, mods: Modifiers): boolean => { }; /** - * `undefined` when the accelerator cannot be parsed. `CmdOrCtrl` is preserved as - * a flag AND resolved into the concrete `meta`/`ctrl` flag for `platform`. + * Electron's `'CmdOrCtrl+Shift+K'`: modifiers plus exactly one key. `CmdOrCtrl` resolves to + * `meta` on macOS and `ctrl` elsewhere; empty, keyless, two-key or unknown input is `undefined`. */ export const parseAccelerator = ( accelerator: string, @@ -145,19 +138,18 @@ export const parseAccelerator = ( } const candidate = normaliseKey(token); if (candidate === undefined) { - return undefined; // unknown token + return undefined; } if (key !== undefined) { - return undefined; // more than one final key + return undefined; } key = candidate; } if (key === undefined) { - return undefined; // modifiers but no key + return undefined; } - // Resolve CmdOrCtrl into the concrete platform modifier. const meta = mods.meta || (mods.cmdOrCtrl && platform === 'macos'); const ctrl = mods.ctrl || (mods.cmdOrCtrl && platform !== 'macos'); diff --git a/src/main/api/clipboard.ts b/src/main/api/clipboard.ts index 674352fe..b85398a3 100644 --- a/src/main/api/clipboard.ts +++ b/src/main/api/clipboard.ts @@ -4,13 +4,7 @@ import * as macosClipboard from '../platform/macos/cocoa-clipboard'; import { windowsClipboardBackend } from '../platform/windows/windows-clipboard'; import { type NativeImage, nativeImage } from './native-image'; -/** - * System clipboard access — the drop-in equivalent of Electron's `clipboard`. - * - * Reads are async on every platform even though only GDK 4's read is async-only: - * a deliberate uniform contract, so app code does not branch per OS. - */ - +/** Reads are async everywhere because GDK 4 can only read async (D033); Electron's are sync. */ export type Clipboard = { /** `''` if the clipboard holds no text. */ readText(): Promise; @@ -60,8 +54,6 @@ const { get: getBackend, setForTesting } = selectBackend('clip export const setClipboardBackendForTesting = setForTesting; export const clipboard: Clipboard = { - // `Promise.resolve` flattens a sync string (macOS) or a Promise (Linux/macOS - // wrapper) uniformly into the async contract without double-wrapping. readText() { return Promise.resolve(getBackend().readText()); }, diff --git a/src/main/api/dialog.ts b/src/main/api/dialog.ts index b8baa291..3f012f08 100644 --- a/src/main/api/dialog.ts +++ b/src/main/api/dialog.ts @@ -5,19 +5,15 @@ import * as cocoaDialog from '../platform/macos/cocoa-dialog'; import { windowsDialogBackend } from '../platform/windows/windows-dialog'; import type { BrowserWindow } from './browser-window'; -/** - * Native system dialogs — the drop-in equivalent of Electron's `dialog`. macOS - * and Windows run their panels modally while Linux is truly async - * (`GAsyncReadyCallback`), so {@link DialogBackend} may return a value OR a - * Promise. - */ - export type MessageBoxOptions = { readonly message: string; readonly detail?: string; - /** Defaults to `['OK']`. The FIRST is the default button. */ + /** + * Defaults to `['OK']`; the first is the default. Windows ignores the labels and + * shows OK, OK/Cancel or Yes/No/Cancel by count. + */ readonly buttons?: ReadonlyArray; - /** Styles the `NSAlert` icon on macOS; GtkAlertDialog has no severity, so a no-op on Linux. */ + /** The alert icon on macOS and Windows; ignored on Linux (GtkAlertDialog has no severity). */ readonly type?: cocoaDialog.MessageBoxType; }; @@ -33,14 +29,11 @@ export type FileFilter = { }; export type OpenDialogOptions = { - /** - * Defaults to `['openFile']`. `createDirectory` (macOS) shows the panel's - * "New Folder" button so the user can create a folder while picking. - */ + /** Defaults to `['openFile']`. Linux v1 always picks one file; `createDirectory` is macOS only. */ readonly properties?: ReadonlyArray< 'openFile' | 'openDirectory' | 'multiSelections' | 'createDirectory' >; - /** For a file path, the panel opens at its containing folder. */ + /** macOS only: the folder to open in, or a file path's folder. Ignored on Linux and Windows. */ readonly defaultPath?: string; /** The selectable extensions are the UNION of every filter's. */ readonly filters?: ReadonlyArray; @@ -52,6 +45,7 @@ export type OpenDialogReturnValue = { }; export type SaveDialogOptions = { + /** A file name, or on Windows also a full path. */ readonly defaultPath?: string; /** The allowed extensions are the UNION of every filter's. */ readonly filters?: ReadonlyArray; @@ -78,6 +72,7 @@ export type SaveDialogReturnValue = { readonly filePath: string; }; +/** macOS and Windows panels are modal and return a value; Linux (GTK) is async and returns a Promise. */ export type DialogBackend = { showMessageBox(spec: cocoaDialog.MessageBoxSpec): number | Promise; showOpenDialog(spec: cocoaDialog.OpenDialogSpec): string[] | Promise; @@ -101,7 +96,7 @@ export const setDialogBackendForTesting = setForTesting; const log = createLogger('dialog'); -/** Electron's optional leading window; accepted, but dialogs are not attached as sheets. */ +/** Electron's optional leading window: accepted, but the dialog is not attached as a sheet. */ type WithWindow = [window: BrowserWindow, options: T]; export type Dialog = { @@ -146,7 +141,7 @@ export const dialog: Dialog = { async showSaveDialog(...args) { const options = (args.length === 2 ? args[1] : args[0]) ?? {}; const filePath = await getBackend().showSaveDialog({ - defaultName: options.defaultPath ?? '', + defaultName: options.defaultPath ?? '', // ponytail: macOS/Linux need dir + name split in their backends extensions: flattenFilterExtensions(options.filters), }); return { canceled: filePath.length === 0, filePath }; diff --git a/src/main/api/global-shortcut.ts b/src/main/api/global-shortcut.ts index 3fc599dc..623b9529 100644 --- a/src/main/api/global-shortcut.ts +++ b/src/main/api/global-shortcut.ts @@ -5,21 +5,9 @@ import { macosGlobalShortcutBackend } from '../platform/macos/carbon-global-shor import { windowsGlobalShortcutBackend } from '../platform/windows/windows-global-shortcut'; import { parseAccelerator } from './accelerator'; -/** - * System-wide keyboard shortcuts — the drop-in equivalent of Electron's - * `globalShortcut`. Backends: Carbon (macOS), X11 `XGrabKey` (Linux), - * `RegisterHotKey` (Windows). - * - * Linux is X11-only. Wayland is unsupported in v1 — it needs the - * `org.freedesktop.portal.GlobalShortcuts` desktop portal. - */ - -/** - * The API owns accelerator parsing and the `isRegistered` registry; the backend - * owns the OS grab and dispatching `callback` when the hot key fires. - */ +/** The API owns parsing and the registry; the backend owns the OS grab and firing `callback`. */ export type GlobalShortcutBackend = { - /** The HONEST per-platform answer to whether global shortcuts can be claimed. */ + /** `false` where no grab is possible, e.g. Linux without an X11 display. */ isSupported(): boolean; /** `false` when the OS refused the grab, e.g. the key is already taken. */ register(accelerator: string, callback: () => void): boolean; @@ -29,7 +17,7 @@ export type GlobalShortcutBackend = { }; const macosBackend: GlobalShortcutBackend = macosGlobalShortcutBackend; -const linuxBackend: GlobalShortcutBackend = linuxGlobalShortcutBackend; +const linuxBackend: GlobalShortcutBackend = linuxGlobalShortcutBackend; // ponytail: X11 only; Wayland needs the GlobalShortcuts portal const { get: getBackend, setForTesting } = selectBackend('globalShortcut', { macos: () => macosBackend, @@ -57,10 +45,7 @@ export type GlobalShortcut = { unregisterAll(): void; }; -/** - * `false` — without touching the backend — when the accelerator is unparseable - * or already registered, and when the OS refuses the grab. - */ +/** `false` when the OS refuses the grab, or, without touching the backend, when unparseable or taken. */ const register = (accelerator: string, callback: () => void): boolean => { const key = canonical(accelerator); if (key === undefined || registry.has(key)) { @@ -100,7 +85,6 @@ const unregisterAll = (): void => { getBackend().unregisterAll(); }; -/** The drop-in `globalShortcut` singleton. */ export const globalShortcut: GlobalShortcut = { register, registerAll, diff --git a/src/main/api/menu.ts b/src/main/api/menu.ts index 8d09a463..d400cfee 100644 --- a/src/main/api/menu.ts +++ b/src/main/api/menu.ts @@ -7,20 +7,9 @@ import * as cocoaMenu from '../platform/macos/cocoa-menu'; import { windowsMenuRealizer } from '../platform/windows/windows-menu'; import type { BrowserWindow } from './browser-window'; -/** - * Application and context menus — the drop-in equivalent of Electron's `Menu` / - * `MenuItem`. Realized as `NSMenu` on macOS, `GMenu` on Linux, `HMENU` on - * Windows. - */ - export type MenuItemType = 'normal' | 'separator' | 'submenu' | 'checkbox' | 'radio'; -/** - * A predefined item role (Electron's `MenuItem.role`): default label + - * accelerator + native behavior with no explicit `click`. On macOS a role maps - * to a first-responder selector routed up the responder chain; on Linux to a - * per-window dispatcher in `gtk-menu.ts` `realizeForWindow`. - */ +/** Electron's `MenuItem.role`: a default label, accelerator and native action (D035, D039). */ export type MenuRole = | 'undo' | 'redo' @@ -40,12 +29,8 @@ export type MenuRole = | 'hideOthers' | 'unhide'; -/** - * A role that expands to a whole standard submenu. `appMenu`/`viewMenu` are - * deferred — `appMenu` needs the app name (a menu→app import cycle) and - * `viewMenu` needs role items Bunmaska doesn't expose yet. - */ -export type MenuMacroRole = 'editMenu' | 'windowMenu'; +/** A role that expands into a standard submenu. */ +export type MenuMacroRole = 'editMenu' | 'windowMenu'; // ponytail: no appMenu/fileMenu/viewMenu; unknown roles degrade to plain items export type MenuItemOptions = { readonly label?: string; @@ -55,8 +40,8 @@ export type MenuItemOptions = { readonly enabled?: boolean; /** Only meaningful for `checkbox`/`radio`. */ readonly checked?: boolean; - /** The key must be a SINGLE character, e.g. `'CmdOrCtrl+Q'`. */ - readonly accelerator?: string; + /** e.g. `'CmdOrCtrl+Q'`. macOS only: Linux and Windows neither bind nor show it. */ + readonly accelerator?: string; // ponytail: Linux GtkShortcutController, Windows accelerator table readonly role?: MenuRole | MenuMacroRole; readonly click?: MenuItemClick; readonly submenu?: Menu | ReadonlyArray; @@ -73,9 +58,8 @@ export type MenuItemClick = ( export type MenuWindowAction = 'minimize' | 'close' | 'zoom' | 'togglefullscreen'; /** - * Linux dispatch is `editingCommand` (a WebKitGTK editing command on the focused - * web view) or `windowAction` (a GTK window op). Roles with neither - * (quit/about/hide/…) have no Linux menu-click wiring yet; macOS wires them all. + * `macSelector` drives macOS (D035); `editingCommand` or `windowAction` drive Linux + * (D039). Windows role items are inert. */ const ROLE_DEFAULTS: Record< MenuRole, @@ -233,17 +217,15 @@ const acceleratorKey = (accelerator: string | undefined): string => { return MAC_NAMED_KEYS.get(key) ?? ''; }; -// NSEventModifierFlags bits (macOS): only the modifier portion matters here. +// NSEventModifierFlags modifier bits. const NS_SHIFT = 1n << 17n; const NS_CONTROL = 1n << 18n; const NS_OPTION = 1n << 19n; const NS_COMMAND = 1n << 20n; /** - * The accelerator's modifiers as an `NSEventModifierFlags` mask. Shares the one - * parser in accelerator.ts, which resolves CmdOrCtrl to Command on macOS; Super - * also lands on Command there. Without this, AppKit assumes Command-only and - * multi-modifier accelerators (redo's `Shift+Cmd+Z`) collapse and collide. + * The accelerator's modifiers as `NSEventModifierFlags`. Without it AppKit assumes + * Command only, so redo's `Shift+Cmd+Z` collapses onto undo (D035). */ const acceleratorModifierMask = (accelerator: string | undefined): bigint => { const parsed = accelerator ? parseAccelerator(accelerator, 'macos') : undefined; @@ -365,7 +347,6 @@ const toSpec = (item: MenuItem, siblings: readonly MenuItem[]): NativeMenuItemSp ? { role: item.role, roleSelector: ROLE_DEFAULTS[item.role].macSelector, - // Linux dispatch (one or neither): a WebKitGTK editing command or a GTK window op. ...(ROLE_DEFAULTS[item.role].editingCommand !== undefined ? { editingCommand: ROLE_DEFAULTS[item.role].editingCommand } : {}), @@ -392,9 +373,9 @@ const toSpec = (item: MenuItem, siblings: readonly MenuItem[]): NativeMenuItemSp export type MenuPopupOptions = { /** Defaults to the focused, else most-recent, window. */ readonly window?: BrowserWindow; - /** Content-relative. Defaults to 0 in v1 — NOT the mouse position. */ + /** Content-relative; defaults to 0, not the mouse position (D040). */ readonly x?: number; - /** Content-relative. Defaults to 0 in v1 — NOT the mouse position. */ + /** Content-relative; defaults to 0, not the mouse position (D040). */ readonly y?: number; }; @@ -403,11 +384,7 @@ export type PopupTarget = { closePopupMenu(): void; }; -/** - * Injected by the BrowserWindow module at load, which alone can see the window - * registry, so `menu.ts` needs no runtime import of `browser-window` — that - * would be an import cycle. - */ +/** Installed by browser-window at load: a runtime import of it here would be a cycle. */ export type WindowResolver = { focused(): PopupTarget | undefined; mostRecent(): PopupTarget | undefined; @@ -490,12 +467,10 @@ export class Menu { return getRealizer().realize(toSpecs(this.items)); } - /** `null` removes the application menu everywhere, including bars already installed. */ + /** `null` removes every menu bar, including installed ones; on macOS it empties the main menu. */ static setApplicationMenu(menu: Menu | null): void { applicationMenuSet = true; applicationMenu = menu; - // null must reach the native side too: it clears the menu bar (Electron - // semantics on Windows/Linux; on macOS it empties the main menu). getRealizer().setApplicationMenu(menu === null ? null : menu.realize()); } @@ -503,11 +478,7 @@ export class Menu { return applicationMenu; } - /** - * macOS BLOCKS — AppKit runs a nested tracking loop until dismissed, the same - * nested-loop class as a modal dialog's `runModal` (D020-safe). Linux is - * non-blocking. - */ + /** Blocks on macOS and Windows (a native tracking loop, D040, D020-safe); returns at once on Linux. */ popup(options?: MenuPopupOptions): void { if (windowResolver === undefined) { throw new BunmaskaError('Menu.popup is unavailable: no window backend installed'); @@ -517,10 +488,7 @@ export class Menu { target.popupMenu(this.realize(), options?.x ?? 0, options?.y ?? 0); } - /** - * On macOS this is meaningful only RE-ENTRANTLY, e.g. from an item's own - * click, since `popup` blocks until dismissal. - */ + /** Where `popup` blocks, only useful re-entrantly, e.g. from an item's own click. */ closePopup(window?: BrowserWindow): void { const target = window !== undefined @@ -533,7 +501,7 @@ export class Menu { let applicationMenu: Menu | null = null; let applicationMenuSet = false; -/** Electron's default menu, minus the roles Bunmaska lacks; skipped once the app set one, even `null`. */ +/** Electron's default menu minus unsupported roles; skipped once the app set one, even `null`. */ export const installDefaultApplicationMenu = (appName: string): void => { if (applicationMenuSet) { return; diff --git a/src/main/api/native-image.ts b/src/main/api/native-image.ts index ad912a55..9ceffbd8 100644 --- a/src/main/api/native-image.ts +++ b/src/main/api/native-image.ts @@ -3,32 +3,16 @@ import { gdkNativeImageBackend } from '../platform/linux/gdk-native-image'; import { cocoaNativeImageBackend } from '../platform/macos/cocoa-native-image'; import { windowsNativeImageBackend } from '../platform/windows/windows-native-image'; -/** - * Image loading, querying, and encoding — a drop-in subset of Electron's - * `nativeImage` module. - * - * SIZE — bun:ffi cannot return a struct by value, so Electron's `NSImage.size` - * (an `NSSize` struct) is unreadable across the FFI boundary. Instead each - * backend reports `width`/`height` via SCALAR getters at decode time (macOS - * `NSBitmapImageRep` `pixelsWide`/`pixelsHigh`, both `NSInteger`; Linux - * `gdk_pixbuf_get_width`/`get_height`, both `int`; Windows GDI+), which `getSize` - * returns directly. No struct ever crosses FFI. - * - * The template flag is plain JS metadata: the macOS `NSImage setTemplate:` is - * applied when the image is realized for a `Tray`/menu, not on the decoded rep - * here. `toJPEG`'s quality is honored on macOS; Linux uses GdkPixbuf's default. - * `getScaleFactors` and `{ scaleFactor }` are deferred, not stubbed. - */ - /** Opaque: an ObjC object address (macOS) or a `Pointer` (Linux), both as `bigint`. */ export type NativeImageHandle = bigint; +/** Size comes from scalar getters at decode time: bun:ffi cannot return `NSSize` by value. */ export type DecodedImage = { /** `0n` when empty or the decode failed. */ readonly handle: NativeImageHandle; - /** Pixel width via a SCALAR getter; `0` when empty. */ + /** Pixels; `0` when empty. */ readonly width: number; - /** Pixel height via a SCALAR getter; `0` when empty. */ + /** Pixels; `0` when empty. */ readonly height: number; /** Set for a bad path or undecodable bytes. */ readonly empty: boolean; @@ -36,7 +20,7 @@ export type DecodedImage = { export type NativeImageBackend = { /** A filesystem path or in-memory PNG/JPEG bytes. */ - decode(source: string | Uint8Array): DecodedImage; + decode(source: string | Uint8Array): DecodedImage; // ponytail: no release(handle); images leak for the process life encodePng(handle: NativeImageHandle): Uint8Array; /** `quality` is 0-100. */ encodeJpeg(handle: NativeImageHandle, quality: number): Uint8Array; @@ -70,7 +54,7 @@ export const resolveResizeDimensions = ( if (hasH) { return { width: Math.max(1, Math.round((height / srcH) * srcW)), height: Math.round(height) }; } - return { width: srcW, height: srcH }; // both omitted → unchanged size + return { width: srcW, height: srcH }; }; /** The rect's intersection with the image; `undefined` when empty. */ @@ -132,7 +116,7 @@ export class NativeImage { return Buffer.from(this.#backend.encodePng(this.#handle)); } - /** `quality` is 0-100, default 92. A zero-length `Buffer` when the image is empty. */ + /** `quality` is 0-100, default 92, honored on macOS only. Zero-length when the image is empty. */ toJPEG(quality = 92): Buffer { if (this.#empty) { return Buffer.alloc(0); @@ -170,10 +154,7 @@ export class NativeImage { return new NativeImage(this.#backend, this.#backend.resize(this.#handle, width, height)); } - /** - * `rect` is in px with a top-left origin. A rect entirely outside the image - * yields an empty image; a partially-overflowing one is clamped to bounds. - */ + /** `rect` is in px, top-left origin, and clipped to the image; no overlap yields an empty image. */ crop(rect: { x: number; y: number; width: number; height: number }): NativeImage { if (this.#empty) { return new NativeImage(this.#backend, EMPTY_DECODE); @@ -188,7 +169,7 @@ export class NativeImage { ); } - /** A template is a monochrome icon the OS recolors for light/dark. */ + /** A monochrome icon the OS recolors for light/dark; applied when a Tray or menu uses it. */ setTemplateImage(option: boolean): void { this.#template = option; } @@ -209,7 +190,6 @@ export const setNativeImageBackendForTesting = setForTesting; const EMPTY_DECODE: DecodedImage = { handle: 0n, width: 0, height: 0, empty: true }; -/** The `nativeImage` module — Electron-compatible image load/query/encode. */ export const nativeImage = { /** A bad or unreadable path yields an empty image, not a throw. */ createFromPath(path: string): NativeImage { diff --git a/src/main/api/native-theme.ts b/src/main/api/native-theme.ts index cd93ca8f..1969f41a 100644 --- a/src/main/api/native-theme.ts +++ b/src/main/api/native-theme.ts @@ -12,14 +12,6 @@ import { } from '../platform/macos/cocoa-native-theme'; import { windowsShouldUseDarkColors } from '../platform/windows/windows-native-theme'; -/** - * System appearance — a drop-in equivalent of Electron's `nativeTheme`. Extends - * {@link EventEmitter} for the `updated` event (D023). - * {@link NativeThemeImpl.startObserving}, wired once at startup, makes `updated` - * also fire when the OS appearance changes underneath the app (macOS/Linux; a - * Windows appearance watcher is a follow-up). - */ - export type ThemeSource = 'system' | 'light' | 'dark'; const osShouldUseDark = (): boolean => { @@ -46,6 +38,7 @@ const osPrefersReducedTransparency = (): boolean => currentPlatform() === 'macos' ? macosPrefersReducedTransparency() : false; const observeOsAppearance = (onChange: () => void): void => { + // ponytail: no Windows appearance watcher const platform = currentPlatform(); if (platform === 'macos') { macosObserveAppearance(onChange); @@ -69,12 +62,12 @@ export class NativeThemeImpl extends EventEmitter { return osShouldUseDark(); } - /** macOS Accessibility "Reduce transparency"; always `false` on Linux. */ + /** macOS Accessibility "Reduce transparency"; always `false` elsewhere. */ get prefersReducedTransparency(): boolean { return osPrefersReducedTransparency(); } - /** `'system'` follows the OS; setting this re-themes web views and emits `updated`. */ + /** `'system'` follows the OS. Setting it emits `updated`; only macOS also re-themes its windows. */ get themeSource(): ThemeSource { return this.#themeSource; } @@ -85,7 +78,7 @@ export class NativeThemeImpl extends EventEmitter { this.emit('updated'); } - /** Idempotent: only the first call registers an observer. */ + /** Called once from bootstrap `onReady` (D034); later calls are no-ops. */ startObserving(observe: (onChange: () => void) => void = observeOsAppearance): void { if (this.#observing) { return; @@ -100,6 +93,5 @@ export class NativeThemeImpl extends EventEmitter { } } -/** The application appearance singleton — Electron's `nativeTheme`. */ export const nativeTheme = new NativeThemeImpl(); export type NativeTheme = NativeThemeImpl; diff --git a/src/main/api/notification.ts b/src/main/api/notification.ts index 9a4457f0..32847b9d 100644 --- a/src/main/api/notification.ts +++ b/src/main/api/notification.ts @@ -4,14 +4,6 @@ import { linuxNotificationBackend } from '../platform/linux/gtk-notification'; import { macosNotificationBackend } from '../platform/macos/cocoa-notification'; import { windowsNotificationBackend } from '../platform/windows/windows-notification'; -/** - * Native desktop notifications — the drop-in equivalent of Electron's - * `Notification`. Events: `show`, emitted synchronously from - * {@link Notification.show}, and `close`, which is BEST-EFFORT — macOS - * un-bundled cannot wire it. `click` is deferred and deliberately not - * advertised, so consumers do not rely on an event Bunmaska never delivers. - */ - export type NotificationOptions = { readonly title?: string; readonly body?: string; @@ -34,7 +26,6 @@ export type NotificationHandle = { }; export type NotificationBackend = { - /** The HONEST per-platform answer to whether notifications can be delivered. */ isSupported(): boolean; present(spec: NotificationSpec): NotificationHandle; }; @@ -51,13 +42,12 @@ const { get: getBackend, setForTesting } = selectBackend('N /** @internal */ export const setNotificationBackendForTesting = setForTesting; +/** Emits `show`, and `close` except on macOS, where it never fires. `click` is not delivered. */ export class Notification extends EventEmitter { - /** The bold first line. */ title: string; body: string; /** Secondary line under the title; macOS only, ignored elsewhere. */ subtitle: string; - /** Suppresses the notification sound. */ silent: boolean; #handle: NotificationHandle | undefined; @@ -70,11 +60,7 @@ export class Notification extends EventEmitter { this.silent = options.silent ?? false; } - /** - * `false` on macOS un-bundled — the default notification center is nil without - * an app bundle, so delivery needs packaging. Linux requires libnotify loaded - * and `notify_init` succeeded. - */ + /** `false` on macOS without an app bundle (D30) and on Linux without libnotify. */ static isSupported(): boolean { return getBackend().isSupported(); } diff --git a/src/main/api/power-monitor.ts b/src/main/api/power-monitor.ts index 4e518860..a8fac980 100644 --- a/src/main/api/power-monitor.ts +++ b/src/main/api/power-monitor.ts @@ -7,14 +7,6 @@ import { } from '../platform/macos/cocoa-power'; import { observePowerEvents as windowsObservePowerEvents } from '../platform/windows/windows-power-monitor'; -/** - * System power + screen-lock events — a drop-in subset of Electron's - * `powerMonitor`. An {@link EventEmitter} (D023) emitting `suspend`, `resume`, - * `lock-screen` and `unlock-screen`. macOS screen-lock rides the shared - * distributed observer (D034); the Linux logind leg is gated behind - * `BUNMASKA_ENABLE_LINUX_POWER` and no-ops without a system bus. - */ - const observePower = (handlers: PowerEventHandlers): void => { const platform = currentPlatform(); if (platform === 'macos') { @@ -26,10 +18,14 @@ const observePower = (handlers: PowerEventHandlers): void => { } }; +/** + * Emits `suspend`, `resume`, `lock-screen` and `unlock-screen`. Linux listens only with + * `BUNMASKA_ENABLE_LINUX_POWER=1` and a system bus (D037). + */ export class PowerMonitorImpl extends EventEmitter { #observing = false; - /** Idempotent: only the first call attaches the native observers. */ + /** Called once from bootstrap `onReady` (D034); later calls are no-ops. */ startObserving(observe: (handlers: PowerEventHandlers) => void = observePower): void { if (this.#observing) { return; @@ -57,6 +53,5 @@ export class PowerMonitorImpl extends EventEmitter { } } -/** The system power monitor singleton — Electron's `powerMonitor`. */ export const powerMonitor = new PowerMonitorImpl(); export type PowerMonitor = PowerMonitorImpl; diff --git a/src/main/api/power-save-blocker.ts b/src/main/api/power-save-blocker.ts index 67f7e1d0..f12ae721 100644 --- a/src/main/api/power-save-blocker.ts +++ b/src/main/api/power-save-blocker.ts @@ -3,27 +3,12 @@ import { linuxPowerSaveBlockerBackend } from '../platform/linux/linux-power-save import { cocoaPowerSaveBlockerBackend } from '../platform/macos/cocoa-power-save-blocker'; import { windowsPowerSaveBlockerBackend } from '../platform/windows/windows-power-save-blocker'; -/** - * Block system/display sleep — a drop-in subset of Electron's `powerSaveBlocker`. - * - * The Linux leg holds an `org.freedesktop.ScreenSaver` inhibition cookie over the - * deadlock-safe bounded GDBus method-call primitive, gated behind - * `BUNMASKA_ENABLE_LINUX_POWER_BLOCKER` and a clean no-op with no session bus. - * - * NO-MECHANISM SEMANTICS, matching Electron: when `acquire` returns null — - * headless CI, or the gate is off — `start()` STILL returns a real id and the - * block is a documented no-op. Callers never get -1. - */ - export type PowerSaveBlockerType = 'prevent-app-suspension' | 'prevent-display-sleep'; -/** Opaque and platform-owned: a CFTypeRef id, a D-Bus cookie, … */ +/** Opaque and platform-owned, e.g. an IOPMAssertion id or a D-Bus cookie. */ export type NativeBlocker = unknown; -/** - * `acquire` returns null when no mechanism is available, making the block a - * no-op; `release` is best-effort and must never throw. - */ +/** `acquire` returns null without a mechanism (the block is then a no-op); `release` is best-effort. */ export type PowerSaveBlockerBackend = { acquire: (type: PowerSaveBlockerType) => NativeBlocker | null; release: (handle: NativeBlocker) => void; @@ -59,17 +44,14 @@ export class PowerSaveBlockerImpl { this.#backend = backend; } - /** - * ALWAYS returns a real id, even with no native mechanism. Ids are unique for - * the process lifetime and never reused. - */ + /** A fresh, never-reused id even with no mechanism (Linux without its gate, D038), as in Electron. */ start(type: PowerSaveBlockerType): number { const id = this.#nextId++; let nativeHandle: NativeBlocker | null = null; try { nativeHandle = this.#backend.acquire(type); } catch { - nativeHandle = null; // acquire must never take down the caller; treat as a no-op. + nativeHandle = null; // A failed acquire is a no-op block, never a throw. } this.#blockers.set(id, { type, nativeHandle }); return id; @@ -103,6 +85,5 @@ export class PowerSaveBlockerImpl { } } -/** The power-save-blocker singleton — Electron's `powerSaveBlocker`. */ export const powerSaveBlocker = new PowerSaveBlockerImpl(); export type PowerSaveBlocker = PowerSaveBlockerImpl; diff --git a/src/main/api/screen.ts b/src/main/api/screen.ts index c4e2e8d6..c2746f89 100644 --- a/src/main/api/screen.ts +++ b/src/main/api/screen.ts @@ -5,16 +5,7 @@ import { cocoaScreenBackend } from '../platform/macos/cocoa-screen'; import type { Rect } from '../platform/native'; import { windowsScreenBackend } from '../platform/windows/windows-screen'; -/** - * Display enumeration and geometry — the drop-in equivalent of Electron's - * `screen` module. - * - * Coordinate origin: Electron uses top-left screen coordinates, and every backend - * already reports top-left-origin rects (CoreGraphics global display space, - * GdkMonitor geometry, Win32 monitor rects), so NO flip is applied here. - */ - -/** Top-left screen coordinates. */ +/** Top-left screen coordinates; backends already report top-left rects, so none is flipped here. */ export type Point = { readonly x: number; readonly y: number; @@ -26,10 +17,9 @@ export type Size = { }; /** - * `workArea` excludes OS chrome (menu bar / dock) where the platform reports it; - * on Linux v1 it EQUALS `bounds` — GTK4 GdkMonitor has no work-area API. - * `scaleFactor` is the device-pixel ratio (>= 1), `rotation` degrees clockwise - * (0/90/180/270), `internal` true for a built-in panel. + * `workArea` excludes the taskbar on Windows only; macOS and Linux report `bounds`. macOS also + * reports every display's origin as (0, 0), since CoreGraphics has no scalar origin getter. + * `scaleFactor` is the device-pixel ratio, `rotation` degrees clockwise. */ export type Display = { readonly id: number; @@ -42,7 +32,7 @@ export type Display = { readonly internal: boolean; }; -/** Straight from a backend, before {@link Display}'s derived sizes are built. */ +/** A backend's display, before the derived sizes. */ export type RawDisplay = { readonly id: number; readonly bounds: Rect; @@ -56,7 +46,6 @@ export type RawDisplay = { export type ScreenBackend = { /** Must return at least one display on a real host. */ getDisplays(): readonly RawDisplay[]; - /** Top-left screen coordinates; best-effort. */ getCursorScreenPoint(): Point; }; @@ -116,7 +105,7 @@ const nearestRaw = (point: Point): RawDisplay => { const getAllDisplays = (): Display[] => rawDisplays().map(toDisplay); -/** Origin-anchored on macOS, index 0 on Linux. */ +/** The display the backend marks primary, else the first. */ const getPrimaryDisplay = (): Display => { const displays = rawDisplays(); const first = displays[0]; @@ -158,7 +147,6 @@ const getDisplayMatching = (rect: Rect): Display => { return toDisplay(nearestRaw(center)); }; -/** The `screen` module — Electron-compatible display enumeration and geometry. */ export const screen = { getAllDisplays, getPrimaryDisplay, diff --git a/src/main/api/shell.ts b/src/main/api/shell.ts index 55618954..a837761e 100644 --- a/src/main/api/shell.ts +++ b/src/main/api/shell.ts @@ -3,11 +3,6 @@ import * as gtkShell from '../platform/linux/gtk-shell'; import * as cocoaShell from '../platform/macos/cocoa-shell'; import { windowsShellBackend } from '../platform/windows/windows-shell'; -/** - * Desktop integration — the drop-in equivalent of Electron's `shell`. - * `openExternal` returns a Promise, matching Electron; the rest are synchronous. - */ - export type ShellBackend = { openExternal(url: string): boolean; openPath(path: string): boolean; @@ -39,7 +34,7 @@ const { get: getBackend, setForTesting } = selectBackend('shell', export const setShellBackendForTesting = setForTesting; export type Shell = { - /** Resolves with whether the launch succeeded. */ + /** Resolves `false` for a non-URL or a failed launch. */ openExternal(url: string): Promise; /** Resolves `''` on success, else an error string. */ openPath(path: string): Promise; diff --git a/src/main/api/tray.ts b/src/main/api/tray.ts index 73d5cbd8..66b2bab5 100644 --- a/src/main/api/tray.ts +++ b/src/main/api/tray.ts @@ -11,21 +11,7 @@ import type { NativeImage } from './native-image'; export type TrayImage = string | NativeImage; -/** - * A status-bar / system-tray icon — the drop-in equivalent of Electron's `Tray`. - * The native status item is created eagerly in the constructor. - * - * Linux is a `StatusNotifierItem` over D-Bus, gated behind - * `BUNMASKA_ENABLE_LINUX_TRAY`; without it (and in CI) the tray is an inert - * no-op rather than a throw, so cross-platform code can construct a Tray safely. - * {@link setContextMenu} is accepted but not yet shown on Linux or Windows. - * - * A bad or unreadable image path does not crash; the icon is simply not set. - * `click` fires on macOS only when NO context menu is set — AppKit consumes the - * click to present the menu. `right-click`/`double-click` are deferred. - */ - -/** Per-image options a backend may honour; the macOS template flag today. */ +/** Only macOS honours `template`. */ export type TrayImageOptions = { readonly template?: boolean }; export type TrayInstance = { @@ -57,16 +43,19 @@ const { get: getBackend, setForTesting } = selectBackend('Tray', { /** @internal */ export const setTrayBackendForTesting = setForTesting; -/** A NativeImage's template flag travels with the path the backends load. */ const imageOptions = (image: TrayImage): TrayImageOptions => typeof image === 'string' ? {} : { template: image.isTemplateImage() }; +/** + * `click` fires on macOS only while no context menu is set: AppKit consumes the click to show + * it. Linux needs `BUNMASKA_ENABLE_LINUX_TRAY=1`, else the tray is inert. A bad image path + * leaves the icon unset. Every method is a no-op after {@link destroy}. + */ export class Tray extends EventEmitter { #instance: TrayInstance; #destroyed = false; #iconDir: string | undefined; - /** A {@link NativeImage} is materialized to a temp PNG the backends load by path. */ constructor(image: TrayImage) { super(); this.#instance = getBackend().create(this.#resolveImagePath(image), imageOptions(image)); @@ -85,7 +74,6 @@ export class Tray extends EventEmitter { return path; } - /** No-op after {@link destroy}. */ setToolTip(toolTip: string): void { if (this.#destroyed) { return; @@ -93,7 +81,7 @@ export class Tray extends EventEmitter { this.#instance.setToolTip(toolTip); } - /** Text beside the icon in the macOS status bar. No-op after destroy. */ + /** Text beside the icon in the macOS status bar. */ setTitle(title: string): void { if (this.#destroyed) { return; @@ -101,7 +89,6 @@ export class Tray extends EventEmitter { this.#instance.setTitle(title); } - /** No-op after destroy. */ setImage(image: TrayImage): void { if (this.#destroyed) { return; @@ -109,7 +96,7 @@ export class Tray extends EventEmitter { this.#instance.setImage(this.#resolveImagePath(image), imageOptions(image)); } - /** `null` clears it. Shown on click. No-op after destroy. */ + /** `null` clears it. Shown on click on macOS only; Linux and Windows accept and ignore it. */ setContextMenu(menu: Menu | null): void { if (this.#destroyed) { return; From 25bae5b57d4c2dc7a619f364bf9fdcec91b0e489 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:25:08 -0700 Subject: [PATCH 276/586] chore: trim keyring and power backend comments to the comment rules --- src/main/platform/linux/libsecret-keyring.ts | 29 +++-------- .../platform/linux/linux-power-monitor.ts | 52 +++---------------- .../linux/linux-power-save-blocker.ts | 30 +++-------- 3 files changed, 20 insertions(+), 91 deletions(-) diff --git a/src/main/platform/linux/libsecret-keyring.ts b/src/main/platform/linux/libsecret-keyring.ts index 9c023971..e9e12bf4 100644 --- a/src/main/platform/linux/libsecret-keyring.ts +++ b/src/main/platform/linux/libsecret-keyring.ts @@ -4,39 +4,26 @@ import type { KeyringBackend } from '../../api/safe-storage'; import { cstr } from '../cstr'; import { loadLibsecretFFI, secretSchema } from './libsecret-ffi'; -/** - * Linux libsecret backend for `safeStorage`. The 32-byte key is stored as a - * lowercase-hex STRING (libsecret passwords are NUL-terminated C strings, so raw - * bytes are unsafe) in the default login keyring under a fixed zero-attribute - * schema. - * - * The real store/lookup is SYNCHRONOUS (blocking D-Bus) and is gated behind - * `BUNMASKA_ENABLE_LINUX_KEYRING` — CI never sets it, so the blocking path is - * unreachable under xvfb (echoing the GIO-read deadlock lesson). Crucially, - * `isAvailable()` is CHEAP + NON-BLOCKING: it only checks the gate + that the - * library dlopens; the one blocking keyring round-trip happens lazily inside - * `getOrCreateKey()` (called once, behind the API's key cache). - */ +// The key is stored as hex: libsecret passwords are NUL-terminated C strings. Env gate and a +// non-blocking isAvailable per D036. +// ponytail: one zero-attribute item is shared by every Bunmaska app; scope it with an 'application' attribute. +// ponytail: the *_sync calls block the JS thread on a keyring unlock prompt; prefetch async at app ready. const LABEL = 'Bunmaska safeStorage key'; -/** Whether the live keyring path is enabled. CI leaves this unset → backend reports unavailable. */ const liveKeyringEnabled = (): boolean => process.env['BUNMASKA_ENABLE_LINUX_KEYRING'] === '1'; -/** Read a transfer-full `gchar*` into a JS string and `secret_password_free` it. */ const takePassword = (password: Pointer): string => { const value = new CString(password).toString(); loadLibsecretFFI().symbols.secret_password_free(password); return value; }; -/** Look up the stored hex key. Returns null if absent OR on any error. Never throws. */ +/** null when absent or on any error. */ const lookupHex = (): string | null => { const lib = loadLibsecretFFI(); let result: Pointer | null; try { - // (schema, cancellable=null, error=null, NULL terminator). A NULL error - // out-param means a null return already covers "absent or failed". result = lib.symbols.secret_password_lookup_sync(secretSchema(), null, null, null); } catch { return null; @@ -44,11 +31,9 @@ const lookupHex = (): string | null => { return result === null ? null : takePassword(result); }; -/** Store the hex key. Returns false on any failure. */ const storeHex = (hex: string): boolean => { const lib = loadLibsecretFFI(); try { - // (schema, collection=null→default, label, password, cancellable=null, error=null, NULL) const ok = lib.symbols.secret_password_store_sync( secretSchema(), null, @@ -64,7 +49,7 @@ const storeHex = (hex: string): boolean => { } }; -/** Decode a stored hex value to a 32-byte key, or throw if it is malformed (never overwrite). */ +/** Throws on a malformed stored key: overwriting it would orphan every blob encrypted under it. */ const decodeKey = (hex: string): Buffer => { const buf = Buffer.from(hex, 'hex'); if (buf.length !== 32) { @@ -76,8 +61,6 @@ const decodeKey = (hex: string): Buffer => { }; export const linuxLibsecretBackend: KeyringBackend = { - // Cheap + non-blocking: the gate must be on AND the library must dlopen. The - // actual keyring round-trip is deferred to getOrCreateKey(). isAvailable: () => { if (!liveKeyringEnabled()) { return false; diff --git a/src/main/platform/linux/linux-power-monitor.ts b/src/main/platform/linux/linux-power-monitor.ts index d3186c6b..5405f3d4 100644 --- a/src/main/platform/linux/linux-power-monitor.ts +++ b/src/main/platform/linux/linux-power-monitor.ts @@ -3,32 +3,9 @@ import type { PowerEventHandlers } from '../macos/cocoa-power'; import { loadGlibFFI } from './glib-ffi'; import { getSystemBus, type SignalEvent, type SignalMatch, subscribeSignal } from './linux-dbus'; -/** - * Linux power + screen-lock events for `powerMonitor` — the GDBus/logind equivalent of - * the macOS cocoa-power module. Emits the SAME four events, so it drops into the existing - * `PowerEventHandlers` seam unchanged. - * - * Source: systemd-logind on the SYSTEM bus (well-known name org.freedesktop.login1): - * - Manager :: `PrepareForSleep(b start)` at /org/freedesktop/login1 - * → start=true ⇒ about to suspend ⇒ onSuspend() - * → start=false ⇒ resumed ⇒ onResume() - * - Session :: `Lock()` / `Unlock()` (no args, any session path) → onLockScreen()/onUnlockScreen() - * - * DEADLOCK-SAFE: no `*_call_sync`. We never resolve the active session's object path - * (which would need a blocking method call); we subscribe with a NULL object path so any - * session's Lock/Unlock matches. Signals fire on the GMainContext via the cooperative pump. - * - * KNOWN COARSENESS (matches Electron's Linux limits): the NULL-path Lock/Unlock match can - * over-fire on multi-seat / fast-user-switching systems (another session's lock fires - * ours), and logind only emits Lock/Unlock when something drives the session's `Lock`/ - * `Unlock` D-Bus methods (e.g. `loginctl lock-session`) — a bare `i3lock`/`xscreensaver` - * that does not integrate with logind won't fire `lock-screen`. These are logind limits, - * not bugs. - * - * NO-BUS-SAFE: when there is no system bus / the gate is off (headless CI), {@link getSystemBus} - * returns null and this is a clean no-op — no subscription, no events, no throw, no hang. - * Lazy: zero FFI at import; everything runs inside `observePowerEvents`, called at onReady. - */ +// logind on the system bus (D037). Lock/Unlock are a Bunmaska extension (Electron has none on Linux) and +// match any session path, so they can over-fire on multi-seat systems. +// ponytail: no delay inhibitor, so 'suspend' can land after wake; hold logind Inhibit('sleep', 'delay'). const LOGIN1_NAME = 'org.freedesktop.login1'; const MANAGER_IFACE = 'org.freedesktop.login1.Manager'; @@ -38,10 +15,6 @@ const PREPARE_FOR_SLEEP = 'PrepareForSleep'; const LOCK = 'Lock'; const UNLOCK = 'Unlock'; -/** - * Map a decoded `PrepareForSleep` boolean to the right handler. PURE (no FFI): true ⇒ - * suspend (about to sleep), false ⇒ resume (woke up). - */ export const decodePrepareForSleep = (start: boolean, handlers: PowerEventHandlers): void => { if (start) { handlers.onSuspend(); @@ -51,13 +24,8 @@ export const decodePrepareForSleep = (start: boolean, handlers: PowerEventHandle }; /** - * Read the `b` out of a `PrepareForSleep` `(b)` parameters tuple (the BORROWED tuple is - * never unref'd; the child from `g_variant_get_child_value` is transfer-full → unref'd). - * - * GUARDED against a malformed/forward-incompatible frame: both `g_variant_get_child_value` - * (out-of-range index) and `g_variant_get_boolean` (non-boolean) ABORT the process, and a - * native abort is NOT catchable by the `try/catch` in `subscribeSignal` — so we check the - * child count and the child's type string first and bail (return false) on a mismatch. + * `g_variant_get_child_value` (bad index) and `g_variant_get_boolean` (non-`b`) ABORT, which no + * try/catch can stop: check the count and type first. The tuple is borrowed; the child is transfer-full. */ const readSleepBoolean = (parameters: Pointer): boolean => { const glib = loadGlibFFI(); @@ -78,27 +46,22 @@ const readSleepBoolean = (parameters: Pointer): boolean => { } }; -/** The native operations the observer needs. */ export type PowerDbusDeps = { getSystemBus: () => Pointer | null; subscribeSignal: (conn: Pointer, match: SignalMatch, cb: (e: SignalEvent) => void) => number; - /** Decode a `PrepareForSleep` signal's `parameters` tuple to its boolean. */ readSleepBoolean: (parameters: Pointer) => boolean; }; const realDeps: PowerDbusDeps = { getSystemBus, subscribeSignal, readSleepBoolean }; -/** - * Subscribe to logind's sleep + lock signals on the system bus. A clean no-op when no - * system bus is present. Subscriptions are permanent (process lifetime) — no teardown. - */ +/** A no-op without a system bus; subscriptions last the process lifetime. */ export const observePowerEvents = ( handlers: PowerEventHandlers, deps: PowerDbusDeps = realDeps, ): void => { const bus = deps.getSystemBus(); if (bus === null) { - return; // no logind / no system bus (e.g. headless CI) → no events, no throw, no hang. + return; } deps.subscribeSignal( bus, @@ -110,7 +73,6 @@ export const observePowerEvents = ( }, (event) => decodePrepareForSleep(deps.readSleepBoolean(event.parameters), handlers), ); - // Lock/Unlock carry no args and arrive on a per-session object path; match any path. deps.subscribeSignal(bus, { sender: LOGIN1_NAME, interface: SESSION_IFACE, member: LOCK }, () => handlers.onLockScreen(), ); diff --git a/src/main/platform/linux/linux-power-save-blocker.ts b/src/main/platform/linux/linux-power-save-blocker.ts index cc271743..d3f2f30d 100644 --- a/src/main/platform/linux/linux-power-save-blocker.ts +++ b/src/main/platform/linux/linux-power-save-blocker.ts @@ -8,33 +8,19 @@ import { cstr } from '../cstr'; import { loadGlibFFI } from './glib-ffi'; import { callMethodSync, getSessionBus } from './linux-dbus'; -/** - * Linux power-save blocker via `org.freedesktop.ScreenSaver` inhibition (session bus). - * - * v1 maps BOTH types to ScreenSaver `Inhibit(app, reason) -> u cookie`; `UnInhibit(cookie)` - * releases. This is the freedesktop fallback Chromium itself uses and avoids ALL fd / - * GUnixFDList complexity (a plain u32 cookie, not a Unix fd). Documented coarseness: - * 'prevent-app-suspension' uses the same idle inhibition as 'prevent-display-sleep' — it - * blocks idle-triggered sleep but is slightly less authoritative than logind's - * `Inhibit(what='sleep')` fd path (a future upgrade), which also blocks lid/explicit sleep. - * - * DEADLOCK-SAFE: the only blocking call is the bounded {@link callMethodSync} (5s timeout), - * whose reply is delivered by GIO's private worker thread, not Bunmaska's pump. CI-HANG-SAFE: - * gated behind `BUNMASKA_ENABLE_LINUX_POWER_BLOCKER` (CI never sets it), so `getSessionBus()` - * returns null and `acquire` is a no-op (`start()` still returns an id). - */ +// D038: both types map to ScreenSaver idle inhibition on the gated session bus. +// ponytail: 'prevent-app-suspension' does not block lid or explicit sleep; logind Inhibit('sleep') is the upgrade. const SS_NAME = 'org.freedesktop.ScreenSaver'; const SS_PATH = '/org/freedesktop/ScreenSaver'; const SS_IFACE = 'org.freedesktop.ScreenSaver'; const INHIBIT = 'Inhibit'; const UNINHIBIT = 'UnInhibit'; -const APP_NAME = 'Bunmaska'; +const APP_NAME = 'Bunmaska'; // ponytail: every app inhibits as 'Bunmaska'; needs app.getName() from the api layer. const reasonFor = (type: PowerSaveBlockerType): string => type === 'prevent-display-sleep' ? 'Preventing display sleep' : 'Preventing app suspension'; -/** Build the floating `(ss)` arg tuple for Inhibit (consumed by callMethodSync). */ const inhibitArgs = (app: string, reason: string): Pointer | null => { const glib = loadGlibFFI(); const a = glib.symbols.g_variant_new_string(cstr(app)); @@ -46,7 +32,6 @@ const inhibitArgs = (app: string, reason: string): Pointer | null => { return glib.symbols.g_variant_new_tuple(ptr(children), 2n); // sinks a, r }; -/** Build the floating `(u)` arg tuple for UnInhibit. */ const uninhibitArgs = (cookie: number): Pointer | null => { const glib = loadGlibFFI(); const c = glib.symbols.g_variant_new_uint32(cookie); @@ -57,7 +42,7 @@ const uninhibitArgs = (cookie: number): Pointer | null => { return glib.symbols.g_variant_new_tuple(ptr(children), 1n); }; -/** Read the `u` cookie out of an `(u)` reply tuple, guarding type (a wrong type ABORTS). */ +/** Type-guarded: `g_variant_get_uint32` on a non-`u` child ABORTS. */ const readCookie = (reply: Pointer): number | null => { const glib = loadGlibFFI(); if (glib.symbols.g_variant_n_children(reply) < 1n) { @@ -80,7 +65,7 @@ const readCookie = (reply: Pointer): number | null => { const acquire = (type: PowerSaveBlockerType): NativeBlocker | null => { const bus = getSessionBus(); if (bus === null) { - return null; // gate off / no session bus → no-op (start() still returns an id). + return null; } const args = inhibitArgs(APP_NAME, reasonFor(type)); if (args === null) { @@ -88,7 +73,7 @@ const acquire = (type: PowerSaveBlockerType): NativeBlocker | null => { } const reply = callMethodSync(bus, SS_NAME, SS_PATH, SS_IFACE, INHIBIT, args); if (reply === null) { - return null; // no ScreenSaver impl, or it errored/timed out. + return null; } try { return readCookie(reply); @@ -108,9 +93,8 @@ const release = (handle: NativeBlocker): void => { } const reply = callMethodSync(bus, SS_NAME, SS_PATH, SS_IFACE, UNINHIBIT, args); if (reply !== null) { - loadGlibFFI().symbols.g_variant_unref(reply); // UnInhibit returns an empty tuple; still unref. + loadGlibFFI().symbols.g_variant_unref(reply); // transfer-full, even when empty. } }; -/** The Linux power-save-blocker backend (org.freedesktop.ScreenSaver inhibition). */ export const linuxPowerSaveBlockerBackend: PowerSaveBlockerBackend = { acquire, release }; From 0d3d50ad0aef7e279e19b4e390d50b61982a8230 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:25:31 -0700 Subject: [PATCH 277/586] fix: deliver Windows global shortcuts during modal loops --- .../windows/windows-global-shortcut.ts | 49 ++++++++++++------- .../windows/windows-global-shortcut.test.ts | 35 +++++++++++-- 2 files changed, 61 insertions(+), 23 deletions(-) diff --git a/src/main/platform/windows/windows-global-shortcut.ts b/src/main/platform/windows/windows-global-shortcut.ts index 1298ed53..2fc570b2 100644 --- a/src/main/platform/windows/windows-global-shortcut.ts +++ b/src/main/platform/windows/windows-global-shortcut.ts @@ -1,12 +1,10 @@ import { parseAccelerator } from '../../api/accelerator'; import type { GlobalShortcutBackend } from '../../api/global-shortcut'; import { loadUser32 } from './win32-ffi'; +import { createMessageWindow, type MessageHandler } from './windows-message-window'; -/** - * `RegisterHotKey(NULL, id, …)` claims a system-wide hot key and posts `WM_HOTKEY` to the - * calling (Bun main) thread's queue; the cooperative pump's message inspector routes that - * message back here via {@link WindowsGlobalShortcutBackend.dispatchHotkeyMessage}. - */ +// WM_HOTKEY is posted to a hidden message window: the pump's inspector consumes it via +// dispatchHotkeyMessage, and a modal loop dispatches it to the window's handler instead. /** `WM_HOTKEY` — posted when a registered hot key fires; `wParam` is the hot-key id. */ export const WM_HOTKEY = 0x0312; @@ -125,10 +123,33 @@ type HotkeyApi = Pick< */ export const createWindowsGlobalShortcutBackend = ( user32: () => HotkeyApi = () => loadUser32().symbols, + createWindow: (handler: MessageHandler) => { readonly hwnd: bigint } = createMessageWindow, ): WindowsGlobalShortcutBackend => { const idByAccelerator = new Map(); const callbackById = new Map void>(); + const dispatchHotkeyMessage = (message: number, wParam: bigint): boolean => { + if (message !== WM_HOTKEY) { + return false; + } + const callback = callbackById.get(Number(wParam)); + if (callback === undefined) { + return false; + } + callback(); + return true; + }; + + // Hot keys target a window, not the thread queue: a modal loop (message box, menu, + // window drag) dispatches window messages but drops thread messages. + let window: { readonly hwnd: bigint } | undefined; + const hotkeyWindow = (): bigint => { + window ??= createWindow((message, wParam) => { + dispatchHotkeyMessage(message, wParam); + }); + return window.hwnd; + }; + return { isSupported: (): boolean => true, @@ -142,7 +163,7 @@ export const createWindowsGlobalShortcutBackend = ( while (callbackById.has(id)) { id += 1; } - if (user32().RegisterHotKey(0n, id, hotkey.modifiers, hotkey.vk) === 0) { + if (user32().RegisterHotKey(hotkeyWindow(), id, hotkey.modifiers, hotkey.vk) === 0) { return false; // the OS refused the grab (reserved/already taken) } idByAccelerator.set(accelerator, id); @@ -155,7 +176,7 @@ export const createWindowsGlobalShortcutBackend = ( if (id === undefined) { return; } - user32().UnregisterHotKey(0n, id); + user32().UnregisterHotKey(hotkeyWindow(), id); idByAccelerator.delete(accelerator); callbackById.delete(id); }, @@ -163,23 +184,13 @@ export const createWindowsGlobalShortcutBackend = ( unregisterAll(): void { const api = user32(); for (const id of callbackById.keys()) { - api.UnregisterHotKey(0n, id); + api.UnregisterHotKey(hotkeyWindow(), id); } idByAccelerator.clear(); callbackById.clear(); }, - dispatchHotkeyMessage(message: number, wParam: bigint): boolean { - if (message !== WM_HOTKEY) { - return false; - } - const callback = callbackById.get(Number(wParam)); - if (callback === undefined) { - return false; - } - callback(); - return true; - }, + dispatchHotkeyMessage, }; }; diff --git a/tests/unit/main/platform/windows/windows-global-shortcut.test.ts b/tests/unit/main/platform/windows/windows-global-shortcut.test.ts index 580d1083..53621d6f 100644 --- a/tests/unit/main/platform/windows/windows-global-shortcut.test.ts +++ b/tests/unit/main/platform/windows/windows-global-shortcut.test.ts @@ -2,7 +2,9 @@ import { describe, expect, test } from 'bun:test'; import { acceleratorToHotkey, createWindowsGlobalShortcutBackend, + WM_HOTKEY, } from '../../../../../src/main/platform/windows/windows-global-shortcut'; +import type { MessageHandler } from '../../../../../src/main/platform/windows/windows-message-window'; /** * Pure accelerator → Windows hot key translation (virtual-key code + RegisterHotKey @@ -71,14 +73,39 @@ describe('acceleratorToHotkey', () => { describe('createWindowsGlobalShortcutBackend', () => { test('reuses a freed hot-key id, so a register/unregister cycle stays in the app id range', () => { const ids: number[] = []; - const backend = createWindowsGlobalShortcutBackend(() => ({ - RegisterHotKey: (_hwnd: unknown, id: unknown) => ids.push(Number(id)), - UnregisterHotKey: () => 1, - })); + const backend = createWindowsGlobalShortcutBackend( + () => ({ + RegisterHotKey: (_hwnd: unknown, id: unknown) => ids.push(Number(id)), + UnregisterHotKey: () => 1, + }), + () => ({ hwnd: 1n }), + ); for (let i = 0; i < 3; i += 1) { backend.register('Ctrl+Alt+K', () => undefined); backend.unregister('Ctrl+Alt+K'); } expect(ids).toEqual([1, 1, 1]); }); + + test('grabs hot keys for its own window, so a modal loop still delivers WM_HOTKEY', () => { + const hwnds: unknown[] = []; + let windowHandler: MessageHandler | undefined; + const backend = createWindowsGlobalShortcutBackend( + () => ({ + RegisterHotKey: (hwnd: unknown) => hwnds.push(hwnd), + UnregisterHotKey: () => 1, + }), + (handler) => { + windowHandler = handler; + return { hwnd: 42n }; + }, + ); + let fired = 0; + backend.register('Ctrl+Alt+K', () => { + fired += 1; + }); + windowHandler?.(WM_HOTKEY, 1n, 0n); + expect(hwnds).toEqual([42n]); + expect(fired).toBe(1); + }); }); From 72a60718f5d79d6fa17f3cc991c0d9bc74b080c6 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:25:54 -0700 Subject: [PATCH 278/586] fix: make the engine store lock a pidfile that survives release races --- src/cli/engine-store.ts | 72 ++++++++++++++++++++++------- tests/unit/cli/engine-store.test.ts | 46 +++++++++++++++++- 2 files changed, 100 insertions(+), 18 deletions(-) diff --git a/src/cli/engine-store.ts b/src/cli/engine-store.ts index 08b0f0de..2a663fa6 100644 --- a/src/cli/engine-store.ts +++ b/src/cli/engine-store.ts @@ -9,19 +9,16 @@ */ import { - closeSync, cpSync, existsSync, mkdirSync, mkdtempSync, - openSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, - writeSync, } from 'node:fs'; import { createHash } from 'node:crypto'; import { homedir } from 'node:os'; @@ -358,40 +355,81 @@ export const gc = async (root: string, deps: GcDeps = {}): Promise => const sleep = (ms: number): Promise => Bun.sleep(ms); +const errorCode = (error: unknown): string | undefined => (error as NodeJS.ErrnoException).code; + +const isAlive = (pid: number): boolean => { + try { + process.kill(pid, 0); + return true; + } catch (error) { + return errorCode(error) === 'EPERM'; + } +}; + +/** Whether a held lock may be stolen: its holder died, or it is older than STALE_LOCK_MS. */ +const isStaleLock = (lock: string): boolean => { + const pid = Number.parseInt(readFileSync(lock, 'utf8'), 10); + return ( + (Number.isInteger(pid) && !isAlive(pid)) || Date.now() - statSync(lock).mtimeMs > STALE_LOCK_MS + ); +}; + +/** Remove the lock only while it still holds `pid`: a stealer may have replaced it. */ +const releaseLock = (lock: string, pid: string): void => { + let holder: string; + try { + holder = readFileSync(lock, 'utf8'); + } catch (error) { + if (errorCode(error) === 'ENOENT') { + return; + } + throw error; + } + if (holder === pid) { + rmSync(lock, { force: true }); + } +}; + /** - * Run `fn` under the store's cross-process lock. A lock older than - * STALE_LOCK_MS is stolen; the lock is always released, even if `fn` throws. + * Run `fn` under the store's cross-process lock, a pidfile. A stale lock is stolen; + * the lock is released even if `fn` throws, but only while it still holds our pid. + * ponytail: two contenders stealing one stale lock at once can both enter; add a steal lock if that bites. */ export const withLock = async (root: string, fn: () => Promise): Promise => { mkdirSync(root, { recursive: true }); const lock = lockPath(root); + const pid = String(process.pid); const deadline = Date.now() + LOCK_TIMEOUT_MS; for (;;) { try { - const fd = openSync(lock, 'wx'); - writeSync(fd, String(process.pid)); - closeSync(fd); + writeFileSync(lock, pid, { flag: 'wx' }); break; } catch (error) { - if ((error as NodeJS.ErrnoException).code !== 'EEXIST') { + if (errorCode(error) !== 'EEXIST') { throw error; } - const age = Date.now() - statSync(lock).mtimeMs; - if (age > STALE_LOCK_MS) { + } + try { + if (isStaleLock(lock)) { rmSync(lock, { force: true }); continue; } - if (Date.now() > deadline) { - throw new BunmaskaError(`engine store: timed out acquiring lock at ${lock}`, { - code: 'ERR_ENGINE_LOCK', - }); + } catch (error) { + if (errorCode(error) === 'ENOENT') { + continue; // released between our attempt and the check } - await sleep(LOCK_RETRY_MS); + throw error; } + if (Date.now() > deadline) { + throw new BunmaskaError(`engine store: timed out acquiring lock at ${lock}`, { + code: 'ERR_ENGINE_LOCK', + }); + } + await sleep(LOCK_RETRY_MS); } try { return await fn(); } finally { - rmSync(lock, { force: true }); + releaseLock(lock, pid); } }; diff --git a/tests/unit/cli/engine-store.test.ts b/tests/unit/cli/engine-store.test.ts index 27d2df5d..40df1e1a 100644 --- a/tests/unit/cli/engine-store.test.ts +++ b/tests/unit/cli/engine-store.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, test } from 'bun:test'; -import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { contentHash } from '../../../src/common/manifest'; @@ -346,6 +346,50 @@ describe('withLock', () => { expect(existsSync(join(root, '__dirlock'))).toBe(false); }); + test('steals a lock left behind by a dead process instead of timing out', async () => { + const root = makeTmpDir(); + const dead = Bun.spawnSync([process.execPath, '-e', '']).pid; + writeFileSync(join(root, '__dirlock'), String(dead)); + expect(await withLock(root, async () => 'ran')).toBe('ran'); + }, 3000); + + test('releases only a lock it still owns', async () => { + const root = makeTmpDir(); + const lock = join(root, '__dirlock'); + await withLock(root, async () => { + writeFileSync(lock, '424242'); // another process took the lock over + }); + expect(readFileSync(lock, 'utf8')).toBe('424242'); + }); + + test('concurrent processes never error or overlap in the critical section', async () => { + const root = makeTmpDir(); + const store = join(import.meta.dir, '../../../src/cli/engine-store.ts'); + const inside = join(root, 'inside'); + const worker = ` + import { rmSync, writeFileSync } from 'node:fs'; + import { withLock } from ${JSON.stringify(store)}; + let errors = 0; + const end = Date.now() + 1500; + while (Date.now() < end) { + try { + await withLock(${JSON.stringify(root)}, async () => { + writeFileSync(${JSON.stringify(inside)}, '', { flag: 'wx' }); + rmSync(${JSON.stringify(inside)}); + }); + } catch (error) { + errors += 1; + console.error(String(error)); + } + } + console.log(errors);`; + const procs = Array.from({ length: 4 }, () => + Bun.spawn([process.execPath, '-e', worker], { stdout: 'pipe', stderr: 'pipe' }), + ); + const outs = await Promise.all(procs.map((p) => new Response(p.stdout).text())); + expect(outs.map((o) => o.trim())).toEqual(['0', '0', '0', '0']); + }, 15000); + test('serializes concurrent critical sections', async () => { const root = makeTmpDir(); const trace: string[] = []; From e29855dae1d1edb4a83971a873743c05c73a19d8 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:25:57 -0700 Subject: [PATCH 279/586] refactor: drop the unreachable empty-buffer branch in pixbuf decode --- src/main/platform/linux/gdk-native-image.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/platform/linux/gdk-native-image.ts b/src/main/platform/linux/gdk-native-image.ts index e47bb6e4..b499c9a6 100644 --- a/src/main/platform/linux/gdk-native-image.ts +++ b/src/main/platform/linux/gdk-native-image.ts @@ -44,8 +44,7 @@ const decodeBuffer = (bytes: Uint8Array): DecodedImage => { const gio = loadGioFFI(); const gobject = loadGObjectFFI(); - const dataPtr = bytes.length === 0 ? null : ptr(bytes); - const gbytes = glib.symbols.g_bytes_new(dataPtr, BigInt(bytes.length)); + const gbytes = glib.symbols.g_bytes_new(ptr(bytes), BigInt(bytes.length)); const stream = gio.symbols.g_memory_input_stream_new_from_bytes(gbytes); // The stream took its own ref on the bytes; drop our local one. glib.symbols.g_bytes_unref(gbytes); From 6c4a635b52717926d1c5e821f42cc27c721dade4 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:26:07 -0700 Subject: [PATCH 280/586] chore: trim Linux FFI comments to the comment rules --- src/main/platform/linux/gdbus-ffi.ts | 51 +++-------------- src/main/platform/linux/gdk-ffi.ts | 14 +---- src/main/platform/linux/gdk-pixbuf-ffi.ts | 23 +------- src/main/platform/linux/gio-ffi.ts | 25 ++------- src/main/platform/linux/glib-ffi.ts | 35 +++--------- src/main/platform/linux/gobject-ffi.ts | 31 ++--------- src/main/platform/linux/gtk-dialog-ffi.ts | 38 ++----------- src/main/platform/linux/gtk-ffi.ts | 19 +------ src/main/platform/linux/gtk-menu-ffi.ts | 30 +--------- src/main/platform/linux/jsc-ffi.ts | 16 +----- src/main/platform/linux/libnotify-ffi.ts | 18 ------ src/main/platform/linux/libsecret-ffi.ts | 17 +----- src/main/platform/linux/soup-ffi.ts | 12 +--- src/main/platform/linux/webkitgtk-ffi.ts | 55 +++++-------------- src/main/platform/linux/x11-ffi.ts | 22 ++------ .../main/platform/linux/linux-ffi-abi.test.ts | 6 +- 16 files changed, 66 insertions(+), 346 deletions(-) diff --git a/src/main/platform/linux/gdbus-ffi.ts b/src/main/platform/linux/gdbus-ffi.ts index d7c9dc75..eb8a095c 100644 --- a/src/main/platform/linux/gdbus-ffi.ts +++ b/src/main/platform/linux/gdbus-ffi.ts @@ -4,28 +4,8 @@ import { currentPlatform } from '../../../common/platform'; import { dlopenLinux } from './glib-ffi'; /** - * GDBus (D-Bus over GIO) symbols behind Bunmaska's deadlock-safe signal-subscription - * primitive (from `libgio-2.0.so.0`, a hard dependency of GTK 4). - * - * SCOPE IS DELIBERATELY MINIMAL — only `g_bus_get_sync` + signal subscribe/unsubscribe. - * `g_dbus_connection_call_sync` is INTENTIONALLY ABSENT: it parks the calling thread on - * a reply that only the GMainContext dispatch can deliver, so on Bunmaska's single pumped - * thread it would DEADLOCK (the same class of hang the synchronous GIO clipboard read - * caused — see gtk-clipboard.ts). Signal SUBSCRIPTION is safe: the registered - * `GDBusSignalCallback` fires on the GMainContext during ordinary cooperative-pump - * iterations (gtk-run-loop.ts), so no thread ever blocks for it. - * - * `g_bus_get_sync` IS permitted: its wire handshake runs on GIO's PRIVATE worker context - * (not Bunmaska's pump), and it FAILS FAST with NULL when no bus is reachable — it never - * needs our pump to turn, so it cannot deadlock. We pass NULL for the `GError**`; a NULL - * return already means "no/failed bus" (the libsecret-keyring.ts discipline). - * - * Convention (matches the existing Linux loaders): `gboolean` is {@link FFIType.i32}; - * `guint`/`GQuark` are {@link FFIType.u32}; `GBusType`/`GDBusSignalFlags` are - * {@link FFIType.i32}/{@link FFIType.u32}; every handle, `GCancellable*`, `GError**`, - * `GDBusSignalCallback`, and `GDestroyNotify` is a real pointer ({@link FFIType.pointer}), - * with NULL passed for the unused ones; `cstring` args are NUL-terminated UTF-8 (or NULL - * to match any value, e.g. a NULL `sender`/`arg0`). + * Deadlock rule (D037, D038): the pumped thread may block only on calls that never wait on the + * default GMainContext, i.e. `g_bus_get_sync` (gated, cached) and a bounded `call_sync`. */ const LIBGIO_PATH = 'libgio-2.0.so.0'; @@ -33,18 +13,12 @@ const LIBGIO_PATH = 'libgio-2.0.so.0'; /** `GBusType` enum (gio/gioenums.h): STARTER=-1, NONE=0, SYSTEM=1, SESSION=2. */ export const G_BUS_TYPE_SYSTEM = 1; export const G_BUS_TYPE_SESSION = 2; -/** `GDBusSignalFlags` — no special matching. */ export const G_DBUS_SIGNAL_FLAGS_NONE = 0; -/** `GDBusCallFlags` — default. */ export const G_DBUS_CALL_FLAGS_NONE = 0; -/** Bounded reply timeout (ms). NEVER `G_MAXINT` — a finite backstop against a peer that never answers. */ +/** Reply timeout (ms). Never `G_MAXINT`: an unbounded call on a bus-less runner hung CI 4h. */ export const DBUS_CALL_TIMEOUT_MS = 5000; -/** - * ABI shape of `GDBusSignalCallback`: - * `(connection, sender_name, object_path, interface_name, signal_name, parameters, user_data) -> void`. - * A `*_CB_DEF` constant (Bun hides a JSCallback's def at runtime) so the ABI is unit-testable. - */ +/** `GDBusSignalCallback`: (conn, sender, path, iface, signal, params, user_data) -> void. */ export const DBUS_SIGNAL_CB_DEF = { args: ['ptr', 'ptr', 'ptr', 'ptr', 'ptr', 'ptr', 'ptr'], returns: 'void', @@ -71,10 +45,9 @@ export const DBUS_SET_PROPERTY_CB_DEF = { /** `GDBusInterfaceVTable` is `{ method_call; get_property; set_property; gpointer padding[8]; }` = 11 slots. */ export const VTABLE_SLOTS = 11; -/** The GDBus FFI symbol descriptor table (from `libgio-2.0.so.0`). */ export const GDBUS_FFI_SYMBOLS = { - // (bus_type:GBusType, cancellable:GCancellable*|null, error:GError**|null) -> GDBusConnection* - // (shared singleton; NULL on failure). Fails FAST (socket connect) when no bus is present. + // (bus_type:GBusType, cancellable|null, error:GError**|null) -> GDBusConnection* + // (shared singleton; NULL fast when no bus is reachable). g_bus_get_sync: { args: [FFIType.i32, FFIType.pointer, FFIType.pointer], returns: FFIType.pointer, @@ -96,12 +69,8 @@ export const GDBUS_FFI_SYMBOLS = { ], returns: FFIType.u32, }, - // Bounded REMOTE method call. SAFE on the pumped thread: the reply is read by the - // connection's PRIVATE GDBusWorker thread and call_sync awaits it on its OWN private - // GMainContext (gdbusconnection.c), so it blocks only THIS thread for a bounded round - // trip and never needs Bunmaska's pump to turn (unlike the clipboard local-pipe read). A - // FINITE timeout_msec (NEVER G_MAXINT) is mandatory. The floating `parameters` GVariant - // is consumed by the call; the reply tuple is transfer-full (caller g_variant_unref). + // Safe on the pumped thread only with a FINITE timeout: the reply is awaited on call_sync's own + // GMainContext (D038). Consumes a floating `parameters`; the reply is transfer-full. // (connection, bus_name, object_path, interface_name, method_name, parameters:GVariant*, // reply_type:GVariantType*|null, flags:GDBusCallFlags, timeout_msec:gint, // cancellable|null, error:GError**|null) -> GVariant* @@ -121,13 +90,12 @@ export const GDBUS_FFI_SYMBOLS = { ], returns: FFIType.pointer, }, - // --- Object export (StatusNotifierItem service) --- // (xml:cstring, error:GError**|null) -> GDBusNodeInfo* (transfer-full; keep alive forever). g_dbus_node_info_new_for_xml: { args: [FFIType.cstring, FFIType.pointer], returns: FFIType.pointer, }, - // (node:GDBusNodeInfo*, name:cstring) -> GDBusInterfaceInfo* (BORROWED — owned by the node). + // (node:GDBusNodeInfo*, name:cstring) -> GDBusInterfaceInfo* (BORROWED - owned by the node). g_dbus_node_info_lookup_interface: { args: [FFIType.pointer, FFIType.cstring], returns: FFIType.pointer, @@ -191,7 +159,6 @@ const requireLinux = (): void => { } }; -/** Open `libgio-2.0.so.0` and expose the GDBus connection + signal symbols. */ export const loadGDBusFFI = () => { requireLinux(); if (cache.ffi) { diff --git a/src/main/platform/linux/gdk-ffi.ts b/src/main/platform/linux/gdk-ffi.ts index 47ea7a24..fb9186ce 100644 --- a/src/main/platform/linux/gdk-ffi.ts +++ b/src/main/platform/linux/gdk-ffi.ts @@ -3,21 +3,9 @@ import { UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; import { dlopenLinux } from './glib-ffi'; -/** - * Loads GDK 4's display, system-beep, and clipboard symbols. - * - * In GTK 4 there is no standalone `libgdk-4.so`: GDK is compiled INTO the GTK 4 - * shared object, so its symbols are resolved from `libgtk-4.so.1` (the same - * library {@link loadGtkFFI} opens). - * - * All GDK handles are real pointers ({@link FFIType.pointer}); the display - * pointer is nullable (NULL when GTK was never initialised) and MUST be guarded - * before use. - */ - +/** GTK 4 ships no libgdk-4: GDK's symbols live inside libgtk-4.so.1. */ const LIBGTK_PATH = 'libgtk-4.so.1'; -/** The GDK 4 FFI symbol descriptor table (resolved from `libgtk-4.so.1`). */ export const GDK_FFI_SYMBOLS = { gdk_display_get_default: { args: [], diff --git a/src/main/platform/linux/gdk-pixbuf-ffi.ts b/src/main/platform/linux/gdk-pixbuf-ffi.ts index cc7756e7..5c0ad01a 100644 --- a/src/main/platform/linux/gdk-pixbuf-ffi.ts +++ b/src/main/platform/linux/gdk-pixbuf-ffi.ts @@ -3,23 +3,8 @@ import { UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; import { dlopenLinux } from './glib-ffi'; -/** - * Loads GdkPixbuf's load/query/encode symbols — the Linux primitives behind - * Bunmaska's `nativeImage`. - * - * GdkPixbuf is a small, stable library that decodes the common raster formats - * (PNG/JPEG/…) and is a transitive dependency of GTK 4, but it ships as its own - * shared object (`libgdk_pixbuf-2.0.so.0`) rather than living inside - * `libgtk-4.so.1`, so it gets its own loader. - * - * Convention (matches the existing Linux loaders): `gboolean` is {@link FFIType.i32} - * (compare `=== 1`); `GError**`, `GCancellable*`, and the out-pointer args are - * real pointers; `cstring` args are NUL-terminated UTF-8. - */ - const LIBGDK_PIXBUF_PATH = 'libgdk_pixbuf-2.0.so.0'; -/** The GdkPixbuf FFI symbol descriptor table. */ export const GDK_PIXBUF_FFI_SYMBOLS = { // (filename, GError** error) -> GdkPixbuf* (transfer-full; NULL on failure) gdk_pixbuf_new_from_file: { @@ -31,22 +16,20 @@ export const GDK_PIXBUF_FFI_SYMBOLS = { args: [FFIType.pointer, FFIType.pointer, FFIType.pointer], returns: FFIType.pointer, }, - // (GdkPixbuf*) -> int width (scalar) gdk_pixbuf_get_width: { args: [FFIType.pointer], returns: FFIType.i32, }, - // (GdkPixbuf*) -> int height (scalar) gdk_pixbuf_get_height: { args: [FFIType.pointer], returns: FFIType.i32, }, - // (GdkPixbuf*) -> guchar* to the packed pixel rows (BORROWED — owned by the pixbuf). + // (GdkPixbuf*) -> guchar* to the packed pixel rows (BORROWED - owned by the pixbuf). gdk_pixbuf_get_pixels: { args: [FFIType.pointer], returns: FFIType.pointer, }, - // (GdkPixbuf*) -> int rowstride (bytes per row; ≥ width*n_channels, often padded). + // (GdkPixbuf*) -> int rowstride (bytes per row; >= width*n_channels, often padded). gdk_pixbuf_get_rowstride: { args: [FFIType.pointer], returns: FFIType.i32, @@ -66,7 +49,7 @@ export const GDK_PIXBUF_FFI_SYMBOLS = { args: [FFIType.pointer, FFIType.i32, FFIType.i32, FFIType.i32, FFIType.i32], returns: FFIType.pointer, }, - // (src) -> GdkPixbuf* (transfer-full; an INDEPENDENT pixel copy — used to detach a subpixbuf). + // (src) -> GdkPixbuf* (transfer-full; an INDEPENDENT pixel copy that detaches a subpixbuf). gdk_pixbuf_copy: { args: [FFIType.pointer], returns: FFIType.pointer, diff --git a/src/main/platform/linux/gio-ffi.ts b/src/main/platform/linux/gio-ffi.ts index a3073f4e..85dcf064 100644 --- a/src/main/platform/linux/gio-ffi.ts +++ b/src/main/platform/linux/gio-ffi.ts @@ -3,26 +3,14 @@ import { UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; import { dlopenLinux } from './glib-ffi'; -/** - * Loads GIO's default-handler URI launcher plus the GFile / GListModel / stream - * helpers the Linux shell, dialog, and clipboard paths need. - * - * Convention (matches the existing Linux loaders): `gboolean` is modelled as - * {@link FFIType.i32} (compare `=== 1`), NOT `bool`; the `GAppLaunchContext*` - * and `GError**` args are real pointers passed as `null`; `cstring` args are - * NUL-terminated UTF-8 strings. - */ - const LIBGIO_PATH = 'libgio-2.0.so.0'; -/** The GIO FFI symbol descriptor table. */ export const GIO_FFI_SYMBOLS = { g_app_info_launch_default_for_uri: { args: [FFIType.cstring, FFIType.pointer, FFIType.pointer], returns: FFIType.i32, }, - // Returns a transfer-full `char*` (the local filesystem path) for a GFile, or - // NULL if the GFile has no native path. The caller MUST `g_free` the result. + // (GFile*) -> char* local path (transfer-full: g_free; NULL when not native). g_file_get_path: { args: [FFIType.pointer], returns: FFIType.pointer, @@ -38,17 +26,14 @@ export const GIO_FFI_SYMBOLS = { returns: FFIType.pointer, }, // (GBytes*) -> GInputStream* (transfer-full). Takes its own ref on the GBytes, - // so the caller unrefs its local GBytes after this returns. Backs the custom - // URL-scheme response body on Linux (the GInputStream WebKit reads from). + // so the caller unrefs its local GBytes after this returns. g_memory_input_stream_new_from_bytes: { args: [FFIType.pointer], returns: FFIType.pointer, }, - // (stream, count /*gsize*/, io_priority /*int; G_PRIORITY_DEFAULT=0*/, cancellable /*null*/, - // GAsyncReadyCallback, user_data /*null*/) -> void. Non-blocking; the result is - // collected in the callback. Used to drain the stream GDK hands back when reading - // a non-text clipboard format (e.g. text/html) WITHOUT freezing the GMainContext - // that feeds it (a synchronous read deadlocks; see gtk-clipboard.ts). + // (stream, count /*gsize*/, io_priority /*G_PRIORITY_DEFAULT=0*/, cancellable /*null*/, + // GAsyncReadyCallback, user_data /*null*/) -> void. Never the sync read: the clipboard + // stream is fed by the pumped GMainContext, so blocking on it deadlocks (gtk-clipboard.ts). g_input_stream_read_bytes_async: { args: [ FFIType.pointer, diff --git a/src/main/platform/linux/glib-ffi.ts b/src/main/platform/linux/glib-ffi.ts index 3fee0af1..3d0aa2d3 100644 --- a/src/main/platform/linux/glib-ffi.ts +++ b/src/main/platform/linux/glib-ffi.ts @@ -14,28 +14,13 @@ import { import { cstr } from '../cstr'; import { dlopen, type NarrowLibrary } from '../dlopen'; -/** - * Loads GLib's main-context iteration symbols plus `g_free`. - * - * GLib (not GTK directly) owns the main-loop primitives Bunmaska uses to pump the - * Linux UI cooperatively, mirroring the macOS CoreFoundation pump (D020). - * `libglib-2.0` is a hard dependency of GTK 4, so it is always present wherever - * `libgtk-4` is. - * - * `g_main_context_iteration(context, may_block)` dispatches at most one set of - * ready sources; a `NULL` context means the default one. `g_main_context_pending` - * reports whether any sources are ready, letting us drain to quiescence without - * ever blocking Bun's thread. `g_free` releases the transfer-full `char*` - * returned by `jsc_value_to_string` (NULL-safe no-op). - */ - const LIBGLIB_PATH = 'libglib-2.0.so.0'; const LIBC_PATH = 'libc.so.6'; const LIBC_FFI_SYMBOLS = { setenv: { args: [FFIType.cstring, FFIType.cstring, FFIType.i32], returns: FFIType.i32 }, } as const; -/** The path to dlopen for `soname`: the pinned engine's bundled copy when it has one, else the bare soname. */ +/** The dlopen path for `soname`: the pinned engine's bundled copy if present, else the soname. */ export const linuxLibPath = ( engine: EngineResolution, soname: string, @@ -55,7 +40,7 @@ export const linuxLibPath = ( return soname; }; -/** Copy the pinned engine's env exports into the C environment: Bun's `process.env` writes never reach `getenv`. */ +/** Copy the pinned engine's env into libc's environ: Bun's `process.env` never reaches `getenv`. */ export const exportEngineEnv = ( engine: EngineResolution, env: StoreEnv, @@ -91,7 +76,6 @@ export const dlopenLinux = >( return dlopen(linuxLibPath(engine, soname), symbols); }; -/** The GLib FFI symbol descriptor table. */ export const GLIB_FFI_SYMBOLS = { g_main_context_iteration: { args: [FFIType.pointer, FFIType.i32], @@ -124,8 +108,7 @@ export const GLIB_FFI_SYMBOLS = { args: [FFIType.pointer, FFIType.pointer], returns: FFIType.pointer, }, - // (string) -> GQuark (a guint32 id). Used to build an error domain for the - // GError handed to webkit_uri_scheme_request_finish_error. + // (string) -> GQuark (guint32). g_quark_from_string: { args: [FFIType.cstring], returns: FFIType.u32, @@ -162,7 +145,7 @@ export const GLIB_FFI_SYMBOLS = { args: [FFIType.pointer, FFIType.u64], returns: FFIType.pointer, }, - // (value) -> void. Drops a ref on a transfer-full GVariant. + // (value) -> void. g_variant_unref: { args: [FFIType.pointer], returns: FFIType.void, @@ -172,7 +155,7 @@ export const GLIB_FFI_SYMBOLS = { args: [FFIType.pointer], returns: FFIType.u32, }, - // (string) -> GVariant* 's' (FLOATING). Builds a D-Bus method arg. + // (string) -> GVariant* 's' (FLOATING). g_variant_new_string: { args: [FFIType.cstring], returns: FFIType.pointer, @@ -193,17 +176,17 @@ export const GLIB_FFI_SYMBOLS = { args: [FFIType.i32], returns: FFIType.pointer, }, - // (value) -> GVariant* 'i' (FLOATING). Width/height for the SNI a(iiay) icon. + // (value) -> GVariant* 'i' (FLOATING). g_variant_new_int32: { args: [FFIType.i32], returns: FFIType.pointer, }, - // (object_path) -> GVariant* 'o' (FLOATING). The SNI Menu property. + // (object_path) -> GVariant* 'o' (FLOATING). g_variant_new_object_path: { args: [FFIType.cstring], returns: FFIType.pointer, }, - // (type_string) -> GVariantType* (transfer-full; g_variant_type_free). Builders BORROW it. + // (type_string) -> GVariantType* (transfer-full). Builders BORROW it. g_variant_type_new: { args: [FFIType.cstring], returns: FFIType.pointer, @@ -213,7 +196,7 @@ export const GLIB_FFI_SYMBOLS = { args: [FFIType.pointer], returns: FFIType.pointer, }, - // (builder, type:GVariantType*) -> void. Opens a nested container. + // (builder, type:GVariantType*) -> void. g_variant_builder_open: { args: [FFIType.pointer, FFIType.pointer], returns: FFIType.void, diff --git a/src/main/platform/linux/gobject-ffi.ts b/src/main/platform/linux/gobject-ffi.ts index b7f49c35..803d6467 100644 --- a/src/main/platform/linux/gobject-ffi.ts +++ b/src/main/platform/linux/gobject-ffi.ts @@ -3,35 +3,12 @@ import { UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; import { dlopenLinux } from './glib-ffi'; -/** - * Loads GObject's signal-connection and refcount primitives plus the - * construct-only `g_object_new` path used to build a `WebKitWebView` with a - * pre-wired `WebKitUserContentManager`. - * - * `libgobject-2.0` is a hard dependency of GTK 4, so it is always present - * wherever `libgtk-4` is. Convention: `gboolean` is {@link FFIType.i32}; - * `gulong`/`GType` are {@link FFIType.u64} (BigInt); `GConnectFlags` is - * {@link FFIType.u32}; all handles are real pointers. - */ - const LIBGOBJECT_PATH = 'libgobject-2.0.so.0'; /** Default `GConnectFlags` (no after/swapped) for `g_signal_connect_data`. */ export const G_CONNECT_DEFAULT = 0; -/** - * The GObject FFI symbol descriptor table. - * - * `g_signal_connect_data` is the real symbol behind the `g_signal_connect` - * C macro; pass `c_handler = jsCallback.ptr`, `data = 0`, `destroy_data = 0`, - * `connect_flags = 0`. It returns the `gulong` handler id kept as a BigInt. - * - * `g_object_new` is true C varargs; the fixed 4-arity `[u64, cstring, ptr, ptr]` - * is valid ONLY for the literal call - * `(webkit_web_view_get_type(), "user-content-manager", ucm, NULL)`. The - * trailing pointer MUST be a real null terminator or g_object_new walks past the - * varargs and corrupts/crashes. - */ +/** `gulong` handler ids and `GType`s are u64 (BigInt), never pointer. */ export const GOBJECT_FFI_SYMBOLS = { g_signal_connect_data: { args: [ @@ -52,13 +29,13 @@ export const GOBJECT_FFI_SYMBOLS = { args: [FFIType.pointer], returns: FFIType.void, }, + // C varargs pinned to (type, name, value, NULL): one pointer-valued property, or a NULL name + // for none. The trailing NULL terminator is mandatory or g_object_new walks past the args. g_object_new: { args: [FFIType.u64, FFIType.cstring, FFIType.pointer, FFIType.pointer], returns: FFIType.pointer, }, - // C varargs; the fixed `[ptr, cstring, ptr (out), ptr (null)]` arity is valid - // ONLY for reading a SINGLE property into a caller-allocated out buffer, e.g. - // `g_object_get(settings, "gtk-application-prefer-dark-theme", &gboolean, NULL)`. + // C varargs pinned to (object, name, &out, NULL): reads ONE property into a caller-owned buffer. g_object_get: { args: [FFIType.pointer, FFIType.cstring, FFIType.pointer, FFIType.pointer], returns: FFIType.void, diff --git a/src/main/platform/linux/gtk-dialog-ffi.ts b/src/main/platform/linux/gtk-dialog-ffi.ts index 18f2f7a6..9101e5e5 100644 --- a/src/main/platform/linux/gtk-dialog-ffi.ts +++ b/src/main/platform/linux/gtk-dialog-ffi.ts @@ -3,32 +3,10 @@ import { UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; import { dlopenLinux } from './glib-ffi'; -/** - * Loads the GTK 4 native-dialog symbols behind Bunmaska's `dialog` API: - * `GtkAlertDialog` (message boxes) and `GtkFileDialog` (open/save panels), both - * added in GTK 4.10. CI runs on ubuntu-latest (24.04 → GTK 4.12+), so these are - * always available there. - * - * Convention (matches the existing Linux loaders): `gboolean` is modelled as - * {@link FFIType.i32}; all GObject/GTK handles are real pointers - * ({@link FFIType.pointer}); `cstring` args are NUL-terminated UTF-8 strings; - * `GType` is {@link FFIType.u64}. - * - * The `*_choose`/`open`/`save` calls are non-blocking: they invoke a - * `GAsyncReadyCallback (source, GAsyncResult*, user_data) -> void` when the user - * settles the dialog, and the matching `*_finish(self, result, error)` extracts - * the value. The `GError**` arg is always passed as `null` (dismissal is - * reported via the return value / sentinel rather than unwrapping the error). - * - * The `GtkAlertDialog` is constructed via the 2-arity `g_object_new(type, NULL)` - * (exposed by {@link loadGtkDialogGObjectFFI}) to avoid the C-varargs - * `gtk_alert_dialog_new(format, ...)` constructor. - */ - +/** Needs GTK >= 4.10 (GtkAlertDialog/GtkFileDialog): Bun fails the whole table on older GTK. */ const LIBGTK_PATH = 'libgtk-4.so.1'; const LIBGOBJECT_PATH = 'libgobject-2.0.so.0'; -/** The GTK 4 dialog FFI symbol descriptor table (from `libgtk-4.so.1`). */ export const GTK_DIALOG_FFI_SYMBOLS = { gtk_alert_dialog_get_type: { args: [], @@ -46,8 +24,8 @@ export const GTK_DIALOG_FFI_SYMBOLS = { args: [FFIType.pointer, FFIType.i32], returns: FFIType.void, }, - // `labels` is a NULL-terminated `const char* const*` — pass `ptr()` of a - // BigUint64Array of cstr pointers with a trailing 0n. + // `labels` is a NULL-terminated `const char* const*`: `ptr()` of a BigUint64Array of cstr + // pointers with a trailing 0n. gtk_alert_dialog_set_buttons: { args: [FFIType.pointer, FFIType.pointer], returns: FFIType.void, @@ -109,15 +87,7 @@ export const GTK_DIALOG_FFI_SYMBOLS = { }, } as const; -/** - * The 2-arity `g_object_new(GType, NULL)` from `libgobject-2.0.so.0`. - * - * `g_object_new` is true C varargs; matching the ABI requires the call shape to - * match exactly. The existing {@link gobject-ffi} table declares a 4-arity - * variant for the `WebKitWebView` construct-only path; the `GtkAlertDialog` is - * built with no construct properties, so it needs this distinct 2-arity - * declaration. The trailing pointer MUST be a true NULL terminator. - */ +// ponytail: duplicate of gobject-ffi's g_object_new; delete once gtk-dialog.ts calls that one. export const GTK_DIALOG_GOBJECT_FFI_SYMBOLS = { g_object_new: { args: [FFIType.u64, FFIType.pointer], diff --git a/src/main/platform/linux/gtk-ffi.ts b/src/main/platform/linux/gtk-ffi.ts index 0c679570..b8aeadda 100644 --- a/src/main/platform/linux/gtk-ffi.ts +++ b/src/main/platform/linux/gtk-ffi.ts @@ -5,14 +5,6 @@ import { dlopenLinux } from './glib-ffi'; const LIBGTK_PATH = 'libgtk-4.so.1'; -/** - * The GTK 4 FFI symbol descriptor table. - * - * Convention (matches the existing Linux loaders): `gboolean` is modelled as - * {@link FFIType.i32} (compare `!== 0`), NOT `bool`; all GObject/GTK handles are - * real pointers ({@link FFIType.pointer}); `cstring` args are NUL-terminated - * UTF-8 strings. - */ export const GTK_FFI_SYMBOLS = { gtk_init_check: { args: [], @@ -35,7 +27,6 @@ export const GTK_FFI_SYMBOLS = { args: [FFIType.pointer, FFIType.f64], returns: FFIType.void, }, - // (widget, min_width, min_height) -> void; constrains the window's minimum size. gtk_widget_set_size_request: { args: [FFIType.pointer, FFIType.i32, FFIType.i32], returns: FFIType.void, @@ -122,15 +113,7 @@ const cache: { ffi: ReturnType> | und ffi: undefined, }; -/** - * Open `libgtk-4.so.1` and expose the GTK 4 window/widget symbols Bunmaska needs. - * - * GTK 3 -> GTK 4 changes reflected here: `gtk_init_check`/`gtk_window_new` take - * no arguments; `gtk_window_set_child` replaces `gtk_container_add`; - * `gtk_widget_set_visible` replaces `gtk_widget_show`/`hide`; `minimize`/ - * `unminimize` are the GTK 4 renames of `iconify`/`deiconify`. There is no - * `gtk_window_is_minimized` — minimized state is tracked in JS. - */ +/** GTK 4 has no `gtk_window_is_minimized`: minimized state is tracked in JS. */ export const loadGtkFFI = () => { const platform = currentPlatform(); if (platform !== 'linux') { diff --git a/src/main/platform/linux/gtk-menu-ffi.ts b/src/main/platform/linux/gtk-menu-ffi.ts index f665d293..6c546bc8 100644 --- a/src/main/platform/linux/gtk-menu-ffi.ts +++ b/src/main/platform/linux/gtk-menu-ffi.ts @@ -3,35 +3,16 @@ import { UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; import { dlopenLinux } from './glib-ffi'; -/** - * Loads the GIO `GMenu`/`GAction` model symbols and the GTK 4 - * `GtkPopoverMenuBar`/`GtkBox` widget symbols behind Bunmaska's Linux `Menu` - * backend. - * - * A GTK 4 application menu bar is built from a backend-neutral *model* (`GMenu`, - * a `GMenuModel`) wired to an *action group* (`GSimpleActionGroup`): each - * clickable item names a `GAction` (e.g. `"bunmaska.menu-0"`), and activating - * that action — via a click, an accelerator, or `g_action_group_activate_action` - * — fires the action's `activate` signal. A `GtkPopoverMenuBar` renders the - * model; the action group is inserted into the window under the `"bunmaska"` - * prefix with `gtk_widget_insert_action_group`. - * - * Convention (matches the existing Linux loaders): `gboolean` is modelled as - * {@link FFIType.i32}; all GObject/GTK handles are real pointers - * ({@link FFIType.pointer}); `cstring` args are NUL-terminated UTF-8 strings; - * nullable pointer args (`param_type`, `param`) are passed as `null`. - */ - const LIBGIO_PATH = 'libgio-2.0.so.0'; const LIBGTK_PATH = 'libgtk-4.so.1'; -/** The GIO `GMenu`/`GAction` FFI symbol descriptor table (from `libgio-2.0.so.0`). */ export const GMENU_FFI_SYMBOLS = { g_menu_new: { args: [], returns: FFIType.pointer, }, - // (menu, label, detailed_action /*e.g. "bunmaska.menu-0"*/) -> void + // (menu, label, detailed_action) -> void. Actions are added to the group bare ("menu-0") + // but named here with the insert_action_group prefix ("bunmaska.menu-0"). g_menu_append: { args: [FFIType.pointer, FFIType.cstring, FFIType.cstring], returns: FFIType.void, @@ -60,7 +41,7 @@ export const GMENU_FFI_SYMBOLS = { args: [FFIType.cstring, FFIType.pointer, FFIType.pointer], returns: FFIType.pointer, }, - // (value /*gboolean*/) -> GVariant* (floating ref) + // ponytail: duplicate of GLIB_FFI_SYMBOLS.g_variant_new_boolean; delete once gtk-menu.ts uses it. g_variant_new_boolean: { args: [FFIType.i32], returns: FFIType.pointer, @@ -81,7 +62,6 @@ export const GMENU_FFI_SYMBOLS = { }, } as const; -/** The GTK 4 menu-bar/box FFI symbol descriptor table (from `libgtk-4.so.1`). */ export const GTK_MENU_FFI_SYMBOLS = { // (orientation /*GtkOrientation; vertical=1*/, spacing) -> GtkBox* gtk_box_new: { @@ -107,7 +87,6 @@ export const GTK_MENU_FFI_SYMBOLS = { args: [FFIType.pointer, FFIType.cstring, FFIType.pointer], returns: FFIType.void, }, - // --- Context-menu popover (Menu.popup) --- // (model /*GMenuModel*/) -> GtkPopoverMenu* (a GtkPopover/GtkWidget) gtk_popover_menu_new_from_model: { args: [FFIType.pointer], @@ -120,7 +99,6 @@ export const GTK_MENU_FFI_SYMBOLS = { }, gtk_popover_popup: { args: [FFIType.pointer], returns: FFIType.void }, gtk_popover_popdown: { args: [FFIType.pointer], returns: FFIType.void }, - // (widget, parent) -> void / (widget) -> void gtk_widget_set_parent: { args: [FFIType.pointer, FFIType.pointer], returns: FFIType.void }, gtk_widget_unparent: { args: [FFIType.pointer], returns: FFIType.void }, } as const; @@ -139,7 +117,6 @@ const requireLinux = (fn: string): void => { } }; -/** Open `libgio-2.0.so.0` and expose the `GMenu`/`GAction` model symbols. */ export const loadGMenuFFI = () => { requireLinux('loadGMenuFFI'); if (cache.gio) { @@ -150,7 +127,6 @@ export const loadGMenuFFI = () => { return ffi; }; -/** Open `libgtk-4.so.1` and expose the menu-bar/box widget symbols. */ export const loadGtkMenuFFI = () => { requireLinux('loadGtkMenuFFI'); if (cache.gtk) { diff --git a/src/main/platform/linux/jsc-ffi.ts b/src/main/platform/linux/jsc-ffi.ts index 0a3d6ffb..9841e7cd 100644 --- a/src/main/platform/linux/jsc-ffi.ts +++ b/src/main/platform/linux/jsc-ffi.ts @@ -3,22 +3,12 @@ import { UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; import { dlopenLinux } from './glib-ffi'; -/** - * Loads JavaScriptCoreGTK 6.0 — a SEPARATE shared object from WebKitGTK - * (`libjavascriptcoregtk-6.0.so.1`, NOT `libwebkitgtk-6.0.so.4`). - * - * In WebKitGTK 6.0 the `script-message-received` signal delivers a `JSCValue*` - * directly; {@link jsc_value_to_string} converts it into the JSON IPC payload - * string. Declared returning {@link FFIType.pointer} (NOT `cstring`) so the - * transfer-full native string can be captured via `CString`, read, then freed - * with `g_free` — declaring `cstring` would leak the string on every IPC - * message. - */ - +/** JavaScriptCoreGTK is its own shared object, separate from libwebkitgtk. */ const LIBJSC_PATH = 'libjavascriptcoregtk-6.0.so.1'; -/** The JavaScriptCoreGTK FFI symbol descriptor table. */ export const JSC_FFI_SYMBOLS = { + // (JSCValue*) -> char* (transfer-full): keep the pointer and g_free it, or every IPC message + // leaks one string. jsc_value_to_string: { args: [FFIType.pointer], returns: FFIType.pointer, diff --git a/src/main/platform/linux/libnotify-ffi.ts b/src/main/platform/linux/libnotify-ffi.ts index 296f3bcd..e6ae0241 100644 --- a/src/main/platform/linux/libnotify-ffi.ts +++ b/src/main/platform/linux/libnotify-ffi.ts @@ -3,26 +3,8 @@ import { UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; import { dlopenLinux } from './glib-ffi'; -/** - * Loads the libnotify symbols behind Bunmaska's `Notification` API on Linux. - * - * libnotify is the freedesktop desktop-notification client library; it forwards - * to the session's notification daemon over D-Bus. CI runs headless (xvfb) with - * NO notification daemon, so `notify_notification_show` may return FALSE / no-op - * there — that is EXPECTED. The integration test therefore asserts only that the - * symbols resolve, `notify_init` runs, and construct/show/close do not throw; it - * does NOT assert a banner appeared. - * - * Convention (matches the existing Linux loaders): `gboolean` is modelled as - * {@link FFIType.i32} (compare `!== 0`); the `NotifyNotification*` handle and the - * `GError**` out-param are real pointers ({@link FFIType.pointer}); `cstring` - * args are NUL-terminated UTF-8 strings. The `GError**` arg is always passed as - * `null` (failures are reported via the gboolean return, not unwrapped). - */ - const LIBNOTIFY_PATH = 'libnotify.so.4'; -/** The libnotify FFI symbol descriptor table (from `libnotify.so.4`). */ export const LIBNOTIFY_FFI_SYMBOLS = { // (app_name) -> gboolean; call once per process before creating notifications. notify_init: { diff --git a/src/main/platform/linux/libsecret-ffi.ts b/src/main/platform/linux/libsecret-ffi.ts index 07d0e967..d07e4bfc 100644 --- a/src/main/platform/linux/libsecret-ffi.ts +++ b/src/main/platform/linux/libsecret-ffi.ts @@ -5,23 +5,13 @@ import { cstr } from '../cstr'; import { dlopenLinux } from './glib-ffi'; /** - * libsecret symbols behind the Linux keyring backend of `safeStorage`. - * - * The simple-password API stores/looks up a single secret under a `SecretSchema`. - * We build the schema with {@link secret_schema_new} (libsecret owns the struct - * layout — no blind offset reasoning) carrying ZERO attributes, so the schema - * identifies one secret and the variadic attribute lists collapse to a trailing - * `NULL`. We pass `NULL` for every `GError**` out-param (a NULL/0 return already - * means "absent or failed"), which sidesteps GError ownership + pointer-precision - * entirely. - * - * These calls are SYNCHRONOUS (blocking D-Bus). They are gated off in CI and - * never run from unit tests (see `libsecret-keyring.ts`). + * The schema carries ZERO attributes, so every variadic attribute list collapses to one trailing + * NULL. Every `GError**` is NULL: a NULL/0 return already means absent or failed. */ const LIBSECRET_PATH = 'libsecret-1.so.0'; const SCHEMA_NAME = 'dev.bunmaska.safeStorage'; -/** `SECRET_SCHEMA_NONE` — the secret is tagged with the schema name, so a zero-attribute lookup finds it. */ +/** Tags the secret with the schema name, so a zero-attribute lookup still finds it. */ const SECRET_SCHEMA_NONE = 0; export const LIBSECRET_FFI_SYMBOLS = { @@ -69,7 +59,6 @@ const requireLinux = (): void => { } }; -/** Open `libsecret-1.so.0` and expose the simple-password symbols. */ export const loadLibsecretFFI = () => { requireLinux(); if (cache.ffi) { diff --git a/src/main/platform/linux/soup-ffi.ts b/src/main/platform/linux/soup-ffi.ts index e7802751..c643f77d 100644 --- a/src/main/platform/linux/soup-ffi.ts +++ b/src/main/platform/linux/soup-ffi.ts @@ -3,17 +3,6 @@ import { UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; import { dlopenLinux } from './glib-ffi'; -/** - * Loads libsoup 3 - the HTTP library WebKitGTK's cookie API traffics in. - * Soup symbols are NOT reachable through the libwebkitgtk dlopen handle, so - * this is its own library, engine-resolved like webkitgtk-ffi (a pinned - * engine bundles its own libsoup). - * - * Convention: `gboolean` is {@link FFIType.i32} (compare `!== 0`); the - * `soup_cookie_get_*` string getters return BORROWED `const char*` declared as - * {@link FFIType.pointer} so NULL is guardable and nothing is freed. - */ - const LIBSOUP_PATH = 'libsoup-3.0.so.0'; export const SOUP_FFI_SYMBOLS = { @@ -27,6 +16,7 @@ export const SOUP_FFI_SYMBOLS = { args: [FFIType.pointer], returns: FFIType.void, }, + // The string getters return BORROWED `const char*`: never free them. soup_cookie_get_name: { args: [FFIType.pointer], returns: FFIType.pointer, diff --git a/src/main/platform/linux/webkitgtk-ffi.ts b/src/main/platform/linux/webkitgtk-ffi.ts index 39a1dd61..84f70aff 100644 --- a/src/main/platform/linux/webkitgtk-ffi.ts +++ b/src/main/platform/linux/webkitgtk-ffi.ts @@ -3,17 +3,9 @@ import { UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; import { dlopenLinux } from './glib-ffi'; -/** - * Loads WebKitGTK 6.0 — the Linux system-WebKit web view (the role - * `WebKit.framework` plays on macOS). - * - * Convention: `gboolean` is {@link FFIType.i32} (compare `!== 0`); handles are - * real pointers; nullable string args use {@link FFIType.pointer} (Bun's - * `cstring` cannot encode NULL). - */ - const LIBWEBKITGTK_PATH = 'libwebkitgtk-6.0.so.4'; +/** `WebKitLoadEvent`: STARTED=0, REDIRECTED=1, COMMITTED=2, FINISHED=3. */ export const WEBKIT_LOAD_STARTED = 0; export const WEBKIT_LOAD_COMMITTED = 2; export const WEBKIT_LOAD_FINISHED = 3; @@ -26,19 +18,6 @@ export const WEBKIT_SNAPSHOT_REGION_VISIBLE = 0; /** `WebKitSnapshotOptions`: no selection highlight, opaque background. */ export const WEBKIT_SNAPSHOT_OPTIONS_NONE = 0; -/** - * The WebKitGTK 6.0 FFI symbol descriptor table. Load-bearing details: - * - `load_html` base_uri is {@link FFIType.pointer} (nullable; was wrongly - * `cstring` in the scaffolding) — pass a pinned NUL-terminated Buffer or 0. - * - `evaluate_javascript` is the 8-arg WK6.0 form; length is `i64` (-1 for - * NUL-terminated); world_name/source_uri/cancellable/callback/user_data are - * pointers passable as null for fire-and-forget (D022). - * - `register_script_message_handler` is the WK6.0 3-arg form; the trailing - * world_name is {@link FFIType.pointer} (nullable; 0 = default world). - * - `webkit_user_script_new_for_world` is the named-world variant of - * `webkit_user_script_new`; its 4th arg (`world_name`) is {@link FFIType.cstring} - * (a real world name, e.g. `BunmaskaPreload`) — the isolated-world injection path. - */ export const WEBKITGTK_FFI_SYMBOLS = { webkit_web_view_get_type: { args: [], @@ -60,18 +39,16 @@ export const WEBKITGTK_FFI_SYMBOLS = { args: [FFIType.pointer], returns: FFIType.void, }, - // (web_view) -> void; aborts any in-progress load. webkit_web_view_stop_loading: { args: [FFIType.pointer], returns: FFIType.void, }, - // (web_view) -> const gchar* title (BORROWED — do NOT free; NULL when none). + // (web_view) -> const gchar* title (BORROWED - do NOT free; NULL when none). webkit_web_view_get_title: { args: [FFIType.pointer], returns: FFIType.pointer, }, - // (web_view, command /*e.g. "Copy","Paste","Cut","SelectAll","Undo","Redo"*/) -> void. - // Non-blocking — queues into the web process. Backs Menu edit-role clicks on Linux. + // (web_view, command /*e.g. "Copy","Paste","SelectAll"*/) -> void; queued, non-blocking. webkit_web_view_execute_editing_command: { args: [FFIType.pointer, FFIType.cstring], returns: FFIType.void, @@ -110,6 +87,8 @@ export const WEBKITGTK_FFI_SYMBOLS = { args: [FFIType.pointer], returns: FFIType.pointer, }, + // WK6.0 8-arg form: (view, script, length:i64 /*-1 = NUL-terminated*/, world_name, source_uri, + // cancellable, callback, user_data); null trailing pointers = fire-and-forget (D022). webkit_web_view_evaluate_javascript: { args: [ FFIType.pointer, @@ -131,7 +110,7 @@ export const WEBKITGTK_FFI_SYMBOLS = { args: [FFIType.pointer, FFIType.i32], returns: FFIType.void, }, - // (settings, user_agent /*cstring; null resets to default*/) -> void + // (settings, user_agent /*null resets to default*/) -> void webkit_settings_set_user_agent: { args: [FFIType.pointer, FFIType.cstring], returns: FFIType.void, @@ -144,7 +123,6 @@ export const WEBKITGTK_FFI_SYMBOLS = { args: [FFIType.pointer], returns: FFIType.void, }, - // (inspector) -> void; closes the inspector window. webkit_web_inspector_close: { args: [FFIType.pointer], returns: FFIType.void, @@ -153,6 +131,7 @@ export const WEBKITGTK_FFI_SYMBOLS = { args: [], returns: FFIType.pointer, }, + // WK6.0 3-arg form: (manager, name, world_name /*null = default world*/) -> gboolean. webkit_user_content_manager_register_script_message_handler: { args: [FFIType.pointer, FFIType.cstring, FFIType.pointer], returns: FFIType.i32, @@ -176,18 +155,17 @@ export const WEBKITGTK_FFI_SYMBOLS = { ], returns: FFIType.pointer, }, - // () -> WebKitWebContext* (the process-wide default context; transfer-none). + // () -> WebKitWebContext* (transfer-none). webkit_web_context_get_default: { args: [], returns: FFIType.pointer, }, - // (WebKitWebView*) -> WebKitWebContext* (the view's context; transfer-none). + // (WebKitWebView*) -> WebKitWebContext* (transfer-none). webkit_web_view_get_context: { args: [FFIType.pointer], returns: FFIType.pointer, }, - // (context, scheme, callback, user_data, destroy_notify) -> void. The callback - // is a `WebKitURISchemeRequestCallback`; user_data/destroy are NULL here. + // (context, scheme, WebKitURISchemeRequestCallback, user_data, destroy_notify) -> void. webkit_web_context_register_uri_scheme: { args: [FFIType.pointer, FFIType.cstring, FFIType.pointer, FFIType.pointer, FFIType.pointer], returns: FFIType.void, @@ -203,12 +181,12 @@ export const WEBKITGTK_FFI_SYMBOLS = { args: [FFIType.pointer, FFIType.pointer, FFIType.i64, FFIType.pointer], returns: FFIType.void, }, - // (request, GError*) -> void. Completes the request with an error response. + // (request, GError*) -> void. webkit_uri_scheme_request_finish_error: { args: [FFIType.pointer, FFIType.pointer], returns: FFIType.void, }, - // () -> WebKitNetworkSession* (the process-default session; transfer-none). + // () -> WebKitNetworkSession* (transfer-none). webkit_network_session_get_default: { args: [], returns: FFIType.pointer, @@ -219,6 +197,7 @@ export const WEBKITGTK_FFI_SYMBOLS = { returns: FFIType.pointer, }, // (manager, cancellable /*null*/, GAsyncReadyCallback, user_data /*null*/) -> void. + // WebKitGTK 2.42+, and Bun resolves the whole table at dlopen: this sets the backend's floor. webkit_cookie_manager_get_all_cookies: { args: [FFIType.pointer, FFIType.pointer, FFIType.pointer, FFIType.pointer], returns: FFIType.void, @@ -229,7 +208,7 @@ export const WEBKITGTK_FFI_SYMBOLS = { args: [FFIType.pointer, FFIType.pointer, FFIType.pointer], returns: FFIType.pointer, }, - // (manager, SoupCookie* /*NOT consumed — caller frees after the finish*/, + // (manager, SoupCookie* /*NOT consumed - caller frees after the finish*/, // cancellable /*null*/, GAsyncReadyCallback, user_data /*null*/) -> void. webkit_cookie_manager_add_cookie: { args: [FFIType.pointer, FFIType.pointer, FFIType.pointer, FFIType.pointer, FFIType.pointer], @@ -289,10 +268,6 @@ export const loadWebKitGtkFFI = () => { return ffi; }; -/** - * Decode the transfer-none `const char*` returned by `webkit_web_view_get_uri`. - * The pointer is owned by WebKit and is NULL before the first load — guard it - * and return `''` rather than freeing or decoding a null pointer. - */ +/** Decode `webkit_web_view_get_uri`'s borrowed string; NULL before the first load reads as `''`. */ export const readGetUriResult = (ptr: Pointer | null): string => ptr === null ? '' : new CString(ptr).toString(); diff --git a/src/main/platform/linux/x11-ffi.ts b/src/main/platform/linux/x11-ffi.ts index 4b5b00da..bd5ab98e 100644 --- a/src/main/platform/linux/x11-ffi.ts +++ b/src/main/platform/linux/x11-ffi.ts @@ -3,23 +3,8 @@ import { UnsupportedPlatformError } from '../../../common/errors'; import { currentPlatform } from '../../../common/platform'; import { dlopenLinux } from './glib-ffi'; -/** - * Xlib FFI for the Linux `globalShortcut` backend (`XGrabKey`). - * - * Loaded only on Linux. On X11 we open a DEDICATED display connection, grab each - * accelerator's keycode+modifier combo on the root window with `XGrabKey`, and - * poll that connection for `KeyPress` events from the cooperative pump. Wayland - * is NOT supported in v1 — global shortcuts there require the - * `org.freedesktop.portal.GlobalShortcuts` desktop portal, which is deferred. - * - * `XEvent` is a ~192-byte union; we never marshal it as a struct — we allocate a - * byte buffer, let `XNextEvent` fill it, and read the `type` (int at offset 0) - * and, for `XKeyEvent`, the `keycode` field by offset. - */ - const LIBX11_PATH = 'libX11.so.6'; -/** The Xlib symbol descriptor table. */ export const X11_FFI_SYMBOLS = { // (const char *display_name) -> Display* (NULL = $DISPLAY) XOpenDisplay: { args: [FFIType.cstring], returns: FFIType.pointer }, @@ -52,11 +37,13 @@ export const X11_FFI_SYMBOLS = { XSelectInput: { args: [FFIType.pointer, FFIType.u64, FFIType.i64], returns: FFIType.i32 }, // (Display*) -> int XPending: { args: [FFIType.pointer], returns: FFIType.i32 }, - // (Display*, XEvent *event_return) -> int + // (Display*, XEvent* out) -> int. XEvent is a 192-byte union: pass a byte buffer and read + // fields by offset, never marshal it as a struct. XNextEvent: { args: [FFIType.pointer, FFIType.pointer], returns: FFIType.i32 }, // (Display*) -> int XFlush: { args: [FFIType.pointer], returns: FFIType.i32 }, - // (int (*handler)(Display*, XErrorEvent*)) -> previous handler (we pass a no-op) + // (int (*handler)(Display*, XErrorEvent*)) -> previous handler. + // ponytail: never installed, so an XGrabKey BadAccess exits the app via Xlib's default handler. XSetErrorHandler: { args: [FFIType.pointer], returns: FFIType.pointer }, } as const; @@ -64,7 +51,6 @@ const cache: { ffi: ReturnType> | und ffi: undefined, }; -/** Open `libX11.so.6` and return the Xlib symbol table. Memoised. */ export const loadX11FFI = () => { const platform = currentPlatform(); if (platform !== 'linux') { diff --git a/tests/unit/main/platform/linux/linux-ffi-abi.test.ts b/tests/unit/main/platform/linux/linux-ffi-abi.test.ts index 5afff155..e4d82c1d 100644 --- a/tests/unit/main/platform/linux/linux-ffi-abi.test.ts +++ b/tests/unit/main/platform/linux/linux-ffi-abi.test.ts @@ -91,11 +91,7 @@ describe('gboolean is i32, never bool', () => { }); }); -/** - * A `cstring` return is decoded eagerly by bun and cannot be NULL-checked or freed. - * These getters must stay raw pointers so the caller can guard 0 and, where the - * transfer is full, hand the buffer back to g_free. - */ +/** These getters stay raw pointers so a transfer-full string keeps the address g_free needs. */ const POINTER_GETTERS: ReadonlyArray = [ ['webkit_web_view_get_uri', WEBKITGTK_FFI_SYMBOLS.webkit_web_view_get_uri], ['jsc_value_to_string', JSC_FFI_SYMBOLS.jsc_value_to_string], From dbe761e553ef79422b882ae3fdd05a1eb23ab335 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:26:11 -0700 Subject: [PATCH 281/586] chore: trim Linux clipboard comments to the comment rules --- src/main/platform/linux/gtk-clipboard.ts | 121 +++++------------------ 1 file changed, 24 insertions(+), 97 deletions(-) diff --git a/src/main/platform/linux/gtk-clipboard.ts b/src/main/platform/linux/gtk-clipboard.ts index 9dc51926..c638dae5 100644 --- a/src/main/platform/linux/gtk-clipboard.ts +++ b/src/main/platform/linux/gtk-clipboard.ts @@ -8,69 +8,26 @@ import { loadGlibFFI } from './glib-ffi'; import { loadGObjectFFI } from './gobject-ffi'; /** - * Linux clipboard backend — the GDK 4 equivalent of the macOS `cocoa-clipboard` - * module. The display's `GdkClipboard*` (from - * `gdk_display_get_clipboard(gdk_display_get_default())`) owns plain-text - * read/write against the system selection. - * - * Unlike Cocoa's synchronous `NSPasteboard stringForType:`, GDK's clipboard read - * is asynchronous-only: `gdk_clipboard_read_text_async` kicks off the read and - * invokes a `GAsyncReadyCallback` when it completes; `gdk_clipboard_read_text_finish` - * extracts the transfer-full `char*` (NULL on empty/none). `readText` therefore - * returns a Promise. Writes are synchronous: a `GdkContentProvider` wrapping the - * UTF-8 bytes is installed via `gdk_clipboard_set_content` (a NULL provider - * clears the clipboard). - * - * HTML uses the same write path with the `text/html` MIME. Reading HTML cannot - * use the text-only `read_text` helper, so it goes through the general - * `gdk_clipboard_read_async` (negotiating the `text/html` format) → - * `gdk_clipboard_read_finish` (a transfer-full `GInputStream*`). - * - * DRAINING THE STREAM **ASYNCHRONOUSLY** is load-bearing. For an own-process - * clipboard, GDK fulfils the read through an in-process `gdk_pipe_io_stream` - * whose data is pushed by a writer `GTask` that ONLY runs when the GMainContext - * iterates. A *synchronous* `g_input_stream_read_bytes` here would park on a - * `g_cond_wait` for that writer while simultaneously freezing the one thread that - * iterates the context → deadlock (this caused a multi-hour CI hang). So the - * stream is drained with `g_input_stream_read_bytes_async` chunk-by-chunk: every - * `await` yields control back to the pump, keeping the GMainContext free to feed - * the pipe. Forward progress therefore requires the event loop to turn between - * pump iterations (the app's CooperativePump and the test pump both yield) — this - * MUST NOT be driven by a tight synchronous `g_main_context_iteration` loop. - * - * JSCallback lifecycle safety (a past SIGSEGV regression — mirrors gtk-dialog's - * `runAsyncDialog`): every `GAsyncReadyCallback` thunk MUST stay reachable until - * GDK fires it, and it MUST NOT be `close()`d synchronously inside its own - * invocation (that frees the native trampoline the GDK caller is about to return - * into). Each in-flight callback is retained in the module-level {@link inFlight} - * set and `close()`d on a later tick via `setTimeout(..., 0)`. The HTML drain - * allocates a FRESH one-shot callback per chunk (reads are strictly serial, so - * there is never more than one in flight per stream — no `G_IO_ERROR_PENDING`). + * GDK 4 clipboard. Stream reads MUST drain asynchronously (D033): an own-process read is fed by + * a writer GTask that runs only when the pumped GMainContext iterates, so a synchronous read + * deadlocks the one thread that could feed it (a multi-hour CI hang). Callback lifetime: gasync.ts. */ -/** The MIME type GDK uses for UTF-8 plain text on the clipboard. */ const TEXT_MIME = 'text/plain;charset=utf-8'; -/** The MIME type for HTML markup on the clipboard. */ const HTML_MIME = 'text/html'; -/** The MIME type for PNG image data on the clipboard. */ const IMAGE_PNG_MIME = 'image/png'; -/** Bytes per `g_input_stream_read_bytes_async` call when draining a clipboard stream. */ const STREAM_CHUNK_SIZE = 65536; -/** Hard cap on drain iterations — a runaway guard (≈ 1 GiB at the chunk size). */ +/** Runaway guard: about 1 GiB at the chunk size. */ const MAX_STREAM_CHUNKS = 16384; -/** Every JSCallback awaiting a GDK clipboard read. Retained so Bun can't GC it. */ +/** Every callback GDK has yet to fire; Bun must not GC it first. */ const inFlight = new Set(); -/** - * Per-read retained buffers for an HTML read: the `text/html\0` C string and the - * `const char**` mime array handed to `gdk_clipboard_read_async`. Kept reachable - * until the async read completes so Bun cannot GC the memory GDK is reading. - */ +/** A read's mime buffers, kept reachable past `gdk_clipboard_read_async` (which copies them). */ const retainedReadBuffers = new Map(); -/** Resolve the display's `GdkClipboard*`, throwing if there is no default display. */ +/** Throws without a default display. */ const getClipboard = (): Pointer => { const gdk = loadGdkFFI(); const display = gdk.symbols.gdk_display_get_default(); @@ -84,19 +41,15 @@ const getClipboard = (): Pointer => { return clipboard; }; -/** Settle inputs for `gdk_clipboard_read_text_finish`, with finish + reader injectable. */ export type SettleReadTextArgs = { readonly result: Pointer; - /** Calls `gdk_clipboard_read_text_finish`; returns a `char*` or null; may throw. */ + /** Calls `gdk_clipboard_read_text_finish`; null when there is no text. */ readonly finish: (result: Pointer) => Pointer | null; - /** Reads (and frees) the string out of a non-null `char*`. */ + /** Reads, then frees, a non-null `char*`. */ readonly readString: (text: Pointer) => string; }; -/** - * Produce the clipboard text from a `GAsyncResult`. A null `char*` (empty/none) - * or a thrown `finish` (GError path) yields `''`. - */ +/** The clipboard text; `''` for a null `char*` or a throwing `finish`. */ export const settleReadText = (args: SettleReadTextArgs): string => { let text: Pointer | null; try { @@ -107,7 +60,7 @@ export const settleReadText = (args: SettleReadTextArgs): string => { return text === null ? '' : args.readString(text); }; -/** Read the transfer-full `char*` into a JS string, then `g_free` it. */ +/** Reads, then `g_free`s, a transfer-full `char*`. */ const readGString = (text: Pointer): string => { const glib = loadGlibFFI(); const value = new CString(text).toString(); @@ -115,20 +68,15 @@ const readGString = (text: Pointer): string => { return value; }; -/** One ASYNC chunk read + the final release of a `GInputStream`. */ +/** Async chunk reads over one `GInputStream`. */ export type AsyncStreamReader = { - /** Resolve up to `count` bytes; an empty result signals EOF (or a swallowed error). */ + /** Up to `count` bytes; an empty chunk is EOF (or a swallowed read error). */ read(count: number): Promise; - /** Release the stream (idempotent). */ + /** Idempotent. */ close(): void; }; -/** - * Drain `reader` fully into a UTF-8 string (capped by {@link MAX_STREAM_CHUNKS}). - * Strictly serial — awaits each read before issuing the next, so only one native - * read is ever in flight. `reader.close()` runs in a `finally`, so the stream is - * released on every terminal path (EOF, the cap, or a thrown read). - */ +/** Strictly serial, so only one native read is ever in flight; always closes the reader. */ export const drainStreamBytesAsync = async (reader: AsyncStreamReader): Promise => { const chunks: Uint8Array[] = []; let total = 0; @@ -147,26 +95,19 @@ export const drainStreamBytesAsync = async (reader: AsyncStreamReader): Promise< return Buffer.concat(chunks, total); }; -/** - * Drain `reader` fully into a UTF-8 string (capped by {@link MAX_STREAM_CHUNKS}). - * Concatenates bytes BEFORE decoding so a multibyte char split across a chunk - * boundary still decodes correctly. - */ +/** Decodes after concatenating, so a multibyte char split across two chunks survives. */ export const drainStreamAsync = async (reader: AsyncStreamReader): Promise => new TextDecoder().decode(await drainStreamBytesAsync(reader)); -/** Settle inputs for `gdk_clipboard_read_finish`, with finish + async drain injectable. */ export type SettleReadStreamArgs = { readonly result: Pointer; - /** Calls `gdk_clipboard_read_finish`; returns a `GInputStream*` or null; may throw. */ + /** Calls `gdk_clipboard_read_finish`; null when no offered format matches. */ readonly finish: (result: Pointer) => Pointer | null; - /** Drains a non-null `GInputStream*`. */ readonly drain: (stream: Pointer) => Promise; - /** The payload when there is no stream. */ readonly empty: T; }; -/** The clipboard payload from a `GAsyncResult`; `empty` for a null stream or a throwing finish. */ +/** The payload; `empty` for a null stream or a throwing `finish`. */ export const settleReadStream = async (args: SettleReadStreamArgs): Promise => { let stream: Pointer | null; try { @@ -177,26 +118,16 @@ export const settleReadStream = async (args: SettleReadStreamArgs): Promis return stream === null ? args.empty : args.drain(stream); }; -/** - * An {@link AsyncStreamReader} over a real GIO `GInputStream*` (transfer-full). - * - * Each `read` allocates a FRESH one-shot `GAsyncReadyCallback` (retained in - * {@link inFlight}, closed on a deferred tick after its own invocation — never - * synchronously), issues the non-blocking `g_input_stream_read_bytes_async`, and - * resolves the chunk when the callback fires. `close` drops the transfer-full ref - * with `g_object_unref` (GIO auto-closes the stream on its last unref — no - * separate, potentially-blocking, synchronous close). - */ +/** Takes a transfer-full `GInputStream*`; one fresh callback per chunk, never re-armed (D033). */ const realAsyncStreamReader = (stream: Pointer): AsyncStreamReader => { const gio = loadGioFFI(); const glib = loadGlibFFI(); let closed = false; - /** Read the chunk bytes out of a completed read's `GAsyncResult`, then unref the GBytes. */ const finishChunk = (result: Pointer): Uint8Array => { const gbytes = gio.symbols.g_input_stream_read_bytes_finish(stream, result, null); if (gbytes === null) { - return new Uint8Array(0); // GError → treat as EOF + return new Uint8Array(0); // a failed read ends the drain like EOF } const size = Number(glib.symbols.g_bytes_get_size(gbytes)); if (size === 0) { @@ -232,7 +163,7 @@ const realAsyncStreamReader = (stream: Pointer): AsyncStreamReader => { const cbPtr = cb.ptr; if (cbPtr === null) { inFlight.delete(cb); - resolve(new Uint8Array(0)); // allocation failure → EOF, ends the drain + resolve(new Uint8Array(0)); // allocation failure ends the drain like EOF return; } gio.symbols.g_input_stream_read_bytes_async(stream, BigInt(count), 0, null, cbPtr, null); @@ -242,7 +173,7 @@ const realAsyncStreamReader = (stream: Pointer): AsyncStreamReader => { return; } closed = true; - // No explicit g_input_stream_close (it can block); GIO closes on last unref. + // The last unref closes the stream (g_input_stream_dispose). loadGObjectFFI().symbols.g_object_unref(stream); }, }; @@ -308,12 +239,10 @@ const readHTML = (): Promise => new Promise((resolve, reject) => { const gdk = loadGdkFFI(); const clipboard = getClipboard(); - // NUL-terminated array of mime-type C strings: ["text/html", NULL]. + // ["text/html", NULL] const mime = new TextEncoder().encode(`${HTML_MIME}\0`); const mimeArray = new BigUint64Array([BigInt(ptr(mime)), 0n]); const callback = new JSCallback((_source: Pointer, result: Pointer, _userData: Pointer) => { - // The drain is async (yields to the pump between chunks); resolve when it - // settles. This kickoff callback's own work is done synchronously here. void settleReadStream({ result, finish: (r) => gdk.symbols.gdk_clipboard_read_finish(clipboard, r, null, null), @@ -341,7 +270,7 @@ const readImage = (): Promise => new Promise((resolve, reject) => { const gdk = loadGdkFFI(); const clipboard = getClipboard(); - // NUL-terminated array of mime-type C strings: ["image/png", NULL]. + // ["image/png", NULL] const mime = new TextEncoder().encode(`${IMAGE_PNG_MIME}\0`); const mimeArray = new BigUint64Array([BigInt(ptr(mime)), 0n]); const callback = new JSCallback((_source: Pointer, result: Pointer, _userData: Pointer) => { @@ -380,7 +309,6 @@ export const formatsFromGdk = (text: string): string[] => [ ), ]; -/** The MIME types currently advertised by the clipboard (Electron's `availableFormats`). */ const availableFormats = (): string[] => { const gdk = loadGdkFFI(); const glib = loadGlibFFI(); @@ -403,7 +331,6 @@ const clear = (): void => { gdk.symbols.gdk_clipboard_set_content(clipboard, null); }; -/** The Linux native clipboard backend (text + HTML + PNG images via GDK 4). */ export const linuxClipboardBackend: ClipboardBackend = { readText, writeText, From 176bd0b13df198487d0a1ad8cb00afff93bba277 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:26:15 -0700 Subject: [PATCH 282/586] fix: refuse quoted or relative paths in Windows showItemInFolder --- src/main/platform/windows/windows-shell.ts | 15 +++++++++++++-- .../platform/windows/windows-shell.test.ts | 18 ++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) create mode 100644 tests/unit/main/platform/windows/windows-shell.test.ts diff --git a/src/main/platform/windows/windows-shell.ts b/src/main/platform/windows/windows-shell.ts index 6a1e7164..19349c7d 100644 --- a/src/main/platform/windows/windows-shell.ts +++ b/src/main/platform/windows/windows-shell.ts @@ -1,4 +1,5 @@ import { ptr } from 'bun:ffi'; +import { win32 } from 'node:path'; import type { ShellBackend } from '../../api/shell'; import { wstr } from './win32'; import { loadUser32 } from './win32-ffi'; @@ -25,6 +26,14 @@ const shellOpen = (target: string, params?: string): boolean => { return result > SHELL_EXECUTE_SUCCESS_THRESHOLD; }; +/** + * Explorer's `/select,""` argument, or `undefined` for a path a caller must not + * forward: a quote would end the argument and inject more, a relative path resolves + * against Explorer's own cwd. + */ +export const explorerSelectArgs = (path: string): string | undefined => + path.includes('"') || !win32.isAbsolute(path) ? undefined : `/select,"${path}"`; + export const windowsShellBackend: ShellBackend = { openExternal(url: string): boolean { return shellOpen(url); @@ -35,8 +44,10 @@ export const windowsShellBackend: ShellBackend = { }, showItemInFolder(path: string): void { - // Open Explorer with the item selected (quotes guard a path with spaces). - shellOpen('explorer.exe', `/select,"${path}"`); + const args = explorerSelectArgs(path); + if (args !== undefined) { + shellOpen('explorer.exe', args); + } }, beep(): void { diff --git a/tests/unit/main/platform/windows/windows-shell.test.ts b/tests/unit/main/platform/windows/windows-shell.test.ts new file mode 100644 index 00000000..901f7b61 --- /dev/null +++ b/tests/unit/main/platform/windows/windows-shell.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, test } from 'bun:test'; +import { explorerSelectArgs } from '../../../../../src/main/platform/windows/windows-shell'; + +describe('explorerSelectArgs', () => { + test('quotes an absolute path into one /select argument', () => { + expect(explorerSelectArgs('C:\\Users\\ip\\My File.txt')).toBe( + '/select,"C:\\Users\\ip\\My File.txt"', + ); + }); + + test('refuses a path that could break out of the quoted argument', () => { + expect(explorerSelectArgs('C:\\a" /root,"C:\\evil')).toBeUndefined(); + }); + + test('refuses a relative path, which explorer would resolve against its own cwd', () => { + expect(explorerSelectArgs('notes.txt')).toBeUndefined(); + }); +}); From 80318e2a4b6e85f521e97c6a7434e2f1be6ea38e Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:26:33 -0700 Subject: [PATCH 283/586] fix: remove an engine's marker before its files in gc --- src/cli/engine-store.ts | 6 +++++- tests/unit/cli/engine-store.test.ts | 13 +++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/cli/engine-store.ts b/src/cli/engine-store.ts index 2a663fa6..949178a4 100644 --- a/src/cli/engine-store.ts +++ b/src/cli/engine-store.ts @@ -309,6 +309,8 @@ export type GcDeps = { readonly exists?: (appPath: string) => boolean; /** Report only; delete nothing. */ readonly dryRun?: boolean; + /** Recursive delete (default: `rmSync`). */ + readonly remove?: (path: string) => void; }; export type GcResult = { @@ -325,6 +327,7 @@ export type GcResult = { export const gc = async (root: string, deps: GcDeps = {}): Promise => { const exists = deps.exists ?? existsSync; const dryRun = deps.dryRun === true; + const remove = deps.remove ?? ((path: string) => rmSync(path, { recursive: true, force: true })); const scan = (): GcResult => { let droppedLinks = 0; const used = new Set(); @@ -343,7 +346,8 @@ export const gc = async (root: string, deps: GcDeps = {}): Promise => const kept = installed.filter((id) => used.has(id)).sort(); if (!dryRun) { for (const id of removed) { - rmSync(engineDir(root, id), { recursive: true, force: true }); + remove(markerPath(root, id)); // first, so a half-deleted engine never looks installed + remove(engineDir(root, id)); } } return { kept, removed, droppedLinks }; diff --git a/tests/unit/cli/engine-store.test.ts b/tests/unit/cli/engine-store.test.ts index 40df1e1a..70bdf9e0 100644 --- a/tests/unit/cli/engine-store.test.ts +++ b/tests/unit/cli/engine-store.test.ts @@ -252,6 +252,19 @@ describe('gc', () => { expect(isInstalled(root, ID2)).toBe(false); }); + test('an interrupted removal never leaves an engine looking installed', async () => { + const root = makeTmpDir(); + await installFromSource(root, fakeSource(ID), { extract: fakeExtract }); + const remove = (path: string): void => { + if (path === engineDir(root, ID)) { + throw new Error('interrupted'); + } + rmSync(path, { recursive: true, force: true }); + }; + await expect(gc(root, { exists: () => true, remove })).rejects.toThrow('interrupted'); + expect(isInstalled(root, ID)).toBe(false); + }); + test('drops links whose app no longer exists, freeing its engine', async () => { const root = makeTmpDir(); await installFromSource(root, fakeSource(ID), { extract: fakeExtract }); From bf4d7cfab7abac3af75807438a5fb2060af231f8 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:26:42 -0700 Subject: [PATCH 284/586] fix: warn when Windows lock/unlock notifications fail to register --- .../platform/windows/windows-power-monitor.ts | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/src/main/platform/windows/windows-power-monitor.ts b/src/main/platform/windows/windows-power-monitor.ts index 887034dc..60d5bb25 100644 --- a/src/main/platform/windows/windows-power-monitor.ts +++ b/src/main/platform/windows/windows-power-monitor.ts @@ -1,3 +1,4 @@ +import { createLogger } from '../../../common/logger'; import type { PowerEventHandlers } from '../macos/cocoa-power'; import { loadWtsapi32, NOTIFY_FOR_THIS_SESSION } from './win32-wts-ffi'; import { createMessageWindow, type MessageWindow } from './windows-message-window'; @@ -8,6 +9,8 @@ import { createMessageWindow, type MessageWindow } from './windows-message-windo * delivered to a hidden, non-WebKit window (see `windows-message-window.ts`). */ +const log = createLogger('windows-power-monitor'); + /** `WM_POWERBROADCAST` — system power-state change. */ export const WM_POWERBROADCAST = 0x0218; /** `WM_WTSSESSION_CHANGE` — a session lock/unlock/connect/disconnect. */ @@ -64,12 +67,18 @@ export const observePowerEvents = (handlers: PowerEventHandlers): void => { observerWindow = createMessageWindow((message, wParam) => dispatchPowerMessage(handlers, message, Number(wParam)), ); + let registered = false; try { - loadWtsapi32().symbols.WTSRegisterSessionNotification( - observerWindow.hwnd, - NOTIFY_FOR_THIS_SESSION, - ); + registered = + loadWtsapi32().symbols.WTSRegisterSessionNotification( + observerWindow.hwnd, + NOTIFY_FOR_THIS_SESSION, + ) !== 0; } catch { - // Lock/unlock notifications are unavailable; suspend/resume still work. + // wtsapi32 is missing; handled as a failed registration below. + } + if (!registered) { + // ponytail: no retry, so an early-logon failure loses lock/unlock until restart + log.warn('lock-screen/unlock-screen unavailable: WTSRegisterSessionNotification failed'); } }; From d566e1d9aed9d797117cebf1b5df26784a73fe92 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:26:53 -0700 Subject: [PATCH 285/586] chore: drop the unused WTSUnRegisterSessionNotification symbol --- src/main/platform/windows/win32-wts-ffi.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/platform/windows/win32-wts-ffi.ts b/src/main/platform/windows/win32-wts-ffi.ts index 1c17ecbc..52c10212 100644 --- a/src/main/platform/windows/win32-wts-ffi.ts +++ b/src/main/platform/windows/win32-wts-ffi.ts @@ -10,8 +10,6 @@ import { winLibraryAccessor } from './win32'; const WTSAPI32_SYMBOLS = { // (HWND, DWORD dwFlags) -> BOOL — deliver WM_WTSSESSION_CHANGE to the window. WTSRegisterSessionNotification: { args: [FFIType.u64, FFIType.u32], returns: FFIType.i32 }, - // (HWND) -> BOOL — stop delivering session-change notifications. - WTSUnRegisterSessionNotification: { args: [FFIType.u64], returns: FFIType.i32 }, } as const; /** `NOTIFY_FOR_THIS_SESSION` — only this session's lock/unlock events. */ From 9566bb9baa06c214780aa91f9afd852a5ce39cd5 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:26:59 -0700 Subject: [PATCH 286/586] chore: trim Linux D-Bus comments to the comment rules --- src/main/platform/linux/linux-dbus.ts | 121 +++++++------------------- 1 file changed, 30 insertions(+), 91 deletions(-) diff --git a/src/main/platform/linux/linux-dbus.ts b/src/main/platform/linux/linux-dbus.ts index 0d18c065..ce9f80e2 100644 --- a/src/main/platform/linux/linux-dbus.ts +++ b/src/main/platform/linux/linux-dbus.ts @@ -11,42 +11,14 @@ import { } from './gdbus-ffi'; /** - * Deadlock-safe GDBus signal-subscription primitive for the Linux backend. - * - * THE RULE (hard-won — a synchronous GIO read once hung CI for hours, see - * gtk-clipboard.ts): never block Bunmaska's single pumped thread on a D-Bus reply that - * only the GMainContext dispatch can deliver. Signal SUBSCRIPTION never blocks (the - * `GDBusSignalCallback` fires on the default GMainContext during ordinary cooperative-pump - * iterations, gtk-run-loop.ts). The one method-call helper, {@link callMethodSync}, uses a - * BOUNDED `g_dbus_connection_call_sync` whose reply is read by the connection's PRIVATE - * GDBusWorker thread and awaited on `call_sync`'s OWN private GMainContext — it stalls the - * caller for at most {@link DBUS_CALL_TIMEOUT_MS} and NEVER needs our pump to turn, so it - * is categorically unlike the clipboard's local-pipe read (whose reply could only come - * from our pump). It is still gated off in CI. - * - * `getSystemBus()` is gated behind `BUNMASKA_ENABLE_LINUX_POWER` (mirroring the libsecret - * keyring gate): CI never sets it, so the bus is NEVER touched on the headless runner and - * the backend is a guaranteed no-op there. When the flag IS set, it calls - * `g_bus_get_sync(SYSTEM)`. That IS blocking socket I/O on the calling thread, but the - * handshake is PUMP-INDEPENDENT (it does not need our GMainContext to turn), so unlike a - * `*_call_sync` reply it cannot deadlock against the pump, and it returns NULL fast when no - * bus is reachable. It is still blocking, hence gated and called AT MOST ONCE (the result - * — including NULL — is cached; the connection is a process-wide singleton anyway). - * - * THREAD INVARIANT: a subscribed signal is dispatched on the thread-default GMainContext - * of the thread that called `subscribeSignal`. The pump (gtk-run-loop.ts) iterates the - * GLOBAL-default context, so subscriptions MUST be made on the pumped main thread with no - * `g_main_context_push_thread_default` in effect (true at `onReady`) — otherwise signals - * dispatch to a context the pump never iterates and silently never fire. - * - * JSCallback lifetime: a subscription here is PERMANENT (never unsubscribed in the live - * backend), so its callback is retained forever in {@link retainedSubscriptionCallbacks} - * — the gtk-native-theme.ts long-lived-connection pattern, NOT the gtk-clipboard one-shot - * deferred-close dance. Because the callback never closes, the close-in-own-invocation - * SIGSEGV class cannot occur here. + * GDBus primitives (D037, D038). Never block the pumped thread on a reply only our GMainContext + * can deliver (the D033 hang): signals dispatch during pump iterations, and callMethodSync's + * bounded call_sync is answered on GDBus's worker thread. THREAD INVARIANT: subscribe on the + * pumped main thread with no thread-default context pushed, or signals dispatch to a context + * the pump never iterates and silently never fire. */ -/** A D-Bus signal match (each field omitted = match any). */ +/** An omitted field matches anything. */ export type SignalMatch = { readonly sender?: string; readonly interface?: string; @@ -55,31 +27,26 @@ export type SignalMatch = { readonly arg0?: string; }; -/** What a decoded signal hands back to JS. */ export type SignalEvent = { readonly signalName: string; - /** The BORROWED `parameters` GVariant tuple — read synchronously; do NOT unref it. */ + /** BORROWED tuple: read it synchronously, never unref it. */ readonly parameters: Pointer; }; -/** Whether the live system-bus path is enabled. CI leaves this unset → no bus is touched. */ +/** Unset in CI, so no system bus is touched there. */ const liveSystemBusEnabled = (): boolean => process.env['BUNMASKA_ENABLE_LINUX_POWER'] === '1'; -/** Cached system-bus result: `undefined` = not probed, `null` = absent/disabled, else the connection. */ +/** `undefined` until probed; `null` when absent or disabled. */ const cache: { systemBus: Pointer | null | undefined } = { systemBus: undefined }; -/** Retain every subscription callback for the process lifetime (Bun must not GC the thunk). */ +/** Subscriptions are permanent, so their callbacks are retained forever and never closed. */ const retainedSubscriptionCallbacks: JSCallback[] = []; -/** - * Call `g_bus_get_sync(SYSTEM)` directly, bypassing the env gate. Returns the connection - * or null; never throws. Exposed so an integration test can verify the call resolves FAST - * (it must not hang) on a runner regardless of whether a system bus is present. - */ +/** Bypasses the env gate so a test can prove the probe returns fast; null without a bus. */ export const probeSystemBusUnchecked = (): Pointer | null => { const gdbus = loadGDBusFFI(); try { - // NULL GError**: a NULL return already means "no/failed bus". + // NULL GError**: a NULL return already means no bus. return gdbus.symbols.g_bus_get_sync(G_BUS_TYPE_SYSTEM, null, null); } catch { return null; @@ -87,10 +54,8 @@ export const probeSystemBusUnchecked = (): Pointer | null => { }; /** - * The system `GDBusConnection*`, or `null` when the env gate is off OR there is no bus. - * NEVER throws and never deadlocks (the bus handshake is pump-independent blocking I/O — - * see the module note). Cached (and caches `null` so a missing/disabled bus is probed at - * most once). + * Null when BUNMASKA_ENABLE_LINUX_POWER is off or there is no bus. g_bus_get_sync blocks on + * socket I/O but never needs the pump; the result, null included, is cached so it runs once. */ export const getSystemBus = (): Pointer | null => { if (cache.systemBus !== undefined) { @@ -101,14 +66,7 @@ export const getSystemBus = (): Pointer | null => { return conn; }; -/** - * Subscribe `cb` to a D-Bus signal on `conn`. The callback fires on the GMainContext - * during normal pump iterations. The JSCallback is retained for the process lifetime - * (subscriptions here are permanent). Returns the `guint` subscription id. - * - * `cb` receives the BORROWED `parameters` GVariant (owned by GIO — read synchronously, - * never unref). A faulty `cb` is swallowed so it cannot take down the pump dispatch. - */ +/** Permanent; returns the subscription id. A throwing `cb` is swallowed. */ export const subscribeSignal = ( conn: Pointer, match: SignalMatch, @@ -131,7 +89,7 @@ export const subscribeSignal = ( parameters, }); } catch { - // A faulty handler must not crash the GMainContext dispatch. + // A throw must not unwind into the GMainContext dispatch. } }, DBUS_SIGNAL_CB_DEF, @@ -155,25 +113,18 @@ export const subscribeSignal = ( ); }; -/** Reset the system-bus probe cache. Test-only. */ +/** Test-only. */ export const resetSystemBusCacheForTesting = (): void => { cache.systemBus = undefined; }; -// --- Session bus + bounded method call (powerSaveBlocker) ------------------------------- - -/** - * Whether the live SESSION-bus method-call path is enabled. A SEPARATE flag from the - * system-bus power flag, so a developer can enable read-only power-monitor signals without - * enabling outbound blocker method calls (different bus, different risk surface). CI never - * sets it → the session bus is never touched and blocker `acquire` is a no-op. - */ +/** Separate from the system-bus flag: outbound calls on another bus. Unset in CI. */ const liveBlockerEnabled = (): boolean => process.env['BUNMASKA_ENABLE_LINUX_POWER_BLOCKER'] === '1'; const sessionCache: { sessionBus: Pointer | null | undefined } = { sessionBus: undefined }; -/** Call `g_bus_get_sync(SESSION)` directly, bypassing the gate. Never throws (see the system probe). */ +/** Bypasses the env gate; null without a bus. */ export const probeSessionBusUnchecked = (): Pointer | null => { const gdbus = loadGDBusFFI(); try { @@ -183,7 +134,7 @@ export const probeSessionBusUnchecked = (): Pointer | null => { } }; -/** The session `GDBusConnection*`, or null when the gate is off OR there is no bus. Cached. */ +/** Null when BUNMASKA_ENABLE_LINUX_POWER_BLOCKER is off or there is no bus. Cached. */ export const getSessionBus = (): Pointer | null => { if (sessionCache.sessionBus !== undefined) { return sessionCache.sessionBus; @@ -194,12 +145,8 @@ export const getSessionBus = (): Pointer | null => { }; /** - * A BOUNDED, deadlock-safe synchronous D-Bus method call. The reply is read by the - * connection's private GDBusWorker thread and awaited on `call_sync`'s own private - * GMainContext, so this blocks only the calling thread for the round-trip (finite - * {@link DBUS_CALL_TIMEOUT_MS}), never the pump. Returns the transfer-FULL reply GVariant - * tuple (caller `g_variant_unref`) or null on any failure (NULL GError**). `parameters` - * (a floating GVariant, or null for no args) is CONSUMED by the call. + * Blocks for at most DBUS_CALL_TIMEOUT_MS. `parameters` (floating, or null) is CONSUMED; the + * reply is transfer-full (the caller unrefs it), or null on any failure. */ export const callMethodSync = ( conn: Pointer, @@ -222,33 +169,29 @@ export const callMethodSync = ( G_DBUS_CALL_FLAGS_NONE, DBUS_CALL_TIMEOUT_MS, null, // cancellable - null, // error (NULL return already means "failed") + null, // error: a NULL return already means failure ); } catch { return null; } }; -/** Reset the session-bus probe cache. Test-only. */ +/** Test-only. */ export const resetSessionBusCacheForTesting = (): void => { sessionCache.sessionBus = undefined; }; -// --- Object export (StatusNotifierItem service) ---------------------------------------- - -/** Parse D-Bus introspection XML into a `GDBusNodeInfo*` (transfer-full — keep alive forever). */ +/** Transfer-full; keep it alive for as long as an object is registered with it. */ export const nodeInfoNewForXml = (xml: string): Pointer | null => loadGDBusFFI().symbols.g_dbus_node_info_new_for_xml(cstr(xml), null); -/** Look up a borrowed `GDBusInterfaceInfo*` (owned by `node`) by interface name. */ +/** BORROWED from `node`. */ export const nodeInfoLookupInterface = (node: Pointer, name: string): Pointer | null => loadGDBusFFI().symbols.g_dbus_node_info_lookup_interface(node, cstr(name)); /** - * Export an object on `conn` at `objectPath` for `interfaceInfo`, dispatched through the - * `GDBusInterfaceVTable` at `vtablePtr`. Returns the registration id (0 = failure). GDBus - * COPIES the vtable and refs the interface info — but the copied vtable holds the RAW - * function pointers of the JSCallbacks, so the CALLER must retain those callbacks forever. + * Returns the registration id (0 on failure). GDBus copies the vtable, but the copy holds the + * JSCallbacks' raw function pointers: the caller must retain those callbacks forever. */ export const registerObject = ( conn: Pointer, @@ -266,15 +209,11 @@ export const registerObject = ( null, ); -/** Remove a previously-registered object. */ export const unregisterObject = (conn: Pointer, registrationId: number): void => { loadGDBusFFI().symbols.g_dbus_connection_unregister_object(conn, registrationId); }; -/** - * Broadcast a signal from `objectPath`/`iface`. `parameters` (a floating GVariant, or null - * for an argument-less signal) is CONSUMED. - */ +/** Broadcast. `parameters` (floating, or null for no arguments) is CONSUMED. */ export const emitSignal = ( conn: Pointer, objectPath: string, @@ -284,7 +223,7 @@ export const emitSignal = ( ): void => { loadGDBusFFI().symbols.g_dbus_connection_emit_signal( conn, - null, // broadcast (no destination) + null, // no destination cstr(objectPath), cstr(iface), cstr(signalName), From 038fcf22c8b5e46dd0224c8e259d6be0b7743e46 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:26:59 -0700 Subject: [PATCH 287/586] chore: trim Windows WebKit comments to the comment rules --- src/main/platform/windows/webkit-string.ts | 9 ++-- src/main/platform/windows/webkit2-ffi.ts | 44 +++++---------- src/main/platform/windows/windows-input.ts | 12 ++--- .../platform/windows/windows-web-contents.ts | 29 +++------- .../platform/windows/windows-webkit-view.ts | 54 +++++-------------- .../windows/fixtures/webkit-ipc-probe.ts | 2 +- .../windows/fixtures/window-close-probe.ts | 2 +- .../windows/windows-webkit-view.test.ts | 2 +- .../platform/windows/webkit2-resolve.test.ts | 10 +--- 9 files changed, 42 insertions(+), 122 deletions(-) diff --git a/src/main/platform/windows/webkit-string.ts b/src/main/platform/windows/webkit-string.ts index 9aa45c61..27d5c490 100644 --- a/src/main/platform/windows/webkit-string.ts +++ b/src/main/platform/windows/webkit-string.ts @@ -3,12 +3,9 @@ import { FFIError } from '../../../common/errors'; import { cstr } from '../cstr'; import { loadWebKit2 } from './webkit2-ffi'; -/** - * WK string objects are reference-counted: every `wk*` creator here returns a +1 - * reference the caller must hand to {@link wkRelease}. - */ +// Every `wk*` creator here returns a +1 reference the caller must hand to `wkRelease`. -/** Create a `WKStringRef` from a JS string. Caller releases it with {@link wkRelease}. */ +/** Create a `WKStringRef` from a JS string. */ export const wkString = (value: string): Pointer => { const ref = loadWebKit2().symbols.WKStringCreateWithUTF8CString(cstr(value)); if (ref === null) { @@ -33,7 +30,7 @@ export const wkStringToJs = (ref: Pointer): string => { return new TextDecoder().decode(buffer.subarray(0, length)); }; -/** Create a `WKURLRef` from a URL string. Caller releases it with {@link wkRelease}. */ +/** Create a `WKURLRef` from a URL string. */ export const wkUrl = (value: string): Pointer => { const ref = loadWebKit2().symbols.WKURLCreateWithUTF8CString(cstr(value)); if (ref === null) { diff --git a/src/main/platform/windows/webkit2-ffi.ts b/src/main/platform/windows/webkit2-ffi.ts index 7e666dc8..82443cc0 100644 --- a/src/main/platform/windows/webkit2-ffi.ts +++ b/src/main/platform/windows/webkit2-ffi.ts @@ -7,11 +7,8 @@ import { type ResolveDeps, resolveEngineWith } from '../../engine/resolve'; import { winLibraryAccessor, wstr } from './win32'; import { loadKernel32 } from './win32-ffi'; -/** - * WinCairo WebKit2 C API FFI. Opaque `WK*Ref` handles are plain pointers (`ptr`) and - * `size_t` is `u64` on x64. Unlike Linux there is NO system-WebKit fallback — Windows - * ships none — so any `system` resolution outcome means "no engine" here. - */ +// Opaque `WK*Ref` handles bind as `ptr`; `size_t` is `u64` on x64. Windows ships no system +// WebKit, so a `system` resolution means "no engine" here. const WEBKIT2_SYMBOLS = { // ── Context + configuration ────────────────────────────────────────────── @@ -44,15 +41,15 @@ const WEBKIT2_SYMBOLS = { WKPageCanGoForward: { args: [FFIType.ptr], returns: FFIType.bool }, WKPageCopyActiveURL: { args: [FFIType.ptr], returns: FFIType.ptr }, WKPageCopyTitle: { args: [FFIType.ptr], returns: FFIType.ptr }, - // (page, script, void* context, completion) — context+completion passed NULL for - // fire-and-forget eval; executeJavaScript results return out-of-band (D022). + // (page, script, void* context, completion): both NULL; executeJavaScript results + // return out-of-band over a script message (D022b). WKPageEvaluateJavaScriptInMainFrame: { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.ptr], returns: FFIType.void, }, WKPageSetPageZoomFactor: { args: [FFIType.ptr, FFIType.f64], returns: FFIType.void }, WKPageSetCustomUserAgent: { args: [FFIType.ptr, FFIType.ptr], returns: FFIType.void }, - // (page, const WKPageNavigationClientBase*) — register navigation lifecycle callbacks. + // (page, const WKPageNavigationClientBase*); NULL clears it. WKPageSetPageNavigationClient: { args: [FFIType.ptr, FFIType.ptr], returns: FFIType.void }, // ── Errors (for did-fail-load) ─────────────────────────────────────────── @@ -102,16 +99,16 @@ const WEBKIT2_SYMBOLS = { WKURLCopyString: { args: [FFIType.ptr], returns: FFIType.ptr }, // ── Website data (used by the session backend) ─────────────────────────── - // () -> WKWebsiteDataStoreRef — the process-wide default store. + // () -> WKWebsiteDataStoreRef, the process-wide default store. WKWebsiteDataStoreGetDefaultDataStore: { args: [], returns: FFIType.ptr }, // (WKWebsiteDataStoreRef) -> WKHTTPCookieStoreRef WKWebsiteDataStoreGetHTTPCookieStore: { args: [FFIType.ptr], returns: FFIType.ptr }, - // (WKHTTPCookieStoreRef, void* context, callback(void* context)) -> void — async. + // (WKHTTPCookieStoreRef, void* context, callback(void* context)) -> void, async. WKHTTPCookieStoreDeleteAllCookies: { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr], returns: FFIType.void, }, - // (WKWebsiteDataStoreRef, void* context, callback(void* context)) -> void — async. + // (WKWebsiteDataStoreRef, void* context, callback(void* context)) -> void, async. WKWebsiteDataStoreRemoveAllFetchCaches: { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr], returns: FFIType.void, @@ -127,12 +124,7 @@ export const WK_INJECT_AT_DOCUMENT_START = 0; /** The subdir an embedded engine is bundled into (must match `build-windows.ts`). */ const BUNDLED_ENGINE_DIRNAME = 'webkit'; -/** - * A WinCairo engine bundled next to the executable — `/webkit/` with a - * `WebKit2.dll` (what `bunmaska build --embed-engine` produces) — or `undefined`. - * This is what lets a packaged `.exe` run with no environment variables. Pure; - * `exists` is a test seam. - */ +/** `/webkit/` if it holds `WebKit2.dll` (from `build --embed-engine`), else `undefined`. */ export const bundledEngineDir = ( execPath: string, exists: (path: string) => boolean, @@ -141,13 +133,7 @@ export const bundledEngineDir = ( return exists(join(dir, 'WebKit2.dll')) ? dir : undefined; }; -/** - * The directory of the WinCairo WebKit engine this process loads, or `undefined` - * when none is available (there is no system WebKit to fall back to on Windows). - * Precedence: an explicit/store pin via {@link resolveEngineWith} (the engine's - * `lib/`, or the verbatim `BUNMASKA_WEBKIT_PATH`), then a {@link bundledEngineDir} - * shipped next to the executable. `deps` is a test seam. - */ +/** The engine dir to load: a pin beats a {@link bundledEngineDir}; `undefined` if neither. */ export const resolveWindowsEngineDir = ( deps: ResolveDeps & { readonly execPath?: string } = {}, ): string | undefined => { @@ -158,15 +144,9 @@ export const resolveWindowsEngineDir = ( return bundledEngineDir(deps.execPath ?? process.execPath, deps.exists ?? existsSync); }; -/** - * Open the engine's `WebKit2.dll` and return its symbol table. Memoised; - * import-safe (throws on non-Windows via the accessor). Puts the engine dir on - * the DLL search path first so the bundled closure resolves beside `WebKit2.dll`. - * A pinned-but-uninstalled engine surfaces the resolver's warning in the error. - */ +/** Memoised `WebKit2.dll` symbols; the engine dir goes on the DLL search path for its closure. */ export const loadWebKit2 = winLibraryAccessor('WebKit2', () => { - // Use the full resolution (store/explicit pin AND an engine bundled next to the - // executable) — NOT resolveEngineWith alone, which misses the bundled fallback. + // Never resolveEngineWith alone: it misses the engine bundled next to the executable. const dir = resolveWindowsEngineDir(); if (dir === undefined) { const detail = resolveEngineWith().warnings.join('; '); diff --git a/src/main/platform/windows/windows-input.ts b/src/main/platform/windows/windows-input.ts index 82fd367c..15be8cad 100644 --- a/src/main/platform/windows/windows-input.ts +++ b/src/main/platform/windows/windows-input.ts @@ -1,13 +1,9 @@ import type { MouseButton, NativeInputEvent } from '../native'; import { loadUser32 } from './win32-ffi'; -/** - * WinCairo WebKit's WKView hosts itself in an HWND whose window procedure turns native - * Win32 input messages into engine-level `PlatformMouseEvent`s, so the page sees - * `isTrusted === true` — exactly what a script-dispatched `element.click()` cannot - * produce. Coordinates are client pixels relative to the view's top-left; per-monitor DPI - * scaling is a follow-up — at 100% scale logical and client pixels coincide. - */ +// Win32 messages to the WKView's HWND become engine-level events with `isTrusted === true`, +// which a script-dispatched `element.click()` cannot produce. +// ponytail: coordinates are client px, equal to logical px only while bun.exe is DPI-unaware. const WM_MOUSEMOVE = 0x0200; const WM_LBUTTONDOWN = 0x0201; @@ -20,7 +16,7 @@ const WM_KEYDOWN = 0x0100; const WM_KEYUP = 0x0101; const WM_CHAR = 0x0102; -/** WPARAM button bits for a *BUTTONDOWN message (which buttons are currently down). */ +/** MK_* WPARAM bits: which buttons are down. */ const MK_LBUTTON = 0x0001; const MK_RBUTTON = 0x0002; const MK_MBUTTON = 0x0010; diff --git a/src/main/platform/windows/windows-web-contents.ts b/src/main/platform/windows/windows-web-contents.ts index 171e1db9..45dc3489 100644 --- a/src/main/platform/windows/windows-web-contents.ts +++ b/src/main/platform/windows/windows-web-contents.ts @@ -14,34 +14,18 @@ import type { NativeInputEvent, NativeNavigationEvent, NativeWebContents } from import { WINDOW_HANDLER_NAME, windowControlsScript } from '../window-controls'; import { WindowsWebView } from './windows-webkit-view'; -/** - * The renderer posts envelopes via `window.webkit.messageHandlers.bunmaska`; the main - * process pushes envelopes back by evaluating `window.__bunmaska._dispatch(...)` - * fire-and-forget (D022). `executeJavaScript` returns out-of-band through a `bunmaskaExec` - * page-world handler — a per-call native completion callback would be freed - * mid-invocation. The `BunmaskaPreload` isolation used on macOS/Linux is a follow-up. - */ - -/** The script-message handler name the preload bridge posts envelopes to. */ const HANDLER_NAME = 'bunmaska'; -/** Page-world handler name `executeJavaScript` posts its result to. */ const EXEC_HANDLER_NAME = 'bunmaskaExec'; const log = createLogger('windows-web-contents'); -/** A pending `executeJavaScript` awaiting its page-world result message. */ interface PendingExec { readonly resolve: (value: unknown) => void; readonly reject: (reason: Error) => void; readonly timer: ReturnType; } -/** - * Out-of-band `executeJavaScript` channel. Injects a wrapper that posts - * `{ execId, ok, result?, error? }` to the `bunmaskaExec` handler (registered once, torn - * down with the window), and settles the matching Promise here. No per-call native - * callback to free. - */ +/** `executeJavaScript` over the `bunmaskaExec` script message, not a native callback (D022b). */ class WindowsExecResultChannel { readonly #evalInPage: (wrapped: string) => void; readonly #pending = new Map(); @@ -121,6 +105,8 @@ export class WindowsWebContents implements NativeWebContents { log.warn(`protocol.handle schemes are not served on Windows yet: ${schemes.join(', ')}`); } const channelId = generateChannelId(); + // ponytail: no context isolation (S03), preload + window.__bunmaska share the page world; + // isolation needs a WKBundle script world, i.e. compiled code (D011). const userScripts: string[] = [ generateIsolatedChannelSetup(channelId), generatePreloadBootstrap(), @@ -185,12 +171,11 @@ export class WindowsWebContents implements NativeWebContents { } } - /** Register a handler for window ops a custom title bar triggers (drag/minimize/…). */ + /** Register a handler for window ops a custom title bar triggers (drag, minimize, ...). */ onWindowOp(callback: (op: string) => void): void { this.#windowOpCallbacks.push(callback); } - /** Route a `{ op }` message from the built-in title-bar script to its handlers. */ #dispatchWindowOp(json: string): void { let op: unknown; try { @@ -262,7 +247,7 @@ export class WindowsWebContents implements NativeWebContents { // Engine-blocked on WinCairo: the UI-process WK2 C API on this build exports no // PDF sink (`WKPageDrawPagesToPDF` is Cocoa-only; only Begin/Compute/EndPrinting - // are present, which paginate but yield no PDF data). Revisit if upstream adds one. + // are present, which paginate but yield no PDF data). printToPDF(): Promise { return Promise.reject( new UnsupportedPlatformError( @@ -325,11 +310,11 @@ export class WindowsWebContents implements NativeWebContents { } setWindowOpenHandler(_callback: (url: string) => void): void { - // ponytail: popups stay blocked but the URL is dropped; forward it via WKPageUIClient createNewPage. + // ponytail: URL dropped (popup still blocked); forward it via WKPageUIClient createNewPage. log.warn('setWindowOpenHandler is not supported on Windows yet: the handler is never called'); } - /** @internal Reject pending execs and release the view. Called on window close. */ + /** @internal Settle pending execs and blank the view. Called on window close. */ dispose(): void { this.#exec.rejectPending(); this.#webView.dispose(); diff --git a/src/main/platform/windows/windows-webkit-view.ts b/src/main/platform/windows/windows-webkit-view.ts index 8af38a3b..1b79b203 100644 --- a/src/main/platform/windows/windows-webkit-view.ts +++ b/src/main/platform/windows/windows-webkit-view.ts @@ -7,39 +7,23 @@ import { loadKernel32, loadUser32 } from './win32-ffi'; import { heldButtonsAfter, postWindowsInputEvent } from './windows-input'; import { createNativeChildHost, ensureOleInitialized } from './windows-native-window'; -/** - * The view is parented into a dedicated NATIVE-WndProc child window - * ({@link createNativeChildHost}); WebKit floods its host with re-entrant messages during - * a load, which a `bun:ffi` `JSCallback` WndProc cannot survive. The public WebKit2 C API - * exposes no named content world, so the injected scripts and the - * `window.webkit.messageHandlers.` bridge run in the PAGE world. - */ - -/** `SetWindowPos` flags for an in-place resize (keep position, z-order, focus). */ +// D043: the view's host must be a native-WndProc child; WebKit's re-entrant message flood +// kills a JSCallback WndProc. The C API has no named content world, so every injected script +// and message handler lives in the PAGE world. + const SWP_NOMOVE_NOZORDER_NOACTIVATE = 0x0002 | 0x0004 | 0x0010; -/** - * Trampolines kept alive for the process lifetime. WebKit's multi-process engine - * tears down asynchronously and may still call a view's script-message/navigation - * callbacks after `dispose`, so they are retained here rather than closed (a small, - * bounded per-window retention — closing them mid-teardown is a use-after-free). - */ +/** Never closed (D043: closing one mid-teardown is a use-after-free); dispose empties its sinks. */ const retainedTrampolines: JSCallback[] = []; const retainTrampolines = (callbacks: readonly JSCallback[]): void => { retainedTrampolines.push(...callbacks); }; -/** `(HANDLE)-1` — the pseudo-handle for the current process. */ +/** `(HANDLE)-1`, the current-process pseudo-handle. */ const CURRENT_PROCESS = 0xffffffffffffffffn; let cleanExitInstalled = false; -/** - * Install a one-shot `exit` handler that HARD-terminates the process. WinCairo - * WebKit crashes in its static / DLL-detach teardown when a process with a live - * engine exits normally; terminating from the `exit` handler — after the app's - * quit events have already run — bypasses that teardown for a clean exit code. - * Installed lazily on first view creation (i.e. only once the engine is loaded). - */ +/** D043: WinCairo crashes in DLL-detach teardown on a normal exit, so hard-terminate on `exit`. */ const installCleanExit = (): void => { if (cleanExitInstalled) { return; @@ -50,12 +34,7 @@ const installCleanExit = (): void => { }); }; -/** - * A single `WKContext` — WebKit's process pool + default website data store (cookies, localStorage) - * — shared by EVERY view, so all windows see ONE session, matching Electron's default-session - * semantics (a per-view context would start each new window logged out). Created lazily and retained - * for the process lifetime (it outlives individual views — never freed). - */ +/** One process pool for every view, never freed. Cookies live in the default WebsiteDataStore. */ let sharedContext: Pointer | null = null; const sharedWebKitContext = (): Pointer => { if (sharedContext !== null) { @@ -97,12 +76,7 @@ const readWkError = (errorRef: Pointer | null): { code: number; description: str return { code, description }; }; -/** - * Register the page navigation client (the WinCairo peer of the macOS/Linux - * navigation delegates) and return the retained trampolines. Each callback fires - * during WebKit's message processing — the same controlled context as the - * script-message handlers — and is closed only on view teardown. - */ +/** Register the page navigation client; returns its trampolines for D043 retention. */ const setupNavigationClient = ( page: Pointer, onEvent: (event: NativeNavigationEvent) => void, @@ -208,7 +182,7 @@ export interface WebViewOptions { readonly userScripts: readonly string[]; /** Renderer->main message handlers, keyed by their `messageHandlers` name. */ readonly messageHandlers: readonly ScriptMessageHandler[]; - /** Navigation lifecycle sink (did-start/commit/finish/fail). Optional. */ + /** Navigation lifecycle sink (did-start/commit/finish/fail). */ readonly onNavigationEvent?: (event: NativeNavigationEvent) => void; } @@ -251,9 +225,6 @@ export class WindowsWebView { installCleanExit(); const wk = loadWebKit2(); const s = wk.symbols; - - // Shared session (Electron parity): every view uses ONE context, so a window opened after login - // sees the logged-in session — the SSO bridge windows (AIS/TRACES) depend on this. const context = sharedWebKitContext(); const controller = s.WKUserContentControllerCreate(); @@ -282,7 +253,7 @@ export class WindowsWebView { callbacks.push(callback); } - // Inject the preload/bridge sources at document-start, in order. + // Main frame only: with no isolated world, an iframe must never get the bridge. for (const source of options.userScripts) { const sourceRef = wkString(source); const userScript = s.WKUserScriptCreateWithSource(sourceRef, WK_INJECT_AT_DOCUMENT_START, 1); @@ -302,8 +273,7 @@ export class WindowsWebView { const hostWindow = createNativeChildHost(options.hwnd, options.width, options.height); - // RECT{left,top,right,bottom}: fill the host child. Win64 passes the 16-byte - // struct by hidden pointer, so we hand WKViewCreate the RECT buffer. + // RECT{left,top,right,bottom}, passed by hidden pointer (see WKViewCreate in webkit2-ffi.ts). const rect = new Int32Array([0, 0, options.width, options.height]); const view = s.WKViewCreate(ptr(rect), pageConfig, hostWindow); wkRelease(pageConfig); diff --git a/tests/integration/windows/fixtures/webkit-ipc-probe.ts b/tests/integration/windows/fixtures/webkit-ipc-probe.ts index d7b64fde..977864bf 100644 --- a/tests/integration/windows/fixtures/webkit-ipc-probe.ts +++ b/tests/integration/windows/fixtures/webkit-ipc-probe.ts @@ -4,7 +4,7 @@ * main process through the cooperative pump. Prints `IPC_OK ` on success. * * Run in a fresh Bun process (not under bun:test) because WebKit's multi-process - * IPC + thread affinity are incompatible with the test-runner host — the Linux + * IPC + thread affinity are incompatible with the test-runner host; the Linux * engine-pinned-load test uses the same spawned-subprocess pattern. Requires * BUNMASKA_WEBKIT_PATH to point at a WinCairo engine directory. */ diff --git a/tests/integration/windows/fixtures/window-close-probe.ts b/tests/integration/windows/fixtures/window-close-probe.ts index cf34b361..c7655f57 100644 --- a/tests/integration/windows/fixtures/window-close-probe.ts +++ b/tests/integration/windows/fixtures/window-close-probe.ts @@ -1,5 +1,5 @@ /** - * Subprocess fixture: a real BrowserWindow loads a page, then closes — proving + * Subprocess fixture: a real BrowserWindow loads a page, then closes, proving * the WebKit-view teardown on window close is crash-free. The `window-all-closed` * listener keeps the app alive so this isolates the window close from app-exit * (synchronous WebKit shutdown at process exit is a separate, documented item). diff --git a/tests/integration/windows/windows-webkit-view.test.ts b/tests/integration/windows/windows-webkit-view.test.ts index 2fea77c4..24461500 100644 --- a/tests/integration/windows/windows-webkit-view.test.ts +++ b/tests/integration/windows/windows-webkit-view.test.ts @@ -6,7 +6,7 @@ import { resolveWindowsEngineDir } from '../../../src/main/platform/windows/webk * Windows + engine only. The load-bearing WinCairo proof: a real `WKView` hosted * in a native Win32 window spawns the WebKit web/network processes, runs an * injected document-start script, and delivers its `postMessage` back to the main - * process through Bunmaska's cooperative Win32 message pump — all in pure + * process through Bunmaska's cooperative Win32 message pump, all in pure * `bun:ffi`, zero compiled native code. * * Driven in a spawned Bun subprocess: WebKit's multi-process IPC + thread diff --git a/tests/unit/main/platform/windows/webkit2-resolve.test.ts b/tests/unit/main/platform/windows/webkit2-resolve.test.ts index 35d3d7b5..6b6a890d 100644 --- a/tests/unit/main/platform/windows/webkit2-resolve.test.ts +++ b/tests/unit/main/platform/windows/webkit2-resolve.test.ts @@ -6,15 +6,7 @@ import { resolveWindowsEngineDir, } from '../../../../../src/main/platform/windows/webkit2-ffi'; -/** - * `resolveWindowsEngineDir` decides which WinCairo WebKit directory THIS Windows - * process loads. Windows ships no system WebKit, so — unlike Linux, where the - * resolver can fall back to the OS WebKitGTK — every "system" outcome here means - * "no engine" (`undefined`). It delegates to the cross-platform `resolveEngineWith`, - * so the precedence (BUNMASKA_WEBKIT_PATH > BUNMASKA_WEBKIT_ID > baked engine.id) - * and the store layout (`//lib`) are inherited; these tests pin down the - * Windows-specific mapping of that resolution to a directory. - */ +// Windows ships no system WebKit, so every "system" resolution means "no engine" (`undefined`). const ID = 'webkit-2-2.52.4-bunmaska1-windows-x64'; const ROOT = 'C:\\store\\webkit'; const APP_DIR = 'C:\\Program Files\\My App'; From 74964c039542a360cd729ea6319b32f33e838fe5 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:27:14 -0700 Subject: [PATCH 288/586] refactor: measure CF_HTML offsets with Buffer.byteLength --- src/main/platform/windows/windows-clipboard.ts | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/main/platform/windows/windows-clipboard.ts b/src/main/platform/windows/windows-clipboard.ts index f25d520f..34e02e62 100644 --- a/src/main/platform/windows/windows-clipboard.ts +++ b/src/main/platform/windows/windows-clipboard.ts @@ -42,8 +42,6 @@ const cfHtmlFormat = (): number => { /** Pad an offset to the fixed 10-digit width CF_HTML headers conventionally use. */ const pad = (value: number): string => String(value).padStart(10, '0'); -const byteLength = (text: string): number => new TextEncoder().encode(text).length; - const FRAGMENT_START = ''; const FRAGMENT_END = ''; @@ -60,11 +58,11 @@ export const buildCfHtml = (markup: string): string => { const pre = `\r\n${FRAGMENT_START}`; const post = `${FRAGMENT_END}\r\n`; // The header's byte length is constant regardless of the (always 10-digit) values. - const headerLength = byteLength(header(0, 0, 0, 0)); + const headerLength = Buffer.byteLength(header(0, 0, 0, 0)); const startHtml = headerLength; - const startFragment = headerLength + byteLength(pre); - const endFragment = startFragment + byteLength(markup); - const endHtml = endFragment + byteLength(post); + const startFragment = headerLength + Buffer.byteLength(pre); + const endFragment = startFragment + Buffer.byteLength(markup); + const endHtml = endFragment + Buffer.byteLength(post); return `${header(startHtml, endHtml, startFragment, endFragment)}${pre}${markup}${post}`; }; From 5b61ba300127eb8c2c6dfaca49fc6101cea63ce5 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:27:15 -0700 Subject: [PATCH 289/586] fix: reclaim stale staging and half-removed engines in gc --- src/cli/engine-store.ts | 28 +++++++++++++++++++++++++++- tests/unit/cli/engine-store.test.ts | 24 +++++++++++++++++++++++- 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/src/cli/engine-store.ts b/src/cli/engine-store.ts index 949178a4..2663d5c5 100644 --- a/src/cli/engine-store.ts +++ b/src/cli/engine-store.ts @@ -23,6 +23,7 @@ import { import { createHash } from 'node:crypto'; import { homedir } from 'node:os'; import { isAbsolute, join, resolve, sep } from 'node:path'; +import { parseEngineId } from '../common/engine-id'; import { BunmaskaError } from '../common/errors'; import { contentHash } from '../common/manifest'; @@ -32,6 +33,8 @@ const LOCK_FILE = '__dirlock'; const STALE_LOCK_MS = 30_000; const LOCK_RETRY_MS = 5; const LOCK_TIMEOUT_MS = 10_000; +/** Younger staging dirs may belong to an install still extracting. */ +const STALE_STAGING_MS = 60 * 60_000; export type StoreEnv = Record; @@ -85,6 +88,15 @@ export const lockPath = (root: string): string => join(root, LOCK_FILE); export const isInstalled = (root: string, id: string): boolean => existsSync(markerPath(root, id)); +const isEngineId = (name: string): boolean => { + try { + parseEngineId(name); + return true; + } catch { + return false; + } +}; + /** The installed (marker-complete) engine ids in the store, sorted. */ export const listInstalled = (root: string): string[] => { if (!existsSync(root)) { @@ -342,13 +354,27 @@ export const gc = async (root: string, deps: GcDeps = {}): Promise => } } const installed = listInstalled(root); - const removed = installed.filter((id) => !used.has(id)).sort(); + const dirs = existsSync(root) + ? readdirSync(root, { withFileTypes: true }) + .filter((entry) => entry.isDirectory()) + .map((entry) => entry.name) + : []; + const broken = dirs.filter((name) => isEngineId(name) && !isInstalled(root, name)); + const staleStaging = dirs.filter( + (name) => + name.startsWith('.tmp-') && + Date.now() - statSync(join(root, name)).mtimeMs > STALE_STAGING_MS, + ); + const removed = [...installed.filter((id) => !used.has(id)), ...broken].sort(); const kept = installed.filter((id) => used.has(id)).sort(); if (!dryRun) { for (const id of removed) { remove(markerPath(root, id)); // first, so a half-deleted engine never looks installed remove(engineDir(root, id)); } + for (const name of staleStaging) { + remove(join(root, name)); + } } return { kept, removed, droppedLinks }; }; diff --git a/tests/unit/cli/engine-store.test.ts b/tests/unit/cli/engine-store.test.ts index 70bdf9e0..4a9a00e2 100644 --- a/tests/unit/cli/engine-store.test.ts +++ b/tests/unit/cli/engine-store.test.ts @@ -1,5 +1,13 @@ import { afterEach, describe, expect, test } from 'bun:test'; -import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + utimesSync, + writeFileSync, +} from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { contentHash } from '../../../src/common/manifest'; @@ -265,6 +273,20 @@ describe('gc', () => { expect(isInstalled(root, ID)).toBe(false); }); + test('reclaims interrupted installs: old staging dirs and marker-less engine dirs', async () => { + const root = makeTmpDir(); + for (const name of ['.tmp-old', '.tmp-new', ID2]) { + mkdirSync(join(root, name, 'lib'), { recursive: true }); + } + const hourAgo = new Date(Date.now() - 2 * 60 * 60 * 1000); + utimesSync(join(root, '.tmp-old'), hourAgo, hourAgo); + const result = await gc(root, { exists: () => true }); + expect(existsSync(join(root, '.tmp-old'))).toBe(false); + expect(existsSync(join(root, '.tmp-new'))).toBe(true); // may be an install in progress + expect(existsSync(engineDir(root, ID2))).toBe(false); + expect(result.removed).toEqual([ID2]); + }); + test('drops links whose app no longer exists, freeing its engine', async () => { const root = makeTmpDir(); await installFromSource(root, fakeSource(ID), { extract: fakeExtract }); From 7c3c76d3725e53139cb6822a4c08a2050a26282b Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:27:36 -0700 Subject: [PATCH 290/586] test: drop Windows shell and notification assertions that cannot fail --- tests/integration/windows/notification.test.ts | 7 +++---- tests/integration/windows/shell.test.ts | 5 ----- 2 files changed, 3 insertions(+), 9 deletions(-) diff --git a/tests/integration/windows/notification.test.ts b/tests/integration/windows/notification.test.ts index db6c768d..0178e599 100644 --- a/tests/integration/windows/notification.test.ts +++ b/tests/integration/windows/notification.test.ts @@ -25,16 +25,15 @@ if (currentPlatform() === 'windows') { test('present shows a balloon and returns a closable handle', () => { const handle = windowsNotificationBackend.present(spec); - expect(typeof handle.close).toBe('function'); expect(() => handle.close()).not.toThrow(); // close is idempotent. expect(() => handle.close()).not.toThrow(); }); test('a silent notification presents without throwing', () => { - const handle = windowsNotificationBackend.present({ ...spec, silent: true }); - handle.close(); - expect(true).toBe(true); + expect(() => + windowsNotificationBackend.present({ ...spec, silent: true }).close(), + ).not.toThrow(); }); test('onClosed registers a callback without firing it eagerly', () => { diff --git a/tests/integration/windows/shell.test.ts b/tests/integration/windows/shell.test.ts index c86d1de3..b9ce763f 100644 --- a/tests/integration/windows/shell.test.ts +++ b/tests/integration/windows/shell.test.ts @@ -24,11 +24,6 @@ if (currentPlatform() === 'windows') { expect(windowsShellBackend.openPath(NON_EXISTENT)).toBe(false); }); - test('exposes openExternal and showItemInFolder', () => { - expect(typeof windowsShellBackend.openExternal).toBe('function'); - expect(typeof windowsShellBackend.showItemInFolder).toBe('function'); - }); - test('the public shell.openPath surfaces the failure as an error string', async () => { const result = await shell.openPath(NON_EXISTENT); expect(result).toContain('Failed to open path'); From 94e3b9951e49d6d3b799605a97b1337ee2c1d170 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:27:44 -0700 Subject: [PATCH 291/586] chore: trim Linux tray comments to the comment rules --- src/main/platform/linux/sni-tray.ts | 74 ++++++++++------------------- 1 file changed, 26 insertions(+), 48 deletions(-) diff --git a/src/main/platform/linux/sni-tray.ts b/src/main/platform/linux/sni-tray.ts index 0ccc6363..120260a5 100644 --- a/src/main/platform/linux/sni-tray.ts +++ b/src/main/platform/linux/sni-tray.ts @@ -22,27 +22,10 @@ import { } from './linux-dbus'; /** - * Linux `Tray` via StatusNotifierItem (SNI) over D-Bus. We EXPORT an - * `org.kde.StatusNotifierItem` object on the session bus (a host — KDE, the GNOME - * AppIndicator extension, Waybar, swaybar — draws the icon by reading our properties), and - * register it with `org.kde.StatusNotifierWatcher`. - * - * v1 ships icon + tooltip + LEFT-CLICK (the host's `Activate` → our `click`). The context - * menu is DEFERRED: SNI's `Menu` points at a separate `com.canonical.dbusmenu` service - * (another large export) — so `setContextMenu` is an accepted soft no-op on Linux v1 (it - * does not throw; cross-platform callers that set a menu unconditionally still work). - * - * DEADLOCK/HANG-SAFE: the only blocking call is the bounded {@link callMethodSync} (5s); the - * vtable callbacks fire on the GMainContext via the cooperative pump. CI-HANG-SAFE: gated - * behind `BUNMASKA_ENABLE_LINUX_TRAY` (CI never sets it) → `create` returns an INERT no-op - * instance, no bus touched, no object exported. - * - * LIFETIME (load-bearing, blind — verified by review, not CI): `register_object` COPIES the - * vtable, so the live wires are the TWO JSCallbacks (the copied vtable holds their raw - * fn-pointers) — they are retained FOREVER (never closed, mirroring the signal-subscription - * discipline; closing would risk the in-flight-reply / own-invocation SIGSEGV class). - * Property getters MUST be on the pumped main thread (the THREAD INVARIANT - * in linux-dbus.ts) or the host's queries dispatch to a context nothing iterates. + * Tray as a StatusNotifierItem on the session bus, gated by BUNMASKA_ENABLE_LINUX_TRAY (unset in + * CI, which gets an inert tray). Create it on the pumped main thread (the linux-dbus THREAD + * INVARIANT). The vtable JSCallbacks are retained forever and never closed: GDBus's copy of the + * vtable holds their raw function pointers. */ const OBJECT_PATH_PREFIX = '/StatusNotifierItem'; @@ -51,8 +34,7 @@ const WATCHER_NAME = 'org.kde.StatusNotifierWatcher'; const WATCHER_PATH = '/StatusNotifierWatcher'; const APP_ID = 'bunmaska'; -/** The interface we export. Only properties we actually serve are declared (a host uses - * defaults for anything absent), so GetAll never hits an unserved property. */ +/** Only served properties are declared, so GetAll never hits an unserved one. */ export const SNI_XML = ` @@ -75,17 +57,16 @@ export const SNI_XML = ` `; -/** Whether the live SNI path is enabled. CI leaves this unset → an inert no-op tray. */ +/** Unset in CI, which gets an inert tray. */ const liveTrayEnabled = (): boolean => process.env['BUNMASKA_ENABLE_LINUX_TRAY'] === '1'; -// Process-lifetime retains (never freed — see the module note): the vtable JSCallbacks -// (the copied vtable holds their raw fn-pointers) + the node infos + vtable arrays. +// Never freed: the vtable JSCallbacks, node infos and vtable arrays of every registered tray. const retained: { callbacks: JSCallback[]; misc: unknown[]; } = { callbacks: [], misc: [] }; -/** Cached `GVariantType*` per type string (allocated once, retained for the process). */ +/** One `GVariantType*` per type string, never freed. */ const variantTypes = new Map(); const variantType = (typeString: string): Pointer => { const cached = variantTypes.get(typeString); @@ -101,10 +82,9 @@ const variantType = (typeString: string): Pointer => { }; /** - * Convert GdkPixbuf rows (RGB or RGBA, `rowstride`-padded) to tightly-packed ARGB32 in - * NETWORK (big-endian) byte order — the SNI IconPixmap wire format. PURE (no FFI): width/ - * height stay native (the `i` members go through g_variant_new_int32); only these pixel - * bytes are pre-swapped. A 3-channel (no-alpha) source synthesizes A=0xFF. + * GdkPixbuf rows (RGB or RGBA, rowstride-padded) to packed ARGB32 in NETWORK byte order, the + * IconPixmap wire format. Only pixel bytes are swapped: width and height stay native through + * g_variant_new_int32. A 3-channel source gets A=0xFF. */ export const rgbaToArgb32Network = ( pixels: Uint8Array, @@ -135,7 +115,7 @@ export const rgbaToArgb32Network = ( type Icon = { argb: Uint8Array; width: number; height: number }; -/** Decode an icon file into ARGB32 pixels, or null if unreadable. Unrefs the pixbuf. */ +/** Null when the file is unreadable. */ const decodeIcon = (path: string): Icon | null => { const pix = loadGdkPixbufFFI(); const pixbuf = pix.symbols.gdk_pixbuf_new_from_file(cstr(path), null); @@ -152,18 +132,18 @@ const decodeIcon = (path: string): Icon | null => { const view = new Uint8Array(toArrayBuffer(pixelsPtr, 0, height * rowstride)); icon = { argb: rgbaToArgb32Network(view, width, height, rowstride, nChannels), width, height }; } - loadGObjectFFI().symbols.g_object_unref(pixbuf); // copied into `argb`; drop the pixbuf. + loadGObjectFFI().symbols.g_object_unref(pixbuf); // the pixels were copied into `argb` return icon; }; /** - * Build a floating `a(iiay)` with the one icon frame. The `ay` BORROWS `icon.argb` - * (from_data, notify=NULL): the tray state owns the buffer, and GDBus serializes the reply - * inside the getter's dispatch, so a later setImage may drop the old buffer. + * A floating one-frame `a(iiay)` whose `ay` BORROWS `icon.argb` (from_data, notify=NULL): the + * tray state owns the buffer, and GDBus serializes the reply inside the getter's dispatch. */ const buildIconPixmap = (icon: Icon): Pointer | null => { const g = loadGlibFFI().symbols; - // ponytail: G_DBUS_DEBUG=message prints queued replies on the worker thread and could read a replaced buffer; copy via g_variant_new_fixed_array to close it. + // ponytail: G_DBUS_DEBUG=message prints queued replies on the worker thread and can read a + // buffer setImage replaced; g_variant_new_fixed_array (a glib-ffi symbol) would copy instead. const builder = g.g_variant_builder_new(variantType('a(iiay)')); g.g_variant_builder_open(builder, variantType('(iiay)')); g.g_variant_builder_add_value(builder, g.g_variant_new_int32(icon.width)); @@ -185,7 +165,7 @@ const buildIconPixmap = (icon: Icon): Pointer | null => { return value; }; -/** Build a floating empty `a(iiay)` (no frames). */ +/** A floating `a(iiay)` with no frames. */ const buildEmptyPixmap = (): Pointer | null => { const g = loadGlibFFI().symbols; const builder = g.g_variant_builder_new(variantType('a(iiay)')); @@ -194,7 +174,7 @@ const buildEmptyPixmap = (): Pointer | null => { return value; }; -/** Build a floating `(sa(iiay)ss)` ToolTip = (iconName, [], title, description). */ +/** A floating `(sa(iiay)ss)`: (iconName, no pixmaps, title, description). */ const buildToolTip = (title: string, text: string): Pointer | null => { const g = loadGlibFFI().symbols; const builder = g.g_variant_builder_new(variantType('(sa(iiay)ss)')); @@ -227,7 +207,7 @@ const stringTuple = (value: string): Pointer | null => { : g.g_variant_new_tuple(ptr(new BigUint64Array([BigInt(child)])), 1n); }; -/** A fully-inert no-op tray (gate off / no bus / export failed) — never touches the bus. */ +/** For a disabled gate, a missing bus or a failed export; never touches the bus. */ const inertInstance = (): TrayInstance => { let destroyed = false; return { @@ -251,7 +231,7 @@ type State = { click: (() => void) | null; }; -/** Serve one SNI property as a floating GVariant, or null for an unknown name. */ +/** A floating GVariant, or null for a name GDBus would already have rejected. */ const getPropertyValue = (state: State, name: string): Pointer | null => { const g = loadGlibFFI().symbols; switch (name) { @@ -280,14 +260,14 @@ const getPropertyValue = (state: State, name: string): Pointer | null => { let trayCount = 0; -/** Build + register the live SNI object; returns a `TrayInstance`, or null on any failure. */ +/** Null on any failure. */ const createLive = (conn: Pointer, initialImage: string): TrayInstance | null => { const gdbus = loadGDBusFFI(); // One object path per tray: a second registration at a shared path fails on one connection. const objectPath = `${OBJECT_PATH_PREFIX}/${trayCount++}`; const node = nodeInfoNewForXml(SNI_XML); if (node === null) { - return null; // malformed XML — never crash (guard the NULL deref). + return null; // malformed XML } const iface = nodeInfoLookupInterface(node, SNI_IFACE); if (iface === null) { @@ -302,8 +282,7 @@ const createLive = (conn: Pointer, initialImage: string): TrayInstance | null => click: null, }; - // The two vtable handlers — each wrapped so a JS throw can't cross the FFI boundary and - // kill the pump. Retained FOREVER (the copied vtable holds their raw fn-pointers). + // Both handlers catch: a throw must not unwind into the GDBus dispatch. const getProp = new JSCallback((_c, _s, _p, _i, propName, error, _u): Pointer | null => { let value: Pointer | null = null; try { @@ -323,7 +302,7 @@ const createLive = (conn: Pointer, initialImage: string): TrayInstance | null => state.click?.(); } } catch { - // A faulty click handler must not crash the GMainContext dispatch. + // A throwing click handler must not skip the reply below. } // Complete every method with an empty reply so the host is never left hanging. gdbus.symbols.g_dbus_method_invocation_return_value(invocation, null); @@ -405,7 +384,7 @@ const createLive = (conn: Pointer, initialImage: string): TrayInstance | null => state.icon = decodeIcon(image); emitSignal(conn, objectPath, SNI_IFACE, 'NewIcon', null); // argument-less; host re-fetches. }, - setContextMenu: () => undefined, // deferred: dbusmenu is a follow-up (soft no-op, never throws). + setContextMenu: () => undefined, // ponytail: no com.canonical.dbusmenu export, so a no-op. onClick: (callback) => { state.click = callback; }, @@ -426,7 +405,6 @@ const createLive = (conn: Pointer, initialImage: string): TrayInstance | null => }; }; -/** The Linux tray backend (StatusNotifierItem over D-Bus). */ export const linuxTrayBackend: TrayBackend = { create: (image) => { if (!liveTrayEnabled()) { From 2435fddfba8337581c82c2c75d10dbaa26b60f13 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:27:52 -0700 Subject: [PATCH 292/586] fix: write engine links atomically and fail prune closed on a bad link --- src/cli/engine-store.ts | 41 +++++++++++++++++++++-------- tests/unit/cli/engine-store.test.ts | 17 ++++++++++++ 2 files changed, 47 insertions(+), 11 deletions(-) diff --git a/src/cli/engine-store.ts b/src/cli/engine-store.ts index 2663d5c5..5b0df14e 100644 --- a/src/cli/engine-store.ts +++ b/src/cli/engine-store.ts @@ -112,36 +112,47 @@ export const listInstalled = (root: string): string[] => { /** A refcount entry: which engine id an installed app needs. */ export type EngineLink = { readonly app: string; readonly engine: string }; -/** Register an installed app as needing `engineId` (a refcount entry). */ +/** Register an app as needing `engineId`; written via rename, so a crash never leaves a torn link. */ export const linkApp = (root: string, appPath: string, engineId: string): void => { mkdirSync(join(root, LINKS_DIR), { recursive: true }); - writeFileSync(linkPath(root, appPath), JSON.stringify({ app: appPath, engine: engineId })); + const path = linkPath(root, appPath); + const staging = `${path}.${process.pid}.tmp`; + writeFileSync(staging, JSON.stringify({ app: appPath, engine: engineId })); + renameSync(staging, path); }; export const unlinkApp = (root: string, appPath: string): void => { rmSync(linkPath(root, appPath), { force: true }); }; -/** Read every refcount entry. Malformed entries are skipped. */ -export const readLinks = (root: string): EngineLink[] => { +/** Link files are named by the sha1 of the app path; anything else is a write in progress. */ +const LINK_NAME = /^[0-9a-f]{40}$/; + +const scanLinks = (root: string): { links: EngineLink[]; unreadable: string[] } => { const dir = join(root, LINKS_DIR); - if (!existsSync(dir)) { - return []; - } const links: EngineLink[] = []; - for (const name of readdirSync(dir)) { + const unreadable: string[] = []; + for (const name of existsSync(dir) ? readdirSync(dir) : []) { + if (!LINK_NAME.test(name)) { + continue; + } try { const raw = JSON.parse(readFileSync(join(dir, name), 'utf8')) as Partial; if (typeof raw.app === 'string' && typeof raw.engine === 'string') { links.push({ app: raw.app, engine: raw.engine }); + continue; } } catch { - // Skip an unreadable/corrupt link entry rather than failing GC. + // Counted below. } + unreadable.push(join(dir, name)); } - return links; + return { links, unreadable }; }; +/** Read every refcount entry. Malformed entries are skipped. */ +export const readLinks = (root: string): EngineLink[] => scanLinks(root).links; + export type InstallSource = { readonly id: string; readonly bytes: Uint8Array; @@ -341,9 +352,17 @@ export const gc = async (root: string, deps: GcDeps = {}): Promise => const dryRun = deps.dryRun === true; const remove = deps.remove ?? ((path: string) => rmSync(path, { recursive: true, force: true })); const scan = (): GcResult => { + const { links, unreadable } = scanLinks(root); + if (unreadable.length > 0) { + // Its engine may be in use: fail closed rather than free it. + throw new BunmaskaError( + `engine store: unreadable app link ${unreadable[0]}; delete it or relaunch that app, then prune again`, + { code: 'ERR_ENGINE_LINK' }, + ); + } let droppedLinks = 0; const used = new Set(); - for (const link of readLinks(root)) { + for (const link of links) { if (exists(link.app)) { used.add(link.engine); } else { diff --git a/tests/unit/cli/engine-store.test.ts b/tests/unit/cli/engine-store.test.ts index 4a9a00e2..624da3b4 100644 --- a/tests/unit/cli/engine-store.test.ts +++ b/tests/unit/cli/engine-store.test.ts @@ -287,6 +287,23 @@ describe('gc', () => { expect(result.removed).toEqual([ID2]); }); + test('refuses to run when a link is unreadable, rather than freeing its engine', async () => { + const root = makeTmpDir(); + await installFromSource(root, fakeSource(ID), { extract: fakeExtract }); + linkApp(root, '/opt/MyApp', ID); + writeFileSync(linkPath(root, '/opt/MyApp'), '{"app":"/opt/My'); // torn write + await expect(gc(root, { exists: () => true })).rejects.toThrow(/unreadable/); + expect(isInstalled(root, ID)).toBe(true); + }); + + test('ignores a link write still in progress', async () => { + const root = makeTmpDir(); + linkApp(root, '/opt/MyApp', ID); + writeFileSync(`${linkPath(root, '/opt/MyApp')}.123.tmp`, '{"app":'); + expect(readLinks(root)).toEqual([{ app: '/opt/MyApp', engine: ID }]); + await expect(gc(root, { exists: () => true })).resolves.toBeDefined(); + }); + test('drops links whose app no longer exists, freeing its engine', async () => { const root = makeTmpDir(); await installFromSource(root, fakeSource(ID), { extract: fakeExtract }); From 16f0cede101d1fef6cd56e82cbb839981789cf4c Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:28:45 -0700 Subject: [PATCH 293/586] chore: trim Windows FFI table comments to the comment rules --- src/main/platform/windows/win32-crypt-ffi.ts | 11 +++----- .../platform/windows/win32-gdiplus-ffi.ts | 28 ++++++------------- .../platform/windows/win32-registry-ffi.ts | 2 -- src/main/platform/windows/win32-shcore-ffi.ts | 8 ++---- src/main/platform/windows/win32-shell-ffi.ts | 14 +++------- src/main/platform/windows/win32-wts-ffi.ts | 8 +----- 6 files changed, 19 insertions(+), 52 deletions(-) diff --git a/src/main/platform/windows/win32-crypt-ffi.ts b/src/main/platform/windows/win32-crypt-ffi.ts index b9eb397c..17c42023 100644 --- a/src/main/platform/windows/win32-crypt-ffi.ts +++ b/src/main/platform/windows/win32-crypt-ffi.ts @@ -3,12 +3,9 @@ import { dlopen } from '../dlopen'; import { winLibraryAccessor } from './win32'; /** - * `CryptProtectData`/`CryptUnprotectData` are flat-C exports (no COM). Each takes - * and returns a `DATA_BLOB { DWORD cbData; BYTE* pbData; }` (16 bytes on x64: - * `cbData` at offset 0, `pbData` at offset 8). The output blob's `pbData` is - * allocated by the system and must be released with `LocalFree` (see - * `win32-ffi.ts`). The unused `LPCWSTR`/`DATA_BLOB*`/`PVOID`/prompt parameters are - * declared `ptr` so they can be passed as `null`. + * Both calls take and return a `DATA_BLOB { DWORD cbData; BYTE* pbData; }` (x64: 16 bytes, + * `pbData` at 8). The output `pbData` is system-allocated: free it with `LocalFree`. The + * unused description/entropy/reserved/prompt parameters are `ptr` so they can be `null`. */ const CRYPT32_SYMBOLS = { // (DATA_BLOB* in, LPCWSTR desc, DATA_BLOB* entropy, PVOID reserved, @@ -40,7 +37,7 @@ const CRYPT32_SYMBOLS = { }, } as const; -/** `CRYPTPROTECT_UI_FORBIDDEN` — never raise UI; fail instead (for a service/GUI app). */ +/** `CRYPTPROTECT_UI_FORBIDDEN`: fail instead of raising UI. */ export const CRYPTPROTECT_UI_FORBIDDEN = 0x1; /** Open crypt32.dll and return its DPAPI symbol table. Memoised; Windows-only. */ diff --git a/src/main/platform/windows/win32-gdiplus-ffi.ts b/src/main/platform/windows/win32-gdiplus-ffi.ts index ff6d376e..c2037292 100644 --- a/src/main/platform/windows/win32-gdiplus-ffi.ts +++ b/src/main/platform/windows/win32-gdiplus-ffi.ts @@ -2,18 +2,12 @@ import { FFIType } from 'bun:ffi'; import { dlopen } from '../dlopen'; import { winLibraryAccessor } from './win32'; -/** - * GDI+ (gdiplus.dll) image FFI, plus the shlwapi memory-stream helper that feeds it. Only - * the `IStream` GDI+ reads/writes is COM, and it is handled with flat ole32 - * (`CreateStreamOnHGlobal`/`GetHGlobalFromStream`) so the bytes come out via `GlobalLock` - * rather than `IStream::Read`. - */ const GDIPLUS_SYMBOLS = { // (ULONG_PTR* token, GdiplusStartupInput* input, GdiplusStartupOutput* output) -> Status GdiplusStartup: { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr], returns: FFIType.i32 }, // (IStream*, GpImage** out) -> Status GdipLoadImageFromStream: { args: [FFIType.u64, FFIType.ptr], returns: FFIType.i32 }, - // (GpImage*, GpImage** out) -> Status — an independent copy (decouples from the source stream). + // (GpImage*, GpImage** out) -> Status GdipCloneImage: { args: [FFIType.u64, FFIType.ptr], returns: FFIType.i32 }, // (GpImage*) -> Status GdipDisposeImage: { args: [FFIType.u64], returns: FFIType.i32 }, @@ -35,7 +29,7 @@ const GDIPLUS_SYMBOLS = { GdipGetImageGraphicsContext: { args: [FFIType.u64, FFIType.ptr], returns: FFIType.i32 }, // (GpGraphics*, InterpolationMode) -> Status GdipSetInterpolationMode: { args: [FFIType.u64, FFIType.i32], returns: FFIType.i32 }, - // (GpGraphics*, GpImage*, INT x, INT y, INT w, INT h) -> Status — draw scaled into the rect. + // (GpGraphics*, GpImage*, INT x, INT y, INT w, INT h) -> Status: draw scaled into the rect GdipDrawImageRectI: { args: [FFIType.u64, FFIType.u64, FFIType.i32, FFIType.i32, FFIType.i32, FFIType.i32], returns: FFIType.i32, @@ -55,31 +49,26 @@ const GDIPLUS_SYMBOLS = { ], returns: FFIType.i32, }, - // (const BITMAPINFO* gdiBitmapInfo, void* gdiBitmapData, GpBitmap** out) -> Status — - // wrap a packed DIB (the CF_DIB clipboard format) as a GDI+ bitmap. Used by the - // clipboard backend's image read. + // (const BITMAPINFO* gdiBitmapInfo, void* gdiBitmapData, GpBitmap** out) -> Status: the + // bitmap reads gdiBitmapData in place, so it must outlive the bitmap. GdipCreateBitmapFromGdiDib: { args: [FFIType.ptr, FFIType.ptr, FFIType.ptr], returns: FFIType.i32, }, - // (GpBitmap*, const GpRect* rect, UINT flags, PixelFormat, BitmapData* out) -> Status — - // expose a bitmap's raw pixels for reading. Used by the clipboard backend's image write. + // (GpBitmap*, const GpRect* rect, UINT flags, PixelFormat, BitmapData* out) -> Status GdipBitmapLockBits: { args: [FFIType.u64, FFIType.ptr, FFIType.u32, FFIType.i32, FFIType.ptr], returns: FFIType.i32, }, - // (GpBitmap*, BitmapData*) -> Status — release a lock taken by GdipBitmapLockBits. + // (GpBitmap*, BitmapData*) -> Status GdipBitmapUnlockBits: { args: [FFIType.u64, FFIType.ptr], returns: FFIType.i32 }, - // (GpBitmap*, HICON* out) -> Status; the caller owns the icon (DestroyIcon). + // (GpBitmap*, HICON* out) -> Status: the caller owns the icon (DestroyIcon) GdipCreateHICONFromBitmap: { args: [FFIType.u64, FFIType.ptr], returns: FFIType.i32 }, } as const; -/** `Ok` GDI+ status. */ export const GDIP_OK = 0; -/** `ImageLockModeRead` — lock pixels for reading only. */ export const IMAGE_LOCK_MODE_READ = 1; export const PIXEL_FORMAT_32BPP_ARGB = 0x0026200a; -/** `InterpolationModeHighQualityBicubic` — smooth downscaling. */ export const INTERPOLATION_HIGH_QUALITY_BICUBIC = 7; /** GDI+ image-encoder CLSIDs (GUID bytes, little-endian for the first three fields). */ @@ -95,9 +84,8 @@ export const loadGdiplus = winLibraryAccessor('gdiplus', () => dlopen('gdiplus.dll', GDIPLUS_SYMBOLS), ); -/** shlwapi.dll `SHCreateMemStream` — an `IStream` over a copy of in-memory bytes. */ const SHLWAPI_SYMBOLS = { - // (const BYTE* pInit, UINT cbInit) -> IStream* + // (const BYTE* pInit, UINT cbInit) -> IStream* over a COPY of the bytes SHCreateMemStream: { args: [FFIType.ptr, FFIType.u32], returns: FFIType.u64 }, } as const; diff --git a/src/main/platform/windows/win32-registry-ffi.ts b/src/main/platform/windows/win32-registry-ffi.ts index e1d47cd8..35b844da 100644 --- a/src/main/platform/windows/win32-registry-ffi.ts +++ b/src/main/platform/windows/win32-registry-ffi.ts @@ -24,9 +24,7 @@ const ADVAPI32_SYMBOLS = { }, } as const; -/** `HKEY_CURRENT_USER` — the predefined root, sign-extended to 64 bits. */ export const HKEY_CURRENT_USER = 0xffffffff80000001n; -/** `RRF_RT_REG_DWORD` — restrict `RegGetValueW` to a `REG_DWORD` value. */ export const RRF_RT_REG_DWORD = 0x00000010; /** Open advapi32.dll and return its registry symbol table. Memoised; Windows-only. */ diff --git a/src/main/platform/windows/win32-shcore-ffi.ts b/src/main/platform/windows/win32-shcore-ffi.ts index 66e3ab70..c469d6ac 100644 --- a/src/main/platform/windows/win32-shcore-ffi.ts +++ b/src/main/platform/windows/win32-shcore-ffi.ts @@ -2,11 +2,8 @@ import { FFIType } from 'bun:ffi'; import { dlopen } from '../dlopen'; import { winLibraryAccessor } from './win32'; -/** - * shcore.dll per-monitor DPI for the screen backend. `GetDpiForMonitor` (Windows 8.1+) - * yields a monitor's effective DPI, from which the device-pixel `scaleFactor` is - * `dpi / 96`; shcore is absent before Windows 8.1, so callers fall back to a 1.0 scale. - */ +// GetDpiForMonitor is Windows 8.1+ (callers fall back to 1.0), and it reports 96 to a +// DPI-unaware process, so scaleFactor stays 1 until the process opts into DPI awareness. const SHCORE_SYMBOLS = { // (HMONITOR, MONITOR_DPI_TYPE, UINT* dpiX, UINT* dpiY) -> HRESULT (0 = S_OK) GetDpiForMonitor: { @@ -15,7 +12,6 @@ const SHCORE_SYMBOLS = { }, } as const; -/** `MDT_EFFECTIVE_DPI` — the DPI used for layout scaling. */ export const MDT_EFFECTIVE_DPI = 0; /** Open shcore.dll and return its DPI symbol table. Memoised; Windows-only. */ diff --git a/src/main/platform/windows/win32-shell-ffi.ts b/src/main/platform/windows/win32-shell-ffi.ts index 3fbdc907..26303e11 100644 --- a/src/main/platform/windows/win32-shell-ffi.ts +++ b/src/main/platform/windows/win32-shell-ffi.ts @@ -2,28 +2,22 @@ import { FFIType } from 'bun:ffi'; import { dlopen } from '../dlopen'; import { winLibraryAccessor } from './win32'; -/** - * shell32.dll desktop-integration FFI. `ShellExecuteW` returns an `HINSTANCE`-typed - * status: a value GREATER than 32 means success; 0–32 is an `SE_ERR_*` failure code. - */ const SHELL32_SYMBOLS = { // (HWND, LPCWSTR verb, LPCWSTR file, LPCWSTR params, LPCWSTR dir, INT show) - // -> HINSTANCE (as an integer; > 32 means success) + // -> HINSTANCE as a status: above 32 is success, 0-32 an SE_ERR_* code ShellExecuteW: { args: [FFIType.u64, FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.i32], returns: FFIType.u64, }, - // (DWORD dwMessage, PNOTIFYICONDATAW) -> BOOL — add/modify/delete a tray icon. + // (DWORD dwMessage, PNOTIFYICONDATAW) -> BOOL Shell_NotifyIconW: { args: [FFIType.u32, FFIType.ptr], returns: FFIType.i32 }, - // (LPBROWSEINFOW) -> PIDLIST_ABSOLUTE — the legacy folder picker (no COM vtables). + // (LPBROWSEINFOW) -> PIDLIST_ABSOLUTE: the legacy folder picker, free of COM vtables SHBrowseForFolderW: { args: [FFIType.ptr], returns: FFIType.u64 }, - // (PCIDLIST_ABSOLUTE pidl, LPWSTR path) -> BOOL — resolve a PIDL to a filesystem path. + // (PCIDLIST_ABSOLUTE pidl, LPWSTR path) -> BOOL SHGetPathFromIDListW: { args: [FFIType.u64, FFIType.ptr], returns: FFIType.i32 }, } as const; -/** `SW_SHOWNORMAL` — show the launched window in its normal state. */ export const SW_SHOWNORMAL = 1; -/** `ShellExecuteW` returns an HINSTANCE > this value on success. */ export const SHELL_EXECUTE_SUCCESS_THRESHOLD = 32n; /** Open shell32.dll and return its symbol table. Memoised; Windows-only. */ diff --git a/src/main/platform/windows/win32-wts-ffi.ts b/src/main/platform/windows/win32-wts-ffi.ts index 52c10212..45705514 100644 --- a/src/main/platform/windows/win32-wts-ffi.ts +++ b/src/main/platform/windows/win32-wts-ffi.ts @@ -2,17 +2,11 @@ import { FFIType } from 'bun:ffi'; import { dlopen } from '../dlopen'; import { winLibraryAccessor } from './win32'; -/** - * wtsapi32.dll session-change notifications for `powerMonitor`'s lock/unlock events. - * `WTSRegisterSessionNotification` makes a window receive `WM_WTSSESSION_CHANGE` (with - * `WTS_SESSION_LOCK` / `WTS_SESSION_UNLOCK` in `wParam`). - */ const WTSAPI32_SYMBOLS = { - // (HWND, DWORD dwFlags) -> BOOL — deliver WM_WTSSESSION_CHANGE to the window. + // (HWND, DWORD dwFlags) -> BOOL: deliver WM_WTSSESSION_CHANGE to the window WTSRegisterSessionNotification: { args: [FFIType.u64, FFIType.u32], returns: FFIType.i32 }, } as const; -/** `NOTIFY_FOR_THIS_SESSION` — only this session's lock/unlock events. */ export const NOTIFY_FOR_THIS_SESSION = 0; /** Open wtsapi32.dll and return its symbol table. Memoised; Windows-only. */ From d48a3dbb5278e499fb26062d7c515bbac3affaed Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:28:54 -0700 Subject: [PATCH 294/586] fix: refuse store installs no app could pin or load --- src/cli/engine-store.ts | 83 +++++++++++++++++------------ tests/unit/cli/engine-store.test.ts | 22 ++++++++ 2 files changed, 70 insertions(+), 35 deletions(-) diff --git a/src/cli/engine-store.ts b/src/cli/engine-store.ts index 5b0df14e..8400bc08 100644 --- a/src/cli/engine-store.ts +++ b/src/cli/engine-store.ts @@ -48,6 +48,15 @@ const defaultHome = (env: StoreEnv): string => export const enginesPath = (env: StoreEnv = process.env): string => env['BUNMASKA_ENGINES_PATH'] ?? join(defaultHome(env), 'webkit'); +const isEngineId = (name: string): boolean => { + try { + parseEngineId(name); + return true; + } catch { + return false; + } +}; + /** * Reject an engine id that is not a single, contained directory segment under * `root`. An id reaches the store from an untrusted source — a remote feed @@ -74,6 +83,12 @@ export const assertSafeEngineId = (root: string, id: string): void => { code: 'ERR_ENGINE_ID', }); } + if (!isEngineId(id)) { + throw new BunmaskaError( + `engine store: ${JSON.stringify(id)} is not a valid engine-id, so no app could pin it`, + { code: 'ERR_ENGINE_ID' }, + ); + } }; export const engineDir = (root: string, id: string): string => join(root, id); @@ -88,15 +103,6 @@ export const lockPath = (root: string): string => join(root, LOCK_FILE); export const isInstalled = (root: string, id: string): boolean => existsSync(markerPath(root, id)); -const isEngineId = (name: string): boolean => { - try { - parseEngineId(name); - return true; - } catch { - return false; - } -}; - /** The installed (marker-complete) engine ids in the store, sorted. */ export const listInstalled = (root: string): string[] => { if (!existsSync(root)) { @@ -168,6 +174,37 @@ export type InstallDeps = { export type InstallResult = { readonly id: string; readonly installed: boolean }; +/** + * Move a populated staging dir into place, then write the marker LAST. Only the + * swap holds the store lock (a concurrent install or gc must not race the rename); + * the slow extract/copy already ran on private staging, outside it. + */ +const swapIn = async ( + root: string, + id: string, + staging: string, + soname: string, + onMarker?: () => void, +): Promise => { + if (!existsSync(join(staging, 'lib', soname))) { + throw new BunmaskaError(`engine ${id}: no lib/${soname} (its engine.json soname)`, { + code: 'ERR_ENGINE_MANIFEST', + }); + } + return withLock(root, async () => { + if (isInstalled(root, id)) { + rmSync(staging, { recursive: true, force: true }); + return { id, installed: false }; + } + const dest = engineDir(root, id); + rmSync(dest, { recursive: true, force: true }); // clear a partial prior install + renameSync(staging, dest); + writeFileSync(markerPath(root, id), `${new Date().toISOString()}\n`); + onMarker?.(); + return { id, installed: true }; + }); +}; + /** * Idempotent: a fully-installed id is left untouched. The marker is written * LAST, after the hash verifies and the staging dir is swapped in. A hash @@ -203,21 +240,7 @@ export const installFromSource = async ( { code: 'ERR_ENGINE_INTEGRITY' }, ); } - // Swap-into-place + marker under the store lock so a concurrent install or gc - // in another process can't race the rename (extract already ran on a private - // staging dir, so the slow part is NOT inside the lock). - return await withLock(root, async () => { - if (isInstalled(root, source.id)) { - rmSync(staging, { recursive: true, force: true }); - return { id: source.id, installed: false }; - } - const dest = engineDir(root, source.id); - rmSync(dest, { recursive: true, force: true }); // clear any partial prior install - renameSync(staging, dest); - writeFileSync(markerPath(root, source.id), `${new Date().toISOString()}\n`); - deps.onMarker?.(); - return { id: source.id, installed: true }; - }); + return await swapIn(root, source.id, staging, extracted.soname, deps.onMarker); } catch (error) { rmSync(staging, { recursive: true, force: true }); throw error; @@ -277,17 +300,7 @@ export const installFromDir = async ( const staging = mkdtempSync(join(root, '.tmp-')); try { copyTree(sourceDir, staging); - return await withLock(root, async () => { - if (isInstalled(root, manifest.id)) { - rmSync(staging, { recursive: true, force: true }); - return { id: manifest.id, installed: false }; - } - const dest = engineDir(root, manifest.id); - rmSync(dest, { recursive: true, force: true }); - renameSync(staging, dest); - writeFileSync(markerPath(root, manifest.id), `${new Date().toISOString()}\n`); - return { id: manifest.id, installed: true }; - }); + return await swapIn(root, manifest.id, staging, manifest.soname); } catch (error) { rmSync(staging, { recursive: true, force: true }); throw error; diff --git a/tests/unit/cli/engine-store.test.ts b/tests/unit/cli/engine-store.test.ts index 624da3b4..c786fb90 100644 --- a/tests/unit/cli/engine-store.test.ts +++ b/tests/unit/cli/engine-store.test.ts @@ -170,6 +170,16 @@ describe('installFromSource', () => { expect(extracted).toBe(false); }); + test('refuses an artifact missing its declared soname, leaving nothing installed', async () => { + const root = makeTmpDir(); + const extract = async (bytes: Uint8Array, dest: string): Promise => { + await fakeExtract(bytes, dest); + rmSync(join(dest, 'lib'), { recursive: true }); + }; + await expect(installFromSource(root, fakeSource(ID), { extract })).rejects.toThrow(/soname/); + expect(isInstalled(root, ID)).toBe(false); + }); + test('rejects a substituted engine — extracted engine.json id must match the claimed id', async () => { const root = makeTmpDir(); // A genuinely-signed OLDER artifact (its engine.json says ID2) served under ID's URL. @@ -209,6 +219,10 @@ describe('assertSafeEngineId', () => { expect(() => assertSafeEngineId(root, ID)).not.toThrow(); }); + test('rejects a name no app could pin', () => { + expect(() => assertSafeEngineId(root, 'webkit-local')).toThrow(/not a valid engine-id/); + }); + test('rejects separators, absolute paths, dot segments, and empties', () => { for (const id of ['../x', '..', '.', '', 'a/b', 'a\\b', '/abs/path', 'x/../../y']) { expect(() => assertSafeEngineId(root, id)).toThrow(/unsafe engine id/); @@ -338,6 +352,14 @@ describe('installFromDir', () => { expect(second).toEqual({ id: ID, installed: false }); }); + test('refuses an engine whose declared soname is missing, leaving nothing installed', async () => { + const root = makeTmpDir(); + const src = makeEngineDir(root, ID); + rmSync(join(src, 'lib', 'libwebkitgtk-6.0.so.4')); + await expect(installFromDir(root, src)).rejects.toThrow(/libwebkitgtk-6\.0\.so\.4/); + expect(isInstalled(root, ID)).toBe(false); + }); + test('rejects a source dir with no readable engine.json', async () => { const root = makeTmpDir(); const { mkdirSync } = await import('node:fs'); From e5a1cff32700cab1efbe6ebb31f294cdbb6f02e2 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:29:34 -0700 Subject: [PATCH 295/586] fix: report engine command failures as exit codes, not stacks --- src/cli/engine-command.ts | 57 ++++++++++++++++----------- tests/unit/cli/engine-command.test.ts | 21 ++++++++++ 2 files changed, 54 insertions(+), 24 deletions(-) diff --git a/src/cli/engine-command.ts b/src/cli/engine-command.ts index 30146b11..c80b9d2b 100644 --- a/src/cli/engine-command.ts +++ b/src/cli/engine-command.ts @@ -200,23 +200,13 @@ const runInstall = async (source: string, deps: EngineCommandDeps): Promise installFromUrl(root, u, key, { fetch: defaultRemoteFetch })); - try { - deps.out(installedMessage(await installUrl(deps.root, url, publicKey))); - return 0; - } catch (error) { - deps.err(`bunmaska engine install: ${error instanceof Error ? error.message : String(error)}`); - return 1; - } + deps.out(installedMessage(await installUrl(deps.root, url, publicKey))); + return 0; }; const runUse = (id: string, forDir: string | undefined, deps: EngineCommandDeps): number => { if (!isSystemEngine(id)) { - try { - parseEngineId(id); - } catch (error) { - deps.err(`bunmaska engine use: ${error instanceof Error ? error.message : String(error)}`); - return 1; - } + parseEngineId(id); } const where = forDir ?? '.'; deps.out( @@ -284,11 +274,7 @@ const runVerify = (id: string, deps: EngineCommandDeps): number => { return 1; }; -/** Run a `bunmaska engine ` command and resolve to the process exit code. */ -export const runEngine = async ( - sub: EngineSubcommand, - deps: EngineCommandDeps, -): Promise => { +const dispatch = async (sub: EngineSubcommand, deps: EngineCommandDeps): Promise => { switch (sub.action) { case 'list': return runList(deps); @@ -307,14 +293,25 @@ export const runEngine = async ( } }; -/** - * Exits non-zero only when the project pins a full engine-id that is not - * installed. - */ -export const runDoctor = async ( - target: string | undefined, +/** Print a failure as one `bunmaska
{/* Content-protection scrim: quiets the dither behind the headline/code. */}
= ({ color = '#e0a019', className, style, - antialias = true, + antialias = false, patternScale = 2, patternDensity = 1, pixelSizeJitter = 0, @@ -285,12 +285,7 @@ const PixelBlast: FC = ({ if (!threeRef.current) { const canvas = document.createElement('canvas'); - const renderer = new THREE.WebGLRenderer({ - canvas, - antialias, - alpha: true, - powerPreference: 'high-performance', - }); + const renderer = new THREE.WebGLRenderer({ canvas, antialias, alpha: true }); renderer.domElement.style.width = '100%'; renderer.domElement.style.height = '100%'; renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2)); From 55ce7acb3f6ec014735d9ae275474942b3e96bb4 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:37:19 -0700 Subject: [PATCH 320/586] chore: trim engine store comments to the comment rules --- src/cli/engine-store.ts | 65 ++++++++++++----------------------------- 1 file changed, 18 insertions(+), 47 deletions(-) diff --git a/src/cli/engine-store.ts b/src/cli/engine-store.ts index f544ec72..9ecbae73 100644 --- a/src/cli/engine-store.ts +++ b/src/cli/engine-store.ts @@ -1,12 +1,6 @@ -/** - * Content-addressed engine store: many WebKit versions live side by side under - * `~/.bunmaska/webkit//` and each app resolves the exact id it was - * built against — there is no global "current" engine. A store dir is kept iff - * some installed app (a `.links/*` refcount entry) still needs it. A fully - * installed engine is the one with an `INSTALLATION_COMPLETE` marker, written - * LAST after the content hash verifies — a half-download has no marker and is - * re-fetched. - */ +// The engine store: `//`, side by side, refcounted by `.links/`. An engine +// is installed iff its INSTALLATION_COMPLETE marker exists, so the marker is written last +// and removed first; a half-written or half-deleted engine never looks installed. import { cpSync, @@ -41,10 +35,6 @@ export type StoreEnv = Record; const defaultHome = (env: StoreEnv): string => env['BUNMASKA_HOME'] ?? join(env['HOME'] ?? env['USERPROFILE'] ?? homedir(), '.bunmaska'); -/** - * `$BUNMASKA_ENGINES_PATH`, else `/webkit`. The single env-reading - * function; every other op takes an explicit `root`. - */ export const enginesPath = (env: StoreEnv = process.env): string => env['BUNMASKA_ENGINES_PATH'] ?? join(defaultHome(env), 'webkit'); @@ -58,12 +48,9 @@ const isEngineId = (name: string): boolean => { }; /** - * Reject an engine id that is not a single, contained directory segment under - * `root`. An id reaches the store from an untrusted source — a remote feed - * manifest (`engine-remote.ts`) or an `engine.json` — and is used verbatim to - * build a directory that install then `rm`s and `rename`s over. Without this an - * id like `../../x` or an absolute path is a traversal + arbitrary-delete. Bars - * separators, absolute paths, `.`/`..`, and anything resolving outside `root`. + * Reject an id that is not one contained dir segment under `root`, or that no app could pin. + * Ids arrive untrusted (feed manifest, engine.json) and name dirs install `rm`s and renames + * over: `../../x` or an absolute path would be traversal plus arbitrary delete. */ export const assertSafeEngineId = (root: string, id: string): void => { const base = resolve(root); @@ -73,7 +60,7 @@ export const assertSafeEngineId = (root: string, id: string): void => { id.includes('/') || id.includes('\\') || id.includes('\0') || - id.startsWith('.') || // .links, .tmp-*, dotfiles — reserved store internals + id.startsWith('.') || // .links, .tmp-*: store internals id === LOCK_FILE || id === INSTALLATION_COMPLETE || isAbsolute(id) || @@ -118,7 +105,7 @@ export const listInstalled = (root: string): string[] => { /** A refcount entry: which engine id an installed app needs. */ export type EngineLink = { readonly app: string; readonly engine: string }; -/** Register an app as needing `engineId`; written via rename, so a crash never leaves a torn link. */ +/** Register an app as needing `engineId`; renamed into place, so a crash never tears it. */ export const linkApp = (root: string, appPath: string, engineId: string): void => { mkdirSync(join(root, LINKS_DIR), { recursive: true }); const path = linkPath(root, appPath); @@ -174,11 +161,7 @@ export type InstallDeps = { export type InstallResult = { readonly id: string; readonly installed: boolean }; -/** - * Move a populated staging dir into place, then write the marker LAST. Only the - * swap holds the store lock (a concurrent install or gc must not race the rename); - * the slow extract/copy already ran on private staging, outside it. - */ +/** Swap populated staging into place under the store lock; the slow extract/copy ran outside it. */ const swapIn = async ( root: string, id: string, @@ -205,11 +188,7 @@ const swapIn = async ( }); }; -/** - * Idempotent: a fully-installed id is left untouched. The marker is written - * LAST, after the hash verifies and the staging dir is swapped in. A hash - * mismatch throws and leaves no engine dir behind. - */ +/** Idempotent; a hash mismatch throws and leaves no engine dir behind. */ export const installFromSource = async ( root: string, source: InstallSource, @@ -259,7 +238,7 @@ export type EngineManifest = { export const readEngineManifest = (dir: string): EngineManifest => { let raw: unknown; try { - // strip a UTF-8 BOM — Windows tooling (PowerShell 5.1) writes one + // PowerShell 5.1 writes a UTF-8 BOM. raw = JSON.parse(readFileSync(join(dir, 'engine.json'), 'utf8').replace(/^\uFEFF/, '')); } catch { throw new BunmaskaError(`engine: no readable engine.json in ${dir}`, { @@ -280,11 +259,7 @@ export const readEngineManifest = (dir: string): EngineManifest => { }; }; -/** - * Install from a local, already-extracted engine tree (`lib/` + `engine.json`). - * Idempotent, marker written last. Signed remote installs go through - * {@link ../cli/engine-remote installFromUrl} instead. - */ +/** Install a local, already-extracted engine tree; unsigned, unlike feed installs. Idempotent. */ export const installFromDir = async ( root: string, sourceDir: string, @@ -313,10 +288,7 @@ export type VerifyResult = { readonly problems: string[]; }; -/** - * Structural check only: marker present, `engine.json` id matches the dir, and - * the declared `soname` exists in `lib/`. - */ +/** Structural check only: the marker, the engine.json id, and its soname in `lib/`. */ export const verifyEngine = (root: string, id: string): VerifyResult => { const problems: string[] = []; const dir = engineDir(root, id); @@ -356,9 +328,8 @@ export type GcResult = { }; /** - * An engine is kept iff some live app still links it. Links whose app no longer - * exists are dropped first, freeing their engines. `dryRun` mutates nothing and - * reports what WOULD be removed. + * Keep the engines a live app links; drop dead links, then remove every other engine + * and interrupted-install leftovers. `dryRun` only reports. */ export const gc = async (root: string, deps: GcDeps = {}): Promise => { const exists = deps.exists ?? existsSync; @@ -453,9 +424,9 @@ const releaseLock = (lock: string, pid: string): void => { }; /** - * Run `fn` under the store's cross-process lock, a pidfile. A stale lock is stolen; - * the lock is released even if `fn` throws, but only while it still holds our pid. - * ponytail: two contenders stealing one stale lock at once can both enter; add a steal lock if that bites. + * Run `fn` under the store's cross-process pidfile lock, stealing a stale one. Released + * even if `fn` throws, but only while it still holds our pid. + * ponytail: two contenders stealing one stale lock can both enter; add a steal lock if it bites */ export const withLock = async (root: string, fn: () => Promise): Promise => { mkdirSync(root, { recursive: true }); From ce9688eb4b54e63a41e59c8664d1788bad89fddf Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:37:46 -0700 Subject: [PATCH 321/586] perf: load the hero code image eagerly at its displayed size --- website/src/components/Hero.astro | 3 +++ 1 file changed, 3 insertions(+) diff --git a/website/src/components/Hero.astro b/website/src/components/Hero.astro index 44c030b8..32a95df4 100644 --- a/website/src/components/Hero.astro +++ b/website/src/components/Hero.astro @@ -42,6 +42,9 @@ import HeroPixels from "./ui/HeroPixels.tsx"; src={codeblock} alt="A minimal Bunmaska app - a few lines of TypeScript that open a native window" class="w-full max-w-[37.5rem] h-auto" + priority + widths={[600, 1200]} + sizes="(min-width: 40rem) 37.5rem, 100vw" />

From 0eeeef7696acf6ca891a995b9ae7c2803fce7dba Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:38:19 -0700 Subject: [PATCH 322/586] chore: trim engine command, index, pack and id comments --- src/cli/engine-command.ts | 12 +++++------- src/cli/engine-index.ts | 11 ++++------- src/cli/engine-pack.ts | 18 +++++------------- src/common/engine-id.ts | 24 +++++------------------- 4 files changed, 19 insertions(+), 46 deletions(-) diff --git a/src/cli/engine-command.ts b/src/cli/engine-command.ts index ba8867ae..3b324ddd 100644 --- a/src/cli/engine-command.ts +++ b/src/cli/engine-command.ts @@ -165,9 +165,8 @@ const isBareEngineId = (source: string): boolean => { const runInstall = async (source: string, deps: EngineCommandDeps): Promise => { const isUrl = /^https?:\/\//.test(source); - // A local, already-extracted engine directory wins over feed routing — a dir - // whose name happens to be a valid engine-id must not be shadowed by the feed, - // and a local install never reads (or is broken by) bunmaska.config. + // A local dir wins over feed routing (even one named like an engine-id), and a + // local install never reads, or is broken by, bunmaska.config. if (!isUrl && existsSync(source) && statSync(source).isDirectory()) { const install = deps.installDir ?? installFromDir; deps.out(installedMessage(await install(deps.root, source))); @@ -228,9 +227,8 @@ const runPrune = async ( force: boolean, deps: EngineCommandDeps, ): Promise => { - // Refcounts are populated by apps at launch. Before any app has registered, - // every engine looks unreferenced — so a plain prune would wipe the whole - // store. Refuse that case unless explicitly forced (or just previewing). + // Apps register links at launch, so before any has, every engine looks + // unreferenced and a plain prune would wipe the whole store. const installed = listInstalled(deps.root); if (!dryRun && !force && installed.length > 0 && readLinks(deps.root).length === 0) { deps.out( @@ -348,7 +346,7 @@ const doctor = async (target: string | undefined, deps: EngineCommandDeps): Prom } }; -/** Exits 1 when the project pins an uninstalled engine for this machine, or doctor itself fails. */ +/** Exits 1 when the project pins an uninstalled engine for this machine, or doctor fails. */ export const runDoctor = async ( target: string | undefined, deps: EngineCommandDeps, diff --git a/src/cli/engine-index.ts b/src/cli/engine-index.ts index 0287a2f9..96674371 100644 --- a/src/cli/engine-index.ts +++ b/src/cli/engine-index.ts @@ -1,8 +1,5 @@ -/** - * os/arch/upstream/family are DERIVED from each entry's id at parse time, so the - * stored index cannot disagree with the id. Layout at a feed: - * `/index.json`, beside each `.tar.zst`. - */ +// The feed's `/index.json`. os/arch/upstream/family are derived from each id at +// parse time, so the index can never disagree with its ids. import { type EngineRef, parseEngineId } from '../common/engine-id'; import { BunmaskaError } from '../common/errors'; @@ -15,7 +12,7 @@ export type EngineIndexEntry = EngineRef & { readonly soname?: string; }; -/** The raw, stored shape of one index entry (before id-derivation). */ +/** One entry as stored, before id-derivation. */ type StoredEntry = { readonly id: string; readonly size?: number; @@ -60,7 +57,7 @@ const readStoredEntries = (text: string): StoredEntry[] => { }); }; -/** The entries this client understands; an id it cannot parse (newer family, os, arch) is skipped. */ +/** The entries this client understands; an id it cannot parse (newer family/os/arch) is skipped. */ export const parseEngineIndex = (text: string): EngineIndexEntry[] => readStoredEntries(text).flatMap((entry) => { try { diff --git a/src/cli/engine-pack.ts b/src/cli/engine-pack.ts index 233a847b..cc431e15 100644 --- a/src/cli/engine-pack.ts +++ b/src/cli/engine-pack.ts @@ -1,8 +1,4 @@ -/** - * The producer side of {@link installFromUrl}. The three outputs map one-to-one - * to the feed's three files (`.tar.zst`, `.json`, `.sig`), so publishing is - * a plain object upload. - */ +// The producer side of `installFromUrl`: one output per feed file (`.tar.zst`, .json, .sig). import { parseEngineId } from '../common/engine-id'; import { BunmaskaError } from '../common/errors'; @@ -11,11 +7,10 @@ import { signArtifact } from './engine-signature'; import { type RemoteManifest, zstdTarExtract } from './engine-remote'; import { readEngineManifest } from './engine-store'; -/** Compress a directory tree to `.tar.zst` bytes — the inverse of {@link zstdTarExtract}. */ +/** The inverse of {@link zstdTarExtract}. */ export const zstdTarCompress = async (srcDir: string): Promise => { - // tar from cwd:srcDir (not `-C `) — Windows bsdtar mangles a backslash path arg. - // Exclude INSTALLATION_COMPLETE: it is a store-LOCAL marker written last by a - // verified install, never shipped inside the artifact (would void the invariant). + // tar from cwd:srcDir, never `-C `: Windows bsdtar mangles a backslash path arg. + // Never pack INSTALLATION_COMPLETE: a store marks an engine installed only after verifying it. const proc = Bun.spawn(['tar', '--exclude', './INSTALLATION_COMPLETE', '-cf', '-', '.'], { cwd: srcDir, stdout: 'pipe', @@ -42,10 +37,7 @@ export type PackDeps = { readonly compress?: (srcDir: string) => Promise; }; -/** - * The signature is detached base64 Ed25519 over the artifact bytes. Throws if - * the dir has no readable `engine.json`. - */ +/** Signs with a detached base64 Ed25519 signature over the artifact bytes. */ export const packEngineDir = async ( engineDir: string, privateKeyPem: string, diff --git a/src/common/engine-id.ts b/src/common/engine-id.ts index 133a9986..be78199a 100644 --- a/src/common/engine-id.ts +++ b/src/common/engine-id.ts @@ -1,13 +1,5 @@ -/** - * The content address of one pinned engine build. Many engine versions coexist in - * the store and the WebKitGTK 6.0 soname (`libwebkitgtk-6.0.so.4`) is shared across - * every upstream release, so the id — not the soname — carries the version. - * - * Format: `-----` (e.g. - * `webkitgtk-6.0-2.52.4-bunmaska1-linux-x64`) where NO field may contain a dash, so - * it splits unambiguously. `'system'` is a reserved sentinel meaning "use the OS - * WebView" and is never a parseable id. - */ +// `-----`, no dash inside a field. The soname is shared +// across releases, so the id carries the version; `system` is reserved and never parses. import { InvalidArgumentError } from './errors'; import { compareVersions } from './manifest'; @@ -41,10 +33,7 @@ const ENGINE_ARCHES: ReadonlySet = new Set(['x64', 'arm64']); /** Whether `id` is the reserved system sentinel (case-insensitive). */ export const isSystemEngine = (id: string): boolean => id.trim().toLowerCase() === SYSTEM_ENGINE; -/** - * Parse a flat engine-id back into an {@link EngineRef}, validating every field. - * Throws {@link InvalidArgumentError} on the system sentinel or any malformed id. - */ +/** Throws {@link InvalidArgumentError} on `system` or any malformed field. */ export const parseEngineId = (id: string): EngineRef => { const parts = id.split('-'); if (parts.length !== 6) { @@ -74,7 +63,7 @@ export const parseEngineId = (id: string): EngineRef => { `engine-id: upstream must be a dotted numeric version (got ${JSON.stringify(upstream)})`, ); } - // Ids become URLs, store paths, and baked files — api/rev must be plain tokens + // Ids become URLs, store paths and baked files: api/rev must be plain tokens // (alphanumeric-bounded, dots/underscores inside), never separators or escapes. const token = /^[A-Za-z0-9](?:[A-Za-z0-9._]*[A-Za-z0-9])?$/; if (!token.test(api) || !token.test(rev)) { @@ -98,10 +87,7 @@ const revOrder = (rev: string): number => { return match ? Number(match[1]) : Number.NaN; }; -/** - * Compare two engine-ids for a deterministic ascending sort: by upstream version - * (SemVer-aware), tie-broken by build-revision counter then the raw id string. - */ +/** Ascending: upstream version, then build-revision counter, then the raw id. */ export const compareEngineIds = (a: string, b: string): -1 | 0 | 1 => { const ra = parseEngineId(a); const rb = parseEngineId(b); From 28e54a1bf06cd3c400f5cc76b5d25d23662ae587 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:38:22 -0700 Subject: [PATCH 323/586] fix: tar Linux packages root-owned, without xattrs or AppleDouble --- src/cli/build-linux.ts | 28 +++++++++-- .../integration/macos/cli-build-linux.test.ts | 49 ++++++++++++++++++- 2 files changed, 71 insertions(+), 6 deletions(-) diff --git a/src/cli/build-linux.ts b/src/cli/build-linux.ts index 5ebed2b7..a22ce74f 100644 --- a/src/cli/build-linux.ts +++ b/src/cli/build-linux.ts @@ -7,7 +7,7 @@ import { chmodSync, copyFileSync, cpSync, existsSync, mkdirSync, writeFileSync } from 'node:fs'; import { dirname, join, posix } from 'node:path'; import { isSystemEngine, parseEngineId } from '../common/engine-id'; -import { type Arch, currentArch } from '../common/platform'; +import { type Arch, currentArch, currentPlatform } from '../common/platform'; import { BUNMASKA_VERSION } from '../common/version'; import { bundlePreloadAssets, copyAppAssets } from './app-assets'; import { runTool } from './run-tool'; @@ -146,6 +146,26 @@ export const buildArArchive = ( ]); }; +/** + * dpkg installs files with the archived owner and paths, so members must be + * root-owned, xattr-free and without macOS bsdtar's AppleDouble `._*` twins + * (which also collide across packages). The flags work in bsdtar and GNU tar. + */ +const tarGz = (archive: string, dir: string, member: string): Promise => + runTool('tar', [ + ...(currentPlatform() === 'macos' ? ['env', 'COPYFILE_DISABLE=1'] : []), + 'tar', + '--no-xattrs', + '--owner=0', + '--group=0', + '--numeric-owner', + '-czf', + archive, + '-C', + dir, + member, + ]); + const compileLinuxBinary = async (entry: string, outfile: string, arch: Arch): Promise => { await runTool('bun build --compile', [ 'bun', @@ -221,7 +241,7 @@ export const buildLinuxApp = async (opts: BuildLinuxAppOptions): Promise. const tarball = join(out, tarballName(opts.name, arch)); - await runTool('tar', ['tar', '-czf', tarball, '-C', out, opts.name]); + await tarGz(tarball, out, opts.name); // An embedded engine ships its own WebKitGTK, so it needs no system Depends. const depends = opts.embedEngine === true ? [] : DEFAULT_LINUX_DEPENDS; @@ -271,10 +291,10 @@ const packageDeb = async (args: { ); const controlTar = join(staging, 'control.tar.gz'); - await runTool('tar', ['tar', '-czf', controlTar, '-C', controlDir, 'control']); + await tarGz(controlTar, controlDir, 'control'); const dataTar = join(staging, 'data.tar.gz'); - await runTool('tar', ['tar', '-czf', dataTar, '-C', layout.appDir, 'usr']); + await tarGz(dataTar, layout.appDir, 'usr'); const debPath = join(out, debFileName(name, version, arch)); const archive = buildArArchive([ diff --git a/tests/integration/macos/cli-build-linux.test.ts b/tests/integration/macos/cli-build-linux.test.ts index 9a33fec0..fc8039c4 100644 --- a/tests/integration/macos/cli-build-linux.test.ts +++ b/tests/integration/macos/cli-build-linux.test.ts @@ -6,6 +6,40 @@ import { join } from 'node:path'; import { buildLinuxApp } from '../../../src/cli/build-linux'; import { currentPlatform } from '../../../src/common/platform'; +/** Members of a gzipped tar: name, owner uid and typeflag (`x` = pax header). */ +const tarMembers = ( + gz: Uint8Array, +): { name: string; uid: number; type: string; body: string }[] => { + const tar = Bun.gunzipSync(new Uint8Array(gz)); + const text = (from: number, to: number): string => + new TextDecoder().decode(tar.subarray(from, to)).replace(/\0.*$/s, ''); + const members = []; + for (let at = 0; at + 512 <= tar.length && tar[at] !== 0; ) { + const size = Number.parseInt(text(at + 124, at + 136), 8); + members.push({ + name: text(at, at + 100), + uid: Number.parseInt(text(at + 108, at + 116), 8), + type: text(at + 156, at + 157), + body: text(at + 512, at + 512 + size), + }); + at += 512 + Math.ceil(size / 512) * 512; + } + return members; +}; + +/** The bytes of one member of an `ar` archive (a `.deb`). */ +const arMember = (ar: Uint8Array, wanted: string): Uint8Array => { + for (let at = 8; at < ar.length; ) { + const name = new TextDecoder().decode(ar.subarray(at, at + 16)).trim(); + const size = Number.parseInt(new TextDecoder().decode(ar.subarray(at + 48, at + 58)), 10); + if (name === wanted) { + return ar.subarray(at + 60, at + 60 + size); + } + at += 60 + size + (size % 2); + } + throw new Error(`no ${wanted} in the ar archive`); +}; + /** * Integration test for the Linux distributable builder, guarded to macOS so it * exercises Bun's `--target=bun-linux-x64` CROSS-compilation. It writes a @@ -24,8 +58,6 @@ if (currentPlatform() === 'macos') { workDir = mkdtempSync(join(tmpdir(), 'bunmaska-cli-build-linux-')); outDir = join(workDir, 'out'); const entry = join(workDir, 'entry.ts'); - Bun.write(entry, "console.log('hi');\nprocess.exit(0);\n"); - // Bun.write returns a promise; ensure it landed before compiling. await Bun.write(entry, "console.log('hi');\nprocess.exit(0);\n"); result = await buildLinuxApp({ arch: 'x64', @@ -93,5 +125,18 @@ if (currentPlatform() === 'macos') { expect(listing.stdout).toContain('control.tar.gz'); expect(listing.stdout).toContain('data.tar.gz'); }); + + test('archives carry no AppleDouble files, xattrs or builder ownership', () => { + const deb = readFileSync(result.deb as string); + for (const gz of [readFileSync(result.tarball), arMember(deb, 'data.tar.gz')]) { + for (const member of tarMembers(gz)) { + expect(member.name).not.toMatch(/(^|\/)\._/); + expect(member.body).not.toContain('xattr'); + if (member.type !== 'x') { + expect(member.uid).toBe(0); + } + } + } + }); }); } From f91adbff70c6bfb6dceff3f838a8ad15b04e4d97 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:38:04 -0700 Subject: [PATCH 324/586] test: collapse the dev supervisor harnesses into one --- tests/unit/cli/dev.test.ts | 329 +++++++++++++------------------------ 1 file changed, 116 insertions(+), 213 deletions(-) diff --git a/tests/unit/cli/dev.test.ts b/tests/unit/cli/dev.test.ts index 891374a7..49f1c35f 100644 --- a/tests/unit/cli/dev.test.ts +++ b/tests/unit/cli/dev.test.ts @@ -2,6 +2,7 @@ import { describe, expect, test } from 'bun:test'; import { classifyChange, DEV_DEFAULT_ENTRY, + type ChangeAction, type DevDeps, DevSupervisor, resolveDevEntry, @@ -58,30 +59,75 @@ describe('classifyChange', () => { }); }); -/** A controllable test harness over the supervisor's seams. */ -const makeHarness = (): { - deps: DevDeps; - spawns: string[]; - kills: number; - reloads: number; - watcherClosed: () => boolean; - fireChange: (relPath: string) => void; - runTimer: () => Promise; - pendingTimers: () => number; -} => { +describe('classifyChange with a renderer root', () => { + test('a source change under the renderer root rebuilds instead of restarting', () => { + // This is the React fix: a component edit re-bundles and reloads, it no + // longer tears the window down. + expect(classifyChange('src/renderer/App.tsx', 'src/renderer')).toBe('rebuild'); + expect(classifyChange('src/renderer/styles.css', 'src/renderer')).toBe('rebuild'); + }); + + test('a main-process source outside the renderer root still restarts', () => { + expect(classifyChange('src/main.ts', 'src/renderer')).toBe('restart'); + expect(classifyChange('bunmaska.config.ts', 'src/renderer')).toBe('restart'); + }); + + test('the renderer output under dist still plain-reloads', () => { + expect(classifyChange('dist/renderer/main.js', 'src/renderer')).toBe('reload'); + }); + + test('a preload under the renderer root still restarts', () => { + expect(classifyChange('src/renderer/preload.js', 'src/renderer')).toBe('restart'); + }); +}); + +type HarnessOptions = { + readonly classify?: (relPath: string) => ChangeAction; + readonly rebuild?: () => void | Promise; + /** Children never exit on kill; the test settles each exit itself. */ + readonly manualExit?: boolean; +}; + +const flush = (): Promise => new Promise((r) => setTimeout(r, 0)); + +/** A controllable harness over the supervisor's seams. */ +const makeHarness = (opts: HarnessOptions = {}) => { const spawns: string[] = []; + const restarts: boolean[] = []; + const logs: string[] = []; + const exits: Array<() => void> = []; let kills = 0; let reloads = 0; + let rebuilds = 0; let closed = false; let onChange: ((relPath: string) => void) | undefined; let timerFn: (() => void) | undefined; const deps: DevDeps = { debounceMs: 100, - spawn: (entry) => { + ...(opts.classify !== undefined ? { classify: opts.classify } : {}), + ...(opts.rebuild !== undefined + ? { + rebuild: () => { + rebuilds += 1; + return opts.rebuild?.(); + }, + } + : {}), + spawn: (entry, spawnOpts) => { spawns.push(entry); + restarts.push(spawnOpts?.restart === true); + let settle: () => void = () => undefined; + const exited = new Promise((r) => { + settle = r; + }); + exits.push(settle); return { + exited, kill: () => { kills += 1; + if (opts.manualExit !== true) { + settle(); + } }, reload: () => { reloads += 1; @@ -105,28 +151,41 @@ const makeHarness = (): { timerFn = undefined; }, }, - log: () => undefined, + log: (m) => { + logs.push(m); + }, }; return { deps, spawns, + restarts, + logs, get kills() { return kills; }, get reloads() { return reloads; }, + get rebuilds() { + return rebuilds; + }, watcherClosed: () => closed, - fireChange: (relPath) => onChange?.(relPath), - runTimer: async () => { + fire: (relPath: string) => onChange?.(relPath), + /** Fire the pending debounce, then let the resulting async work settle. */ + tick: async () => { timerFn?.(); - // A restart awaits the old child's `exited`; yield so it can finish. - await new Promise((r) => setTimeout(r, 0)); + await flush(); }, pendingTimers: () => (timerFn === undefined ? 0 : 1), + /** Settle the exit of the `index`-th spawned child (default: the latest). */ + settleExit: (index = exits.length - 1) => exits[index]?.(), }; }; +const noop = (): void => undefined; + +const rendererAt = (relPath: string): ChangeAction => classifyChange(relPath, 'src/renderer'); + describe('DevSupervisor', () => { test('spawns the entry on construction', () => { const h = makeHarness(); @@ -137,20 +196,29 @@ describe('DevSupervisor', () => { test('a TypeScript change restarts the child after the debounce fires', async () => { const h = makeHarness(); const sup = new DevSupervisor('/proj', 'src/main.ts', h.deps); - h.fireChange('src/main.ts'); - expect(h.spawns).toHaveLength(1); // not yet — debounced - await h.runTimer(); + h.fire('src/main.ts'); + expect(h.spawns).toHaveLength(1); + await h.tick(); expect(h.spawns).toEqual(['src/main.ts', 'src/main.ts']); expect(sup.starts).toBe(2); expect(sup.reloads).toBe(0); }); + test('the first spawn is not a restart; every respawn is', async () => { + // The respawned app reads this to show its window without stealing focus. + const h = makeHarness(); + new DevSupervisor('/proj', 'src/main.ts', h.deps); + h.fire('src/main.ts'); + await h.tick(); + expect(h.restarts).toEqual([false, true]); + }); + test('a renderer asset change live-reloads instead of restarting', async () => { const h = makeHarness(); const sup = new DevSupervisor('/proj', 'src/main.ts', h.deps); - h.fireChange('src/index.html'); - await h.runTimer(); - expect(h.spawns).toHaveLength(1); // no respawn — the window stays open + h.fire('src/index.html'); + await h.tick(); + expect(h.spawns).toHaveLength(1); expect(h.reloads).toBe(1); expect(sup.reloads).toBe(1); expect(sup.starts).toBe(1); @@ -159,9 +227,9 @@ describe('DevSupervisor', () => { test('a restart supersedes a reload coalesced into the same window', async () => { const h = makeHarness(); const sup = new DevSupervisor('/proj', 'src/main.ts', h.deps); - h.fireChange('src/index.html'); // would reload - h.fireChange('src/main.ts'); // but a TS change wins - await h.runTimer(); + h.fire('src/index.html'); + h.fire('src/main.ts'); + await h.tick(); expect(sup.starts).toBe(2); expect(h.reloads).toBe(0); }); @@ -169,18 +237,18 @@ describe('DevSupervisor', () => { test('an ignored change never schedules anything', () => { const h = makeHarness(); new DevSupervisor('/proj', 'src/main.ts', h.deps); - h.fireChange('node_modules/x.js'); + h.fire('node_modules/x.js'); expect(h.pendingTimers()).toBe(0); }); test('rapid changes coalesce into a single action', async () => { const h = makeHarness(); new DevSupervisor('/proj', 'src/main.ts', h.deps); - h.fireChange('src/a.ts'); - h.fireChange('src/b.ts'); - h.fireChange('src/c.ts'); - await h.runTimer(); - expect(h.spawns).toHaveLength(2); // initial + one coalesced restart + h.fire('src/a.ts'); + h.fire('src/b.ts'); + h.fire('src/c.ts'); + await h.tick(); + expect(h.spawns).toHaveLength(2); }); test('stop closes the watcher, kills the child, and ignores later changes', () => { @@ -188,112 +256,37 @@ describe('DevSupervisor', () => { const sup = new DevSupervisor('/proj', 'src/main.ts', h.deps); sup.stop(); expect(h.watcherClosed()).toBe(true); - h.fireChange('src/main.ts'); + expect(h.kills).toBe(1); + h.fire('src/main.ts'); expect(h.pendingTimers()).toBe(0); expect(h.spawns).toHaveLength(1); }); }); -describe('classifyChange with a renderer root', () => { - test('a source change under the renderer root rebuilds instead of restarting', () => { - // This is the React fix: a component edit re-bundles and reloads, it no - // longer tears the window down. - expect(classifyChange('src/renderer/App.tsx', 'src/renderer')).toBe('rebuild'); - expect(classifyChange('src/renderer/styles.css', 'src/renderer')).toBe('rebuild'); - }); - - test('a main-process source outside the renderer root still restarts', () => { - expect(classifyChange('src/main.ts', 'src/renderer')).toBe('restart'); - expect(classifyChange('bunmaska.config.ts', 'src/renderer')).toBe('restart'); - }); - - test('the renderer output under dist still plain-reloads', () => { - expect(classifyChange('dist/renderer/main.js', 'src/renderer')).toBe('reload'); - }); - - test('a preload under the renderer root still restarts', () => { - expect(classifyChange('src/renderer/preload.js', 'src/renderer')).toBe('restart'); - }); -}); - describe('DevSupervisor rebuild action', () => { - const makeRebuildHarness = () => { - let rebuilds = 0; - let reloads = 0; - const spawns: string[] = []; - let timerFn: (() => void) | undefined; - let onChange: ((relPath: string) => void) | undefined; - const deps: DevDeps = { - classify: (relPath) => classifyChange(relPath, 'src/renderer'), - rebuild: () => { - rebuilds += 1; - }, - spawn: (entry) => { - spawns.push(entry); - return { - kill: () => undefined, - reload: () => { - reloads += 1; - }, - exited: new Promise(() => undefined), - }; - }, - watch: (_dir, cb) => { - onChange = cb; - return { close: () => undefined }; - }, - timers: { - set: (fn) => { - timerFn = fn; - return 1; - }, - clear: () => { - timerFn = undefined; - }, - }, - log: () => undefined, - }; - return { - deps, - spawns, - get rebuilds() { - return rebuilds; - }, - get reloads() { - return reloads; - }, - fire: (p: string) => onChange?.(p), - tick: async () => { - timerFn?.(); - await new Promise((r) => setTimeout(r, 0)); - }, - }; - }; - test('a renderer change rebuilds without restarting or reloading directly', async () => { - const h = makeRebuildHarness(); + const h = makeHarness({ classify: rendererAt, rebuild: noop }); new DevSupervisor('/proj', 'src/main.ts', h.deps); h.fire('src/renderer/App.tsx'); await h.tick(); expect(h.rebuilds).toBe(1); - expect(h.spawns).toHaveLength(1); // no restart - expect(h.reloads).toBe(0); // the reload arrives later, from the output write + expect(h.spawns).toHaveLength(1); + // The reload arrives later, from the output write. + expect(h.reloads).toBe(0); }); test('a restart coalesced with a rebuild wins', async () => { - const h = makeRebuildHarness(); + const h = makeHarness({ classify: rendererAt, rebuild: noop, manualExit: true }); new DevSupervisor('/proj', 'src/main.ts', h.deps); h.fire('src/renderer/App.tsx'); h.fire('src/main.ts'); await h.tick(); expect(h.rebuilds).toBe(0); - // kill fired; respawn is parked on the never-settling exited, which is the - // await-exit behaviour, so no second spawn yet. expect(h.spawns).toHaveLength(1); }); test('a rebuild coalesced with a reload wins', async () => { - const h = makeRebuildHarness(); + const h = makeHarness({ classify: rendererAt, rebuild: noop }); new DevSupervisor('/proj', 'src/main.ts', h.deps); h.fire('dist/renderer/main.js'); h.fire('src/renderer/App.tsx'); @@ -304,117 +297,27 @@ describe('DevSupervisor rebuild action', () => { }); describe('DevSupervisor child lifecycle', () => { - /** A harness whose children expose a controllable `exited`. */ - const makeLifecycle = () => { - const spawns: string[] = []; - const logs: string[] = []; - let settleLast: (() => void) | undefined; - let timerFn: (() => void) | undefined; - let onChange: ((relPath: string) => void) | undefined; - let reloads = 0; - const deps: DevDeps = { - spawn: (entry) => { - spawns.push(entry); - let settle: () => void = () => undefined; - const exited = new Promise((r) => { - settle = r; - }); - settleLast = settle; - return { - exited, - kill: () => undefined, - reload: () => { - reloads += 1; - }, - }; - }, - watch: (_dir, cb) => { - onChange = cb; - return { close: () => undefined }; - }, - timers: { - set: (fn) => { - timerFn = fn; - return 1; - }, - clear: () => { - timerFn = undefined; - }, - }, - log: (m) => { - logs.push(m); - }, - }; - return { - deps, - spawns, - logs, - get reloads() { - return reloads; - }, - fire: (p: string) => onChange?.(p), - tick: async () => { - timerFn?.(); - await new Promise((r) => setTimeout(r, 0)); - }, - settleExit: () => settleLast?.(), - }; - }; - test('a restart waits for the old child to exit before spawning the new one', async () => { - const h = makeLifecycle(); + const h = makeHarness({ manualExit: true }); new DevSupervisor('/proj', 'src/main.ts', h.deps); - const first = h.settleExit; // the child spawned in the constructor h.fire('src/main.ts'); await h.tick(); - // Killed, but its exit has not settled — spawning now would leave two live - // apps racing for the window and the single-instance lock. + // Killed but not yet exited: spawning now would leave two live apps racing + // for the window and the single-instance lock. expect(h.spawns).toHaveLength(1); - first(); - await new Promise((r) => setTimeout(r, 0)); + h.settleExit(0); + await flush(); expect(h.spawns).toHaveLength(2); }); test('a reload after the app quits says so instead of reporting success', async () => { - const h = makeLifecycle(); + const h = makeHarness({ manualExit: true }); new DevSupervisor('/proj', 'src/main.ts', h.deps); - h.settleExit(); // the user quit the app - await new Promise((r) => setTimeout(r, 0)); + h.settleExit(); + await flush(); h.fire('src/index.html'); await h.tick(); expect(h.reloads).toBe(0); expect(h.logs.join(' ')).toContain('not running'); }); }); - -describe('DevSupervisor restart marking', () => { - test('the first spawn is not a restart; every respawn is', async () => { - // The respawned app reads this to show its window without stealing focus. - const spawns: Array<{ restart: boolean }> = []; - let timerFn: (() => void) | undefined; - let onChange: ((p: string) => void) | undefined; - const deps: DevDeps = { - spawn: (_entry, opts) => { - spawns.push({ restart: opts?.restart === true }); - return { kill: () => undefined, reload: () => undefined, exited: Promise.resolve() }; - }, - watch: (_dir, cb) => { - onChange = cb; - return { close: () => undefined }; - }, - timers: { - set: (fn) => { - timerFn = fn; - return 1; - }, - clear: () => undefined, - }, - log: () => undefined, - }; - new DevSupervisor('/proj', 'src/main.ts', deps); - onChange?.('src/main.ts'); - timerFn?.(); - await new Promise((r) => setTimeout(r, 0)); - expect(spawns).toEqual([{ restart: false }, { restart: true }]); - }); -}); From b8d8db9ed0419e7076bdc68d90c541c5b8f4f5fe Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:38:41 -0700 Subject: [PATCH 325/586] fix: keep renderer bundle diagnostics with Bun.build throw: false --- src/cli/renderer-build.ts | 1 + tests/unit/cli/renderer-build.test.ts | 8 ++++++++ 2 files changed, 9 insertions(+) diff --git a/src/cli/renderer-build.ts b/src/cli/renderer-build.ts index 0ece842c..2cc424b2 100644 --- a/src/cli/renderer-build.ts +++ b/src/cli/renderer-build.ts @@ -38,6 +38,7 @@ const defaultBundler: RendererBundler = async (entry, outDir, mode) => { // The define picks the JSX runtime too: development emits jsxDEV, production jsx. define: { 'process.env.NODE_ENV': JSON.stringify(mode) }, naming: '[dir]/[name].[ext]', + throw: false, }); if (!result.success) { const messages = result.logs.map((log) => log.message).join('\n'); diff --git a/tests/unit/cli/renderer-build.test.ts b/tests/unit/cli/renderer-build.test.ts index c9d127e1..e6295643 100644 --- a/tests/unit/cli/renderer-build.test.ts +++ b/tests/unit/cli/renderer-build.test.ts @@ -59,4 +59,12 @@ describe('buildRenderer', () => { buildRenderer(dir, { entry: 'src/renderer/main.ts', copy: ['missing.html'] }), ).rejects.toThrow(/renderer.copy source not found/); }); + + test('a bundle error names the entry and the parser diagnostic', async () => { + const dir = makeProject(); + writeFileSync(join(dir, 'src', 'renderer', 'main.ts'), 'const x = ;\n'); + await expect(buildRenderer(dir, { entry: 'src/renderer/main.ts' })).rejects.toThrow( + /renderer build failed for .*main\.ts:\nUnexpected ;/, + ); + }); }); From dfaa90fc3e0aa2a8fa58f59bbb41da5247239ded Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:38:46 -0700 Subject: [PATCH 326/586] fix: server-render the final bundle size, not Electron's 150MB --- website/src/components/FeatureGrid.astro | 2 +- website/src/components/ui/BundleSizeCounter.tsx | 16 ++++++---------- 2 files changed, 7 insertions(+), 11 deletions(-) diff --git a/website/src/components/FeatureGrid.astro b/website/src/components/FeatureGrid.astro index b2d79f35..a0b45032 100644 --- a/website/src/components/FeatureGrid.astro +++ b/website/src/components/FeatureGrid.astro @@ -7,7 +7,7 @@ import BundleSizeCounter from "./ui/BundleSizeCounter";

Bundle size

- +

The whole app, not a browser you re-ship with it. Downloads in seconds; updates are a fraction of the size. diff --git a/website/src/components/ui/BundleSizeCounter.tsx b/website/src/components/ui/BundleSizeCounter.tsx index db0331fd..c40d2e9d 100644 --- a/website/src/components/ui/BundleSizeCounter.tsx +++ b/website/src/components/ui/BundleSizeCounter.tsx @@ -11,13 +11,16 @@ export default function BundleCounter({ to = 16, duration = 2400, }: BundleCounterProps) { - const [value, setValue] = useState(from); - const [progress, setProgress] = useState(0); + // SSR the real number: crawlers and no-JS readers must never see `from`. + const [value, setValue] = useState(to); + const [progress, setProgress] = useState(1); const ref = useRef(null); useEffect(() => { - if (!ref.current) return; + if (!ref.current || window.matchMedia('(prefers-reduced-motion: reduce)').matches) return; + setValue(from); + setProgress(0); const easeOutCubic = (x: number) => 1 - (1 - x) ** 3; @@ -27,13 +30,6 @@ export default function BundleCounter({ observer.disconnect(); - // Respect reduced-motion: jump straight to the final value, no animation. - if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) { - setProgress(1); - setValue(to); - return; - } - const start = performance.now(); const animate = (now: number) => { From b5bd8620d708122515a599468666e3592e7ed62d Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:39:19 -0700 Subject: [PATCH 327/586] fix: badge Windows as beta on the platforms grid --- website/src/components/Platforms.astro | 26 +++++--------------------- 1 file changed, 5 insertions(+), 21 deletions(-) diff --git a/website/src/components/Platforms.astro b/website/src/components/Platforms.astro index 1d054e55..b08ee5ac 100644 --- a/website/src/components/Platforms.astro +++ b/website/src/components/Platforms.astro @@ -1,8 +1,6 @@ --- import { HEAD } from "../styles/constants"; -// Platform support matrix. macOS + Linux ship today (x64 + ARM). Windows is in beta -// (x64) on a from-source WinCairo backend, green on CI, with one hosted engine on the feed. const apple = ''; const windows = @@ -10,32 +8,18 @@ const windows = const linux = ''; -type Status = "shipping" | "beta" | "planned"; +type Status = "shipping" | "beta"; -const STATUS: Record< - Status, - { label: string; badge: string; style: string; icon: string; cell: string } -> = { +const STATUS: Record = { shipping: { label: "Shipping", badge: "border-accent/40 text-accent-text", style: "background:var(--accent-bg);", - icon: "text-text", - cell: "", }, beta: { label: "Beta", badge: "border-border-strong text-text-muted", style: "background:var(--bg-muted);", - icon: "text-text", - cell: "", - }, - planned: { - label: "Planned", - badge: "border-border-strong text-text-faint", - style: "", - icon: "text-text-faint", - cell: "bg-bg-subtle", }, }; @@ -63,7 +47,7 @@ const platforms: { { name: "Windows", icon: windows, - status: "shipping", + status: "beta", arch: "x64 today · ARM64 on the roadmap", note: "WinCairo WebKit, built from source. One hosted engine on the feed; stable-train and ARM64 next.", }, @@ -99,11 +83,11 @@ const platforms: { platforms.map((p) => { const s = STATUS[p.status]; return ( -

+
+ Skip to content From 87da6947b3c0044b2566c7fedd7e3553ba25094d Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:45:21 -0700 Subject: [PATCH 356/586] fix: remove the fired once wrapper, not an on of the same listener --- src/renderer/api/ipc-renderer.ts | 8 +- tests/unit/renderer/ipc-renderer.test.ts | 111 ++++++++--------------- 2 files changed, 43 insertions(+), 76 deletions(-) diff --git a/src/renderer/api/ipc-renderer.ts b/src/renderer/api/ipc-renderer.ts index 0f773a88..9d1f7270 100644 --- a/src/renderer/api/ipc-renderer.ts +++ b/src/renderer/api/ipc-renderer.ts @@ -78,10 +78,12 @@ export const createIpcRenderer = (): IpcRenderer => { getBridge().on(channel, wrap(channel, listener)); }, once(channel, listener) { - // The bridge drops the wrapper after one dispatch, so the tracked wrapper - // also drops its own entry when it fires (keeps removeListener consistent). + // The bridge drops a fired once, so drop this exact entry, not an `on` of the same listener. const wrapper: BridgeListener = (...args) => { - takeWrapper(channel, listener); + const index = wrappers.findIndex((e) => e.wrapper === wrapper); + if (index !== -1) { + wrappers.splice(index, 1); + } listener({}, ...args); }; wrappers.push({ channel, listener, wrapper }); diff --git a/tests/unit/renderer/ipc-renderer.test.ts b/tests/unit/renderer/ipc-renderer.test.ts index f5d1d58c..16315f80 100644 --- a/tests/unit/renderer/ipc-renderer.test.ts +++ b/tests/unit/renderer/ipc-renderer.test.ts @@ -1,76 +1,23 @@ import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; import { createIpcRenderer } from '../../../src/renderer/api/ipc-renderer'; +import { generatePreloadBootstrap } from '../../../src/renderer/preload-bootstrap'; -type Listener = (...args: unknown[]) => void; - -type FakeBridge = { - send: (channel: string, ...args: unknown[]) => void; - invoke: (channel: string, ...args: unknown[]) => Promise; - on: (channel: string, listener: Listener) => void; - once: (channel: string, listener: Listener) => void; - removeListener: (channel: string, listener: Listener) => void; - removeAllListeners: (channel?: string) => void; -}; - -type Record = { fn: Listener; once: boolean }; - -let sent: Array<{ channel: string; args: unknown[] }>; -let invoked: Array<{ channel: string; args: unknown[] }>; -let registered: Map; - -/** Mirror the real bridge dispatch so once/remove semantics are exercised. */ -const dispatch = (channel: string, ...args: unknown[]): void => { - const live = registered.get(channel) ?? []; - for (const record of [...live]) { - const current = registered.get(channel) ?? []; - if (!current.includes(record)) { - continue; - } - if (record.once) { - current.splice(current.indexOf(record), 1); - } - record.fn(...args); - } -}; +type Bridge = { _dispatch: (raw: string) => void }; + +let bridge: Bridge; +let posted: string[]; + +/** Deliver a main-to-renderer `send` through the real bootstrap. */ +const dispatch = (channel: string, ...args: unknown[]): void => + bridge._dispatch(JSON.stringify({ kind: 'send', channel, args })); beforeEach(() => { - sent = []; - invoked = []; - registered = new Map(); - const bridge: FakeBridge = { - send: (channel, ...args) => sent.push({ channel, args }), - invoke: (channel, ...args) => { - invoked.push({ channel, args }); - return Promise.resolve(`result:${channel}`); - }, - on: (channel, listener) => { - const list = registered.get(channel) ?? []; - list.push({ fn: listener, once: false }); - registered.set(channel, list); - }, - once: (channel, listener) => { - const list = registered.get(channel) ?? []; - list.push({ fn: listener, once: true }); - registered.set(channel, list); - }, - removeListener: (channel, listener) => { - const list = registered.get(channel); - if (!list) { - return; - } - const index = list.findIndex((r) => r.fn === listener); - if (index !== -1) { - list.splice(index, 1); - } - }, - removeAllListeners: (channel) => { - if (channel === undefined) { - registered.clear(); - } else { - registered.delete(channel); - } - }, + posted = []; + const scope: Record = { + webkit: { messageHandlers: { bunmaska: { postMessage: (msg: string) => posted.push(msg) } } }, }; + new Function('globalThis', generatePreloadBootstrap())(scope); + bridge = scope['__bunmaska'] as Bridge; Reflect.set(globalThis, '__bunmaska', bridge); }); @@ -79,17 +26,21 @@ afterEach(() => { }); describe('ipcRenderer.send', () => { - test('forwards channel and args to the bridge', () => { + test('posts a send envelope with the channel and args', () => { createIpcRenderer().send('ping', 1, 2); - expect(sent).toEqual([{ channel: 'ping', args: [1, 2] }]); + expect(posted.map((raw) => JSON.parse(raw))).toEqual([ + { kind: 'send', channel: 'ping', args: [1, 2] }, + ]); }); }); describe('ipcRenderer.invoke', () => { - test('forwards to the bridge and returns its promise', async () => { - const result = await createIpcRenderer().invoke('compute', 41); - expect(invoked).toEqual([{ channel: 'compute', args: [41] }]); - expect(result).toBe('result:compute'); + test('resolves with the reply to its invoke envelope', async () => { + const result = createIpcRenderer().invoke('compute', 41); + const env = JSON.parse(posted[0] ?? ''); + expect(env).toMatchObject({ kind: 'invoke', channel: 'compute', args: [41] }); + bridge._dispatch(JSON.stringify({ kind: 'reply', id: env.id, ok: true, result: 42 })); + expect(await result).toBe(42); }); }); @@ -110,6 +61,20 @@ describe('ipcRenderer.once', () => { dispatch('news', 'again'); expect(received).toEqual([{ event: {}, args: ['hello', 7] }]); }); + + test('firing a once leaves an on listener of the same function removable', () => { + const ipc = createIpcRenderer(); + let calls = 0; + const listener = (): void => { + calls += 1; + }; + ipc.on('state', listener); + ipc.once('state', listener); + dispatch('state'); + ipc.removeListener('state', listener); + dispatch('state'); + expect(calls).toBe(2); + }); }); describe('ipcRenderer.removeListener', () => { From a8439bd14248b96d14137ea4e28c784cb081caa7 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:45:33 -0700 Subject: [PATCH 357/586] fix: key dev watch events by slash paths and skip the state file --- src/cli/dev-watch.ts | 8 ++++++-- src/cli/dev.ts | 5 ++--- tests/unit/cli/dev-watch.test.ts | 22 +++++++++++++++++++++- 3 files changed, 29 insertions(+), 6 deletions(-) diff --git a/src/cli/dev-watch.ts b/src/cli/dev-watch.ts index a1b49d4f..e469240a 100644 --- a/src/cli/dev-watch.ts +++ b/src/cli/dev-watch.ts @@ -3,6 +3,9 @@ import { type Dirent, readdirSync, readFileSync, statSync, watch as fsWatch } from 'node:fs'; import { resolve } from 'node:path'; +/** The dev window-state file `bunmaska dev` keeps in the project root. */ +export const DEV_STATE_FILE = '.bunmaska-dev-state.json'; + /** * Top-level output dirs of common tools. `dist` is deliberately NOT here: the * renderer bundle lives there, and ignoring it means a rebuild never reloads. @@ -171,10 +174,11 @@ export const makeWatchHandler = ( } }; return (filename) => { - if (filename === null) { + if (filename === null || filename === DEV_STATE_FILE) { return; } - const relPath = filename; + // One key per file: libuv reports Windows paths with backslashes, the seed uses slashes. + const relPath = pathParts(filename).join('/'); const tempDir = editorTempDir(relPath); if (tempDir !== undefined) { rescan(tempDir); diff --git a/src/cli/dev.ts b/src/cli/dev.ts index 77aca94f..8e21d07f 100644 --- a/src/cli/dev.ts +++ b/src/cli/dev.ts @@ -8,7 +8,7 @@ import { extname, resolve } from 'node:path'; import type { BunmaskaConfig } from '../common/config-schema'; import { InvalidArgumentError } from '../common/errors'; import { DEV_RELOAD_COMMAND } from '../main/dev-reload'; -import { isIgnoredPath, pathParts, watchTree } from './dev-watch'; +import { DEV_STATE_FILE, isIgnoredPath, pathParts, watchTree } from './dev-watch'; export const DEV_DEFAULT_ENTRY = 'src/main.ts'; @@ -300,8 +300,7 @@ export const defaultDevDeps = ( ...process.env, ...extraEnv, BUNMASKA_DEV: '1', - // Dot-named so the watcher never classifies the state file itself. - BUNMASKA_DEV_STATE: resolve(cwd, '.bunmaska-dev-state.json'), + BUNMASKA_DEV_STATE: resolve(cwd, DEV_STATE_FILE), ...(opts?.restart ? { BUNMASKA_DEV_RESTART: '1' } : {}), }, stdin: 'pipe', diff --git a/tests/unit/cli/dev-watch.test.ts b/tests/unit/cli/dev-watch.test.ts index d2f61dae..24194932 100644 --- a/tests/unit/cli/dev-watch.test.ts +++ b/tests/unit/cli/dev-watch.test.ts @@ -2,7 +2,12 @@ import { describe, expect, test } from 'bun:test'; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { editorTempDir, makeContentFilter, makeWatchHandler } from '../../../src/cli/dev-watch'; +import { + DEV_STATE_FILE, + editorTempDir, + makeContentFilter, + makeWatchHandler, +} from '../../../src/cli/dev-watch'; const bytes = (text: string): Uint8Array => new TextEncoder().encode(text); @@ -113,6 +118,21 @@ describe('makeWatchHandler', () => { expect(p.fired).toEqual(['assets/a.png']); }); + test('a backslash-separated event shares the baseline of its slash-separated seed', () => { + // libuv reports Windows paths with backslashes; the seed walk uses slashes. + using p = project({ 'src/main.ts': 'v1' }); + p.handle('src\\main.ts'); + expect(p.fired).toEqual([]); + }); + + test('a dev window-state write does not rescan the project root', () => { + using p = project({ 'README.md': 'a' }); + p.write('README.md', 'b'); + p.write(DEV_STATE_FILE, '{}'); + p.handle(DEV_STATE_FILE); + expect(p.fired).toEqual([]); + }); + test('ignores edits inside dot directories', () => { using p = project({ '.idea/workspace.xml': 'a' }); p.write('.idea/workspace.xml', 'b'); From d66b7671741b2cfe7e230f9d42f6bb20093a70dd Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:45:40 -0700 Subject: [PATCH 358/586] fix: point page code at contextBridge when ipcRenderer is missing --- src/renderer/api/ipc-renderer.ts | 2 +- tests/unit/renderer/ipc-renderer.test.ts | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/renderer/api/ipc-renderer.ts b/src/renderer/api/ipc-renderer.ts index 9d1f7270..98eda214 100644 --- a/src/renderer/api/ipc-renderer.ts +++ b/src/renderer/api/ipc-renderer.ts @@ -34,7 +34,7 @@ const getBridge = (): RendererBridge => { const bridge = Reflect.get(globalThis, '__bunmaska') as RendererBridge | undefined; if (bridge === undefined) { throw new BunmaskaError( - 'Bunmaska preload bridge is not available; ensure a preload script ran before renderer code', + 'ipcRenderer is only available in the preload (isolated world); expose what the page needs with contextBridge', ); } return bridge; diff --git a/tests/unit/renderer/ipc-renderer.test.ts b/tests/unit/renderer/ipc-renderer.test.ts index 16315f80..2fb59bc0 100644 --- a/tests/unit/renderer/ipc-renderer.test.ts +++ b/tests/unit/renderer/ipc-renderer.test.ts @@ -133,8 +133,10 @@ describe('ipcRenderer.removeAllListeners', () => { }); describe('ipcRenderer without a bridge', () => { - test('throws a clear error if the preload bridge is absent', () => { + test('throws pointing page code at contextBridge when the bridge is absent', () => { Reflect.deleteProperty(globalThis, '__bunmaska'); - expect(() => createIpcRenderer().send('x')).toThrow(/preload/i); + expect(() => createIpcRenderer().send('x')).toThrow( + /only available in the preload \(isolated world\).*contextBridge/, + ); }); }); From 617d5cc747e618ce6931ef61aebcecbe1c7d2ca7 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:45:46 -0700 Subject: [PATCH 359/586] fix: ping IndexNow for every route a changed source file feeds --- website/scripts/indexnow-urls.py | 65 +++++++++++++++++++++----------- 1 file changed, 42 insertions(+), 23 deletions(-) diff --git a/website/scripts/indexnow-urls.py b/website/scripts/indexnow-urls.py index 0f71b9f6..4c2bc584 100644 --- a/website/scripts/indexnow-urls.py +++ b/website/scripts/indexnow-urls.py @@ -1,13 +1,8 @@ #!/usr/bin/env python3 -"""Map changed repo paths to the site URLs worth an IndexNow ping. +"""Print the sitemap URLs whose source changed; IndexNow wants changed URLs, never the whole sitemap. usage: indexnow-urls.py < changed-files.txt - -Prints one URL per line. A change under a site-wide file (layout, component, -stylesheet, nav/site data, config) prints every sitemap URL; a change to one -docs page or one route prints just that URL; anything else prints nothing, so -the caller can skip the ping. IndexNow asks for changed URLs only, never the -whole sitemap on every deploy. + indexnow-urls.py --self-test """ import glob @@ -16,41 +11,43 @@ SITE = "https://bunmaska.org" SITEWIDE = ( + "website/src/assets/", "website/src/components/", "website/src/layouts/", "website/src/styles/", "website/src/nav.ts", "website/src/site.ts", + "website/src/fonts.ts", + "website/src/content.config.ts", "website/src/rehype-copy-button.mjs", "website/astro.config.mjs", "website/package.json", ) -# Data files that feed exactly one route. ROUTE_DATA = { - "website/src/faq.ts": SITE, - "website/src/roadmap-data.ts": f"{SITE}/roadmap", + "website/src/faq.ts": (SITE, f"{SITE}/alternatives"), + "website/src/roadmap-data.ts": (f"{SITE}/roadmap",), } +DOCS_ROUTE = "website/src/pages/docs/[...slug].astro" def sitemap_urls(dist: str) -> list[str]: - urls: list[str] = [] + locs: list[str] = [] for path in sorted(glob.glob(f"{dist}/sitemap-*.xml")): with open(path, encoding="utf-8") as f: - urls += re.findall(r"([^<]+)", f.read()) - return [u for u in urls if not u.endswith(".xml")] + locs += re.findall(r"([^<]+)", f.read()) + return [u for u in locs if not u.endswith(".xml")] -def main() -> None: - dist = sys.argv[1] - known = sitemap_urls(dist) - changed = [line.strip() for line in sys.stdin if line.strip()] +def urls(changed: list[str], known: list[str]) -> list[str]: wanted: set[str] = set() for path in changed: if path.startswith(SITEWIDE): - print("\n".join(known)) - return + return known if path in ROUTE_DATA: - wanted.add(ROUTE_DATA[path]) + wanted.update(ROUTE_DATA[path]) + continue + if path == DOCS_ROUTE: + wanted.update(url for url in known if url.startswith(f"{SITE}/docs/")) continue doc = re.match(r"website/src/content/docs/(.+)\.mdx?$", path) if doc: @@ -62,9 +59,31 @@ def main() -> None: if name.startswith("docs/") or name == "404": continue wanted.add(SITE if name == "index" else f"{SITE}/{name}") - for url in known: - if url in wanted: - print(url) + return [url for url in known if url in wanted] + + +def self_test() -> None: + docs = [f"{SITE}/docs/introduction", f"{SITE}/docs/api/app"] + known = [SITE, f"{SITE}/about", f"{SITE}/alternatives", f"{SITE}/roadmap", *docs] + assert urls(["website/src/faq.ts"], known) == [SITE, f"{SITE}/alternatives"] + assert urls(["website/src/pages/docs/[...slug].astro"], known) == docs + assert urls(["website/src/fonts.ts"], known) == known + assert urls(["website/src/content.config.ts"], known) == known + assert urls(["website/src/content/docs/api/app.md", "website/src/pages/about.astro"], known) == [ + f"{SITE}/about", + f"{SITE}/docs/api/app", + ] + assert urls(["README.md", "website/src/pages/404.astro"], known) == [] + print("indexnow-urls self-test ok") + + +def main() -> None: + if sys.argv[1] == "--self-test": + self_test() + return + changed = [line.strip() for line in sys.stdin if line.strip()] + for url in urls(changed, sitemap_urls(sys.argv[1])): + print(url) if __name__ == "__main__": From a7cd170a56141068a0ef60044b705aa623396c7d Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:45:52 -0700 Subject: [PATCH 360/586] fix: clear each builder's earlier output so stale files stop shipping --- src/cli/build-linux.ts | 2 ++ src/cli/build-macos.ts | 2 ++ src/cli/build-windows.ts | 15 ++++++++++++- .../integration/macos/cli-build-linux.test.ts | 17 ++++++++++++++- .../macos/cli-build-windows-cross.test.ts | 8 +++++-- tests/integration/macos/cli-build.test.ts | 21 +++++++++++++++++-- 6 files changed, 59 insertions(+), 6 deletions(-) diff --git a/src/cli/build-linux.ts b/src/cli/build-linux.ts index acec0310..bed725af 100644 --- a/src/cli/build-linux.ts +++ b/src/cli/build-linux.ts @@ -228,6 +228,8 @@ export const buildLinuxApp = async (opts: BuildLinuxAppOptions): Promise`; const description = `${opts.name} built with Bunmaska`; + // Start clean (everything the build writes is under usr/): cpSync merges into stale trees. + rmSync(join(layout.appDir, 'usr'), { recursive: true, force: true }); mkdirSync(dirname(layout.binPath), { recursive: true }); mkdirSync(dirname(layout.desktopPath), { recursive: true }); diff --git a/src/cli/build-macos.ts b/src/cli/build-macos.ts index 9adaa494..05f06ded 100644 --- a/src/cli/build-macos.ts +++ b/src/cli/build-macos.ts @@ -368,6 +368,8 @@ export const buildMacApp = async (opts: BuildMacAppOptions): Promise => const version = opts.version ?? BUNMASKA_VERSION; const layout = appBundleLayout(out, opts.name); + // Start clean: cpSync merges, so files an earlier build shipped would ship again. + rmSync(layout.appDir, { recursive: true, force: true }); mkdirSync(layout.macosDir, { recursive: true }); mkdirSync(layout.resourcesDir, { recursive: true }); diff --git a/src/cli/build-windows.ts b/src/cli/build-windows.ts index f7c13706..d65061a9 100644 --- a/src/cli/build-windows.ts +++ b/src/cli/build-windows.ts @@ -6,7 +6,15 @@ * `engine.id`) or `BUNMASKA_WEBKIT_PATH`. */ -import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { + cpSync, + existsSync, + mkdirSync, + readdirSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs'; import { join } from 'node:path'; import { currentPlatform, type Platform } from '../common/platform'; import { BUNMASKA_VERSION } from '../common/version'; @@ -163,6 +171,11 @@ export const buildWindowsApp = async ( ); } + // Start clean, but only over our own earlier output (it always holds engine.id): + // cpSync merges, so a stale webkit/ or asset would ship again. + if (existsSync(layout.engineIdPath)) { + rmSync(layout.appDir, { recursive: true, force: true }); + } mkdirSync(layout.appDir, { recursive: true }); if (currentPlatform() !== 'windows') { diff --git a/tests/integration/macos/cli-build-linux.test.ts b/tests/integration/macos/cli-build-linux.test.ts index 6b3d6e9d..86e4b7b9 100644 --- a/tests/integration/macos/cli-build-linux.test.ts +++ b/tests/integration/macos/cli-build-linux.test.ts @@ -1,6 +1,14 @@ import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; import { spawnSync } from 'node:child_process'; -import { mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs'; +import { + existsSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + statSync, + writeFileSync, +} from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { buildLinuxApp } from '../../../src/cli/build-linux'; @@ -127,6 +135,13 @@ if (currentPlatform() === 'macos') { expect(readdirSync(outDir).filter((name) => name.startsWith('.'))).toEqual([]); }); + test('a rebuild drops files the previous build shipped', async () => { + const stale = join(result.appDir, 'usr', 'bin', 'stale.html'); + writeFileSync(stale, 'old'); + await buildLinuxApp({ arch: 'x64', entry: join(workDir, 'entry.ts'), name, out: outDir }); + expect(existsSync(stale)).toBe(false); + }, 30000); + test('archives carry no AppleDouble files, xattrs or builder ownership', () => { const deb = readFileSync(result.deb as string); for (const gz of [readFileSync(result.tarball), arMember(deb, 'data.tar.gz')]) { diff --git a/tests/integration/macos/cli-build-windows-cross.test.ts b/tests/integration/macos/cli-build-windows-cross.test.ts index 599d705f..8d6bc90b 100644 --- a/tests/integration/macos/cli-build-windows-cross.test.ts +++ b/tests/integration/macos/cli-build-windows-cross.test.ts @@ -1,5 +1,5 @@ import { afterAll, describe, expect, test } from 'bun:test'; -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { buildWindowsApp } from '../../../src/cli/build-windows'; @@ -20,15 +20,19 @@ describe('buildWindowsApp cross-compiled from macOS (integration)', () => { }); test.skipIf(currentPlatform() !== 'macos')( - 'produces a GUI-subsystem .exe and its zip', + 'produces a GUI-subsystem .exe and its zip, replacing an earlier build', async () => { const entry = join(workDir, 'entry.ts'); writeFileSync(entry, "console.log('hi');\n"); + const staleEngine = join(workDir, 'out', 'Cross App', 'webkit'); + mkdirSync(staleEngine, { recursive: true }); + writeFileSync(join(staleEngine, '..', 'engine.id'), 'system\n'); const result = await buildWindowsApp({ entry, name: 'Cross App', out: join(workDir, 'out') }); expect(peSubsystem(readFileSync(result.exePath))).toBe(2); expect(readFileSync(result.zip).subarray(0, 2).toString()).toBe('PK'); + expect(existsSync(staleEngine)).toBe(false); }, 120000, ); diff --git a/tests/integration/macos/cli-build.test.ts b/tests/integration/macos/cli-build.test.ts index 7b40efab..c2e6a366 100644 --- a/tests/integration/macos/cli-build.test.ts +++ b/tests/integration/macos/cli-build.test.ts @@ -1,8 +1,16 @@ import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; import { spawnSync } from 'node:child_process'; -import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + statSync, + writeFileSync, +} from 'node:fs'; import { tmpdir } from 'node:os'; -import { join } from 'node:path'; +import { dirname, join } from 'node:path'; import { buildMacApp } from '../../../src/cli/build-macos'; import { currentPlatform } from '../../../src/common/platform'; @@ -67,6 +75,15 @@ if (currentPlatform() === 'macos') { expect(result.stdout).toContain('hi'); }, 30000); + test('replaces an earlier bundle instead of merging into it', async () => { + const out = join(workDir, 'rebuild'); + const stale = join(out, 'Re App.app', 'Contents', 'MacOS', 'stale.html'); + mkdirSync(dirname(stale), { recursive: true }); + writeFileSync(stale, 'old'); + await buildMacApp({ entry, name: 'Re App', out }); + expect(existsSync(stale)).toBe(false); + }, 30000); + test('defaults the bundle id from the name when --id is omitted', async () => { const appPath = await buildMacApp({ entry, From 23e7786f87533847ba27b99cc5a063b8903bcbf2 Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:46:02 -0700 Subject: [PATCH 361/586] fix: log a dev file-watch error instead of crashing the supervisor --- src/cli/dev-watch.ts | 5 +++++ src/cli/dev.ts | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/cli/dev-watch.ts b/src/cli/dev-watch.ts index e469240a..3e692e13 100644 --- a/src/cli/dev-watch.ts +++ b/src/cli/dev-watch.ts @@ -196,11 +196,16 @@ export const makeWatchHandler = ( export const watchTree = ( dir: string, onChange: (relPath: string) => void, + log: (message: string) => void, ): { readonly close: () => void } => { const handle = makeWatchHandler(dir, onChange); const watcher = fsWatch(dir, { recursive: true }, (_event, filename) => { handle(filename === null ? null : filename.toString()); }); + // Unhandled, a watch error (inotify ENOSPC, root removed) kills the supervisor and orphans the app. + watcher.on('error', (error) => { + log(`file watching stopped (${error.message}); restart bunmaska dev`); + }); return { close: () => { watcher.close(); diff --git a/src/cli/dev.ts b/src/cli/dev.ts index 8e21d07f..484e1eda 100644 --- a/src/cli/dev.ts +++ b/src/cli/dev.ts @@ -322,7 +322,7 @@ export const defaultDevDeps = ( }, }; }, - watch: watchTree, + watch: (dir, onChange) => watchTree(dir, onChange, log), timers: defaultTimers, log, }); From 1ef69daa948a06106bcf3ee23c61b2ba50ab428e Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:46:05 -0700 Subject: [PATCH 362/586] fix: drop the duplicate brand from the Tauri page title --- website/src/pages/compare/tauri.astro | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/src/pages/compare/tauri.astro b/website/src/pages/compare/tauri.astro index 952b7bac..f070ce4b 100644 --- a/website/src/pages/compare/tauri.astro +++ b/website/src/pages/compare/tauri.astro @@ -4,7 +4,7 @@ import Base from "../../layouts/Base.astro"; import Nav from "../../components/Nav.astro"; import Footer from "../../components/Footer.astro"; -const title = "Tauri without Rust: a Tauri alternative in TypeScript - bunmaska"; +const title = "Tauri without Rust: a Tauri alternative in TypeScript"; const description = "Want Tauri's tiny, no-Chromium apps but all TypeScript instead of Rust? bunmaska keeps the Electron mental model on Bun and system WebKit. Trade-offs, honestly."; --- From 541508a9912042db05e47b29f566b4ef5b13e35d Mon Sep 17 00:00:00 2001 From: indrajeetor Date: Mon, 28 Sep 2026 10:46:05 -0700 Subject: [PATCH 363/586] fix: noindex the 404 page --- website/src/pages/404.astro | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/src/pages/404.astro b/website/src/pages/404.astro index 1798574f..b094e7d0 100644 --- a/website/src/pages/404.astro +++ b/website/src/pages/404.astro @@ -6,7 +6,7 @@ import Footer from "../components/Footer.astro"; import { DISPLAY } from "../styles/constants"; --- - +