From 54fb7a2a064eb54eb735dd5493bc7844cc425bf6 Mon Sep 17 00:00:00 2001 From: Anthony Sistilli Date: Sun, 22 Nov 2026 12:24:33 -0500 Subject: [PATCH 1/5] test(webext-macos): reproduce popup worker failure after unclean exit --- .../fixtures/popup-restart/README.md | 27 ++++ .../fixtures/popup-restart/manifest.json | 9 ++ .../fixtures/popup-restart/popup.html | 9 ++ .../fixtures/popup-restart/popup.js | 16 +++ .../fixtures/popup-restart/worker.js | 7 + eval/webext-popup-restart-2026-11-22.md | 47 +++++++ scripts/qualification/macos-popup-restart.mjs | 123 ++++++++++++++++++ 7 files changed, 238 insertions(+) create mode 100644 crates/zephium-webext-macos/fixtures/popup-restart/README.md create mode 100644 crates/zephium-webext-macos/fixtures/popup-restart/manifest.json create mode 100644 crates/zephium-webext-macos/fixtures/popup-restart/popup.html create mode 100644 crates/zephium-webext-macos/fixtures/popup-restart/popup.js create mode 100644 crates/zephium-webext-macos/fixtures/popup-restart/worker.js create mode 100644 eval/webext-popup-restart-2026-11-22.md create mode 100644 scripts/qualification/macos-popup-restart.mjs diff --git a/crates/zephium-webext-macos/fixtures/popup-restart/README.md b/crates/zephium-webext-macos/fixtures/popup-restart/README.md new file mode 100644 index 000000000..4ce34c1c1 --- /dev/null +++ b/crates/zephium-webext-macos/fixtures/popup-restart/README.md @@ -0,0 +1,27 @@ +# Popup worker restart probe + +Run from the repository root on macOS with the pinned toolchain: + +```sh +node scripts/qualification/macos-popup-restart.mjs +``` + +The script builds `webext-lab` with `--locked` and launches it three times +against one newly generated WebKit profile identifier. The first process +closes the popup and unloads the extension before exiting. The second exits +with them still live. Both exits are followed by a five-second pause. + +Each process invokes the native toolbar action and checks that its popup +receives a response from a newly started worker. A fixture-only storage +marker checks that the restarts use the same persistent profile. The probe +fails if a process times out, no popup/result arrives, the worker response +is missing, the worker boot identifier repeats, or the storage marker is +wrong. The cold startup has a 2.5-second settling period so this probe does +not also measure startup latency. + +The command exits nonzero on a failed phase and preserves scenarios, logs +and `results.json` under Cargo's target directory in `popup-restart/`. +WebKit manages the disposable profile's platform storage separately. This +is a manual investigation probe, not a default CI gate or a product fix. +It needs no marketplace download, account, native messaging host, personal +profile or network page. It does not establish Windows acceptance. diff --git a/crates/zephium-webext-macos/fixtures/popup-restart/manifest.json b/crates/zephium-webext-macos/fixtures/popup-restart/manifest.json new file mode 100644 index 000000000..6337aa5e0 --- /dev/null +++ b/crates/zephium-webext-macos/fixtures/popup-restart/manifest.json @@ -0,0 +1,9 @@ +{ + "manifest_version": 3, + "name": "Popup worker restart fixture", + "description": "Checks a popup's worker response across native runtime launches.", + "version": "1.0", + "permissions": ["storage"], + "background": { "service_worker": "worker.js" }, + "action": { "default_popup": "popup.html" } +} diff --git a/crates/zephium-webext-macos/fixtures/popup-restart/popup.html b/crates/zephium-webext-macos/fixtures/popup-restart/popup.html new file mode 100644 index 000000000..03027dddd --- /dev/null +++ b/crates/zephium-webext-macos/fixtures/popup-restart/popup.html @@ -0,0 +1,9 @@ + + + + Popup worker restart + +

Waiting for worker

+ + + diff --git a/crates/zephium-webext-macos/fixtures/popup-restart/popup.js b/crates/zephium-webext-macos/fixtures/popup-restart/popup.js new file mode 100644 index 000000000..8c971e25a --- /dev/null +++ b/crates/zephium-webext-macos/fixtures/popup-restart/popup.js @@ -0,0 +1,16 @@ +globalThis.popupRestart = { status: "waiting" }; + +const settle = (result) => { + globalThis.popupRestart = result; + document.querySelector("#status").textContent = result.status; +}; + +chrome.runtime.sendMessage("popup-restart-probe").then( + (reply) => + settle( + reply?.status === "ready" && typeof reply.boot === "string" + ? reply + : { status: "missing-worker-response" }, + ), + (error) => settle({ status: "rejected", error: String(error) }), +); diff --git a/crates/zephium-webext-macos/fixtures/popup-restart/worker.js b/crates/zephium-webext-macos/fixtures/popup-restart/worker.js new file mode 100644 index 000000000..34cb054dd --- /dev/null +++ b/crates/zephium-webext-macos/fixtures/popup-restart/worker.js @@ -0,0 +1,7 @@ +const boot = crypto.randomUUID(); + +chrome.runtime.onMessage.addListener((message, _sender, reply) => { + if (message !== "popup-restart-probe") return false; + reply({ status: "ready", boot }); + return false; +}); diff --git a/eval/webext-popup-restart-2026-11-22.md b/eval/webext-popup-restart-2026-11-22.md new file mode 100644 index 000000000..326147ac2 --- /dev/null +++ b/eval/webext-popup-restart-2026-11-22.md @@ -0,0 +1,47 @@ +# macOS popup worker restart investigation + +## Scope + +A report that the installed 1Password toolbar button does nothing led to +this native runtime investigation. The installed failure was observed, but +its causal link to the fixture failure below is not established. A separate +disposable, unsigned-in 1Password session also produced an empty popup. +This change supplies a reproduction, not a verified 1Password fix. + +The committed fixture contains no third-party extension code or user data. +No installed application or personal profile is used by the probe. + +## Native reproduction + +Host: Apple Silicon, macOS 26.5.2. Base: `2e95353e3346d674a907c7ec07e59498048da2bf`. + +```sh +node scripts/qualification/macos-popup-restart.mjs +``` + +| Phase | Popup response | Persistent fixture marker | Result | +| --- | --- | --- | --- | +| First launch | `ready`, new worker boot ID | Absent initially | Pass | +| Reopen after closing popup and unloading context | `ready`, different boot ID | Preserved | Pass | +| Reopen after process exit with popup/context live | `missing-worker-response` | Preserved | Fail | + +Two fresh-profile runs reproduced this pass/pass/fail sequence. The command +returns exit code 1. The native background-loading callback +reports success in the failing phase, but the worker-start trace is absent +and the popup receives no response object. The failure is below the frame's +button handling: this probe uses `Runtime::perform_action` directly. + +Timing matters: an immediate relaunch passed all three phases in an earlier +control. The committed probe waits five seconds after both shutdown modes. +This is evidence of a restart-sensitive runtime failure, not proof of a +particular WebKit cache or persistence mechanism. + +## Limits and checks + +- JavaScript syntax checks and `cargo fmt --all -- --check` passed. +- `cargo clippy -p zephium-webext-macos --all-targets --features lab --locked -- -D warnings` passed on macOS. +- No production behavior, generated contracts or permission policy changes. +- Windows native execution, the full workspace CI matrix and signed-in + 1Password acceptance have not been performed. +- Earlier popup-retention and URL-scheme experiments did not establish a + fix; their diagnostic changes were removed. diff --git a/scripts/qualification/macos-popup-restart.mjs b/scripts/qualification/macos-popup-restart.mjs new file mode 100644 index 000000000..9eab3cecf --- /dev/null +++ b/scripts/qualification/macos-popup-restart.mjs @@ -0,0 +1,123 @@ +// Manual native qualification: three processes, one fresh disposable WebKit +// profile. No marketplace packages, accounts, personal profiles or native hosts. +import { randomUUID } from "node:crypto"; +import { spawnSync } from "node:child_process"; +import { mkdirSync, writeFileSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { setTimeout as delay } from "node:timers/promises"; + +if (process.platform !== "darwin") { + throw new Error("This probe requires native macOS WebKit."); +} +const root = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); +const cargo = (args) => { + const result = spawnSync("cargo", args, { + cwd: root, + encoding: "utf8", + stdio: ["ignore", "pipe", "inherit"], + }); + if (result.error) throw result.error; + if (result.status !== 0) + throw new Error(`cargo ${args[0]} failed (${result.status})`); + return result.stdout; +}; +const metadata = JSON.parse( + cargo(["metadata", "--no-deps", "--format-version", "1", "--locked"]), +); +cargo([ + "build", + "-p", + "zephium-webext-macos", + "--features", + "lab", + "--bin", + "webext-lab", + "--locked", +]); +const binary = join(metadata.target_directory, "debug/webext-lab"); +const profile = randomUUID(); +const output = join(metadata.target_directory, "popup-restart", profile); +mkdirSync(output, { recursive: true }); +const marker = "popup-restart-fixture-v1"; +const report = ` + const deadline = Date.now() + 5000; + while (globalThis.popupRestart?.status === 'waiting' && Date.now() < deadline) { + await new Promise(resolve => setTimeout(resolve, 50)); + } + const previous = (await chrome.storage.local.get('restartMarker')).restartMarker ?? null; + await chrome.storage.local.set({ restartMarker: ${JSON.stringify(marker)} }); + return { popup: globalThis.popupRestart ?? null, previous }; +`; +const steps = [ + { + load: join(root, "crates/zephium-webext-macos/fixtures/popup-restart"), + compat: true, + }, + { background: true }, + { blank: true }, + { sleep: 2500 }, + { action: true }, + { eval: report, as: "popup-restart", timeout: 8000 }, +]; + +const runs = []; +for (const phase of ["first-launch", "clean-restart", "unclean-restart"]) { + const scenario = join(output, `${phase}.json`); + // The lab ends with process::exit. Only the control explicitly closes the + // popup and unloads its context; the second process leaves them live. + const shutdown = + phase === "first-launch" + ? [{ close: "popup" }, { unload: true }, { sleep: 500 }] + : []; + writeFileSync(scenario, JSON.stringify([...steps, ...shutdown], null, 2)); + const result = spawnSync(binary, [scenario], { + cwd: root, + env: { ...process.env, LAB_PROFILE: profile, ZEPHIUM_WEBEXT_TRACE: "1" }, + encoding: "utf8", + timeout: 45_000, + maxBuffer: 2 * 1024 * 1024, + }); + writeFileSync( + join(output, `${phase}.log`), + `${result.stdout ?? ""}\n${result.stderr ?? ""}`, + ); + const line = result.stdout + ?.split("\n") + .find((line) => line.startsWith("RESULT popup-restart ")); + let value; + try { + value = JSON.parse(line?.slice("RESULT popup-restart ".length)); + } catch { + /* A missing/invalid result fails below. */ + } + const expectedPrevious = phase === "first-launch" ? null : marker; + const passed = + !result.error && + result.status === 0 && + value?.popup?.status === "ready" && + typeof value.popup.boot === "string" && + value.previous === expectedPrevious && + (phase === "first-launch" || + value.popup.boot !== runs.at(-1)?.value?.popup?.boot); + runs.push({ + phase, + passed, + value: value ?? null, + exit: result.status, + error: result.error?.message ?? null, + }); + console.log( + `${phase}: ${passed ? "PASS" : "FAIL"} ${JSON.stringify(value ?? null)}`, + ); + if (!passed) break; + // An immediate relaunch can mask the failure. Keep the same pause after + // both shutdown modes; do not infer durability from the child exiting. + if (phase !== "unclean-restart") await delay(5000); +} +writeFileSync( + join(output, "results.json"), + JSON.stringify({ profile, binary, runs }, null, 2), +); +console.log(`Evidence: ${output}`); +process.exitCode = runs.length === 3 && runs.every((run) => run.passed) ? 0 : 1; From b0a4e3612113d177db220eebd7a6b1b1db9de5a3 Mon Sep 17 00:00:00 2001 From: Anthony Sistilli Date: Sun, 22 Nov 2026 13:45:23 -0500 Subject: [PATCH 2/5] fix(extensions): recover stalled macOS background workers --- crates/zephium-engine/src/host/webext.rs | 2 + .../src/platform/macos/private_api.rs | 1 + .../fixtures/popup-restart/README.md | 38 ++- .../fixtures/popup-restart/module.js | 1 + crates/zephium-webext-macos/src/background.rs | 308 ++++++++++++++++++ .../src/background/recover.js | 37 +++ .../src/bin/webext-lab.rs | 41 +++ crates/zephium-webext-macos/src/bridge.rs | 1 + crates/zephium-webext-macos/src/lib.rs | 1 + crates/zephium-webext-macos/src/runtime.rs | 22 +- eval/webext-popup-restart-2026-11-22.md | 93 +++--- .../macos-popup-recovery.test.mjs | 144 ++++++++ scripts/qualification/macos-popup-restart.mjs | 258 ++++++++++----- 13 files changed, 816 insertions(+), 131 deletions(-) create mode 100644 crates/zephium-webext-macos/fixtures/popup-restart/module.js create mode 100644 crates/zephium-webext-macos/src/background.rs create mode 100644 crates/zephium-webext-macos/src/background/recover.js create mode 100644 scripts/qualification/macos-popup-recovery.test.mjs diff --git a/crates/zephium-engine/src/host/webext.rs b/crates/zephium-engine/src/host/webext.rs index 21a68f0b7..478f32445 100644 --- a/crates/zephium-engine/src/host/webext.rs +++ b/crates/zephium-engine/src/host/webext.rs @@ -274,6 +274,7 @@ impl WebextHost { external_native_messaging: load.external_native_messaging, native_messaging_grantable: load.native_messaging_grantable, inspectable: true, + verify_background_start: true, }; let install = load.install; let start_background = load.start_background || reloaded; @@ -379,6 +380,7 @@ impl WebextHost { external_native_messaging: false, native_messaging_grantable: false, inspectable: false, + verify_background_start: true, }; runtime.load(spec, move |_| { super::dispatch::best_effort_with(move |host| { diff --git a/crates/zephium-engine/src/platform/macos/private_api.rs b/crates/zephium-engine/src/platform/macos/private_api.rs index 18b2835bc..ec4df1145 100644 --- a/crates/zephium-engine/src/platform/macos/private_api.rs +++ b/crates/zephium-engine/src/platform/macos/private_api.rs @@ -24,6 +24,7 @@ const IMPLEMENTED: &[(&CStr, &[&CStr])] = &[ ], ), (c"WKBackForwardList", &[c"_clear"]), + (c"WKWebExtensionContext", &[c"_backgroundWebView"]), ( c"WKUserContentController", &[c"_removeAllUserScriptsAssociatedWithContentWorld:"], diff --git a/crates/zephium-webext-macos/fixtures/popup-restart/README.md b/crates/zephium-webext-macos/fixtures/popup-restart/README.md index 4ce34c1c1..e30b91aa4 100644 --- a/crates/zephium-webext-macos/fixtures/popup-restart/README.md +++ b/crates/zephium-webext-macos/fixtures/popup-restart/README.md @@ -1,27 +1,35 @@ -# Popup worker restart probe +# Popup worker restart qualification Run from the repository root on macOS with the pinned toolchain: ```sh node scripts/qualification/macos-popup-restart.mjs +node --test scripts/qualification/macos-popup-recovery.test.mjs ``` -The script builds `webext-lab` with `--locked` and launches it three times -against one newly generated WebKit profile identifier. The first process -closes the popup and unloads the extension before exiting. The second exits -with them still live. Both exits are followed by a five-second pause. +The native script builds `webext-lab` with `--locked` and exercises both classic +and module workers in separate disposable WebKit profiles. Each variant first +closes its popup and unloads the extension, then restarts and exits with them +still live, then restarts again. Five-second pauses prevent an immediate +relaunch from masking the failure. Each process invokes the native toolbar action and checks that its popup -receives a response from a newly started worker. A fixture-only storage -marker checks that the restarts use the same persistent profile. The probe -fails if a process times out, no popup/result arrives, the worker response -is missing, the worker boot identifier repeats, or the storage marker is -wrong. The cold startup has a 2.5-second settling period so this probe does -not also measure startup latency. +receives a response from a newly started worker. Markers in `chrome.storage.local`, +localStorage and IndexedDB must survive every restart. The module variant +imports its worker from another module, checking recovery preserves module type. +The cold startup has a 2.5-second settling period; this is not a latency benchmark. + +The same profile then checks concurrent recovery (64 accepted waiters and one +capacity refusal), unload cancellation (eight callers each settle once), and +successful reload after cancellation. The probe observes callbacks beyond both +readiness deadlines to catch duplicate settlement. The command exits nonzero on a failed phase and preserves scenarios, logs and `results.json` under Cargo's target directory in `popup-restart/`. -WebKit manages the disposable profile's platform storage separately. This -is a manual investigation probe, not a default CI gate or a product fix. -It needs no marketplace download, account, native messaging host, personal -profile or network page. It does not establish Windows acceptance. +WebKit manages the disposable profile's platform storage separately. The Node +tests exercise the exact recovery script's origin, registration, unregister +and activation refusal paths; they do not replace native qualification. + +These probes need no marketplace download, account, native messaging host, +personal profile or network page. They do not establish signed-in password +manager behavior or Windows acceptance. diff --git a/crates/zephium-webext-macos/fixtures/popup-restart/module.js b/crates/zephium-webext-macos/fixtures/popup-restart/module.js new file mode 100644 index 000000000..6b212b7ee --- /dev/null +++ b/crates/zephium-webext-macos/fixtures/popup-restart/module.js @@ -0,0 +1 @@ +import "./worker.js"; diff --git a/crates/zephium-webext-macos/src/background.rs b/crates/zephium-webext-macos/src/background.rs new file mode 100644 index 000000000..021068ae8 --- /dev/null +++ b/crates/zephium-webext-macos/src/background.rs @@ -0,0 +1,308 @@ +//! WebKit can restore a service-worker registration after an unclean exit +//! without starting its worker, while reporting successful background loading. +//! Verify the prepared worker's startup signal before opening a popup. Repair +//! only that worker's registration from its own native background page. + +use std::cell::{Cell, RefCell}; +use std::ptr::NonNull; +use std::rc::{Rc, Weak}; + +use block2::RcBlock; +use objc2::rc::{Retained, Weak as ObjcWeak}; +use objc2::runtime::AnyObject; +use objc2::{msg_send, sel, Message}; +use objc2_foundation::{ + NSError, NSObjectProtocol, NSRunLoop, NSRunLoopCommonModes, NSString, NSTimer, +}; +use objc2_web_kit::{WKContentWorld, WKWebExtensionContext, WKWebView}; + +use crate::runtime::Shared; + +type Done = Box)>; +const START_SECONDS: f64 = 5.0; +const MAX_WAITERS: usize = 64; + +pub(crate) struct State { + verify: bool, + ready: RefCell>, + pending: RefCell>>, +} + +impl State { + pub(crate) fn new(verify: bool) -> Self { + Self { + verify, + ready: RefCell::default(), + pending: RefCell::default(), + } + } + + pub(crate) fn cancel(&self) { + let pending = self.pending.borrow_mut().take(); + if let Some(pending) = pending { + pending.finish(Err("The extension was unloaded.".into())); + } + } +} + +impl Drop for State { + fn drop(&mut self) { + if let Some(pending) = self.pending.get_mut().take() { + pending.finish(Err("The extension runtime was closed.".into())); + } + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Phase { + Waiting, + Repairing, + Settled, +} + +struct Attempt { + state: Weak, + shared: Weak, + context: Retained, + view: Retained, + phase: Cell, + waiters: RefCell>, + timer: RefCell>>, +} + +fn state_for(shared: &Shared, context: &WKWebExtensionContext) -> Option> { + shared + .loaded + .borrow() + .values() + .find(|loaded| std::ptr::eq(&*loaded.context, context)) + .map(|loaded| loaded.background.clone()) +} + +fn view(context: &WKWebExtensionContext) -> Option> { + if !context.respondsToSelector(sel!(_backgroundWebView)) { + return None; + } + // SAFETY: guarded, read-only WebKit getter, called on its main thread. + unsafe { msg_send![context, _backgroundWebView] } +} + +fn worker_script(context: &WKWebExtensionContext) -> Option<(String, bool)> { + // SAFETY: the loaded context and its manifest are main-thread WebKit objects. + let manifest = unsafe { context.webExtension().manifest() }; + let manifest = crate::json::from_object(Some(&manifest)); + let background = manifest.get("background")?; + let path = background.get("service_worker")?.as_str()?; + let base = unsafe { context.baseURL() }.absoluteString()?.to_string(); + let base = url::Url::parse(&base).ok()?; + let script = base.join(path).ok()?; + if !same_origin(&base, &script) { + return None; + } + Some(( + script.into(), + background.get("type").and_then(|v| v.as_str()) == Some("module"), + )) +} + +fn same_origin(base: &url::Url, target: &url::Url) -> bool { + base.scheme() == target.scheme() + && base.host_str() == target.host_str() + && base.port() == target.port() +} + +pub(crate) fn wait(shared: &Rc, context: &WKWebExtensionContext, done: Done) { + let Some(state) = state_for(shared, context) else { + return done(Err("The extension was unloaded.".into())); + }; + // Background pages and unadapted lab fixtures do not send our worker signal. + if !state.verify || worker_script(context).is_none() { + return done(Ok(())); + } + let Some(view) = view(context) else { + return done(Err("The extension background view is unavailable.".into())); + }; + let previous = state.pending.borrow().clone(); + if let Some(previous) = previous { + if std::ptr::eq(&*previous.view, &*view) { + if previous.waiters.borrow().len() >= MAX_WAITERS { + return done(Err("Too many extension background requests.".into())); + } + previous.waiters.borrow_mut().push(done); + return; + } + previous.finish(Err("The extension background was replaced.".into())); + } + // Settling an older attempt invokes callers, which may unload this context. + if !state_for(shared, context).is_some_and(|current| Rc::ptr_eq(¤t, &state)) { + return done(Err("The extension was unloaded.".into())); + } + let ready = state + .ready + .borrow() + .load() + .is_some_and(|ready| std::ptr::eq(&*ready, &*view)); + if ready { + return done(Ok(())); + } + let attempt = Rc::new(Attempt { + state: Rc::downgrade(&state), + shared: Rc::downgrade(shared), + context: context.retain(), + view, + phase: Cell::new(Phase::Waiting), + waiters: RefCell::new(vec![done]), + timer: RefCell::default(), + }); + *state.pending.borrow_mut() = Some(attempt.clone()); + attempt.arm(); +} + +pub(crate) fn started(shared: &Rc, context: &WKWebExtensionContext) { + let (Some(state), Some(view)) = (state_for(shared, context), view(context)) else { + return; + }; + *state.ready.borrow_mut() = ObjcWeak::from_retained(&view); + let pending = state.pending.borrow().clone(); + if let Some(pending) = pending { + // A repair also waits for the new registration to activate. A late + // startup from the old worker cannot release its waiters early. + if pending.phase.get() == Phase::Waiting && std::ptr::eq(&*pending.view, &*view) { + pending.finish(Ok(())); + } + } +} + +impl Attempt { + fn current(&self) -> bool { + self.shared + .upgrade() + .is_some_and(|shared| state_for(&shared, &self.context).is_some()) + && view(&self.context).is_some_and(|view| std::ptr::eq(&*view, &*self.view)) + } + + fn finish(&self, result: Result<(), String>) { + if self.phase.replace(Phase::Settled) == Phase::Settled { + return; + } + let result = if result.is_ok() && !self.current() { + Err("The extension background was replaced.".into()) + } else { + result + }; + if let Some(timer) = self.timer.borrow_mut().take() { + timer.invalidate(); + } + if let Some(state) = self.state.upgrade() { + *state.ready.borrow_mut() = if result.is_ok() { + ObjcWeak::from_retained(&self.view) + } else { + ObjcWeak::default() + }; + let ours = state + .pending + .borrow() + .as_ref() + .is_some_and(|pending| std::ptr::eq(&**pending, self)); + if ours { + state.pending.borrow_mut().take(); + } + } + let waiters = std::mem::take(&mut *self.waiters.borrow_mut()); + for done in waiters { + done(result.clone()); + } + } + + fn arm(self: &Rc) { + if let Some(timer) = self.timer.borrow_mut().take() { + timer.invalidate(); + } + let weak = Rc::downgrade(self); + let fire = RcBlock::new(move |_: NonNull| { + let Some(attempt) = weak.upgrade() else { + return; + }; + if !attempt.current() { + attempt.finish(Err("The extension background was replaced.".into())); + } else if attempt.phase.get() == Phase::Waiting { + attempt.repair(); + } else if attempt.phase.get() == Phase::Repairing { + attempt.finish(Err("The extension background did not start.".into())); + } + }); + // SAFETY: native main thread; NSTimer copies the block. Only a weak + // reference is captured, and completion invalidates the timer. + let timer = + unsafe { NSTimer::timerWithTimeInterval_repeats_block(START_SECONDS, false, &fire) }; + // SAFETY: the main run loop and mode constant are valid here. Menu + // tracking must not suspend a background-start deadline. + unsafe { + NSRunLoop::mainRunLoop().addTimer_forMode(&timer, NSRunLoopCommonModes); + } + *self.timer.borrow_mut() = Some(timer); + } + + fn repair(self: &Rc) { + let Some((expected, modules)) = worker_script(&self.context) else { + return self.finish(Err("The extension worker URL is invalid.".into())); + }; + let Some(shared) = self.shared.upgrade() else { + return; + }; + self.phase.set(Phase::Repairing); + self.arm(); + let script = format!( + "const expected = {}; const modules = {};\n{}", + serde_json::to_string(&expected).expect("a URL string is JSON"), + modules, + include_str!("background/recover.js") + ); + let weak = Rc::downgrade(self); + let complete = RcBlock::new(move |value: *mut AnyObject, error: *mut NSError| { + let Some(attempt) = weak.upgrade() else { + return; + }; + let ok = error.is_null() + && crate::json::from_object(unsafe { value.as_ref() }).as_bool() == Some(true); + attempt.finish(if ok { + Ok(()) + } else { + Err("The extension worker could not be recovered.".into()) + }); + }); + // SAFETY: evaluate only in this context's native background page. + // Unloading the context closes that view; callbacks also check identity. + unsafe { + self.view + .callAsyncJavaScript_arguments_inFrame_inContentWorld_completionHandler( + &NSString::from_str(&script), + None, + None, + &WKContentWorld::pageWorld(shared.mtm), + Some(&complete), + ); + } + } +} + +#[cfg(test)] +mod tests { + use super::same_origin; + + #[test] + fn worker_recovery_stays_in_its_extension_origin() { + let base = url::Url::parse("chrome-extension://example/").unwrap(); + assert!(same_origin( + &base, + &base.join("background/worker.js").unwrap() + )); + for other in [ + "https://example/worker.js", + "chrome-extension://other/worker.js", + "chrome-extension://example:81/worker.js", + ] { + assert!(!same_origin(&base, &url::Url::parse(other).unwrap())); + } + } +} diff --git a/crates/zephium-webext-macos/src/background/recover.js b/crates/zephium-webext-macos/src/background/recover.js new file mode 100644 index 000000000..b785a5134 --- /dev/null +++ b/crates/zephium-webext-macos/src/background/recover.js @@ -0,0 +1,37 @@ +// This body runs only in WebKit's native background page, whose service-worker +// client can unregister its own worker. Ordinary extension pages cannot do so. +const script = new URL(expected); +const here = new URL(location.href); +const sameOrigin = (a, b) => + a.protocol === b.protocol && a.hostname === b.hostname && a.port === b.port; +if (!sameOrigin(script, here)) throw new Error("Worker origin mismatch"); +const registration = await navigator.serviceWorker.getRegistration(expected); +if ( + !registration?.active || + registration.active.scriptURL !== expected || + !sameOrigin(script, new URL(registration.scope)) +) { + throw new Error("Worker registration mismatch"); +} +const scope = registration.scope; +if (!(await registration.unregister())) + throw new Error("Worker unregister failed"); +const replacement = await navigator.serviceWorker.register(expected, { + scope, + type: modules ? "module" : "classic", +}); +const worker = + replacement.installing ?? replacement.waiting ?? replacement.active; +if (!worker) throw new Error("Worker replacement missing"); +await new Promise((resolve, reject) => { + const changed = () => { + if (worker.state === "activated" || worker.state === "redundant") { + worker.removeEventListener("statechange", changed); + if (worker.state === "activated") resolve(); + else reject(new Error("Worker replacement failed")); + } + }; + worker.addEventListener("statechange", changed); + changed(); +}); +return true; diff --git a/crates/zephium-webext-macos/src/bin/webext-lab.rs b/crates/zephium-webext-macos/src/bin/webext-lab.rs index 90eb5426a..ea44ab933 100644 --- a/crates/zephium-webext-macos/src/bin/webext-lab.rs +++ b/crates/zephium-webext-macos/src/bin/webext-lab.rs @@ -6,7 +6,11 @@ //! //! A scenario is a JSON array of steps, run in order: //! - `{"load": "", "compat": true, "id": ""}` +//! Use `"compat": false, "verify_background_start": true` for an already +//! prepared package that reports the worker startup signal. //! - `{"background": true}` starts the last loaded extension's background +//! - `{"background_waiters": 8, "cancel": false}` checks concurrent startup +//! settlement, optionally unloading while readiness is pending //! - `{"tab": ""}` opens a tab and waits for it to load; `{"blank": true}` //! opens one with no page, as the browser's new tab //! - `{"page": ""}` opens one of the extension's pages in a probe view @@ -357,6 +361,10 @@ impl Lab { .and_then(Value::as_bool) .unwrap_or(false), inspectable: true, + verify_background_start: step + .get("verify_background_start") + .and_then(Value::as_bool) + .unwrap_or(compat), }; this.runtime.load(spec, move |result| { println!("LOADED {result:?}"); @@ -445,6 +453,39 @@ impl Lab { } else if let Some(path) = step.get("page").and_then(Value::as_str) { let view = this.open_page(path); wait_loaded(view, next); + } else if step.get("background_waiters").is_some() { + let id = this.extension.borrow().clone().unwrap_or_default(); + let count = step + .get("background_waiters") + .and_then(Value::as_u64) + .unwrap_or(8) + .clamp(1, 65); + let results = Rc::new(RefCell::new(Vec::new())); + for _ in 0..count { + let results = results.clone(); + this.runtime.start_background(&id, move |result| { + results.borrow_mut().push(result.is_ok()); + }); + } + if step.get("cancel").and_then(Value::as_bool) == Some(true) { + let lab = this.clone(); + after(500, move || { + lab.runtime.unload(&id); + }); + } + // Outlive both readiness deadlines, so late callbacks are counted. + after(11_000, move || { + let results = results.borrow(); + println!( + "RESULT background-waiters {}", + serde_json::json!({ + "requested": count, "settled": results.len(), + "ok": results.iter().filter(|ok| **ok).count(), + "errors": results.iter().filter(|ok| !**ok).count(), + }) + ); + next(); + }); } else if let Some(body) = step.get("eval").and_then(Value::as_str) { let timeout = step.get("timeout").and_then(Value::as_u64).unwrap_or(5000); let view = match step.get("in").and_then(Value::as_str) { diff --git a/crates/zephium-webext-macos/src/bridge.rs b/crates/zephium-webext-macos/src/bridge.rs index 43434a36f..4ffa9c2db 100644 --- a/crates/zephium-webext-macos/src/bridge.rs +++ b/crates/zephium-webext-macos/src/bridge.rs @@ -172,6 +172,7 @@ pub(crate) fn handle( } crate::worker_gone(shared, &id); crate::lifetime::started(shared, &id); + crate::background::started(shared, context); Ok(Value::Null) } Some("offscreen.close") => Ok(Value::Bool(offscreen::close(shared, &extension(context)))), diff --git a/crates/zephium-webext-macos/src/lib.rs b/crates/zephium-webext-macos/src/lib.rs index 38a0c9cb2..4dacb62e2 100644 --- a/crates/zephium-webext-macos/src/lib.rs +++ b/crates/zephium-webext-macos/src/lib.rs @@ -9,6 +9,7 @@ mod access; mod api; mod auth; +mod background; mod bookmarks; mod bridge; pub mod compat; diff --git a/crates/zephium-webext-macos/src/runtime.rs b/crates/zephium-webext-macos/src/runtime.rs index 3d50c97d8..dff07c05c 100644 --- a/crates/zephium-webext-macos/src/runtime.rs +++ b/crates/zephium-webext-macos/src/runtime.rs @@ -49,6 +49,8 @@ pub struct ExtensionSpec { /// `nativeMessaging` optional. pub native_messaging_grantable: bool, pub inspectable: bool, + /// The prepared worker reports `worker.started` through our compatibility layer. + pub verify_background_start: bool, } #[derive(Clone, Debug)] @@ -65,6 +67,7 @@ pub(crate) struct Loaded { pub(crate) native_messaging_grantable: bool, /// Granted permissions of the APIs the browser implements itself. pub(crate) browser_permissions: RefCell>, + pub(crate) background: Rc, } /// One profile's state. WebKit gives an extension the same identifier in @@ -303,12 +306,17 @@ impl Runtime { return done(Err(format!("{id} is not loaded"))); }; let done = RefCell::new(Some(done)); + let owner = Rc::downgrade(&self.shared); + let target = context.clone(); let completion = RcBlock::new(move |error: *mut NSError| { if let Some(done) = done.take() { - done(match unsafe { error.as_ref() } { - None => Ok(()), - Some(error) => Err(describe(Some(error))), - }); + if let Some(error) = unsafe { error.as_ref() } { + return done(Err(describe(Some(error)))); + } + let Some(shared) = owner.upgrade() else { + return done(Err("The extension runtime was closed.".into())); + }; + crate::background::wait(&shared, &target, Box::new(done)); } }); unsafe { context.loadBackgroundContentWithCompletionHandler(&completion) }; @@ -711,6 +719,7 @@ fn activate( external_native_messaging: std::cell::Cell::new(spec.external_native_messaging), native_messaging_grantable: spec.native_messaging_grantable, browser_permissions, + background: Rc::new(crate::background::State::new(spec.verify_background_start)), }, ); Ok(loaded) @@ -838,7 +847,10 @@ fn unload(shared: &Rc, controller: &WKWebExtensionController, id: &str) shared.popouts.borrow_mut().remove(id); crate::api::forget(id); crate::cookies::refresh(shared); - unsafe { controller.unloadExtensionContext_error(&loaded.context) }.is_ok() + let result = unsafe { controller.unloadExtensionContext_error(&loaded.context) }.is_ok(); + // Unloading closes the native background view before settling its waiters. + loaded.background.cancel(); + result } /// Deletes an unloaded extension's `chrome.storage` areas. diff --git a/eval/webext-popup-restart-2026-11-22.md b/eval/webext-popup-restart-2026-11-22.md index 326147ac2..66f90bcd1 100644 --- a/eval/webext-popup-restart-2026-11-22.md +++ b/eval/webext-popup-restart-2026-11-22.md @@ -1,47 +1,66 @@ -# macOS popup worker restart investigation +# macOS extension worker recovery -## Scope +## Failure and change -A report that the installed 1Password toolbar button does nothing led to -this native runtime investigation. The installed failure was observed, but -its causal link to the fixture failure below is not established. A separate -disposable, unsigned-in 1Password session also produced an empty popup. -This change supplies a reproduction, not a verified 1Password fix. +After an exit with an extension context still live, WebKit can restore its +service-worker registration without starting the worker. Its native background +completion reports success, but the popup's runtime message receives no response. +Two fresh-profile baseline runs at `2e95353e3346d674a907c7ec07e59498048da2bf` +produced pass/pass/fail for first launch, clean restart and unclean restart. +An immediate restart could mask the failure; both controls wait five seconds. -The committed fixture contains no third-party extension code or user data. -No installed application or personal profile is used by the probe. +The runtime now waits for the prepared worker's existing `worker.started` +signal. After five seconds without it, a guarded `_backgroundWebView` getter +accesses that context's native background page. From that page, recovery +unregisters only the exact expected worker and registers the same URL, scope +and classic/module type. It waits for activation and has a further five-second +deadline. Ordinary extension pages cannot perform this recovery on the tested +WebKit (`InvalidStateError: Client is unknown`). -## Native reproduction +The operation checks origin, script URL, context and view identity. Concurrent +callers share one attempt, capped at 64 waiters. Unload cancels pending callers; +late callbacks cannot settle a replacement context. The ready view is weakly +held so it does not keep an idle worker alive. Background pages and unadapted +fixtures retain their existing behavior. Permission policy is unchanged. +No website registrations, extension storage or native messaging grants are reset. -Host: Apple Silicon, macOS 26.5.2. Base: `2e95353e3346d674a907c7ec07e59498048da2bf`. +## Native qualification + +Host: Apple Silicon M5 Max, macOS 26.5.2 (25F84). Run: ```sh node scripts/qualification/macos-popup-restart.mjs ``` -| Phase | Popup response | Persistent fixture marker | Result | -| --- | --- | --- | --- | -| First launch | `ready`, new worker boot ID | Absent initially | Pass | -| Reopen after closing popup and unloading context | `ready`, different boot ID | Preserved | Pass | -| Reopen after process exit with popup/context live | `missing-worker-response` | Preserved | Fail | - -Two fresh-profile runs reproduced this pass/pass/fail sequence. The command -returns exit code 1. The native background-loading callback -reports success in the failing phase, but the worker-start trace is absent -and the popup receives no response object. The failure is below the frame's -button handling: this probe uses `Runtime::perform_action` directly. - -Timing matters: an immediate relaunch passed all three phases in an earlier -control. The committed probe waits five seconds after both shutdown modes. -This is evidence of a restart-sensitive runtime failure, not proof of a -particular WebKit cache or persistence mechanism. - -## Limits and checks - -- JavaScript syntax checks and `cargo fmt --all -- --check` passed. -- `cargo clippy -p zephium-webext-macos --all-targets --features lab --locked -- -D warnings` passed on macOS. -- No production behavior, generated contracts or permission policy changes. -- Windows native execution, the full workspace CI matrix and signed-in - 1Password acceptance have not been performed. -- Earlier popup-retention and URL-scheme experiments did not establish a - fix; their diagnostic changes were removed. +| Case | Classic worker | Module worker | +| --- | --- | --- | +| First launch: popup answers with a boot ID | Pass | Pass | +| Clean restart: new worker answers | Pass | Pass | +| Unclean restart: new worker answers | Pass | Pass | +| 65 concurrent requests: 64 succeed, one refused | Pass | Pass | +| Eight cancelled requests: eight errors, no late duplicate | Pass | Pass | +| Reload after cancellation: popup answers | Pass | Pass | + +Markers in chrome.storage.local, localStorage and IndexedDB survived every +restart and the reload after cancellation. Raw fixture evidence is under Cargo's +`target/popup-restart/1d9ce3c0-2699-49b9-9a24-6552c17fb3fc` (classic) and +`267197bc-83ea-4483-9d66-718d0eabdca5` (module). + +An existing disposable, unsigned-in 1Password 8.12.46.29 profile that previously +had no worker-start trace now starts its module worker and responds to its native +action by requesting its welcome page. External native messaging was denied in +this lab session. This is worker/action evidence only: no account sign-in, +vault unlock, autofill or desktop-app integration was tested. The installed +user-profile symptom was observed earlier; its causal equivalence to this +restart failure is not conclusively established. + +## Checks and remaining evidence + +- `node --test scripts/qualification/macos-popup-recovery.test.mjs`: six passing + tests, including wrong-origin/registration refusal and activation waiting. +- `cargo clippy -p zephium-webext-macos --all-targets --features lab --locked -- -D warnings`: passed. +- `cargo test -p zephium-webext-macos --lib --locked`: 30 passed. +- Workspace/macOS CI results are recorded in the pull request after final checks. +- Windows native execution and signed-in 1Password acceptance remain untested. + This change is confined to the macOS adapter; Windows compilation is not + a substitute for native acceptance. diff --git a/scripts/qualification/macos-popup-recovery.test.mjs b/scripts/qualification/macos-popup-recovery.test.mjs new file mode 100644 index 000000000..98556667d --- /dev/null +++ b/scripts/qualification/macos-popup-recovery.test.mjs @@ -0,0 +1,144 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; + +const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor; +const recover = new AsyncFunction( + "expected", + "modules", + "navigator", + "location", + readFileSync( + new URL( + "../../crates/zephium-webext-macos/src/background/recover.js", + import.meta.url, + ), + "utf8", + ), +); +const expected = "chrome-extension://fixture/background/worker.js"; + +function fixture({ + scope = "chrome-extension://fixture/background/", + scriptURL = expected, + removed = true, + finalState = "activated", +} = {}) { + const calls = []; + const worker = new EventTarget(); + worker.state = finalState; + const registration = { + scope, + active: { scriptURL }, + async unregister() { + calls.push("unregister"); + return removed; + }, + }; + const navigator = { + serviceWorker: { + async getRegistration(url) { + calls.push(["get", url]); + return registration; + }, + async register(url, options) { + calls.push(["register", url, options]); + return { active: worker }; + }, + }, + }; + return { + calls, + registration, + navigator, + worker, + location: { href: expected }, + }; +} + +test("recovery preserves the worker URL, scope and classic/module type", async () => { + for (const modules of [false, true]) { + const f = fixture(); + assert.equal( + await recover(expected, modules, f.navigator, f.location), + true, + ); + assert.deepEqual(f.calls.at(-1), [ + "register", + expected, + { scope: f.registration.scope, type: modules ? "module" : "classic" }, + ]); + } +}); + +test("a different origin is refused before registration access", async () => { + for (const href of [ + "https://fixture/background/worker.js", + "chrome-extension://other/background/worker.js", + "chrome-extension://fixture:81/background/worker.js", + ]) { + const f = fixture(); + await assert.rejects( + recover(expected, false, f.navigator, { href }), + /origin mismatch/, + ); + assert.deepEqual(f.calls, []); + } +}); + +test("a missing, different or cross-origin registration is never unregistered", async () => { + for (const options of [ + { scriptURL: "chrome-extension://fixture/other.js" }, + { scope: "chrome-extension://other/" }, + ]) { + const f = fixture(options); + await assert.rejects( + recover(expected, false, f.navigator, f.location), + /registration mismatch/, + ); + assert.equal(f.calls.includes("unregister"), false); + } + const f = fixture(); + f.navigator.serviceWorker.getRegistration = async () => undefined; + await assert.rejects( + recover(expected, false, f.navigator, f.location), + /registration mismatch/, + ); + assert.deepEqual(f.calls, []); +}); + +test("failed unregister does not create a second worker", async () => { + const f = fixture({ removed: false }); + await assert.rejects( + recover(expected, false, f.navigator, f.location), + /unregister failed/, + ); + assert.equal( + f.calls.some((call) => Array.isArray(call) && call[0] === "register"), + false, + ); +}); + +test("activation failure is not reported as success", async () => { + const f = fixture({ finalState: "redundant" }); + await assert.rejects( + recover(expected, true, f.navigator, f.location), + /replacement failed/, + ); +}); + +test("recovery waits for activation instead of accepting an installing worker", async () => { + const f = fixture({ finalState: "installing" }); + let settled = false; + const result = recover(expected, false, f.navigator, f.location).then( + (value) => { + settled = true; + return value; + }, + ); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(settled, false); + f.worker.state = "activated"; + f.worker.dispatchEvent(new Event("statechange")); + assert.equal(await result, true); +}); diff --git a/scripts/qualification/macos-popup-restart.mjs b/scripts/qualification/macos-popup-restart.mjs index 9eab3cecf..2e4ea92ed 100644 --- a/scripts/qualification/macos-popup-restart.mjs +++ b/scripts/qualification/macos-popup-restart.mjs @@ -2,7 +2,7 @@ // profile. No marketplace packages, accounts, personal profiles or native hosts. import { randomUUID } from "node:crypto"; import { spawnSync } from "node:child_process"; -import { mkdirSync, writeFileSync } from "node:fs"; +import { cpSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { setTimeout as delay } from "node:timers/promises"; @@ -36,88 +36,198 @@ cargo([ "--locked", ]); const binary = join(metadata.target_directory, "debug/webext-lab"); -const profile = randomUUID(); -const output = join(metadata.target_directory, "popup-restart", profile); -mkdirSync(output, { recursive: true }); -const marker = "popup-restart-fixture-v1"; -const report = ` +const outcomes = []; +for (const kind of ["classic", "module"]) { + const profile = randomUUID(); + const output = join(metadata.target_directory, "popup-restart", profile); + mkdirSync(output, { recursive: true }); + const fixture = join(output, "fixture"); + cpSync( + join(root, "crates/zephium-webext-macos/fixtures/popup-restart"), + fixture, + { recursive: true }, + ); + if (kind === "module") { + const manifest = JSON.parse( + readFileSync(join(fixture, "manifest.json"), "utf8"), + ); + manifest.background = { service_worker: "module.js", type: "module" }; + writeFileSync(join(fixture, "manifest.json"), JSON.stringify(manifest)); + } + const marker = "popup-restart-fixture-v1"; + const report = ` const deadline = Date.now() + 5000; while (globalThis.popupRestart?.status === 'waiting' && Date.now() < deadline) { await new Promise(resolve => setTimeout(resolve, 50)); } const previous = (await chrome.storage.local.get('restartMarker')).restartMarker ?? null; await chrome.storage.local.set({ restartMarker: ${JSON.stringify(marker)} }); - return { popup: globalThis.popupRestart ?? null, previous }; + const localPrevious = localStorage.getItem('restartMarker'); + localStorage.setItem('restartMarker', ${JSON.stringify(marker)}); + const database = await new Promise((resolve, reject) => { + const request = indexedDB.open('popup-restart-fixture', 1); + request.onupgradeneeded = () => request.result.createObjectStore('state'); + request.onsuccess = () => resolve(request.result); + request.onerror = () => reject(request.error); + }); + const indexedPrevious = await new Promise((resolve, reject) => { + const transaction = database.transaction('state', 'readwrite'); + const store = transaction.objectStore('state'); + let before = null; + const request = store.get('restartMarker'); + request.onsuccess = () => { before = request.result ?? null; store.put(${JSON.stringify(marker)}, 'restartMarker'); }; + transaction.oncomplete = () => resolve(before); + transaction.onabort = transaction.onerror = () => reject(transaction.error); + }); + database.close(); + return { popup: globalThis.popupRestart ?? null, previous, localPrevious, indexedPrevious }; `; -const steps = [ - { - load: join(root, "crates/zephium-webext-macos/fixtures/popup-restart"), - compat: true, - }, - { background: true }, - { blank: true }, - { sleep: 2500 }, - { action: true }, - { eval: report, as: "popup-restart", timeout: 8000 }, -]; + const steps = [ + { + load: fixture, + compat: true, + }, + { background: true }, + { blank: true }, + { sleep: 2500 }, + { action: true }, + { eval: report, as: "popup-restart", timeout: 8000 }, + ]; -const runs = []; -for (const phase of ["first-launch", "clean-restart", "unclean-restart"]) { - const scenario = join(output, `${phase}.json`); - // The lab ends with process::exit. Only the control explicitly closes the - // popup and unloads its context; the second process leaves them live. - const shutdown = - phase === "first-launch" - ? [{ close: "popup" }, { unload: true }, { sleep: 500 }] - : []; - writeFileSync(scenario, JSON.stringify([...steps, ...shutdown], null, 2)); - const result = spawnSync(binary, [scenario], { - cwd: root, - env: { ...process.env, LAB_PROFILE: profile, ZEPHIUM_WEBEXT_TRACE: "1" }, - encoding: "utf8", - timeout: 45_000, - maxBuffer: 2 * 1024 * 1024, - }); + const runs = []; + for (const phase of ["first-launch", "clean-restart", "unclean-restart"]) { + const scenario = join(output, `${phase}.json`); + // The lab ends with process::exit. Only the control explicitly closes the + // popup and unloads its context; the second process leaves them live. + const shutdown = + phase === "first-launch" + ? [{ close: "popup" }, { unload: true }, { sleep: 500 }] + : []; + writeFileSync(scenario, JSON.stringify([...steps, ...shutdown], null, 2)); + const result = spawnSync(binary, [scenario], { + cwd: root, + env: { ...process.env, LAB_PROFILE: profile, ZEPHIUM_WEBEXT_TRACE: "1" }, + encoding: "utf8", + timeout: 45_000, + maxBuffer: 2 * 1024 * 1024, + }); + writeFileSync( + join(output, `${phase}.log`), + `${result.stdout ?? ""}\n${result.stderr ?? ""}`, + ); + const line = result.stdout + ?.split("\n") + .find((line) => line.startsWith("RESULT popup-restart ")); + let value; + try { + value = JSON.parse(line?.slice("RESULT popup-restart ".length)); + } catch { + /* A missing/invalid result fails below. */ + } + const expectedPrevious = phase === "first-launch" ? null : marker; + const passed = + !result.error && + result.status === 0 && + value?.popup?.status === "ready" && + typeof value.popup.boot === "string" && + value.previous === expectedPrevious && + value.localPrevious === expectedPrevious && + value.indexedPrevious === expectedPrevious && + (phase === "first-launch" || + value.popup.boot !== runs.at(-1)?.value?.popup?.boot); + runs.push({ + phase, + passed, + value: value ?? null, + exit: result.status, + error: result.error?.message ?? null, + }); + console.log( + `${kind} ${phase}: ${passed ? "PASS" : "FAIL"} ${JSON.stringify(value ?? null)}`, + ); + if (!passed) break; + // An immediate relaunch can mask the failure. Keep the same pause after + // both shutdown modes; do not infer durability from the child exiting. + if (phase !== "unclean-restart") await delay(5000); + } + // The last restart leaves its context live again. Reopen that same profile + // to exercise single-flight recovery, the waiter bound, and unload cancellation. + const waiterRuns = []; + if (runs.length === 3 && runs.every((run) => run.passed)) { + for (const cancel of [false, true]) { + await delay(5000); + const phase = cancel ? "cancel-waiters" : "concurrent-waiters"; + const count = cancel ? 8 : 65; + const scenario = join(output, `${phase}.json`); + const probeSteps = [steps[0], { background_waiters: count, cancel }]; + if (cancel) { + // Reload the same extension immediately after cancellation. An old + // callback must not settle the replacement context's readiness. + probeSteps.push(...steps); + } + writeFileSync(scenario, JSON.stringify(probeSteps, null, 2)); + const result = spawnSync(binary, [scenario], { + cwd: root, + env: { + ...process.env, + LAB_PROFILE: profile, + ZEPHIUM_WEBEXT_TRACE: "1", + }, + encoding: "utf8", + timeout: 45_000, + maxBuffer: 2 * 1024 * 1024, + }); + writeFileSync( + join(output, `${phase}.log`), + `${result.stdout ?? ""}\n${result.stderr ?? ""}`, + ); + const parse = (label) => { + const prefix = `RESULT ${label} `; + const line = result.stdout + ?.split("\n") + .find((line) => line.startsWith(prefix)); + try { + return JSON.parse(line?.slice(prefix.length)); + } catch { + return null; + } + }; + const value = parse("background-waiters"); + const popup = parse("popup-restart"); + const passed = + !result.error && + result.status === 0 && + value?.settled === count && + value.ok === (cancel ? 0 : 64) && + value.errors === (cancel ? 8 : 1) && + (!cancel || + (popup?.popup?.status === "ready" && + popup.previous === marker && + popup.localPrevious === marker && + popup.indexedPrevious === marker)); + waiterRuns.push({ + phase, + passed, + value, + popup, + exit: result.status, + error: result.error?.message ?? null, + }); + console.log( + `${kind} ${phase}: ${passed ? "PASS" : "FAIL"} ${JSON.stringify(value)}`, + ); + } + } writeFileSync( - join(output, `${phase}.log`), - `${result.stdout ?? ""}\n${result.stderr ?? ""}`, + join(output, "results.json"), + JSON.stringify({ kind, profile, binary, runs, waiterRuns }, null, 2), ); - const line = result.stdout - ?.split("\n") - .find((line) => line.startsWith("RESULT popup-restart ")); - let value; - try { - value = JSON.parse(line?.slice("RESULT popup-restart ".length)); - } catch { - /* A missing/invalid result fails below. */ - } - const expectedPrevious = phase === "first-launch" ? null : marker; - const passed = - !result.error && - result.status === 0 && - value?.popup?.status === "ready" && - typeof value.popup.boot === "string" && - value.previous === expectedPrevious && - (phase === "first-launch" || - value.popup.boot !== runs.at(-1)?.value?.popup?.boot); - runs.push({ - phase, - passed, - value: value ?? null, - exit: result.status, - error: result.error?.message ?? null, - }); - console.log( - `${phase}: ${passed ? "PASS" : "FAIL"} ${JSON.stringify(value ?? null)}`, + console.log(`Evidence: ${output}`); + outcomes.push( + runs.length === 3 && + runs.every((run) => run.passed) && + waiterRuns.length === 2 && + waiterRuns.every((run) => run.passed), ); - if (!passed) break; - // An immediate relaunch can mask the failure. Keep the same pause after - // both shutdown modes; do not infer durability from the child exiting. - if (phase !== "unclean-restart") await delay(5000); } -writeFileSync( - join(output, "results.json"), - JSON.stringify({ profile, binary, runs }, null, 2), -); -console.log(`Evidence: ${output}`); -process.exitCode = runs.length === 3 && runs.every((run) => run.passed) ? 0 : 1; +process.exitCode = outcomes.every(Boolean) ? 0 : 1; From cfb2290ab61d2000c372648c01f27164dc3f2963 Mon Sep 17 00:00:00 2001 From: Anthony Sistilli Date: Sun, 22 Nov 2026 13:51:36 -0500 Subject: [PATCH 3/5] test(extensions): force pending worker recovery in concurrency probes --- .../fixtures/popup-restart/README.md | 10 +++--- eval/webext-popup-restart-2026-11-22.md | 28 +++++++++++++--- scripts/qualification/macos-popup-restart.mjs | 33 ++++++++++++------- 3 files changed, 52 insertions(+), 19 deletions(-) diff --git a/crates/zephium-webext-macos/fixtures/popup-restart/README.md b/crates/zephium-webext-macos/fixtures/popup-restart/README.md index e30b91aa4..f265d1037 100644 --- a/crates/zephium-webext-macos/fixtures/popup-restart/README.md +++ b/crates/zephium-webext-macos/fixtures/popup-restart/README.md @@ -19,10 +19,12 @@ localStorage and IndexedDB must survive every restart. The module variant imports its worker from another module, checking recovery preserves module type. The cold startup has a 2.5-second settling period; this is not a latency benchmark. -The same profile then checks concurrent recovery (64 accepted waiters and one -capacity refusal), unload cancellation (eight callers each settle once), and -successful reload after cancellation. The probe observes callbacks beyond both -readiness deadlines to catch duplicate settlement. +A second profile uses the raw fixture without the compatibility startup signal, +while explicitly enabling verification. This forces the pending state even when +WebKit happens to restart promptly. It checks concurrent recovery (64 accepted +waiters and one capacity refusal), unload cancellation (eight callers each settle +once), and successful reload after cancellation. The probe observes callbacks +beyond both readiness deadlines to catch duplicate settlement. The command exits nonzero on a failed phase and preserves scenarios, logs and `results.json` under Cargo's target directory in `popup-restart/`. diff --git a/eval/webext-popup-restart-2026-11-22.md b/eval/webext-popup-restart-2026-11-22.md index 66f90bcd1..3ceffd5c3 100644 --- a/eval/webext-popup-restart-2026-11-22.md +++ b/eval/webext-popup-restart-2026-11-22.md @@ -42,9 +42,13 @@ node scripts/qualification/macos-popup-restart.mjs | Reload after cancellation: popup answers | Pass | Pass | Markers in chrome.storage.local, localStorage and IndexedDB survived every -restart and the reload after cancellation. Raw fixture evidence is under Cargo's -`target/popup-restart/1d9ce3c0-2699-49b9-9a24-6552c17fb3fc` (classic) and -`267197bc-83ea-4483-9d66-718d0eabdca5` (module). +restart and the reload after cancellation. Capacity and cancellation now use a +separate raw fixture with startup verification enabled but no startup signal, +forcing the pending state. An earlier capacity probe assumed every unclean +restart would stall; a post-merge run correctly started promptly and settled all +65 requests, exposing that test assumption rather than a capacity-limit failure. Raw fixture evidence is under Cargo's +`target/popup-restart/eb529596-f874-43f8-b5e0-32f4c659a3cd` (classic) and +`fdab5858-36b6-49c8-9404-f7c13cdb4bb9` (module). An existing disposable, unsigned-in 1Password 8.12.46.29 profile that previously had no worker-start trace now starts its module worker and responds to its native @@ -60,7 +64,23 @@ restart failure is not conclusively established. tests, including wrong-origin/registration refusal and activation waiting. - `cargo clippy -p zephium-webext-macos --all-targets --features lab --locked -- -D warnings`: passed. - `cargo test -p zephium-webext-macos --lib --locked`: 30 passed. -- Workspace/macOS CI results are recorded in the pull request after final checks. +- `cargo fmt --all -- --check`, workspace Clippy with both `--all-targets` and + `--lib`, and `-D warnings`: passed after merging main `5cf563fec`. +- `cargo nextest run --workspace --locked --profile ci --retries 2`: 6,472 passed, + 50 skipped. One existing trash-retention test was slow; the xtask test + `agent_controller_boundary::tests::mutation_cannot_bypass_action_authority_or_drop_pending_ownership` + passed with a nextest leaked-child report. Its focused rerun passed without + that report; the original result was not suppressed. +- `cargo test -p tauri-plugin-updater --lib --locked`: 17 passed. Generated IPC + bindings, work constants and theme presets show no drift. +- Engine floors, advisory exceptions, agentic probe boundaries, fork locks and + `cargo deny --locked check`: passed. Engine-floor checks emitted the existing + November 17 review-deadline warnings. Fork fetch/check commands ran at the + same commit in a temporary worktree outside the parent workspace, because the + nested worktree confuses Cargo's independent vendored workspace discovery. +- Native bundled seed compile/reload and admission self-test, blocker scriptlet + runtime checks and off-list corpus refusal checks: passed using the CI recipes. +- Hosted CI awaits GitHub workflow approval; no hosted result is claimed here. - Windows native execution and signed-in 1Password acceptance remain untested. This change is confined to the macOS adapter; Windows compilation is not a substitute for native acceptance. diff --git a/scripts/qualification/macos-popup-restart.mjs b/scripts/qualification/macos-popup-restart.mjs index 2e4ea92ed..2a5987e96 100644 --- a/scripts/qualification/macos-popup-restart.mjs +++ b/scripts/qualification/macos-popup-restart.mjs @@ -150,8 +150,15 @@ for (const kind of ["classic", "module"]) { // both shutdown modes; do not infer durability from the child exiting. if (phase !== "unclean-restart") await delay(5000); } - // The last restart leaves its context live again. Reopen that same profile - // to exercise single-flight recovery, the waiter bound, and unload cancellation. + // Force a missing startup signal in a separate profile: the raw fixture + // intentionally has no compatibility layer, while verification is enabled. + // This makes the waiting/capacity cases independent of WebKit's restart race. + const waiterProfile = randomUUID(); + const waiterLoad = { + load: fixture, + compat: false, + verify_background_start: true, + }; const waiterRuns = []; if (runs.length === 3 && runs.every((run) => run.passed)) { for (const cancel of [false, true]) { @@ -159,18 +166,19 @@ for (const kind of ["classic", "module"]) { const phase = cancel ? "cancel-waiters" : "concurrent-waiters"; const count = cancel ? 8 : 65; const scenario = join(output, `${phase}.json`); - const probeSteps = [steps[0], { background_waiters: count, cancel }]; + const probeSteps = [waiterLoad, { background_waiters: count, cancel }]; if (cancel) { // Reload the same extension immediately after cancellation. An old // callback must not settle the replacement context's readiness. - probeSteps.push(...steps); + probeSteps.push(waiterLoad, { background: true }); } + probeSteps.push(...steps.slice(2)); writeFileSync(scenario, JSON.stringify(probeSteps, null, 2)); const result = spawnSync(binary, [scenario], { cwd: root, env: { ...process.env, - LAB_PROFILE: profile, + LAB_PROFILE: waiterProfile, ZEPHIUM_WEBEXT_TRACE: "1", }, encoding: "utf8", @@ -200,11 +208,10 @@ for (const kind of ["classic", "module"]) { value?.settled === count && value.ok === (cancel ? 0 : 64) && value.errors === (cancel ? 8 : 1) && - (!cancel || - (popup?.popup?.status === "ready" && - popup.previous === marker && - popup.localPrevious === marker && - popup.indexedPrevious === marker)); + popup?.popup?.status === "ready" && + popup.previous === (cancel ? marker : null) && + popup.localPrevious === (cancel ? marker : null) && + popup.indexedPrevious === (cancel ? marker : null); waiterRuns.push({ phase, passed, @@ -220,7 +227,11 @@ for (const kind of ["classic", "module"]) { } writeFileSync( join(output, "results.json"), - JSON.stringify({ kind, profile, binary, runs, waiterRuns }, null, 2), + JSON.stringify( + { kind, profile, waiterProfile, binary, runs, waiterRuns }, + null, + 2, + ), ); console.log(`Evidence: ${output}`); outcomes.push( From 527aee4c25eb61077bf36d75e951b50dd562d9af Mon Sep 17 00:00:00 2001 From: crynta <3nnigma.dev@gmail.com> Date: Sun, 22 Nov 2026 20:45:08 +0100 Subject: [PATCH 4/5] fix(extensions): keep woken toolbar clicks and joined waiters on their context A toolbar click waits for the worker before running its action. If the extension was unloaded or reloaded meanwhile, the action ran on the replacement context and could leave the old popup anchor behind. The click now keeps the context it was made on and drops the action, and the anchor, when that context is no longer current. Settling a replaced attempt runs callers that may start a new attempt for the same view; wait now joins that attempt instead of overwriting it and dropping its waiters. --- crates/zephium-engine/src/host/webext.rs | 15 ++++++++++++-- crates/zephium-webext-macos/src/background.rs | 20 ++++++++++--------- 2 files changed, 24 insertions(+), 11 deletions(-) diff --git a/crates/zephium-engine/src/host/webext.rs b/crates/zephium-engine/src/host/webext.rs index 478f32445..2c78937a1 100644 --- a/crates/zephium-engine/src/host/webext.rs +++ b/crates/zephium-engine/src/host/webext.rs @@ -687,11 +687,11 @@ impl WebextHost { }; let extension_id = install.extension_id.clone(); let tab = entry.bridge.ids.borrow_mut().tab(request.tab()); - if runtime.context(&extension_id).is_none() { + let Some(clicked) = runtime.context(&extension_id) else { return ExtensionActionSettlement::Rejected( ExtensionActionRejection::RuntimeUnavailable, ); - } + }; if let Some(rows) = request.menu_rows() { let tab_object = runtime.tab_object(tab); // SAFETY: the context and tab object are live on the WebKit main thread. @@ -721,12 +721,23 @@ impl WebextHost { // WebKit drops what a popup sends while the worker sleeps, and the // popup then waits forever; wake it first (immediate when running). let waking = extension_id.clone(); + let clicked = objc2::rc::Weak::from_retained(&clicked); runtime.wake_then(&waking, move || { super::dispatch::best_effort_with(move |host| { if let Some(entry) = host.webext.profiles.get(&profile) { let Some(runtime) = &entry.runtime else { return; }; + // An unload or reload while the worker was waking leaves + // this click without the context it was made on. + let same = match (clicked.load(), runtime.context(&extension_id)) { + (Some(clicked), Some(current)) => std::ptr::eq(&*clicked, &*current), + _ => false, + }; + if !same { + entry.bridge.popup.borrow_mut().take(); + return; + } // Only a popup consumes the anchor; left behind, it would // retain the button and place a later action.openPopup // on it, perhaps in a window since closed. diff --git a/crates/zephium-webext-macos/src/background.rs b/crates/zephium-webext-macos/src/background.rs index 021068ae8..78f17f31c 100644 --- a/crates/zephium-webext-macos/src/background.rs +++ b/crates/zephium-webext-macos/src/background.rs @@ -123,20 +123,22 @@ pub(crate) fn wait(shared: &Rc, context: &WKWebExtensionContext, done: D return done(Err("The extension background view is unavailable.".into())); }; let previous = state.pending.borrow().clone(); - if let Some(previous) = previous { - if std::ptr::eq(&*previous.view, &*view) { - if previous.waiters.borrow().len() >= MAX_WAITERS { - return done(Err("Too many extension background requests.".into())); - } - previous.waiters.borrow_mut().push(done); - return; - } + if let Some(previous) = previous.filter(|previous| !std::ptr::eq(&*previous.view, &*view)) { previous.finish(Err("The extension background was replaced.".into())); } - // Settling an older attempt invokes callers, which may unload this context. + // Settling an older attempt invokes callers, which may unload this context + // or start an attempt for this view. if !state_for(shared, context).is_some_and(|current| Rc::ptr_eq(¤t, &state)) { return done(Err("The extension was unloaded.".into())); } + let pending = state.pending.borrow().clone(); + if let Some(pending) = pending.filter(|pending| std::ptr::eq(&*pending.view, &*view)) { + if pending.waiters.borrow().len() >= MAX_WAITERS { + return done(Err("Too many extension background requests.".into())); + } + pending.waiters.borrow_mut().push(done); + return; + } let ready = state .ready .borrow() From e1cf1f7a186b641b116760aa0176a51ef5f3766d Mon Sep 17 00:00:00 2001 From: crynta <3nnigma.dev@gmail.com> Date: Sun, 22 Nov 2026 20:57:15 +0100 Subject: [PATCH 5/5] fix(extensions): let a toolbar click clear only its own popup anchor The popup anchor is one slot per profile. A woken click that turned out stale, or whose action has no popup, cleared it unconditionally and could drop a newer click's anchor, so that click's popup never opened. Each click now records a number with its anchor and clears the slot only while no newer click has replaced it. --- crates/zephium-engine/src/host/webext.rs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/crates/zephium-engine/src/host/webext.rs b/crates/zephium-engine/src/host/webext.rs index 2c78937a1..e0ff0151e 100644 --- a/crates/zephium-engine/src/host/webext.rs +++ b/crates/zephium-engine/src/host/webext.rs @@ -189,6 +189,7 @@ impl WebextHost { pending_pages: RefCell::new(HashMap::new()), next_request: Cell::new(1), popup: RefCell::new(None), + popup_click: Cell::new(0), self_weak: RefCell::new(std::rc::Weak::new()), repeats: RefCell::new(HashMap::new()), access: RefCell::new(HashMap::new()), @@ -717,6 +718,8 @@ impl WebextHost { } return ExtensionActionSettlement::Dispatched; } + let click = entry.bridge.popup_click.get().wrapping_add(1); + entry.bridge.popup_click.set(click); *entry.bridge.popup.borrow_mut() = parent.map(|parent| (parent, request.anchor().rect())); // WebKit drops what a popup sends while the worker sleeps, and the // popup then waits forever; wake it first (immediate when running). @@ -728,6 +731,12 @@ impl WebextHost { let Some(runtime) = &entry.runtime else { return; }; + // A newer click owns the anchor once it has stored its own. + let release = || { + if entry.bridge.popup_click.get() == click { + entry.bridge.popup.borrow_mut().take(); + } + }; // An unload or reload while the worker was waking leaves // this click without the context it was made on. let same = match (clicked.load(), runtime.context(&extension_id)) { @@ -735,8 +744,7 @@ impl WebextHost { _ => false, }; if !same { - entry.bridge.popup.borrow_mut().take(); - return; + return release(); } // Only a popup consumes the anchor; left behind, it would // retain the button and place a later action.openPopup @@ -747,7 +755,7 @@ impl WebextHost { .and_then(|context| unsafe { context.actionForTab(tab_object.as_deref()) }) .is_some_and(|action| unsafe { action.presentsPopup() }); if !popup { - entry.bridge.popup.borrow_mut().take(); + release(); } runtime.perform_action(&extension_id, Some(tab)); } @@ -1212,6 +1220,8 @@ struct Bridge { pending_pages: RefCell>, next_request: Cell, popup: RefCell, Rect)>>, + /// The toolbar click that stored `popup`. + popup_click: Cell, self_weak: RefCell>, repeats: RefCell>, access: RefCell>,