Repository navigation
Description
What
react-x11 pumps this bridge from JS: pump2() every 8 ms from a setInterval on Node's main thread, which on macOS is also AppKit's (addon.mm's header: "We never call [NSApp run]; instead JS drives an event pump"). Two costs follow, both measured on the react-x11 side:
- Input waits for the pump — up to 8 ms between an event arriving and JS seeing it.
- A modal loop freezes Node. Live resize, menu tracking, drag sessions and
runModalall run inside thepump2call. With a drag up, a 25 mssetIntervaldid not fire for 31 s (fix(cocoa): a drag renders from the callback that reports it, so the preview follows the pointer sidorares/react-x11#484), and a microtask queued inside a backend event does not drain until the pump returns. react-x11 lives with it by doing a frame's work inside the callbacks that do arrive (CocoaApp._afterInput); anything else — a timer, a socket read, anawait— waits for the gesture to end.
react-x11's Windows PRD answers the same two costs with a UI thread of the addon's own (docs/windows.md §"Threads and the event loop", sidorares/react-x11#538): one thread owns every window and runs every modal loop, JS stays on Node's thread, and events cross through a napi_threadsafe_function. Win32 lets any thread own a window. AppKit does not — createWindow2 called from a worker aborts with "NSWindow should only be instantiated on the main thread!" — so on macOS the shape runs with the roles swapped:
The UI thread is the process main thread, parked in a real
[NSApp run]for the life of the app. The renderer's JS — React, layout, painting — runs on aworker_threadsWorker.
This issue is the proposal, the measurements and the probe that took them; the work is split into the sub-issues at the bottom. The renderer's half is written up in react-x11 docs/macos.md §"JS on a worker: a UI thread of the bridge's own" (sidorares/react-x11#539).
Measured
2026-09-11, Apple M1 Pro, macOS 15.2, Node 26.0.0 and Bun 1.4.0. The probe (code below) is its own small addon in the proposed shape — a command queue drained by a version-0 CFRunLoopSource in kCFRunLoopCommonModes, events out through one threadsafe call per wake with motion folded, a layer-hosting window like CALBackendView, and a bounded live-resize wait. Its worker ran a 5 ms timer and posted a layer change every 16 ms through every phase.
| today: the 8 ms pump | the probe: JS on a worker | |
|---|---|---|
| an event reaching JS | waits for the next tick, 0–8 ms | 0.02 ms p50; p95 0.13 ms idle, 1.3–1.8 ms inside a modal loop |
| JS through menu tracking | frozen (a drag: 31 s, react-x11#484) | 5 ms timer's worst gap 14.0 ms |
JS through NSAlert runModal |
frozen | worst gap 9.7 ms |
| JS through a live resize | only delegate callbacks run | worst gap 12.5 ms |
| a microtask queued inside an event delivery | runs when the gesture ends | 0.01–0.02 ms later, p50 |
| a layer change posted by JS | inline | applied 0.02 ms later, p50 — 72 of them inside NSEventTrackingRunLoopMode during the menu, 75 inside NSModalPanelRunLoopMode during the alert |
| a frame at the new size during a live resize | same thread, same call | 39 of 39 ticks inside a 50 ms bounded wait (and 30 of 30 programmatic setFrame:); waited 3.1 ms p50, 4.4 max, for 3 ms of simulated layout |
| the main thread busy for 300 ms | JS frozen | JS timers unaffected, worst gap 6.1 ms |
| JS busy for 200 ms | every window frozen | the UI thread keeps running; the 10 events JS missed arrive as one batch |
| cost | — | +16 MB RSS for the worker's isolate (bare node 46.5 → 62.5 MB); 26–31 ms from new Worker() to its first line |
Two more results that shape the design:
- Today's bridge inside a Worker (
bridge-worker.mjsbelow): all 182 verbs load — the addon is context-aware. CG drawing +ctxGetImageDatareadback and CoreText work from the worker, andlistScreenshappens to answer.createWindow2aborts withNSInternalInconsistencyException.measureControl+drawControlIntoSurfacedraw correct pixels and then the process segfaults at exit (139) — see the bezel sub-issue. - Pumping the main thread's own Node environment from inside
[NSApp run]with a nesteduv_run(the shape of react-x11's run-loop "option 2", and of an inversion without owningmain()): main-thread timers fire, but the microtasks and next-ticks they queue never run — Node drains them only when the outermost callback scope closes, and auv_runstarted under a JS call is never outermost. That is why the JS has to leave the main thread rather than share it with a nested loop. (Bun has no libuv loop to nest at all.)
Not measured: a hardware live resize (the probe posts mouse events into the same tracking loop), a real NSDraggingSession (it holds the pointer for ~30 s), and anything on glass.
The proposal
Who owns what
| thread | owns | reaches the other by |
|---|---|---|
| main thread = the UI thread | NSApplication + delegate; every NSWindow, view, panel and their delegates; menu bar, Dock, status items; cursor; pasteboard; drag sessions; file panels; colour sampler; control bezels; the CATransaction that applies each frame's layer changes; the live-resize wait |
batched events through one threadsafe function per Node environment; state it publishes under a lock |
| the renderer's worker | React, layout; CoreGraphics into IOSurface-backed surfaces; CoreText and fonts; <glarea>'s CGL context |
commands queued to the UI thread — one wake per frame |
EventKit, UserNotifications, permissions and the colour sampler already answer through threadsafe functions from queues of their own; they follow whichever environment calls them.
The three rules (react-x11 docs/windows.md §"The rules that keep it from deadlocking", unchanged)
- JS never waits on the UI thread. Every AppKit verb is a command; a handle is allocated at the call and bound when the UI thread creates the object; what JS reads back synchronously (frames, visibility, screens) is state the UI thread publishes.
- What AppKit asks synchronously, and JS can know in advance, is pushed ahead. This bridge already works that way:
setDropResponse's standing answer, the drag source's masks,applicationDockMenu:,windowShouldClose:→ NO with a close request to JS,applicationShouldTerminate:→ Cancel with a quit request to JS.NSTextInputClient'sfirstRectForCharacterRange:and NSAccessibility follow the same rule when they arrive. - The UI thread may wait on JS — bounded, and only where JS alone has the answer: the live-resize handshake.
Pump mode stays
Threaded mode is opt-in (runMain() having been called is the switch) until react-x11's bench says it wins. One verb body serves both modes: arguments parsed on the calling thread into a block, which runs inline on the main thread (pump mode) and is queued from any other thread (threaded mode).
Sub-issues
- Threaded mode: the threading core — runMain, a command queue drained in the common modes, one batched event channel, published state #50 — the threading core:
runMain, the command queue, one batched event channel, published state, exit and signals - Threaded mode: route the AppKit verbs through the command queue — handles at the call, published reads, async answers #51 — route the AppKit verbs through the queue: handles at the call, published reads, async answers
- Threaded mode: a frame's layer changes as one batch applied on the UI thread, IOSurface buffers handed over by event #52 — frames across the boundary: layer changes as one batch per frame, IOSurface handoff by event
- Threaded mode: live-resize handshake — the UI thread waits, bounded, for a frame at the new size #53 — the live-resize handshake: a bounded wait for a frame at the new size
- measureControl / drawControlIntoSurface are main-thread only: from a Worker they draw, then crash at exit #54 —
measureControl/drawControlIntoSurfaceare main-thread only
The probe
Standalone — its own addon, not a patch to this repo — plus one script that loads the shipped bridge in a Worker. In the scratch directory holding these files:
npx node-gyp@11 rebuild
node main.mjs patched # the full run; prints a JSON summary per phase
PROBE_QUICK=1 node main.mjs default # worker console.log lost; its process.exit orphans [NSApp run]
PROBE_QUICK=1 node main.mjs uv # nested uv_run: main timers fire, their microtasks never drain
bun main.mjs patched # the same under Bun
node bridge-worker.mjs draw # CG + CoreText from a worker: fine
node bridge-worker.mjs window # createWindow2 from a worker: abort
BEZEL_KIND=push node bridge-worker.mjs bezel # draws, then SIGSEGV at exitIt pops a real menu and an NSAlert, and posts mouse events for the live resize. Wake the display first (caffeinate -u -t 30 &). bridge-worker.mjs resolves @windowkit/appkit from a package.json path at its top — point it at any checkout that has the bridge installed.
binding.gyp
{
"targets": [
{
"target_name": "uiprobe",
"sources": ["probe.mm"],
"xcode_settings": {
"CLANG_ENABLE_OBJC_ARC": "YES",
"CLANG_CXX_LANGUAGE_STANDARD": "c++17",
"OTHER_CFLAGS": ["-fobjc-arc"],
"MACOSX_DEPLOYMENT_TARGET": "12.0"
},
"link_settings": {
"libraries": ["-framework Cocoa", "-framework QuartzCore"]
}
}
]
}probe.mm — the addon: command queue in, batched events out, the resize handshake
// uiprobe: the smallest honest model of "AppKit owns the main thread, JS runs
// on a worker" — a command queue into the main run loop (a version-0 source
// in the common modes), and a batched threadsafe function out of it.
#define NAPI_VERSION 8
#include <node_api.h>
#include <uv.h>
#import <Cocoa/Cocoa.h>
#import <QuartzCore/QuartzCore.h>
#include <mach/mach_time.h>
#include <pthread.h>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstdio>
#include <deque>
#include <mutex>
#include <string>
#include <vector>
static double NowMs() {
static mach_timebase_info_data_t tb;
if (!tb.denom) mach_timebase_info(&tb);
return (double)mach_absolute_time() * tb.numer / tb.denom / 1e6;
}
static std::string CurrentMode() {
CFStringRef m = CFRunLoopCopyCurrentMode(CFRunLoopGetCurrent());
if (!m) return "none";
char buf[160];
CFStringGetCString(m, buf, sizeof buf, kCFStringEncodingUTF8);
CFRelease(m);
return buf;
}
// ---------------------------------------------------------------------------
// UI thread -> JS: append to a queue, one threadsafe call per wake
// ---------------------------------------------------------------------------
struct Ev {
std::string type, mode;
double t = 0, a = 0, b = 0, c = 0;
};
static std::mutex gEvMu;
static std::vector<Ev> gEvQ;
static std::mutex gTsfnMu;
static napi_threadsafe_function gTsfn = nullptr;
static std::atomic<bool> gWakePending{false};
static std::atomic<int> gWakes{0};
static std::atomic<int> gEvents{0};
static void Emit(Ev e) {
gEvents++;
{
std::lock_guard<std::mutex> l(gEvMu);
// consecutive motion folds to its latest position before it crosses
if (e.type == "mousemove" && !gEvQ.empty() && gEvQ.back().type == "mousemove")
gEvQ.back() = e;
else
gEvQ.push_back(std::move(e));
}
std::lock_guard<std::mutex> l(gTsfnMu);
if (gTsfn && !gWakePending.exchange(true)) {
gWakes++;
napi_call_threadsafe_function(gTsfn, nullptr, napi_tsfn_nonblocking);
}
}
static void EmitSimple(const char* type, double a = 0, double b = 0, double c = 0) {
Ev e;
e.type = type;
e.mode = CurrentMode();
e.t = NowMs();
e.a = a;
e.b = b;
e.c = c;
Emit(std::move(e));
}
static void SetNum(napi_env env, napi_value o, const char* k, double v) {
napi_value n;
napi_create_double(env, v, &n);
napi_set_named_property(env, o, k, n);
}
static void SetStr(napi_env env, napi_value o, const char* k, const std::string& s) {
napi_value n;
napi_create_string_utf8(env, s.c_str(), s.size(), &n);
napi_set_named_property(env, o, k, n);
}
static void CallJs(napi_env env, napi_value cb, void*, void*) {
if (!env) return;
std::vector<Ev> batch;
{
std::lock_guard<std::mutex> l(gEvMu);
gWakePending = false;
batch.swap(gEvQ);
}
double recv = NowMs();
napi_value arr;
napi_create_array_with_length(env, batch.size(), &arr);
for (uint32_t i = 0; i < batch.size(); i++) {
napi_value o;
napi_create_object(env, &o);
SetStr(env, o, "type", batch[i].type);
SetStr(env, o, "mode", batch[i].mode);
SetNum(env, o, "t", batch[i].t);
SetNum(env, o, "a", batch[i].a);
SetNum(env, o, "b", batch[i].b);
SetNum(env, o, "c", batch[i].c);
SetNum(env, o, "recv", recv);
napi_set_element(env, arr, i, o);
}
napi_value undef;
napi_get_undefined(env, &undef);
napi_call_function(env, undef, cb, 1, &arr, nullptr);
}
// ---------------------------------------------------------------------------
// JS -> UI thread: commands, drained by a run loop source in common modes
// ---------------------------------------------------------------------------
struct Cmd {
std::string op;
double a = 0, b = 0, c = 0, d = 0, t = 0;
};
static std::mutex gCmdMu;
static std::condition_variable gCmdCv;
static std::deque<Cmd> gCmdQ;
static CFRunLoopRef gMainRL = nullptr;
static CFRunLoopSourceRef gCmdSrc = nullptr;
static bool gOrphanExit = true;
static double gHandshakeMs = 0;
static int gExitCode = 0;
static NSWindow* gWin = nil;
static NSView* gView = nil;
static CALayer* gBox = nil;
static void ApplyCmd(const Cmd& c);
static void DrainCmds() {
std::deque<Cmd> batch;
{
std::lock_guard<std::mutex> l(gCmdMu);
batch.swap(gCmdQ);
}
if (batch.empty()) return;
double now = NowMs(), maxLat = 0;
[CATransaction begin];
[CATransaction setDisableActions:YES];
for (auto& c : batch) {
maxLat = std::max(maxLat, now - c.t);
ApplyCmd(c);
}
[CATransaction commit];
EmitSimple("applied", batch.size(), maxLat);
}
static void CmdSourcePerform(void*) { DrainCmds(); }
// A command that starts a modal loop runs from a callout of its own, never
// from inside the drain: a nested loop inside the drain would hold the rest
// of that batch until the gesture ends.
static void Defer(void (^block)(void)) {
CFRunLoopPerformBlock(gMainRL, kCFRunLoopDefaultMode, block);
CFRunLoopWakeUp(gMainRL);
}
// ---------------------------------------------------------------------------
// the window: layer-hosting, like @windowkit/appkit's CALBackendView
// ---------------------------------------------------------------------------
@interface ProbeView : NSView
@end
@implementation ProbeView
- (BOOL)isFlipped { return YES; }
- (BOOL)acceptsFirstMouse:(NSEvent*)e { (void)e; return YES; }
- (void)emit:(const char*)type event:(NSEvent*)e {
NSPoint p = [self convertPoint:e.locationInWindow fromView:nil];
Ev v;
v.type = type;
v.mode = CurrentMode();
v.t = e.timestamp * 1000.0; // systemUptime: the same clock as NowMs
v.a = p.x;
v.b = p.y;
v.c = NowMs();
Emit(std::move(v));
}
- (void)mouseDown:(NSEvent*)e { [self emit:"mousedown" event:e]; }
- (void)mouseDragged:(NSEvent*)e { [self emit:"mousemove" event:e]; }
- (void)mouseMoved:(NSEvent*)e { [self emit:"mousemove" event:e]; }
- (void)mouseUp:(NSEvent*)e { [self emit:"mouseup" event:e]; }
@end
@interface ProbeDelegate : NSObject <NSWindowDelegate, NSMenuDelegate>
@end
@implementation ProbeDelegate
- (void)windowWillStartLiveResize:(NSNotification*)n { (void)n; EmitSimple("live-resize-begin"); }
- (void)windowDidEndLiveResize:(NSNotification*)n { (void)n; EmitSimple("live-resize-end"); }
- (BOOL)windowShouldClose:(NSWindow*)w { (void)w; EmitSimple("close-request"); return NO; }
- (void)menuWillOpen:(NSMenu*)m { (void)m; EmitSimple("menu-open"); }
- (void)menuDidClose:(NSMenu*)m { (void)m; EmitSimple("menu-closed"); }
// The resize handshake: publish the size, wake JS, and wait — bounded — for
// a frame at that size, then commit it in this resize's own transaction.
- (void)windowDidResize:(NSNotification*)n {
(void)n;
NSSize s = gWin.contentView.bounds.size;
EmitSimple("window-resize", s.width, s.height, gWin.inLiveResize ? 1 : 0);
if (gHandshakeMs <= 0) return;
double t0 = NowMs(), deadline = t0 + gHandshakeMs;
bool ok = false;
{
std::unique_lock<std::mutex> l(gCmdMu);
while (true) {
for (auto& c : gCmdQ)
if (c.op == "frame" && c.a == s.width && c.b == s.height) ok = true;
if (ok) break;
double left = deadline - NowMs();
if (left <= 0) break;
gCmdCv.wait_for(l, std::chrono::microseconds((long)(left * 1000)));
}
}
DrainCmds();
EmitSimple("resize-ack", NowMs() - t0, ok ? 1 : 0, gWin.inLiveResize ? 1 : 0);
}
@end
static ProbeDelegate* gDelegate = nil;
static void SetBoxColor(double r, double g, double b) {
if (!gBox) return;
CGColorRef c = CGColorCreateSRGB(r, g, b, 1);
gBox.backgroundColor = c;
CGColorRelease(c);
}
static void CreateWindow(double w, double h) {
NSRect rect = NSMakeRect(200, 200, w, h);
gWin = [[NSWindow alloc]
initWithContentRect:rect
styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
NSWindowStyleMaskResizable |
NSWindowStyleMaskMiniaturizable
backing:NSBackingStoreBuffered
defer:NO];
gWin.releasedWhenClosed = NO;
gWin.title = @"uiprobe";
gWin.delegate = gDelegate;
gWin.acceptsMouseMovedEvents = YES;
gView = [[ProbeView alloc] initWithFrame:rect];
CALayer* root = [CALayer layer];
root.geometryFlipped = YES;
CGColorRef bg = CGColorCreateSRGB(0.95, 0.95, 0.95, 1);
root.backgroundColor = bg;
CGColorRelease(bg);
[gView setLayer:root];
[gView setWantsLayer:YES];
gWin.contentView = gView;
gBox = [CALayer layer];
gBox.frame = CGRectMake(10, 10, w - 20, h - 20);
[root addSublayer:gBox];
SetBoxColor(0.2, 0.4, 0.8);
[gWin center];
[gWin makeKeyAndOrderFront:nil];
[NSApp activateIgnoringOtherApps:YES];
EmitSimple("window-created", gWin.windowNumber);
}
static void PopMenu(double ms) {
NSMenu* m = [[NSMenu alloc] initWithTitle:@"probe"];
[m addItemWithTitle:@"One" action:nil keyEquivalent:@""];
[m addItemWithTitle:@"Two" action:nil keyEquivalent:@""];
m.delegate = gDelegate;
NSTimer* t = [NSTimer timerWithTimeInterval:ms / 1000.0
repeats:NO
block:^(NSTimer* tm) {
(void)tm;
[m cancelTrackingWithoutAnimation];
}];
[[NSRunLoop mainRunLoop] addTimer:t forMode:NSRunLoopCommonModes];
double t0 = NowMs();
BOOL r = [m popUpMenuPositioningItem:nil atLocation:NSMakePoint(20, 20) inView:gView];
EmitSimple("menu-returned", NowMs() - t0, r);
}
static void RunAlert(double ms) {
NSAlert* a = [NSAlert new];
a.messageText = @"uiprobe";
[a addButtonWithTitle:@"OK"];
NSTimer* t = [NSTimer timerWithTimeInterval:ms / 1000.0
repeats:NO
block:^(NSTimer* tm) {
(void)tm;
[NSApp abortModal];
}];
[[NSRunLoop mainRunLoop] addTimer:t forMode:NSRunLoopCommonModes];
double t0 = NowMs();
EmitSimple("modal-begin");
[a runModal];
EmitSimple("modal-end", NowMs() - t0);
}
// A live resize from posted events: press on the bottom-right corner, drag
// on a timer, release. Screen points are fixed; each event is placed in the
// window's frame as it is at that moment.
static void PostAt(NSEventType type, NSPoint screen) {
NSRect cur = gWin.frame;
NSPoint inWin = NSMakePoint(screen.x - cur.origin.x, screen.y - cur.origin.y);
NSEvent* e = [NSEvent mouseEventWithType:type
location:inWin
modifierFlags:0
timestamp:NSProcessInfo.processInfo.systemUptime
windowNumber:gWin.windowNumber
context:nil
eventNumber:0
clickCount:1
pressure:type == NSEventTypeLeftMouseUp ? 0 : 1];
[NSApp postEvent:e atStart:NO];
}
static void SyntheticLiveResize(int steps, double stepMs, double dx, double dy) {
NSRect f = gWin.frame;
NSPoint corner = NSMakePoint(NSMaxX(f) - 2, NSMinY(f) + 2);
PostAt(NSEventTypeLeftMouseDown, corner);
__block int i = 0;
NSTimer* t = [NSTimer
timerWithTimeInterval:stepMs / 1000.0
repeats:YES
block:^(NSTimer* tm) {
i++;
NSPoint p = NSMakePoint(corner.x + dx * std::min(i, steps) / steps,
corner.y - dy * std::min(i, steps) / steps);
if (i <= steps) {
PostAt(NSEventTypeLeftMouseDragged, p);
} else {
PostAt(NSEventTypeLeftMouseUp, p);
[tm invalidate];
}
}];
[[NSRunLoop mainRunLoop] addTimer:t forMode:NSRunLoopCommonModes];
}
static void ProgrammaticSteps(int steps, double stepMs) {
NSRect f0 = gWin.frame;
__block int i = 0;
NSTimer* t = [NSTimer timerWithTimeInterval:stepMs / 1000.0
repeats:YES
block:^(NSTimer* tm) {
i++;
if (i > steps) {
[tm invalidate];
EmitSimple("steps-done");
return;
}
NSRect f = f0;
f.size.width -= 3 * i;
f.size.height -= 2 * i;
f.origin.y += 2 * i;
[gWin setFrame:f display:YES];
}];
[[NSRunLoop mainRunLoop] addTimer:t forMode:NSRunLoopCommonModes];
}
static void Quit() {
[NSApp stop:nil];
NSEvent* e = [NSEvent otherEventWithType:NSEventTypeApplicationDefined
location:NSZeroPoint
modifierFlags:0
timestamp:0
windowNumber:0
context:nil
subtype:0
data1:0
data2:0];
[NSApp postEvent:e atStart:YES];
}
static void ApplyCmd(const Cmd& c) {
if (c.op == "window") {
CreateWindow(c.a, c.b);
} else if (c.op == "color") {
SetBoxColor(c.a, c.b, c.c);
} else if (c.op == "frame") {
if (gBox) gBox.frame = CGRectMake(10, 10, c.a - 20, c.b - 20);
} else if (c.op == "handshake") {
gHandshakeMs = c.a;
} else if (c.op == "menu") {
double ms = c.a;
Defer(^{ PopMenu(ms); });
} else if (c.op == "alert") {
double ms = c.a;
Defer(^{ RunAlert(ms); });
} else if (c.op == "liveresize") {
int steps = (int)c.a;
double stepMs = c.b, dx = c.c, dy = c.d;
Defer(^{ SyntheticLiveResize(steps, stepMs, dx, dy); });
} else if (c.op == "steps") {
int steps = (int)c.a;
double stepMs = c.b;
Defer(^{ ProgrammaticSteps(steps, stepMs); });
} else if (c.op == "busyui") {
double until = NowMs() + c.a;
while (NowMs() < until) {
}
} else if (c.op == "quit") {
Quit();
} else if (c.op == "exit") {
// Never exit() from here: the worker is still running, and static
// destructors would race it. runMain returns the code instead, and
// Node's process.exit on the main thread stops the worker first.
gExitCode = (int)c.a;
Quit();
}
}
// The JS environment the events went to is gone. Nothing JS-side can end
// [NSApp run] any more.
static void TsfnFinalize(napi_env, void*, void*) {
{
std::lock_guard<std::mutex> l(gTsfnMu);
gTsfn = nullptr;
}
if (!gMainRL) return;
CFRunLoopPerformBlock(gMainRL, kCFRunLoopCommonModes, ^{
fprintf(stderr, "[ui] the worker's environment is gone; nothing ends [NSApp run] now\n");
if (gOrphanExit) {
NSTimer* t = [NSTimer timerWithTimeInterval:1.0
repeats:NO
block:^(NSTimer* tm) {
(void)tm;
fprintf(stderr, "[ui] orphaned: exit(3)\n");
exit(3);
}];
[[NSRunLoop mainRunLoop] addTimer:t forMode:NSRunLoopCommonModes];
}
});
CFRunLoopWakeUp(gMainRL);
}
// ---------------------------------------------------------------------------
// N-API surface
// ---------------------------------------------------------------------------
static bool GetBool(napi_env env, napi_value o, const char* k, bool d) {
bool has = false;
napi_has_named_property(env, o, k, &has);
if (!has) return d;
napi_value v;
napi_get_named_property(env, o, k, &v);
bool out = d;
if (napi_get_value_bool(env, v, &out) != napi_ok) return d;
return out;
}
static double GetNum(napi_env env, napi_value o, const char* k, double d) {
bool has = false;
napi_has_named_property(env, o, k, &has);
if (!has) return d;
napi_value v;
napi_get_named_property(env, o, k, &v);
double out = d;
if (napi_get_value_double(env, v, &out) != napi_ok) return d;
return out;
}
static bool gInUv = false;
// runMain({ uv, orphanExit }): the process main thread only. Never returns
// until a 'quit' command.
static napi_value RunMain(napi_env env, napi_callback_info info) {
size_t argc = 1;
napi_value argv[1];
napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
if (!pthread_main_np()) {
napi_throw_error(env, nullptr, "runMain: not the process main thread");
return nullptr;
}
bool uv = argc > 0 ? GetBool(env, argv[0], "uv", false) : false;
gOrphanExit = argc > 0 ? GetBool(env, argv[0], "orphanExit", true) : true;
[NSApplication sharedApplication];
[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
gDelegate = [ProbeDelegate new];
{
std::lock_guard<std::mutex> l(gCmdMu);
gMainRL = CFRunLoopGetMain();
CFRunLoopSourceContext ctx = {};
ctx.perform = CmdSourcePerform;
gCmdSrc = CFRunLoopSourceCreate(nullptr, 0, &ctx);
CFRunLoopAddSource(gMainRL, gCmdSrc, kCFRunLoopCommonModes);
CFRunLoopSourceSignal(gCmdSrc); // whatever was posted before this
}
NSTimer* tick = [NSTimer timerWithTimeInterval:0.020
repeats:YES
block:^(NSTimer* tm) {
(void)tm;
EmitSimple("uitick");
}];
[[NSRunLoop mainRunLoop] addTimer:tick forMode:NSRunLoopCommonModes];
if (uv) {
// The main environment's own loop, pumped from inside [NSApp run] — a
// uv_run nested under the JS call that entered runMain.
uv_loop_t* loop = nullptr;
napi_get_uv_event_loop(env, &loop);
NSTimer* ut = [NSTimer timerWithTimeInterval:0.002
repeats:YES
block:^(NSTimer* tm) {
(void)tm;
if (gInUv) return;
gInUv = true;
uv_run(loop, UV_RUN_NOWAIT);
gInUv = false;
}];
[[NSRunLoop mainRunLoop] addTimer:ut forMode:NSRunLoopCommonModes];
}
EmitSimple("ready");
[NSApp run];
napi_value code;
napi_create_int32(env, gExitCode, &code);
return code;
}
static napi_value Connect(napi_env env, napi_callback_info info) {
size_t argc = 1;
napi_value argv[1];
napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
napi_value name;
napi_create_string_utf8(env, "uiprobe-events", NAPI_AUTO_LENGTH, &name);
napi_threadsafe_function f;
napi_create_threadsafe_function(env, argv[0], nullptr, name, 0, 1, nullptr,
TsfnFinalize, nullptr, CallJs, &f);
{
std::lock_guard<std::mutex> l(gTsfnMu);
gTsfn = f;
}
gWakePending = false;
{
std::lock_guard<std::mutex> l(gEvMu);
if (!gEvQ.empty()) {
gWakePending = true;
napi_call_threadsafe_function(f, nullptr, napi_tsfn_nonblocking);
}
}
napi_value undef;
napi_get_undefined(env, &undef);
return undef;
}
static napi_value Post(napi_env env, napi_callback_info info) {
size_t argc = 1;
napi_value argv[1];
napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
Cmd c;
napi_value opv;
napi_get_named_property(env, argv[0], "op", &opv);
char buf[64];
size_t len = 0;
napi_get_value_string_utf8(env, opv, buf, sizeof buf, &len);
c.op.assign(buf, len);
c.a = GetNum(env, argv[0], "a", 0);
c.b = GetNum(env, argv[0], "b", 0);
c.c = GetNum(env, argv[0], "c", 0);
c.d = GetNum(env, argv[0], "d", 0);
c.t = NowMs();
{
std::lock_guard<std::mutex> l(gCmdMu);
gCmdQ.push_back(std::move(c));
if (gCmdSrc) {
CFRunLoopSourceSignal(gCmdSrc);
CFRunLoopWakeUp(gMainRL);
}
}
gCmdCv.notify_all();
napi_value undef;
napi_get_undefined(env, &undef);
return undef;
}
static napi_value Now(napi_env env, napi_callback_info) {
napi_value v;
napi_create_double(env, NowMs(), &v);
return v;
}
static napi_value IsMainThread(napi_env env, napi_callback_info) {
napi_value v;
napi_get_boolean(env, pthread_main_np() != 0, &v);
return v;
}
static napi_value Counters(napi_env env, napi_callback_info) {
napi_value o;
napi_create_object(env, &o);
SetNum(env, o, "wakes", gWakes.load());
SetNum(env, o, "events", gEvents.load());
return o;
}
NAPI_MODULE_INIT() {
napi_property_descriptor props[] = {
{"runMain", nullptr, RunMain, nullptr, nullptr, nullptr, napi_default, nullptr},
{"connect", nullptr, Connect, nullptr, nullptr, nullptr, napi_default, nullptr},
{"post", nullptr, Post, nullptr, nullptr, nullptr, napi_default, nullptr},
{"now", nullptr, Now, nullptr, nullptr, nullptr, napi_default, nullptr},
{"isMainThread", nullptr, IsMainThread, nullptr, nullptr, nullptr, napi_default, nullptr},
{"counters", nullptr, Counters, nullptr, nullptr, nullptr, napi_default, nullptr},
};
napi_define_properties(env, exports, sizeof props / sizeof props[0], props);
return exports;
}main.mjs — the process main thread
// The process main thread: start the JS worker, then hand the thread to
// AppKit for good. argv[2]: 'default' | 'uv' | 'patched'.
import { Worker } from 'node:worker_threads';
import { createRequire } from 'node:module';
import fs from 'node:fs';
const require = createRequire(import.meta.url);
const probe = require('./build/Release/uiprobe.node');
const mode = process.argv[2] ?? 'default';
const say = (s) => fs.writeSync(2, `[main] ${s}\n`);
const t0 = probe.now();
const w = new Worker(new URL('./worker.mjs', import.meta.url), {
argv: [mode],
workerData: { t0 },
});
if (mode === 'uv') {
// Main-thread JS reached only through the nested uv_run: do its timers
// fire, and do the microtasks and next-ticks they queue ever drain?
let n = 0;
const iv = setInterval(() => {
const k = ++n;
say(`main-thread timer ${k} fired`);
Promise.resolve().then(() => say(`main-thread microtask from timer ${k}`));
process.nextTick(() => say(`main-thread nextTick from timer ${k}`));
if (k >= 3) clearInterval(iv);
}, 150);
}
w.on('exit', (code) => {
say(`worker 'exit' event reached the main thread, code ${code}`);
probe.post({ op: 'quit' });
});
w.on('error', (e) => say(`worker error ${e?.stack ?? e}`));
say(`runMain on the process main thread: ${probe.isMainThread()}`);
const code = probe.runMain({ uv: mode === 'uv', orphanExit: true });
say(`runMain returned ${code}`);
process.exit(code);worker.mjs — the JS thread, and the stdio/exit bootstrap
// The JS thread: everything React would do, off the main thread.
import { createRequire } from 'node:module';
import { Writable } from 'node:stream';
import { workerData } from 'node:worker_threads';
import fs from 'node:fs';
const mode = process.argv[2] ?? 'default';
const say = (s) => fs.writeSync(1, `[worker] ${s}\n`);
if (mode === 'patched') {
// Write-through stdio: a worker's process.stdout forwards to the main
// thread's loop, which is parked in [NSApp run].
const direct = (fd) =>
new Writable({
write(chunk, _enc, cb) {
try {
fs.writeSync(fd, chunk);
} catch (err) {
return cb(err);
}
cb();
},
});
for (const [name, fd] of [
['stdout', 1],
['stderr', 2],
]) {
try {
Object.defineProperty(process, name, {
value: direct(fd),
configurable: true,
writable: true,
});
} catch (err) {
say(`cannot redefine process.${name}: ${err.message}`);
}
}
// Bun's console does not write through process.stdout: replace it too.
const { Console } = await import('node:console');
globalThis.console = new Console({
stdout: process.stdout,
stderr: process.stderr,
});
// process.exit in a worker ends the worker; the process has to be ended
// by the thread that owns it.
const exitWorker = process.exit.bind(process);
process.exit = (code) => {
if (code !== undefined) process.exitCode = code;
const c = process.exitCode ?? 0;
try {
process.emit('exit', c);
} finally {
probe.post({ op: 'exit', a: c });
exitWorker(c);
}
};
}
const require = createRequire(import.meta.url);
const probe = require('./build/Release/uiprobe.node');
say(`on the process main thread: ${probe.isMainThread()}`);
say(`worker running ${(probe.now() - workerData.t0).toFixed(1)}ms after new Worker()`);
console.log(`[worker] console.log from the worker (${mode})`);
const now = () => probe.now();
const busy = (ms) => {
const t = now();
while (now() - t < ms);
};
const q = (xs, p) => {
if (!xs.length) return null;
const s = [...xs].sort((a, b) => a - b);
return +s[Math.min(s.length - 1, Math.floor(p * s.length))].toFixed(3);
};
let phase = 'boot';
const stats = {};
const st = (p) =>
(stats[p] ??= {
batches: 0,
batchMax: 0,
events: {},
uiModes: {},
uitickLat: [],
applied: {},
appliedLat: [],
micro: [],
gaps: [],
acks: [],
live: 0,
});
const waiters = new Map();
const waitFor = (type) => new Promise((r) => waiters.set(type, r));
let layoutMs = 3;
probe.connect((batch) => {
const s = st(phase);
s.batches++;
s.batchMax = Math.max(s.batchMax, batch.length);
const t0 = now();
queueMicrotask(() => s.micro.push(now() - t0));
for (const ev of batch) {
s.events[ev.type] = (s.events[ev.type] ?? 0) + 1;
if (ev.type === 'uitick') {
s.uitickLat.push(ev.recv - ev.t);
s.uiModes[ev.mode] = (s.uiModes[ev.mode] ?? 0) + 1;
} else if (ev.type === 'applied') {
s.appliedLat.push(ev.b);
s.applied[ev.mode] = (s.applied[ev.mode] ?? 0) + ev.a;
} else if (ev.type === 'window-resize') {
if (ev.c) s.live++;
// the frame at the new size: a layout's worth of work, then the commit
busy(layoutMs);
probe.post({ op: 'frame', a: ev.a, b: ev.b });
} else if (ev.type === 'resize-ack') {
s.acks.push({ waited: +ev.a.toFixed(3), got: ev.b, live: ev.c });
} else if (
ev.type === 'menu-returned' ||
ev.type === 'modal-end' ||
ev.type === 'menu-open'
) {
s[ev.type] = { ms: +ev.a.toFixed(1), mode: ev.mode };
}
waiters.get(ev.type)?.();
waiters.delete(ev.type);
}
});
// a 5ms timer on the JS thread: does it keep firing through each phase?
let last = now();
const timer = setInterval(() => {
const t = now();
st(phase).gaps.push(t - last);
last = t;
}, 5);
// and a frame's worth of layer work posted every 16ms
const painter = setInterval(() => {
probe.post({ op: 'color', a: Math.random(), b: Math.random(), c: 0.8 });
}, 16);
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function run(name, ms, start) {
phase = name;
start?.();
await sleep(ms);
}
const created = waitFor('window-created');
probe.post({ op: 'window', a: 480, b: 320 });
await created;
await run('idle', 800);
if (process.env.PROBE_QUICK !== '1') {
await run('menu', 1500, () => probe.post({ op: 'menu', a: 1200 }));
await run('alert', 1500, () => probe.post({ op: 'alert', a: 1200 }));
probe.post({ op: 'handshake', a: 50 });
await run('liveresize', 1800, () =>
probe.post({ op: 'liveresize', a: 40, b: 25, c: 200, d: 120 }),
);
await run('steps', 900, () => probe.post({ op: 'steps', a: 30, b: 20 }));
probe.post({ op: 'handshake', a: 0 });
await run('busyui', 600, () => probe.post({ op: 'busyui', a: 300 }));
await run('busyjs', 400, () => busy(200));
}
clearInterval(timer);
clearInterval(painter);
const out = {};
for (const [name, s] of Object.entries(stats)) {
out[name] = {
batches: s.batches,
batchMax: s.batchMax,
events: s.events,
uiModes: s.uiModes,
uitickLatMs: { p50: q(s.uitickLat, 0.5), p95: q(s.uitickLat, 0.95), max: q(s.uitickLat, 1) },
appliedByMode: s.applied,
cmdLatMs: { p50: q(s.appliedLat, 0.5), p95: q(s.appliedLat, 0.95), max: q(s.appliedLat, 1) },
microMs: { p50: q(s.micro, 0.5), max: q(s.micro, 1) },
timerGapMs: { n: s.gaps.length, p50: q(s.gaps, 0.5), max: q(s.gaps, 1) },
...(s.acks.length
? {
acks: s.acks.length,
acksMet: s.acks.filter((a) => a.got).length,
ackWaitMs: {
p50: q(s.acks.map((a) => a.waited), 0.5),
max: q(s.acks.map((a) => a.waited), 1),
},
liveResizeEvents: s.live,
}
: {}),
...(s['menu-open'] ? { menuOpen: s['menu-open'] } : {}),
...(s['menu-returned'] ? { menuReturned: s['menu-returned'] } : {}),
...(s['modal-end'] ? { modalEnd: s['modal-end'] } : {}),
};
}
out.counters = probe.counters();
out.rssMB = +(process.memoryUsage().rss / 1048576).toFixed(1);
say(JSON.stringify(out, null, 1));
console.log('[worker] console.log at the end');
process.exit(0);bridge-worker.mjs — today's bridge inside a Worker
// The shipped @windowkit/appkit bridge, loaded inside a Worker: which of its
// verbs are thread-agnostic today, and which are AppKit's main thread's?
// argv[2]: 'draw' | 'screens' | 'window'. The main thread only waits.
import { Worker, isMainThread } from 'node:worker_threads';
import { createRequire } from 'node:module';
import fs from 'node:fs';
const say = (s) => fs.writeSync(1, `${s}\n`);
const step = process.argv[2] ?? 'draw';
if (isMainThread) {
const w = new Worker(new URL(import.meta.url), { argv: [step] });
w.on('exit', (code) => say(`[main] worker exit ${code}`));
w.on('error', (e) => say(`[main] worker error: ${e?.message ?? e}`));
} else {
const require = createRequire(
'/Users/laplace/Projects/react-x11/package.json',
);
const { native } = require('@windowkit/appkit');
say(`[worker] loaded the bridge in a worker (${Object.keys(native).length} verbs)`);
if (step === 'draw') {
const s = native.createSurface(8, 8, 1);
native.ctxSetFillColor(s, 1, 0, 0, 1);
native.ctxFillRect(s, 0, 0, 8, 8);
say(`[worker] CG draw + readback: ${[...native.ctxGetImageData(s, 0, 0, 1, 1)]}`);
const f = native.fontByPostScriptName?.('Helvetica', 13) ?? null;
say(`[worker] CoreText font from a worker: ${f ? 'ok' : 'n/a'}`);
} else if (step === 'screens') {
say(`[worker] listScreens: ${JSON.stringify(native.listScreens())}`);
} else if (step === 'bezel') {
const kind = process.env.BEZEL_KIND ?? 'button';
const m = native.measureControl({ kind, controlSize: 'regular' });
say(`[worker] measureControl: ${JSON.stringify(m)}`);
const pw = Math.round((m.width + 24) * 2);
const ph = Math.round(m.height * 2);
const s = native.createSurface(pw, ph, 2);
native.drawControlIntoSurface(s, {
kind,
controlSize: 'regular',
state: 1,
value: 0.5,
enabled: true,
appearance: 'light',
});
const px = native.ctxGetImageData(s, 0, 0, pw, ph);
let ink = 0;
for (let i = 3; i < px.length; i += 4) if (px[i]) ink++;
say(`[worker] drawControlIntoSurface(${kind}): ${ink} of ${pw * ph} pixels inked`);
} else if (step === 'window') {
const h = native.createWindow2({ width: 200, height: 100, title: 'x' });
say(`[worker] createWindow2 returned ${h}`);
}
}
Activity
docs(macos): JS on a worker, a UI thread of the bridge's own, measured (
sidorares commentedon Sep 11, 2026
Every sub-issue is done, so this closes.
runMain, the command queue, the event channel, published statesurface-releasedFollow-ups that came out of sidorares/react-x11#542, also merged:
connect's callback is the environment's uncaught exceptionwindow-live-resizebegin and end events, andliveResizein the published window stateAPPKIT_ACTIVATION_POLICY, andrunMain({ activationPolicy })Bun: CI runs Node 18, 22 and 26 only. Under Bun 1.4.0 locally, all six threaded-mode suites pass:
threaded.js,threaded-frames.js,threaded-resize.js,ending-worker.js,live-resize.jsandactivation-policy.js. Inthreaded.js, every command applied inside the menu and the modal alert, and the worker's 5 ms timer's worst gap was 7.1 ms. Inthreaded-resize.js, 28 of 28 live-resize waits were met, 3.2 ms p50.Outside this issue:
>= 0.10.NSDraggingSession, and anything on glass.feat(cocoa): threaded mode, the app on a worker and AppKit on the mai…