From b3489e9473ff4c99db20fee993a051c6c8d368ca Mon Sep 17 00:00:00 2001 From: Makisuo Date: Sat, 14 Nov 2026 13:58:46 +0100 Subject: [PATCH 1/6] feat(native): push notifications on iOS The iOS app asks for notifications through the web app's own flow (alert, sound, badge; notify.rs moves into the library for macOS and iOS), registers with APNs once allowed and on every launch, and hands the token to the runtime, which registers it for the signed-in user (pushDevice.register) and forgets it on sign-out. A push shows nothing while the app is in front; a tap opens the app at the notification's hazel.path, a cold start's first page loads there. Becoming active clears the badge. The simulator embeds aps-environment development, a release is signed with production. Co-Authored-By: Claude Opus 5.5 --- apps/native/README.md | 22 ++ apps/native/host/Cargo.lock | 2 + apps/native/host/Cargo.toml | 13 +- apps/native/host/ios/Cargo.toml | 2 + apps/native/host/ios/build.rs | 5 +- apps/native/host/ios/src/bridge.rs | 49 +++- apps/native/host/ios/src/main.rs | 6 + apps/native/host/ios/src/push.rs | 224 +++++++++++++++++++ apps/native/host/src/lib.rs | 1 + apps/native/host/src/main.rs | 1 - apps/native/host/src/notify.rs | 63 ++++-- apps/native/host/src/runtime.rs | 5 +- apps/native/scripts/ios.ts | 34 ++- apps/native/src/config.ts | 6 + apps/native/src/ios.ts | 37 ++- apps/native/src/push.test.ts | 37 +++ apps/native/src/push.ts | 86 +++++++ apps/web-foldkit/src/app/auth.ts | 8 +- apps/web-foldkit/src/platform/push-device.ts | 30 +++ 19 files changed, 583 insertions(+), 48 deletions(-) create mode 100644 apps/native/host/ios/src/push.rs create mode 100644 apps/native/src/push.test.ts create mode 100644 apps/native/src/push.ts create mode 100644 apps/web-foldkit/src/platform/push-device.ts diff --git a/apps/native/README.md b/apps/native/README.md index 2d9c9251c..592604458 100644 --- a/apps/native/README.md +++ b/apps/native/README.md @@ -164,6 +164,28 @@ over its box. A finger on an inline page also reaches Rune's view, so a drag ove list and a long press opens the message's menu, while a tap presses what is under it in the page; a fullscreen page scrolls itself. +**Push notifications** (`host/ios/src/push.rs`, `src/push.ts`). The app asks for notifications +through the web app's own flow (`host/src/notify.rs`, as on the Mac; Settings > Notifications' +test asks offline, live asks at start), for alerts, sounds and the badge. Once allowed, and again +on every launch, it registers with APNs; the token goes to every runtime, which registers it for +the signed-in user (`pushDevice.register`, with the build's APNs environment and the bundle ID). +Signing in loads a fresh runtime, which registers it then; signing out forgets it first +(`web-foldkit/src/platform/push-device.ts`). Offline, nothing is registered. Winit runs +`UIApplicationMain` without an application delegate, so the app sets its own for APNs's two +answers. A push shows while the app is away and nothing while it is in front (the app shows its +own); a tap opens the app at its `hazel.path`, a cold start's first page loads there. Becoming +active clears the badge. The simulator's executable embeds `aps-environment` `development` +(`host/ios/build.rs`): an Apple-silicon simulator gets a real sandbox token. A release is signed +with `production`, which its provisioning profile must grant (the App ID's Push Notifications +capability; `scripts/ios.ts` stops otherwise). The log has each step (`[push] ...`: the +permission, the token's first 8 characters, the registration, a tap's path). To try it: + +```sh +xcrun simctl push sh.hazel.ios payload.json +# {"aps":{"alert":{"title":"Maki · #engineering","body":"Can you look at the deploy?"},"badge":3}, +# "hazel":{"path":"/hazel/chat/00000005-0000-4000-8000-000000000002"}} +``` + Not yet on iOS: updates. ### TestFlight diff --git a/apps/native/host/Cargo.lock b/apps/native/host/Cargo.lock index 53bfa1eef..990239370 100644 --- a/apps/native/host/Cargo.lock +++ b/apps/native/host/Cargo.lock @@ -1220,6 +1220,7 @@ dependencies = [ "objc2-foundation 0.3.2", "objc2-quartz-core 0.3.2", "objc2-ui-kit 0.3.2", + "objc2-user-notifications 0.3.2", "objc2-web-kit", "resvg", "rune", @@ -2351,6 +2352,7 @@ dependencies = [ "bitflags 2.13.2", "block2 0.6.2", "objc2 0.6.5", + "objc2-core-location 0.3.2", "objc2-foundation 0.3.2", ] diff --git a/apps/native/host/Cargo.toml b/apps/native/host/Cargo.toml index 31bfde7f4..b6714994f 100644 --- a/apps/native/host/Cargo.toml +++ b/apps/native/host/Cargo.toml @@ -46,12 +46,7 @@ objc2-web-kit = "0.3" objc2-quartz-core = "0.3" objc2-core-graphics = "0.3" objc2-core-foundation = "0.3" - -[target.'cfg(target_os = "ios")'.dependencies] -objc2-ui-kit = "0.3" - -[target.'cfg(target_os = "macos")'.dependencies] -objc2-app-kit = "0.3" +# System notifications (`src/notify.rs`): the web app's on macOS, the permission for pushes on iOS. objc2-user-notifications = { version = "0.3", default-features = false, features = [ "std", "UNUserNotificationCenter", @@ -62,6 +57,12 @@ objc2-user-notifications = { version = "0.3", default-features = false, features "block2", ] } +[target.'cfg(target_os = "ios")'.dependencies] +objc2-ui-kit = "0.3" + +[target.'cfg(target_os = "macos")'.dependencies] +objc2-app-kit = "0.3" + [profile.release] debug = false diff --git a/apps/native/host/ios/Cargo.toml b/apps/native/host/ios/Cargo.toml index d89040590..7dfd1a177 100644 --- a/apps/native/host/ios/Cargo.toml +++ b/apps/native/host/ios/Cargo.toml @@ -26,3 +26,5 @@ resvg = "0.45" objc2-quartz-core = "0.3" objc2-ui-kit = "0.3" objc2-web-kit = "0.3" +# Pushes: the notification center's delegate and the badge (`src/push.rs`). +objc2-user-notifications = "0.3" diff --git a/apps/native/host/ios/build.rs b/apps/native/host/ios/build.rs index 885fe10c7..5ffee0f7b 100644 --- a/apps/native/host/ios/build.rs +++ b/apps/native/host/ios/build.rs @@ -1,6 +1,7 @@ //! The simulator takes an app's entitlements from its executable (`__TEXT,__entitlements`), as //! Xcode's simulator builds embed them: the keychain (the sign-in vault) serves only an app with -//! an identifier and an access group. An ad-hoc signature carries none. +//! an identifier and an access group. An ad-hoc signature carries none. `aps-environment` lets it +//! register for pushes: an Apple-silicon simulator gets a sandbox (`development`) token. use std::path::PathBuf; /// The team prefix of an ad-hoc signed simulator build: any ten characters do. @@ -24,6 +25,8 @@ fn main() { application-identifier {id} + aps-environment + development keychain-access-groups {id} diff --git a/apps/native/host/ios/src/bridge.rs b/apps/native/host/ios/src/bridge.rs index 66124137c..69af8db8c 100644 --- a/apps/native/host/ios/src/bridge.rs +++ b/apps/native/host/ios/src/bridge.rs @@ -52,6 +52,34 @@ thread_local! { /// Where the last full page load went; a restart goes back there. static LAST_PATH: RefCell> = const { RefCell::new(None) }; static RESTARTS: RefCell = RefCell::new(Restarts::default()); + /// This device's push token (`push.rs`): every runtime hears it once its page is ready. + static PUSH_TOKEN: RefCell> = const { RefCell::new(None) }; + /// The path a notification's tap opens, until a runtime can take it. + static OPEN_PATH: RefCell> = const { RefCell::new(None) }; +} + +/// Whether the page loaded last can take lines and replies. +fn page_ready() -> bool { + EARLY.with_borrow(Option::is_none) +} + +/// This device's push token, for the runtime to register (`src/push.ts`): now, and again for +/// every runtime a page load starts (signing in loads one). +pub fn set_push_token(message: serde_json::Value) { + if page_ready() { + reply(&message); + } + PUSH_TOKEN.set(Some(message)); +} + +/// Opens the app at `path` (a notification's tap): the runtime follows it as a link once it is +/// up; a cold start from the tap loads its first page there. +pub fn open_path(path: String) { + if page_ready() { + reply(&serde_json::json!({ "openPath": path })); + } else { + OPEN_PATH.set(Some(path)); + } } /// Where the runtime's trees go: the running app. @@ -214,11 +242,13 @@ fn receive(line: &str) { Routed::Shell(ShellRequest::Update { .. } | ShellRequest::Relaunch { .. }) => { log("[host] updates are not on iOS"); } - // Not offered on iOS (no `HAZEL_NOTIFICATIONS`); a request still gets its answer. - Routed::Shell(ShellRequest::NotifyPermission { id, .. }) => { - outbox::write_line(shell::permission_reply(id, false)); + // The web app's notification flow: its permission is the one pushes need. + Routed::Shell(ShellRequest::NotifyPermission { id, request }) => { + hazel_native::notify::permission(id, request, crate::push::after_permission); + } + Routed::Shell(ShellRequest::Notify { title, body, group }) => { + hazel_native::notify::show(&title, &body, group.as_deref()); } - Routed::Shell(ShellRequest::Notify { .. }) => {} } } @@ -238,6 +268,12 @@ fn request(mtm: MainThreadMarker, body: &NSDictionary) { for text in EARLY.take().unwrap_or_default() { to_worker(&text); } + if let Some(token) = PUSH_TOKEN.with_borrow(Clone::clone) { + reply(&token); + } + if let Some(path) = OPEN_PATH.take() { + reply(&serde_json::json!({ "openPath": path })); + } } } else if let Some(line) = field("log") { log(&line); @@ -378,7 +414,10 @@ fn start() -> bool { } NAVIGATION.set(Some(navigation)); WEB.set(Some(web)); - load_page(mtm, None); + // A tap on a notification that launched the app: the first page opens where it leads. + let path = OPEN_PATH.take(); + load_page(mtm, path.as_deref()); + LAST_PATH.set(path); if let Some(handle) = HANDLE.get().map(|h| h.lock().unwrap().clone()) { crate::keyboard::observe(mtm, handle); } diff --git a/apps/native/host/ios/src/main.rs b/apps/native/host/ios/src/main.rs index 1a0eefdef..94acf7b60 100644 --- a/apps/native/host/ios/src/main.rs +++ b/apps/native/host/ios/src/main.rs @@ -15,6 +15,8 @@ mod menu_sheet; #[cfg(any(test, target_os = "ios"))] mod page; #[cfg(target_os = "ios")] +mod push; +#[cfg(target_os = "ios")] mod sign_in; #[cfg(target_os = "ios")] mod system; @@ -42,6 +44,10 @@ fn main() { // The UIKit views the app's `data-native` elements get, and HTML renders' web views, go // where their boxes were drawn, after every frame. islands::install(); + // Before the app runs, as Apple asks: a tap on a notification that launches it is heard. + if let Some(mtm) = objc2::MainThreadMarker::new() { + push::install(mtm); + } let app = App::new(spec) .font_smoothing(TEXT_SMOOTHING) .on_frame_drawn(|runtime| { diff --git a/apps/native/host/ios/src/push.rs b/apps/native/host/ios/src/push.rs new file mode 100644 index 000000000..3b8a70d33 --- /dev/null +++ b/apps/native/host/ios/src/push.rs @@ -0,0 +1,224 @@ +//! Push notifications on iOS. APNs hands the app a device token once the user allows +//! notifications (`hazel_native::notify::permission`, the web app's own flow); the runtime +//! registers it with the API (`pushDevice.register`, `src/push.ts`), whose pushes then show while +//! the app is away. A tap on one opens the app at the notification's `hazel.path`. +//! +//! Winit's iOS event loop runs `UIApplicationMain` without an application delegate, so the app +//! sets its own (`HazelAppDelegate`) for the two calls APNs makes, just before it registers. +use std::cell::{Cell, RefCell}; +use std::ptr::NonNull; + +use block2::{DynBlock, RcBlock}; +use dispatch2::DispatchQueue; +use objc2::rc::Retained; +use objc2::runtime::ProtocolObject; +use objc2::{MainThreadMarker, MainThreadOnly, define_class, msg_send}; +use objc2_foundation::{ + NSBundle, NSData, NSDictionary, NSError, NSNotification, NSNotificationCenter, NSObject, + NSObjectProtocol, NSOperationQueue, NSString, +}; +use objc2_ui_kit::{ + UIApplication, UIApplicationDelegate, UIApplicationDidBecomeActiveNotification, +}; +use objc2_user_notifications::{ + UNNotification, UNNotificationPresentationOptions, UNNotificationResponse, + UNNotificationSettings, UNPushNotificationTrigger, UNUserNotificationCenter, + UNUserNotificationCenterDelegate, +}; + +use crate::bridge::log; + +thread_local! { + static NOTIFICATIONS: RefCell>> = const { RefCell::new(None) }; + /// The application's delegate (UIKit holds it weakly). + static APP_DELEGATE: RefCell>> = const { RefCell::new(None) }; + /// The app has been active once: it checked whether it may register for pushes. + static LAUNCHED: Cell = const { Cell::new(false) }; +} + +/// Before the app runs: the notification center's delegate (Apple asks for it before launch +/// ends, so a tap that launched the app is heard), and what the app does each time it becomes +/// active. +pub fn install(mtm: MainThreadMarker) { + let delegate: Retained = { + let this = Notifications::alloc(mtm).set_ivars(()); + unsafe { msg_send![super(this), init] } + }; + UNUserNotificationCenter::currentNotificationCenter() + .setDelegate(Some(ProtocolObject::from_ref(&*delegate))); + NOTIFICATIONS.set(Some(delegate)); + + let block = RcBlock::new(|_: NonNull| became_active()); + // SAFETY: UIKit's constant; the center copies the block. + let token = unsafe { + NSNotificationCenter::defaultCenter().addObserverForName_object_queue_usingBlock( + Some(UIApplicationDidBecomeActiveNotification), + None, + Some(&NSOperationQueue::mainQueue()), + &block, + ) + }; + // The app observes for as long as it runs. + std::mem::forget(token); +} + +/// The app came to the front: what it showed as unread is about to be seen, so the badge goes. +/// The first time (the launch), an app the user allowed already registers again: the token can +/// change, and the API keeps the latest. +fn became_active() { + UNUserNotificationCenter::currentNotificationCenter() + .setBadgeCount_withCompletionHandler(0, None); + if LAUNCHED.replace(true) { + return; + } + let answered = RcBlock::new(|settings: NonNull| { + // SAFETY: the framework passes valid settings. + if hazel_native::notify::allowed(unsafe { settings.as_ref() }) { + after_permission(true); + } + }); + UNUserNotificationCenter::currentNotificationCenter() + .getNotificationSettingsWithCompletionHandler(&answered); +} + +/// The user's answer to the notification permission (or the settings it was read from): once +/// allowed, the app registers for pushes, on the main thread as UIKit asks. +pub fn after_permission(granted: bool) { + DispatchQueue::main().exec_async(move || { + log(&format!( + "[push] notification permission: {}", + if granted { "granted" } else { "not granted" } + )); + if !granted { + return; + } + let Some(mtm) = MainThreadMarker::new() else { + return; + }; + let app = UIApplication::sharedApplication(mtm); + APP_DELEGATE.with_borrow_mut(|held| { + if held.is_none() { + let delegate: Retained = { + let this = AppDelegate::alloc(mtm).set_ivars(()); + unsafe { msg_send![super(this), init] } + }; + // SAFETY: the delegate lives as long as the app (`APP_DELEGATE`). + unsafe { app.setDelegate(Some(ProtocolObject::from_ref(&*delegate))) }; + *held = Some(delegate); + } + }); + app.registerForRemoteNotifications(); + }); +} + +/// A device token as APNs's provider API takes it: lowercase hex. +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|byte| format!("{byte:02x}")).collect() +} + +/// The path a notification opens the app at: its `hazel.path`, an app path. +fn path_of(user_info: &NSDictionary) -> Option { + let hazel = user_info.objectForKey(&**NSString::from_str("hazel"))?; + let hazel = hazel.downcast::().ok()?; + let path = hazel.objectForKey(&**NSString::from_str("path"))?; + let path = path.downcast::().ok()?.to_string(); + path.starts_with('/').then_some(path) +} + +define_class!( + // SAFETY: NSObject has no subclassing requirements; the class does not implement `Drop`. + #[unsafe(super(NSObject))] + #[thread_kind = MainThreadOnly] + #[name = "HazelAppDelegate"] + /// Hears APNs's answer to the app's registration. + struct AppDelegate; + + unsafe impl NSObjectProtocol for AppDelegate {} + + unsafe impl UIApplicationDelegate for AppDelegate { + #[unsafe(method(application:didRegisterForRemoteNotificationsWithDeviceToken:))] + fn registered(&self, _app: &UIApplication, token: &NSData) { + let token = hex(&token.to_vec()); + let bundle_id = NSBundle::mainBundle() + .bundleIdentifier() + .map(|id| id.to_string()) + .unwrap_or_default(); + log(&format!( + "[push] device token {}… for {bundle_id}", + &token[..token.len().min(8)] + )); + crate::bridge::set_push_token(serde_json::json!({ + "pushToken": token, + "bundleId": bundle_id, + })); + } + + #[unsafe(method(application:didFailToRegisterForRemoteNotificationsWithError:))] + fn failed(&self, _app: &UIApplication, error: &NSError) { + log(&format!( + "[push] could not register for pushes: {} ({} {})", + error.localizedDescription(), + error.domain(), + error.code() + )); + } + } +); + +define_class!( + // SAFETY: NSObject has no subclassing requirements; the class does not implement `Drop`. + #[unsafe(super(NSObject))] + #[thread_kind = MainThreadOnly] + #[name = "HazelNotifications"] + /// The notification center's delegate: what shows while the app is in front, and taps. + struct Notifications; + + unsafe impl NSObjectProtocol for Notifications {} + + unsafe impl UNUserNotificationCenterDelegate for Notifications { + /// A push while the app is in front shows nothing: the app shows its own in-app + /// notification. The web app's own (Settings' test notification) still shows. + #[unsafe(method(userNotificationCenter:willPresentNotification:withCompletionHandler:))] + fn will_present( + &self, + _center: &UNUserNotificationCenter, + notification: &UNNotification, + completion: &DynBlock, + ) { + let pushed = notification.request().trigger().is_some_and(|trigger| { + trigger + .downcast_ref::() + .is_some() + }); + if pushed { + log("[push] a push arrived while the app is in front: not shown"); + } + completion.call((if pushed { + UNNotificationPresentationOptions::empty() + } else { + UNNotificationPresentationOptions::Banner + | UNNotificationPresentationOptions::List + | UNNotificationPresentationOptions::Sound + },)); + } + + /// A tap on a notification: the app opens at its path, once the runtime can take it. + #[unsafe(method(userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:))] + fn did_receive( + &self, + _center: &UNUserNotificationCenter, + response: &UNNotificationResponse, + completion: &DynBlock, + ) { + let user_info = response.notification().request().content().userInfo(); + match path_of(&user_info) { + Some(path) => { + log(&format!("[push] opened from a notification: {path}")); + crate::bridge::open_path(path); + } + None => log("[push] opened from a notification without a path"), + } + completion.call(()); + } + } +); diff --git a/apps/native/host/src/lib.rs b/apps/native/host/src/lib.rs index bd4acc405..27c1ed8de 100644 --- a/apps/native/host/src/lib.rs +++ b/apps/native/host/src/lib.rs @@ -9,6 +9,7 @@ pub mod images; pub mod islands; pub mod layout; mod margins; +pub mod notify; pub mod outbox; mod render; pub mod shell; diff --git a/apps/native/host/src/main.rs b/apps/native/host/src/main.rs index c281902e5..2d9d0e628 100644 --- a/apps/native/host/src/main.rs +++ b/apps/native/host/src/main.rs @@ -1,7 +1,6 @@ //! Hazel's native window on macOS: runs Hazel's Foldkit app in a Bun child process and draws the //! tree it renders (`hazel_native`), sending presses, edits and the window's size and theme back. mod capture; -mod notify; mod platform; mod runtime; mod updater; diff --git a/apps/native/host/src/notify.rs b/apps/native/host/src/notify.rs index e9612b1ac..c7103f861 100644 --- a/apps/native/host/src/notify.rs +++ b/apps/native/host/src/notify.rs @@ -1,26 +1,27 @@ //! System notifications through UserNotifications, for the web app's own notification flow -//! (`core/lib/native-notifications.ts`, over `desktop-bridge.ts`'s `notification`). macOS only -//! shows them for an app it knows by its bundle identifier, so a host run from source (no bundle) -//! offers none: the runtime then sees no notification API, as a browser without one. -//! Windows and Linux have none yet (`available` is false), so the runtime offers none. -#[cfg(target_os = "macos")] -pub use mac::{available, permission, show}; +//! (`core/lib/native-notifications.ts`, over `desktop-bridge.ts`'s `notification`), on macOS and +//! iOS. The system only shows them for an app it knows by its bundle identifier, so a macOS host +//! run from source (no bundle) offers none: the runtime then sees no notification API, as a +//! browser without one. On iOS the permission also covers the app's badge, and pushes are the +//! real channel (`host/ios/src/push.rs`). Windows and Linux have none yet (`available` is false). +#[cfg(target_vendor = "apple")] +pub use apple::{allowed, available, permission, show}; -#[cfg(not(target_os = "macos"))] +#[cfg(not(target_vendor = "apple"))] pub fn available() -> bool { false } -#[cfg(not(target_os = "macos"))] -pub fn permission(id: u64, _request: bool) { - hazel_native::outbox::write_line(hazel_native::shell::permission_reply(id, false)); +#[cfg(not(target_vendor = "apple"))] +pub fn permission(id: u64, _request: bool, _then: fn(bool)) { + crate::outbox::write_line(crate::shell::permission_reply(id, false)); } -#[cfg(not(target_os = "macos"))] +#[cfg(not(target_vendor = "apple"))] pub fn show(_title: &str, _body: &str, _group: Option<&str>) {} -#[cfg(target_os = "macos")] -mod mac { +#[cfg(target_vendor = "apple")] +mod apple { use block2::RcBlock; use objc2::runtime::Bool; use objc2_foundation::{NSBundle, NSError, NSString}; @@ -31,8 +32,18 @@ mod mac { use std::ptr::NonNull; use std::sync::atomic::{AtomicU64, Ordering}; - use hazel_native::outbox::write_line; - use hazel_native::shell::permission_reply; + use crate::outbox::write_line; + use crate::shell::permission_reply; + + /// What the app asks to do: a phone's notifications also set the app's badge. + fn options() -> UNAuthorizationOptions { + let options = UNAuthorizationOptions::Alert | UNAuthorizationOptions::Sound; + if cfg!(target_os = "ios") { + options | UNAuthorizationOptions::Badge + } else { + options + } + } /// Whether this process can show notifications: it runs from a bundle with an identifier. /// (Asking for the notification center without one raises an Objective-C exception.) @@ -41,8 +52,9 @@ mod mac { } /// Answers permission request `id`: whether notifications are allowed, asking the user first - /// when `request` is set and they have not decided yet. - pub fn permission(id: u64, request: bool) { + /// when `request` is set and they have not decided yet. `then` hears the answer too, on the + /// framework's queue (iOS registers for pushes once allowed). + pub fn permission(id: u64, request: bool, then: fn(bool)) { if !available() { return write_line(permission_reply(id, false)); } @@ -57,23 +69,26 @@ mod mac { ); } write_line(permission_reply(id, granted.as_bool())); + then(granted.as_bool()); }); - center.requestAuthorizationWithOptions_completionHandler( - UNAuthorizationOptions::Alert | UNAuthorizationOptions::Sound, - &answered, - ); + center.requestAuthorizationWithOptions_completionHandler(options(), &answered); } else { let answered = RcBlock::new(move |settings: NonNull| { // SAFETY: the framework passes valid settings. - let status = unsafe { settings.as_ref() }.authorizationStatus(); - let granted = status == UNAuthorizationStatus::Authorized - || status == UNAuthorizationStatus::Provisional; + let granted = allowed(unsafe { settings.as_ref() }); write_line(permission_reply(id, granted)); + then(granted); }); center.getNotificationSettingsWithCompletionHandler(&answered); } } + /// Whether `settings` let the app notify (provisional delivery counts). + pub fn allowed(settings: &UNNotificationSettings) -> bool { + let status = settings.authorizationStatus(); + status == UNAuthorizationStatus::Authorized || status == UNAuthorizationStatus::Provisional + } + /// Shows a notification now; `group` threads a channel's notifications together. pub fn show(title: &str, body: &str, group: Option<&str>) { if !available() { diff --git a/apps/native/host/src/runtime.rs b/apps/native/host/src/runtime.rs index 1abffcfff..48baf96a9 100644 --- a/apps/native/host/src/runtime.rs +++ b/apps/native/host/src/runtime.rs @@ -11,7 +11,8 @@ use hazel_native::outbox::{self, write_line}; use hazel_native::shell::{self, Restarts, Routed, ShellRequest}; use hazel_native::wire::RuntimeMsg; -use crate::{notify, platform, updater}; +use crate::{platform, updater}; +use hazel_native::notify; /// What the window hears from the runtime. // One message at a time, as `RuntimeMsg` itself; boxing the tree would only add an allocation. @@ -143,7 +144,7 @@ pub fn spawn_runtime() -> Result<(RuntimeChild, Receiver), String> } Routed::Shell(ShellRequest::Update { id, op }) => updater::answer(id, op), Routed::Shell(ShellRequest::NotifyPermission { id, request }) => { - notify::permission(id, request) + notify::permission(id, request, |_| {}) } Routed::Shell(ShellRequest::Notify { title, body, group }) => { notify::show(&title, &body, group.as_deref()) diff --git a/apps/native/scripts/ios.ts b/apps/native/scripts/ios.ts index 1fa1b9785..0a3ceb158 100644 --- a/apps/native/scripts/ios.ts +++ b/apps/native/scripts/ios.ts @@ -24,6 +24,12 @@ const app = `${out}/Hazel.app` // The simulator's executable carries its entitlements for this ID (`host/ios/build.rs`). const bundleId = release ? process.env.HAZEL_IOS_BUNDLE_ID || "hazel.app" : "sh.hazel.ios" const minimumOS = "17.0" +/** + * The APNs host this build's device tokens belong to: the simulator's executable embeds + * `development` (`host/ios/build.rs`), a release is signed with `production`. The runtime sends it + * with the token (`src/push.ts`). + */ +const apsEnvironment = release ? "production" : "development" const run = (command: string, args: Array, options: { cwd?: string; env?: NodeJS.ProcessEnv } = {}) => execFileSync(command, args, { cwd: options.cwd ?? root, stdio: "inherit", env: options.env }) @@ -47,8 +53,11 @@ cpSync(`${root}host/target/${target}/release/hazel-ios`, `${app}/hazel-ios`) cpSync(`${out}/runtime.js`, `${app}/runtime.js`) // What the runtime reads from `process.env`. A simulator build is offline unless `HAZEL_DATA=live` // was set when building; a release build is live against production (`scripts/bundle.ts`'s origins). +// Both offer the app's notifications (the permission pushes need) and name their APNs host. +const platformEnvironment = { HAZEL_NOTIFICATIONS: "1", HAZEL_APNS_ENV: apsEnvironment } const environment: Record = release ? { + ...platformEnvironment, HAZEL_DATA: "live", VITE_BACKEND_URL: process.env.HAZEL_BACKEND_URL || "https://api.hazel.sh", VITE_APP_URL: process.env.HAZEL_APP_URL || "https://app.hazel.sh", @@ -64,10 +73,12 @@ const environment: Record = release "NATIVE_PATH", "HAZEL_ISLANDS", "HAZEL_FIXTURE_HTML", - ].flatMap((name) => { - const value = process.env[name] - return value === undefined ? [] : [[name, value]] - }), + ] + .flatMap((name) => { + const value = process.env[name] + return value === undefined ? [] : [[name, value]] + }) + .concat(Object.entries(platformEnvironment)), ) writeFileSync(`${app}/environment.json`, JSON.stringify(environment)) cpSync(`${root}../web-foldkit/public`, `${app}/public`, { recursive: true }) @@ -182,6 +193,20 @@ const team = read("plutil", ["-extract", "TeamIdentifier.0", "raw", "-o", "-", d const granted = read("plutil", ["-extract", "Entitlements.application-identifier", "raw", "-o", "-", decoded]) const appId = `${team}.${bundleId}` if (granted !== appId) throw new Error(`HAZEL_IOS_PROFILE is for ${granted}, not ${appId}`) +// Pushes need the profile to grant them (the App ID's Push Notifications capability); a build +// signed without the grant installs, but APNs never hands it a token. +const grantedAps = (() => { + try { + return read("plutil", ["-extract", "Entitlements.aps-environment", "raw", "-o", "-", decoded]) + } catch { + return undefined + } +})() +if (grantedAps !== apsEnvironment) + throw new Error( + `HAZEL_IOS_PROFILE grants aps-environment ${grantedAps ?? "(none)"}, not ${apsEnvironment}: ` + + "enable Push Notifications for the App ID and download the profile again", + ) const entitlements = `${out}/build/entitlements.plist` writeFileSync( `${out}/build/entitlements.json`, @@ -189,6 +214,7 @@ writeFileSync( "application-identifier": appId, "com.apple.developer.team-identifier": team, "keychain-access-groups": [appId], + "aps-environment": apsEnvironment, "get-task-allow": false, "beta-reports-active": true, }), diff --git a/apps/native/src/config.ts b/apps/native/src/config.ts index 34a791c37..11d29f18d 100644 --- a/apps/native/src/config.ts +++ b/apps/native/src/config.ts @@ -27,6 +27,8 @@ export type RuntimeConfig = { readonly version: string | undefined /** The host can show system notifications (a bundle the system knows by its identifier). */ readonly notifications: boolean + /** The APNs host this build's push tokens belong to (iOS, `HAZEL_APNS_ENV`, set when building). */ + readonly apnsEnvironment: "development" | "production" | undefined /** `HAZEL_DEV=1` keeps the web app's dev build (its debug pages). */ readonly dev: boolean /** `NATIVE_DEBUG`: log every Message, link, edit and offline request. */ @@ -74,6 +76,10 @@ export const readConfig = (env: Env): RuntimeConfig => { updates: env.HAZEL_UPDATES === "1", version: env.HAZEL_APP_VERSION || undefined, notifications: env.HAZEL_NOTIFICATIONS === "1", + apnsEnvironment: + env.HAZEL_APNS_ENV === "development" || env.HAZEL_APNS_ENV === "production" + ? env.HAZEL_APNS_ENV + : undefined, dev: env.HAZEL_DEV === "1", debug: Boolean(env.NATIVE_DEBUG), statsPath: env.NATIVE_STATS || undefined, diff --git a/apps/native/src/ios.ts b/apps/native/src/ios.ts index 77d9be2db..d6aea7145 100644 --- a/apps/native/src/ios.ts +++ b/apps/native/src/ios.ts @@ -6,8 +6,11 @@ import { nativeClient, nativeHeaders } from "@hazel/auth/contract" import type { PrecompiledStyles } from "@hazel/foldkit-rune" import { parseHostLine } from "@hazel/foldkit-rune" +import { PUSH_DEVICE_GLOBAL, type PushDevice } from "../../web-foldkit/src/platform/push-device" import { SYSTEM_UI_GLOBAL, type SystemUi } from "../../web-foldkit/src/platform/system-ui" +import { readConfig } from "./config" import type { NativePlatform } from "./platform" +import { makePushDevice, type PushToken } from "./push" /** What the page set before this worker's source: the host's environment. */ declare const __HAZEL_ENV__: Record @@ -53,6 +56,16 @@ let deliver: ((line: string) => void) | undefined const replies = new Map void>() /** The edge swipe went back. */ type BackReply = { readonly back: true } +/** A notification's tap opens the app at this path (`host/ios/src/push.rs`). */ +type OpenPathReply = { readonly openPath: string } +/** What the host hands the worker that is not a line or a fetch's answer. */ +type HostReply = BackReply | PushToken | OpenPathReply +/** What waits for the runtime to start: the push token, a notification's path. */ +const afterStart: Array<() => void> = [] +let isRuntimeStarted = false +const whenStarted = (run: () => void) => (isRuntimeStarted ? run() : afterStart.push(run)) +/** Set below, once `log` exists. */ +let push: ReturnType | undefined /** The back chevrons on screen, latest last: the swipe goes where the latest leads. */ const backTargets: Array<{ readonly href: string }> = [] /** A URL's path, query and hash: what the host keys its pictures of pages by. */ @@ -66,9 +79,19 @@ const goBack = () => { // The runtime's link handling, as a tap on the chevron would follow it. void import("./document-bridge").then(({ followLink }) => followLink(target.href)) } -globalThis.onmessage = (event: MessageEvent) => { +const isHostReply = (data: FetchReply | HostReply): data is HostReply => !("id" in data) +const hostReply = (reply: HostReply) => { + if ("back" in reply) goBack() + else if ("pushToken" in reply) whenStarted(() => void push?.register(reply)) + else + whenStarted(() => { + log(`[push] opening ${reply.openPath}`) + void import("./document-bridge").then(({ followLink }) => followLink(reply.openPath)) + }) +} +globalThis.onmessage = (event: MessageEvent) => { const data = event.data - if (typeof data !== "string" && "back" in data) goBack() + if (typeof data !== "string" && isHostReply(data)) hostReply(data) else if (typeof data !== "string") { replies.get(data.id)?.(data) replies.delete(data.id) @@ -181,8 +204,14 @@ const systemUi: SystemUi = { }, } -// Read by the app (`platform/system-ui.ts`), as the desktop shells install `window.__TAURI__`. -Object.assign(globalThis, { [SYSTEM_UI_GLOBAL]: systemUi }) +push = makePushDevice({ config: readConfig(process.env), log }) +const pushDevice: PushDevice = { unregister: () => push?.unregister() ?? Promise.resolve() } + +// Read by the app (`platform/system-ui.ts`, `platform/push-device.ts`), as the desktop shells +// install `window.__TAURI__`. +Object.assign(globalThis, { [SYSTEM_UI_GLOBAL]: systemUi, [PUSH_DEVICE_GLOBAL]: pushDevice }) const { startRuntime } = await import("./runtime") await startRuntime(platform) +isRuntimeStarted = true +for (const run of afterStart.splice(0)) run() diff --git a/apps/native/src/push.test.ts b/apps/native/src/push.test.ts new file mode 100644 index 000000000..c42c4c2f0 --- /dev/null +++ b/apps/native/src/push.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from "vitest" + +import { readConfig } from "./config" +import { makePushDevice } from "./push" + +const token = "0a1b2c3d4e5f60718293a4b5c6d7e8f9" + +const makeDevice = (env: Record) => { + const lines: Array = [] + const device = makePushDevice({ config: readConfig(env), log: (line) => lines.push(line) }) + return { device, lines } +} + +describe("push device", () => { + it("registers nothing offline, and logs only the token's start", async () => { + const { device, lines } = makeDevice({ HAZEL_APNS_ENV: "development" }) + await device.register({ pushToken: token, bundleId: "sh.hazel.ios" }) + expect(lines).toEqual(["[push] offline: not registering 0a1b2c3d…"]) + }) + + it("registers nothing for a build that names no APNs environment", async () => { + const { device, lines } = makeDevice({ HAZEL_DATA: "live", HAZEL_SESSION_TOKEN: "t" }) + await device.register({ pushToken: token, bundleId: "hazel.app" }) + expect(lines).toEqual(["[push] this build names no APNs environment: not registering"]) + }) + + it("has nothing to forget before a token was registered", async () => { + const { device, lines } = makeDevice({ HAZEL_DATA: "live", HAZEL_APNS_ENV: "production" }) + await device.unregister() + expect(lines).toEqual([]) + }) + + it("reads the build's APNs environment, and nothing else", () => { + expect(readConfig({ HAZEL_APNS_ENV: "production" }).apnsEnvironment).toBe("production") + expect(readConfig({ HAZEL_APNS_ENV: "staging" }).apnsEnvironment).toBeUndefined() + }) +}) diff --git a/apps/native/src/push.ts b/apps/native/src/push.ts new file mode 100644 index 000000000..0c66dee80 --- /dev/null +++ b/apps/native/src/push.ts @@ -0,0 +1,86 @@ +/** + * Push notifications (iOS): the host hands every runtime this device's APNs token once the user + * allows notifications (`host/ios/src/push.rs`), and the runtime registers it with the API for the + * signed-in user (`pushDevice.register`), whose pushes then reach the phone. Signing in loads a + * fresh runtime, which hears the token again; signing out forgets it first + * (`web-foldkit/src/platform/push-device.ts`). Offline, nothing is registered. + */ +import type { RuntimeConfig } from "./config" + +/** The host's token, as `push.rs` hands it over. */ +export type PushToken = { readonly pushToken: string; readonly bundleId: string } + +/** The API calls this module makes. */ +type Call = + | { + readonly rpc: "pushDevice.register" + readonly payload: { + readonly token: string + readonly environment: "development" | "production" + readonly bundleId: string + } + } + | { readonly rpc: "pushDevice.unregister"; readonly payload: { readonly token: string } } + +/** A token for the log: its first 8 characters only. */ +const short = (token: string) => `${token.slice(0, 8)}…` + +const describe = (error: unknown) => + error instanceof Error ? `${error.name}: ${error.message}` : String(error) + +export const makePushDevice = (options: { + readonly config: Pick + readonly log: (line: string) => void +}) => { + const { config, log } = options + /** The token the API has for this user, once registered. */ + let registered: string | undefined + + /** Makes `call` when a session is signed in; `false` when none is. */ + const withSession = async (call: Call): Promise => { + const { Effect } = await import("effect") + const { sessionAuthorizationEffect } = await import("../../web-foldkit/src/core/lib/session-bearer") + const { HazelRpc, HazelRpcLive } = await import("../../web-foldkit/src/rpc") + const program = Effect.gen(function* () { + if ((yield* sessionAuthorizationEffect) === null) return false + const client = yield* HazelRpc + if (call.rpc === "pushDevice.register") yield* client(call.rpc, call.payload) + else yield* client(call.rpc, call.payload) + return true + }).pipe(Effect.provide(HazelRpcLive)) + return Effect.runPromise(program) + } + + const register = async ({ pushToken, bundleId }: PushToken): Promise => { + if (config.dataMode !== "live") return log(`[push] offline: not registering ${short(pushToken)}`) + const environment = config.apnsEnvironment + if (environment === undefined) + return log("[push] this build names no APNs environment: not registering") + try { + const signedIn = await withSession({ + rpc: "pushDevice.register", + payload: { token: pushToken, environment, bundleId }, + }) + if (!signedIn) return log(`[push] signed out: not registering ${short(pushToken)}`) + registered = pushToken + log(`[push] registered ${short(pushToken)} (${environment}, ${bundleId})`) + } catch (error) { + log(`[push] register failed: ${describe(error)}`) + } + } + + /** Forgets the registered token (sign-out); never rejects. */ + const unregister = async (): Promise => { + const token = registered + if (token === undefined) return + try { + await withSession({ rpc: "pushDevice.unregister", payload: { token } }) + registered = undefined + log(`[push] unregistered ${short(token)}`) + } catch (error) { + log(`[push] unregister failed: ${describe(error)}`) + } + } + + return { register, unregister } +} diff --git a/apps/web-foldkit/src/app/auth.ts b/apps/web-foldkit/src/app/auth.ts index e5964fa5f..20e4b3903 100644 --- a/apps/web-foldkit/src/app/auth.ts +++ b/apps/web-foldkit/src/app/auth.ts @@ -5,6 +5,7 @@ import { CommonReason, reasonOfUnknown } from "~/lib/error-messages" import { HazelAuthClient } from "../auth/client" import { desktopAuthClient } from "../platform/desktop" import { runDesktopAuth } from "../platform/desktop-auth" +import { unregisterPushDevice } from "../platform/push-device" import type { SessionAnswer } from "./message" /** @@ -54,8 +55,13 @@ export class SignOutError extends Schema.TaggedError()("SignOutErr reason: CommonReason, }) {} -/** Ends the session on the API, closes every sync connection and drops the cached access token. */ +/** + * Forgets this device's push token, ends the session on the API, closes every sync connection and + * drops the cached access token. + */ export const signOut: Effect.Effect = Effect.gen(function* () { + // The phone stops getting this user's pushes; the session still says whose device it is. + yield* unregisterPushDevice if (desktopAuthClient !== null) { // Ends only the desktop app's session; the browser it signed in with stays signed in. yield* runDesktopAuth((auth) => auth.signOut) diff --git a/apps/web-foldkit/src/platform/push-device.ts b/apps/web-foldkit/src/platform/push-device.ts new file mode 100644 index 000000000..b58e0d830 --- /dev/null +++ b/apps/web-foldkit/src/platform/push-device.ts @@ -0,0 +1,30 @@ +import { Effect } from "effect" + +/** + * This device's push registration, where the app runs in a shell that has one: the iOS app + * (`apps/native/src/push.ts`) registers its APNs token with the API itself, and installs this on + * the global object before the app starts, as it installs `system-ui.ts`'s controls. Sign-out + * forgets the device first, while the session can still say whose it is. A browser has none. + */ +export type PushDevice = Readonly<{ + /** Forgets this device's token on the API (`pushDevice.unregister`); never rejects. */ + unregister: () => Promise +}> + +/** The global a shell installs its push registration as. */ +export const PUSH_DEVICE_GLOBAL = "__HAZEL_PUSH_DEVICE__" + +type PushDeviceGlobal = typeof globalThis & { [PUSH_DEVICE_GLOBAL]?: PushDevice } + +/** How long sign-out waits for the API to forget the device. */ +const UNREGISTER_TIMEOUT = "3 seconds" + +/** Forgets this device's push token before signing out; a browser, or a failure, does nothing. */ +export const unregisterPushDevice: Effect.Effect = Effect.suspend(() => { + const device = (globalThis as PushDeviceGlobal)[PUSH_DEVICE_GLOBAL] + if (device === undefined) return Effect.void + return Effect.tryPromise(() => device.unregister()).pipe( + Effect.timeout(UNREGISTER_TIMEOUT), + Effect.ignore, + ) +}) From 4bc9c739eede129910ceefd2691cee6ffa5c3927 Mon Sep 17 00:00:00 2001 From: Makisuo Date: Sat, 14 Nov 2026 14:13:50 +0100 Subject: [PATCH 2/6] fix(native): iOS push review fixes - A notification opens only the app's own paths: `shell::app_path` refuses `//host`, any backslash and control characters (unit tested), and the runtime checks the path resolves to the page's origin before following it. - Sign-out forgets the token the host sent last, after a registration still on its way. - A failed registration is retried with backoff (1 to 16 seconds, 5 times), but not when signed out. - A tap's path is held until the runtime says it followed it; a page whose process ended first restarts at it. - The app registers with APNs on every activation, so notifications turned on in iOS Settings start when the user comes back; the same token reaches the runtime, and the API, once. - The notification center's callbacks hand their work to the main queue. Co-Authored-By: Claude Opus 5.5 --- apps/native/host/ios/src/bridge.rs | 33 ++++++--- apps/native/host/ios/src/push.rs | 84 +++++++++++----------- apps/native/host/src/shell.rs | 38 ++++++++++ apps/native/src/ios.ts | 20 ++++-- apps/native/src/push.test.ts | 89 +++++++++++++++++++++--- apps/native/src/push.ts | 108 +++++++++++++++++++++-------- 6 files changed, 281 insertions(+), 91 deletions(-) diff --git a/apps/native/host/ios/src/bridge.rs b/apps/native/host/ios/src/bridge.rs index 69af8db8c..1a36cb051 100644 --- a/apps/native/host/ios/src/bridge.rs +++ b/apps/native/host/ios/src/bridge.rs @@ -54,7 +54,8 @@ thread_local! { static RESTARTS: RefCell = RefCell::new(Restarts::default()); /// This device's push token (`push.rs`): every runtime hears it once its page is ready. static PUSH_TOKEN: RefCell> = const { RefCell::new(None) }; - /// The path a notification's tap opens, until a runtime can take it. + /// The path a notification's tap opens, until a runtime says it followed it (`openedPath`): + /// a page that ends before then (WebKit ended its process in the background) gets it again. static OPEN_PATH: RefCell> = const { RefCell::new(None) }; } @@ -64,22 +65,27 @@ fn page_ready() -> bool { } /// This device's push token, for the runtime to register (`src/push.ts`): now, and again for -/// every runtime a page load starts (signing in loads one). -pub fn set_push_token(message: serde_json::Value) { +/// every runtime a page load starts (signing in loads one). The same token again (APNs answers +/// every activation) goes nowhere; false then. +pub fn set_push_token(message: serde_json::Value) -> bool { + if PUSH_TOKEN.with_borrow(|held| held.as_ref() == Some(&message)) { + return false; + } if page_ready() { reply(&message); } PUSH_TOKEN.set(Some(message)); + true } /// Opens the app at `path` (a notification's tap): the runtime follows it as a link once it is -/// up; a cold start from the tap loads its first page there. +/// up, and the path is held until it says so; a cold start from the tap loads its first page +/// there. pub fn open_path(path: String) { if page_ready() { reply(&serde_json::json!({ "openPath": path })); - } else { - OPEN_PATH.set(Some(path)); } + OPEN_PATH.set(Some(path)); } /// Where the runtime's trees go: the running app. @@ -271,10 +277,17 @@ fn request(mtm: MainThreadMarker, body: &NSDictionary) { if let Some(token) = PUSH_TOKEN.with_borrow(Clone::clone) { reply(&token); } - if let Some(path) = OPEN_PATH.take() { + if let Some(path) = OPEN_PATH.with_borrow(Clone::clone) { reply(&serde_json::json!({ "openPath": path })); } } + } else if let Some(path) = field("openedPath") { + // The runtime followed the tap's path: a page that ends from now on need not. + OPEN_PATH.with_borrow_mut(|held| { + if held.as_deref() == Some(path.as_str()) { + *held = None; + } + }); } else if let Some(line) = field("log") { log(&line); } else if let (Some(url), Some(scheme)) = (field("signIn"), field("callbackScheme")) { @@ -347,7 +360,11 @@ define_class!( return log("[host] the page's process keeps ending; not starting it again"); } log("[host] the page's process ended; starting the runtime again"); - let path = LAST_PATH.with_borrow(Clone::clone); + // A tap the old runtime never followed (the process ended first) leads instead. + let path = OPEN_PATH.take().or_else(|| LAST_PATH.with_borrow(Clone::clone)); + if path.is_some() { + LAST_PATH.set(path.clone()); + } load_page(self.mtm(), path.as_deref()); } } diff --git a/apps/native/host/ios/src/push.rs b/apps/native/host/ios/src/push.rs index 3b8a70d33..8d68d68f2 100644 --- a/apps/native/host/ios/src/push.rs +++ b/apps/native/host/ios/src/push.rs @@ -5,7 +5,7 @@ //! //! Winit's iOS event loop runs `UIApplicationMain` without an application delegate, so the app //! sets its own (`HazelAppDelegate`) for the two calls APNs makes, just before it registers. -use std::cell::{Cell, RefCell}; +use std::cell::RefCell; use std::ptr::NonNull; use block2::{DynBlock, RcBlock}; @@ -32,8 +32,6 @@ thread_local! { static NOTIFICATIONS: RefCell>> = const { RefCell::new(None) }; /// The application's delegate (UIKit holds it weakly). static APP_DELEGATE: RefCell>> = const { RefCell::new(None) }; - /// The app has been active once: it checked whether it may register for pushes. - static LAUNCHED: Cell = const { Cell::new(false) }; } /// Before the app runs: the notification center's delegate (Apple asks for it before launch @@ -63,18 +61,16 @@ pub fn install(mtm: MainThreadMarker) { } /// The app came to the front: what it showed as unread is about to be seen, so the badge goes. -/// The first time (the launch), an app the user allowed already registers again: the token can -/// change, and the API keeps the latest. +/// An app the user allows registers again each time: the token can change, and notifications +/// the user turned on in iOS Settings meanwhile start now (the same token reaches the runtime +/// once, `bridge::set_push_token`). fn became_active() { UNUserNotificationCenter::currentNotificationCenter() .setBadgeCount_withCompletionHandler(0, None); - if LAUNCHED.replace(true) { - return; - } let answered = RcBlock::new(|settings: NonNull| { // SAFETY: the framework passes valid settings. if hazel_native::notify::allowed(unsafe { settings.as_ref() }) { - after_permission(true); + DispatchQueue::main().exec_async(register_for_pushes); } }); UNUserNotificationCenter::currentNotificationCenter() @@ -89,26 +85,30 @@ pub fn after_permission(granted: bool) { "[push] notification permission: {}", if granted { "granted" } else { "not granted" } )); - if !granted { - return; + if granted { + register_for_pushes(); + } + }); +} + +/// Registers with APNs, which answers `HazelAppDelegate`; on the main thread. +fn register_for_pushes() { + let Some(mtm) = MainThreadMarker::new() else { + return; + }; + let app = UIApplication::sharedApplication(mtm); + APP_DELEGATE.with_borrow_mut(|held| { + if held.is_none() { + let delegate: Retained = { + let this = AppDelegate::alloc(mtm).set_ivars(()); + unsafe { msg_send![super(this), init] } + }; + // SAFETY: the delegate lives as long as the app (`APP_DELEGATE`). + unsafe { app.setDelegate(Some(ProtocolObject::from_ref(&*delegate))) }; + *held = Some(delegate); } - let Some(mtm) = MainThreadMarker::new() else { - return; - }; - let app = UIApplication::sharedApplication(mtm); - APP_DELEGATE.with_borrow_mut(|held| { - if held.is_none() { - let delegate: Retained = { - let this = AppDelegate::alloc(mtm).set_ivars(()); - unsafe { msg_send![super(this), init] } - }; - // SAFETY: the delegate lives as long as the app (`APP_DELEGATE`). - unsafe { app.setDelegate(Some(ProtocolObject::from_ref(&*delegate))) }; - *held = Some(delegate); - } - }); - app.registerForRemoteNotifications(); }); + app.registerForRemoteNotifications(); } /// A device token as APNs's provider API takes it: lowercase hex. @@ -116,13 +116,13 @@ fn hex(bytes: &[u8]) -> String { bytes.iter().map(|byte| format!("{byte:02x}")).collect() } -/// The path a notification opens the app at: its `hazel.path`, an app path. +/// A notification's `hazel.path`, as sent; `hazel_native::shell::app_path` says whether the app +/// may open it. fn path_of(user_info: &NSDictionary) -> Option { let hazel = user_info.objectForKey(&**NSString::from_str("hazel"))?; let hazel = hazel.downcast::().ok()?; let path = hazel.objectForKey(&**NSString::from_str("path"))?; - let path = path.downcast::().ok()?.to_string(); - path.starts_with('/').then_some(path) + Some(path.downcast::().ok()?.to_string()) } define_class!( @@ -143,14 +143,14 @@ define_class!( .bundleIdentifier() .map(|id| id.to_string()) .unwrap_or_default(); - log(&format!( - "[push] device token {}… for {bundle_id}", - &token[..token.len().min(8)] - )); - crate::bridge::set_push_token(serde_json::json!({ + let start = token[..token.len().min(8)].to_string(); + let changed = crate::bridge::set_push_token(serde_json::json!({ "pushToken": token, "bundleId": bundle_id, })); + if changed { + log(&format!("[push] device token {start}… for {bundle_id}")); + } } #[unsafe(method(application:didFailToRegisterForRemoteNotificationsWithError:))] @@ -191,7 +191,9 @@ define_class!( .is_some() }); if pushed { - log("[push] a push arrived while the app is in front: not shown"); + DispatchQueue::main().exec_async(|| { + log("[push] a push arrived while the app is in front: not shown") + }); } completion.call((if pushed { UNNotificationPresentationOptions::empty() @@ -211,13 +213,17 @@ define_class!( completion: &DynBlock, ) { let user_info = response.notification().request().content().userInfo(); - match path_of(&user_info) { - Some(path) => { + let path = path_of(&user_info); + DispatchQueue::main().exec_async(move || match path { + Some(path) if hazel_native::shell::app_path(&path).is_some() => { log(&format!("[push] opened from a notification: {path}")); crate::bridge::open_path(path); } + Some(path) => log(&format!( + "[push] opened from a notification whose path is not the app's: {path:?}" + )), None => log("[push] opened from a notification without a path"), - } + }); completion.call(()); } } diff --git a/apps/native/host/src/shell.rs b/apps/native/host/src/shell.rs index 1aa57a3e3..5f4e91b03 100644 --- a/apps/native/host/src/shell.rs +++ b/apps/native/host/src/shell.rs @@ -33,6 +33,20 @@ pub fn permission_reply(id: u64, granted: bool) -> serde_json::Value { serde_json::json!({ "t": "notifyPermission", "id": id, "granted": granted }) } +/// The longest path a notification may open (a channel's or a thread's is well under it). +const MAX_APP_PATH: usize = 1024; + +/// A path a notification may open the app at: one of the app's own (`/hazel/chat/...`), never +/// a link that leaves it. `//host/x` and `/\host/x` are another origin to a URL parser (WebKit +/// reads `\` as `/`), so a backslash or a control character anywhere refuses the path. +pub fn app_path(path: &str) -> Option<&str> { + let refused = !path.starts_with('/') + || path.starts_with("//") + || path.len() > MAX_APP_PATH + || path.chars().any(|c| c == '\\' || c.is_control()); + (!refused).then_some(path) +} + /// The window became the key window or stopped being it: the runtime's `document.hasFocus()`, /// which notifications wait on. pub fn window_focus_message(focused: bool) -> serde_json::Value { @@ -157,6 +171,30 @@ mod tests { )); } + #[test] + fn a_notification_opens_only_the_apps_own_paths() { + let channel = "/hazel/chat/00000005-0000-4000-8000-000000000002"; + assert_eq!(app_path(channel), Some(channel)); + assert_eq!( + app_path("/hazel/chat/c?thread=1#m"), + Some("/hazel/chat/c?thread=1#m") + ); + for refused in [ + "", + "hazel/chat/c", + "https://evil.com/x", + "//evil.com/x", + "/\\evil.com/x", + "/hazel\\..\\x", + "/\t/evil.com", + "/hazel/chat\n/c", + "/\u{0}", + ] { + assert_eq!(app_path(refused), None, "{refused:?}"); + } + assert_eq!(app_path(&format!("/{}", "a".repeat(MAX_APP_PATH))), None); + } + #[test] fn the_window_copies_and_opens_only_web_and_mail_links() { let parse = |line: &str| serde_json::from_str::(line).expect("message"); diff --git a/apps/native/src/ios.ts b/apps/native/src/ios.ts index d6aea7145..f23896c29 100644 --- a/apps/native/src/ios.ts +++ b/apps/native/src/ios.ts @@ -10,7 +10,7 @@ import { PUSH_DEVICE_GLOBAL, type PushDevice } from "../../web-foldkit/src/platf import { SYSTEM_UI_GLOBAL, type SystemUi } from "../../web-foldkit/src/platform/system-ui" import { readConfig } from "./config" import type { NativePlatform } from "./platform" -import { makePushDevice, type PushToken } from "./push" +import { isAppPath, makePushDevice, type PushToken } from "./push" /** What the page set before this worker's source: the host's environment. */ declare const __HAZEL_ENV__: Record @@ -34,6 +34,8 @@ export type IosRequest = | { readonly haptic: true } /** Where the edge swipe goes back to; empty turns the swipe off. */ | { readonly swipeBack: string } + /** The runtime followed a notification's path (`openPath`): the host stops holding it. */ + | { readonly openedPath: string } /** The host's answer to a `fetch` request. */ type FetchReply = @@ -80,14 +82,20 @@ const goBack = () => { void import("./document-bridge").then(({ followLink }) => followLink(target.href)) } const isHostReply = (data: FetchReply | HostReply): data is HostReply => !("id" in data) +/** Follows a notification's path, one of the app's own only (the host checks it too). */ +const openPath = (path: string) => { + if (!isAppPath(path, globalThis.location.href)) { + log(`[push] not opening a path that leaves the app: ${JSON.stringify(path)}`) + } else { + log(`[push] opening ${path}`) + void import("./document-bridge").then(({ followLink }) => followLink(path)) + } + request({ openedPath: path }) +} const hostReply = (reply: HostReply) => { if ("back" in reply) goBack() else if ("pushToken" in reply) whenStarted(() => void push?.register(reply)) - else - whenStarted(() => { - log(`[push] opening ${reply.openPath}`) - void import("./document-bridge").then(({ followLink }) => followLink(reply.openPath)) - }) + else if ("openPath" in reply) whenStarted(() => openPath(reply.openPath)) } globalThis.onmessage = (event: MessageEvent) => { const data = event.data diff --git a/apps/native/src/push.test.ts b/apps/native/src/push.test.ts index c42c4c2f0..1fb64f86d 100644 --- a/apps/native/src/push.test.ts +++ b/apps/native/src/push.test.ts @@ -1,33 +1,84 @@ import { describe, expect, it } from "vitest" import { readConfig } from "./config" -import { makePushDevice } from "./push" +import { isAppPath, makePushDevice, type PushCall } from "./push" const token = "0a1b2c3d4e5f60718293a4b5c6d7e8f9" +const other = "ffeeddccbbaa99887766554433221100" +const live = { HAZEL_DATA: "live", HAZEL_SESSION_TOKEN: "t", HAZEL_APNS_ENV: "production" } -const makeDevice = (env: Record) => { +const makeDevice = (env: Record, answer: (call: PushCall) => Promise) => { const lines: Array = [] - const device = makePushDevice({ config: readConfig(env), log: (line) => lines.push(line) }) - return { device, lines } + const calls: Array = [] + const device = makePushDevice({ + config: readConfig(env), + log: (line) => lines.push(line), + send: (call) => { + calls.push(call) + return answer(call) + }, + }) + return { device, lines, calls } } +const signedIn = () => Promise.resolve(true) + describe("push device", () => { it("registers nothing offline, and logs only the token's start", async () => { - const { device, lines } = makeDevice({ HAZEL_APNS_ENV: "development" }) + const { device, lines, calls } = makeDevice({ HAZEL_APNS_ENV: "development" }, signedIn) await device.register({ pushToken: token, bundleId: "sh.hazel.ios" }) expect(lines).toEqual(["[push] offline: not registering 0a1b2c3d…"]) + expect(calls).toEqual([]) }) it("registers nothing for a build that names no APNs environment", async () => { - const { device, lines } = makeDevice({ HAZEL_DATA: "live", HAZEL_SESSION_TOKEN: "t" }) + const { device, lines } = makeDevice({ HAZEL_DATA: "live", HAZEL_SESSION_TOKEN: "t" }, signedIn) await device.register({ pushToken: token, bundleId: "hazel.app" }) expect(lines).toEqual(["[push] this build names no APNs environment: not registering"]) }) - it("has nothing to forget before a token was registered", async () => { - const { device, lines } = makeDevice({ HAZEL_DATA: "live", HAZEL_APNS_ENV: "production" }) + it("registers a token once, and again when it changes", async () => { + const { device, calls } = makeDevice(live, signedIn) + await device.register({ pushToken: token, bundleId: "hazel.app" }) + await device.register({ pushToken: token, bundleId: "hazel.app" }) + await device.register({ pushToken: other, bundleId: "hazel.app" }) + expect(calls.map((call) => call.payload.token)).toEqual([token, other]) + expect(calls[0]).toEqual({ + rpc: "pushDevice.register", + payload: { token, environment: "production", bundleId: "hazel.app" }, + }) + }) + + it("signing out waits for the registration on its way, then forgets the token", async () => { + let finish: (signedIn: boolean) => void = () => {} + const { device, calls } = makeDevice(live, (call) => + call.rpc === "pushDevice.register" + ? new Promise((resolve) => (finish = resolve)) + : Promise.resolve(true), + ) + void device.register({ pushToken: token, bundleId: "hazel.app" }) + const signedOut = device.unregister() + await Promise.resolve() + expect(calls.map((call) => call.rpc)).toEqual(["pushDevice.register"]) + finish(true) + await signedOut + expect(calls.map((call) => call.rpc)).toEqual(["pushDevice.register", "pushDevice.unregister"]) + }) + + it("signing out forgets the host's token even when its registration failed", async () => { + const { device, calls, lines } = makeDevice(live, (call) => + call.rpc === "pushDevice.register" ? Promise.reject(new Error("offline")) : Promise.resolve(true), + ) + await device.register({ pushToken: token, bundleId: "hazel.app" }) + await device.unregister() + expect(lines[0]).toBe("[push] register failed: Error: offline") + expect(calls.at(-1)).toEqual({ rpc: "pushDevice.unregister", payload: { token } }) + }) + + it("has nothing to forget before the host sent a token", async () => { + const { device, calls } = makeDevice(live, signedIn) await device.unregister() - expect(lines).toEqual([]) + expect(calls).toEqual([]) }) it("reads the build's APNs environment, and nothing else", () => { @@ -35,3 +86,23 @@ describe("push device", () => { expect(readConfig({ HAZEL_APNS_ENV: "staging" }).apnsEnvironment).toBeUndefined() }) }) + +describe("a notification's path", () => { + const base = "https://app.hazel.sh/hazel/chat/c" + + it("opens the app's own paths", () => { + expect(isAppPath("/hazel/chat/00000005-0000-4000-8000-000000000002", base)).toBe(true) + expect(isAppPath("/hazel/chat/c?thread=1#m", base)).toBe(true) + }) + + it("never leaves the app", () => { + for (const path of [ + "//evil.com/x", + "/\\evil.com/x", + "https://evil.com/x", + "evil.com", + "/\t/evil.com", + ]) + expect(isAppPath(path, base), path).toBe(false) + }) +}) diff --git a/apps/native/src/push.ts b/apps/native/src/push.ts index 0c66dee80..f206e33b6 100644 --- a/apps/native/src/push.ts +++ b/apps/native/src/push.ts @@ -11,7 +11,7 @@ import type { RuntimeConfig } from "./config" export type PushToken = { readonly pushToken: string; readonly bundleId: string } /** The API calls this module makes. */ -type Call = +export type PushCall = | { readonly rpc: "pushDevice.register" readonly payload: { @@ -22,61 +22,111 @@ type Call = } | { readonly rpc: "pushDevice.unregister"; readonly payload: { readonly token: string } } +/** Makes a call when a session is signed in, resolving `false` when none is. */ +export type SendPushCall = (call: PushCall) => Promise + +/** A failed call is tried again this many times, waiting 1, 2, 4, 8 and 16 seconds. */ +const RETRIES = 5 + +/** + * Whether a notification's `path` is one of the app's own: it resolves against the page's `base` + * to the same origin (`//host/x`, `/\host/x` and `https:` links do not). + */ +export const isAppPath = (path: string, base: string): boolean => { + if (!path.startsWith("/")) return false + const target = URL.parse(path, base) + return target !== null && target.origin === new URL(base).origin +} + /** A token for the log: its first 8 characters only. */ const short = (token: string) => `${token.slice(0, 8)}…` const describe = (error: unknown) => error instanceof Error ? `${error.name}: ${error.message}` : String(error) +/** + * The API client's call, retried with backoff while the API or the network fails; a signed-out + * session (no session, or the API's `UnauthorizedError`) is not retried. + */ +const sendWithSession: SendPushCall = async (call) => { + const { Effect, Schedule } = await import("effect") + const { sessionAuthorizationEffect } = await import("../../web-foldkit/src/core/lib/session-bearer") + const { HazelRpc, HazelRpcLive } = await import("../../web-foldkit/src/rpc") + const program = Effect.gen(function* () { + if ((yield* sessionAuthorizationEffect) === null) return false + const client = yield* HazelRpc + yield* client(call.rpc, call.payload) + return true + }).pipe( + Effect.retry({ + schedule: Schedule.exponential("1 second"), + times: RETRIES, + while: (error) => error._tag !== "UnauthorizedError", + }), + Effect.provide(HazelRpcLive), + ) + return Effect.runPromise(program) +} + export const makePushDevice = (options: { readonly config: Pick readonly log: (line: string) => void + /** The API call (tests answer it themselves). */ + readonly send?: SendPushCall }) => { - const { config, log } = options - /** The token the API has for this user, once registered. */ + const { config, log, send = sendWithSession } = options + /** The token the host sent last: what sign-out forgets, registered or not. */ + let latest: string | undefined + /** The token the API has for this user from this runtime. */ let registered: string | undefined + /** The registration on its way, which sign-out waits for. */ + let inFlight: { readonly token: string; readonly done: Promise } | undefined - /** Makes `call` when a session is signed in; `false` when none is. */ - const withSession = async (call: Call): Promise => { - const { Effect } = await import("effect") - const { sessionAuthorizationEffect } = await import("../../web-foldkit/src/core/lib/session-bearer") - const { HazelRpc, HazelRpcLive } = await import("../../web-foldkit/src/rpc") - const program = Effect.gen(function* () { - if ((yield* sessionAuthorizationEffect) === null) return false - const client = yield* HazelRpc - if (call.rpc === "pushDevice.register") yield* client(call.rpc, call.payload) - else yield* client(call.rpc, call.payload) - return true - }).pipe(Effect.provide(HazelRpcLive)) - return Effect.runPromise(program) - } - - const register = async ({ pushToken, bundleId }: PushToken): Promise => { - if (config.dataMode !== "live") return log(`[push] offline: not registering ${short(pushToken)}`) + const registerNow = async (token: string, bundleId: string): Promise => { const environment = config.apnsEnvironment if (environment === undefined) return log("[push] this build names no APNs environment: not registering") try { - const signedIn = await withSession({ + const signedIn = await send({ rpc: "pushDevice.register", - payload: { token: pushToken, environment, bundleId }, + payload: { token, environment, bundleId }, }) - if (!signedIn) return log(`[push] signed out: not registering ${short(pushToken)}`) - registered = pushToken - log(`[push] registered ${short(pushToken)} (${environment}, ${bundleId})`) + if (!signedIn) return log(`[push] signed out: not registering ${short(token)}`) + registered = token + log(`[push] registered ${short(token)} (${environment}, ${bundleId})`) } catch (error) { log(`[push] register failed: ${describe(error)}`) } } - /** Forgets the registered token (sign-out); never rejects. */ + const register = ({ pushToken, bundleId }: PushToken): Promise => { + if (config.dataMode !== "live") { + log(`[push] offline: not registering ${short(pushToken)}`) + return Promise.resolve() + } + latest = pushToken + // The same token again: already registered, or on its way. + if (registered === pushToken) return Promise.resolve() + if (inFlight?.token === pushToken) return inFlight.done + const done = registerNow(pushToken, bundleId).finally(() => { + if (inFlight?.done === done) inFlight = undefined + }) + inFlight = { token: pushToken, done } + return done + } + + /** + * Forgets this device's token on the API (sign-out), after a registration still on its way: + * the host's latest, even if this runtime's registration failed. Never rejects. + */ const unregister = async (): Promise => { - const token = registered + await inFlight?.done + const token = latest if (token === undefined) return try { - await withSession({ rpc: "pushDevice.unregister", payload: { token } }) + const signedIn = await send({ rpc: "pushDevice.unregister", payload: { token } }) registered = undefined - log(`[push] unregistered ${short(token)}`) + if (signedIn) log(`[push] unregistered ${short(token)}`) } catch (error) { log(`[push] unregister failed: ${describe(error)}`) } From 3aca4aa8a228b4f49222f56dc387a1fc46d72888 Mon Sep 17 00:00:00 2001 From: Makisuo Date: Sat, 14 Nov 2026 14:25:00 +0100 Subject: [PATCH 3/6] fix(native): sign-out stops a registration on its way, a failed one retries on activation The host hands the runtime the token on every activation (the runtime calls the API only for a token it has not registered), sign-out interrupts a registration still retrying and unregisters at once, inside its timeout, and a tapped path is acknowledged once it is followed. Co-Authored-By: Claude Opus 5.5 --- apps/native/host/ios/src/bridge.rs | 11 ++++----- apps/native/host/ios/src/push.rs | 2 +- apps/native/src/ios.ts | 11 ++++++--- apps/native/src/push.test.ts | 35 +++++++++++++++++---------- apps/native/src/push.ts | 39 +++++++++++++++++------------- 5 files changed, 57 insertions(+), 41 deletions(-) diff --git a/apps/native/host/ios/src/bridge.rs b/apps/native/host/ios/src/bridge.rs index 1a36cb051..e14b2e190 100644 --- a/apps/native/host/ios/src/bridge.rs +++ b/apps/native/host/ios/src/bridge.rs @@ -65,17 +65,16 @@ fn page_ready() -> bool { } /// This device's push token, for the runtime to register (`src/push.ts`): now, and again for -/// every runtime a page load starts (signing in loads one). The same token again (APNs answers -/// every activation) goes nowhere; false then. +/// every runtime a page load starts (signing in loads one). APNs answers every activation; the +/// same token still goes to the runtime, which retries a registration that failed and calls the +/// API only for a token it has not registered. Whether the token is new. pub fn set_push_token(message: serde_json::Value) -> bool { - if PUSH_TOKEN.with_borrow(|held| held.as_ref() == Some(&message)) { - return false; - } if page_ready() { reply(&message); } + let new = PUSH_TOKEN.with_borrow(|held| held.as_ref() != Some(&message)); PUSH_TOKEN.set(Some(message)); - true + new } /// Opens the app at `path` (a notification's tap): the runtime follows it as a link once it is diff --git a/apps/native/host/ios/src/push.rs b/apps/native/host/ios/src/push.rs index 8d68d68f2..82d140174 100644 --- a/apps/native/host/ios/src/push.rs +++ b/apps/native/host/ios/src/push.rs @@ -63,7 +63,7 @@ pub fn install(mtm: MainThreadMarker) { /// The app came to the front: what it showed as unread is about to be seen, so the badge goes. /// An app the user allows registers again each time: the token can change, and notifications /// the user turned on in iOS Settings meanwhile start now (the same token reaches the runtime -/// once, `bridge::set_push_token`). +/// with each, `bridge::set_push_token`; the API hears it once). fn became_active() { UNUserNotificationCenter::currentNotificationCenter() .setBadgeCount_withCompletionHandler(0, None); diff --git a/apps/native/src/ios.ts b/apps/native/src/ios.ts index f23896c29..f4746c09f 100644 --- a/apps/native/src/ios.ts +++ b/apps/native/src/ios.ts @@ -86,11 +86,14 @@ const isHostReply = (data: FetchReply | HostReply): data is HostReply => !("id" const openPath = (path: string) => { if (!isAppPath(path, globalThis.location.href)) { log(`[push] not opening a path that leaves the app: ${JSON.stringify(path)}`) - } else { - log(`[push] opening ${path}`) - void import("./document-bridge").then(({ followLink }) => followLink(path)) + return request({ openedPath: path }) } - request({ openedPath: path }) + log(`[push] opening ${path}`) + // The host holds the path until it is followed: a page that ends first restarts at it. + void import("./document-bridge").then(({ followLink }) => { + followLink(path) + request({ openedPath: path }) + }) } const hostReply = (reply: HostReply) => { if ("back" in reply) goBack() diff --git a/apps/native/src/push.test.ts b/apps/native/src/push.test.ts index 1fb64f86d..336f69b07 100644 --- a/apps/native/src/push.test.ts +++ b/apps/native/src/push.test.ts @@ -49,20 +49,29 @@ describe("push device", () => { }) }) - it("signing out waits for the registration on its way, then forgets the token", async () => { - let finish: (signedIn: boolean) => void = () => {} - const { device, calls } = makeDevice(live, (call) => - call.rpc === "pushDevice.register" - ? new Promise((resolve) => (finish = resolve)) - : Promise.resolve(true), - ) - void device.register({ pushToken: token, bundleId: "hazel.app" }) - const signedOut = device.unregister() - await Promise.resolve() - expect(calls.map((call) => call.rpc)).toEqual(["pushDevice.register"]) - finish(true) - await signedOut + it("signing out stops the registration on its way and forgets the token at once", async () => { + const signals: Array = [] + const lines: Array = [] + const calls: Array = [] + const device = makePushDevice({ + config: readConfig(live), + log: (line) => lines.push(line), + send: (call, signal) => { + calls.push(call) + signals.push(signal) + if (call.rpc === "pushDevice.unregister") return Promise.resolve(true) + // A registration still retrying: it ends only when stopped. + return new Promise((_, reject) => + signal?.addEventListener("abort", () => reject(new Error("interrupted"))), + ) + }, + }) + const registering = device.register({ pushToken: token, bundleId: "hazel.app" }) + await device.unregister() + await registering + expect(signals[0]?.aborted).toBe(true) expect(calls.map((call) => call.rpc)).toEqual(["pushDevice.register", "pushDevice.unregister"]) + expect(lines).toContain("[push] register stopped: Error: interrupted") }) it("signing out forgets the host's token even when its registration failed", async () => { diff --git a/apps/native/src/push.ts b/apps/native/src/push.ts index f206e33b6..8ce555b55 100644 --- a/apps/native/src/push.ts +++ b/apps/native/src/push.ts @@ -22,8 +22,8 @@ export type PushCall = } | { readonly rpc: "pushDevice.unregister"; readonly payload: { readonly token: string } } -/** Makes a call when a session is signed in, resolving `false` when none is. */ -export type SendPushCall = (call: PushCall) => Promise +/** Makes a call when a session is signed in, resolving `false` when none is; `signal` stops it. */ +export type SendPushCall = (call: PushCall, signal?: AbortSignal) => Promise /** A failed call is tried again this many times, waiting 1, 2, 4, 8 and 16 seconds. */ const RETRIES = 5 @@ -48,7 +48,7 @@ const describe = (error: unknown) => * The API client's call, retried with backoff while the API or the network fails; a signed-out * session (no session, or the API's `UnauthorizedError`) is not retried. */ -const sendWithSession: SendPushCall = async (call) => { +const sendWithSession: SendPushCall = async (call, signal) => { const { Effect, Schedule } = await import("effect") const { sessionAuthorizationEffect } = await import("../../web-foldkit/src/core/lib/session-bearer") const { HazelRpc, HazelRpcLive } = await import("../../web-foldkit/src/rpc") @@ -65,7 +65,7 @@ const sendWithSession: SendPushCall = async (call) => { }), Effect.provide(HazelRpcLive), ) - return Effect.runPromise(program) + return Effect.runPromise(program, { signal }) } export const makePushDevice = (options: { @@ -79,23 +79,25 @@ export const makePushDevice = (options: { let latest: string | undefined /** The token the API has for this user from this runtime. */ let registered: string | undefined - /** The registration on its way, which sign-out waits for. */ - let inFlight: { readonly token: string; readonly done: Promise } | undefined + /** The registration on its way, which sign-out stops. */ + let inFlight: + | { readonly token: string; readonly done: Promise; readonly stop: AbortController } + | undefined - const registerNow = async (token: string, bundleId: string): Promise => { + const registerNow = async (token: string, bundleId: string, signal: AbortSignal): Promise => { const environment = config.apnsEnvironment if (environment === undefined) return log("[push] this build names no APNs environment: not registering") try { - const signedIn = await send({ - rpc: "pushDevice.register", - payload: { token, environment, bundleId }, - }) + const signedIn = await send( + { rpc: "pushDevice.register", payload: { token, environment, bundleId } }, + signal, + ) if (!signedIn) return log(`[push] signed out: not registering ${short(token)}`) registered = token log(`[push] registered ${short(token)} (${environment}, ${bundleId})`) } catch (error) { - log(`[push] register failed: ${describe(error)}`) + log(`[push] register ${signal.aborted ? "stopped" : "failed"}: ${describe(error)}`) } } @@ -108,19 +110,22 @@ export const makePushDevice = (options: { // The same token again: already registered, or on its way. if (registered === pushToken) return Promise.resolve() if (inFlight?.token === pushToken) return inFlight.done - const done = registerNow(pushToken, bundleId).finally(() => { + const stop = new AbortController() + const done = registerNow(pushToken, bundleId, stop.signal).finally(() => { if (inFlight?.done === done) inFlight = undefined }) - inFlight = { token: pushToken, done } + inFlight = { token: pushToken, done, stop } return done } /** - * Forgets this device's token on the API (sign-out), after a registration still on its way: - * the host's latest, even if this runtime's registration failed. Never rejects. + * Forgets this device's token on the API (sign-out): the host's latest, even if this runtime's + * registration failed. A registration on its way (and its retries) stops first, so the call + * goes out at once, while the session it needs still exists. Never rejects. */ const unregister = async (): Promise => { - await inFlight?.done + inFlight?.stop.abort() + inFlight = undefined const token = latest if (token === undefined) return try { From 18b350390db2923bae7ce414b157f09f9e0b7855 Mon Sep 17 00:00:00 2001 From: Makisuo Date: Sat, 14 Nov 2026 14:33:09 +0100 Subject: [PATCH 4/6] test(native): the register retry policy runs in a test (withRetries) Co-Authored-By: Claude Opus 5.5 --- apps/native/src/push.test.ts | 35 ++++++++++++++++++++++++++++++++++- apps/native/src/push.ts | 30 +++++++++++++++++------------- 2 files changed, 51 insertions(+), 14 deletions(-) diff --git a/apps/native/src/push.test.ts b/apps/native/src/push.test.ts index 336f69b07..94937f9b5 100644 --- a/apps/native/src/push.test.ts +++ b/apps/native/src/push.test.ts @@ -1,7 +1,8 @@ +import { Effect, Exit, Schedule } from "effect" import { describe, expect, it } from "vitest" import { readConfig } from "./config" -import { isAppPath, makePushDevice, type PushCall } from "./push" +import { isAppPath, makePushDevice, type PushCall, withRetries } from "./push" const token = "0a1b2c3d4e5f60718293a4b5c6d7e8f9" const other = "ffeeddccbbaa99887766554433221100" @@ -115,3 +116,35 @@ describe("a notification's path", () => { expect(isAppPath(path, base), path).toBe(false) }) }) + +describe("withRetries", () => { + const failing = (tag: string) => { + let attempts = 0 + const call = Effect.suspend(() => { + attempts++ + return Effect.fail({ _tag: tag }) + }) + const run = Effect.runPromiseExit(withRetries(call, Schedule.spaced("1 millis"))) + return run.then((exit) => ({ exit, attempts })) + } + + it("tries a failing call five more times, then fails", async () => { + const { exit, attempts } = await failing("RpcClientError") + expect(attempts).toBe(6) + expect(Exit.isFailure(exit)).toBe(true) + }) + + it("does not retry a signed-out session", async () => { + const { attempts } = await failing("UnauthorizedError") + expect(attempts).toBe(1) + }) + + it("stops retrying once a call succeeds", async () => { + let attempts = 0 + const call = Effect.suspend(() => + ++attempts < 3 ? Effect.fail({ _tag: "RpcClientError" }) : Effect.succeed("ok"), + ) + expect(await Effect.runPromise(withRetries(call, Schedule.spaced("1 millis")))).toBe("ok") + expect(attempts).toBe(3) + }) +}) diff --git a/apps/native/src/push.ts b/apps/native/src/push.ts index 8ce555b55..f097c44ff 100644 --- a/apps/native/src/push.ts +++ b/apps/native/src/push.ts @@ -5,6 +5,7 @@ * fresh runtime, which hears the token again; signing out forgets it first * (`web-foldkit/src/platform/push-device.ts`). Offline, nothing is registered. */ +import { Effect, Schedule } from "effect" import type { RuntimeConfig } from "./config" /** The host's token, as `push.rs` hands it over. */ @@ -28,6 +29,20 @@ export type SendPushCall = (call: PushCall, signal?: AbortSignal) => Promise( + call: Effect.Effect, + base: Schedule.Schedule = Schedule.exponential("1 second"), +) => + Effect.retry(call, { + schedule: base, + times: RETRIES, + while: (error) => error._tag !== "UnauthorizedError", + }) + /** * Whether a notification's `path` is one of the app's own: it resolves against the page's `base` * to the same origin (`//host/x`, `/\host/x` and `https:` links do not). @@ -44,12 +59,8 @@ const short = (token: string) => `${token.slice(0, 8)}…` const describe = (error: unknown) => error instanceof Error ? `${error.name}: ${error.message}` : String(error) -/** - * The API client's call, retried with backoff while the API or the network fails; a signed-out - * session (no session, or the API's `UnauthorizedError`) is not retried. - */ +/** The API client's call (`withRetries`); with no session, none is made. */ const sendWithSession: SendPushCall = async (call, signal) => { - const { Effect, Schedule } = await import("effect") const { sessionAuthorizationEffect } = await import("../../web-foldkit/src/core/lib/session-bearer") const { HazelRpc, HazelRpcLive } = await import("../../web-foldkit/src/rpc") const program = Effect.gen(function* () { @@ -57,14 +68,7 @@ const sendWithSession: SendPushCall = async (call, signal) => { const client = yield* HazelRpc yield* client(call.rpc, call.payload) return true - }).pipe( - Effect.retry({ - schedule: Schedule.exponential("1 second"), - times: RETRIES, - while: (error) => error._tag !== "UnauthorizedError", - }), - Effect.provide(HazelRpcLive), - ) + }).pipe(withRetries, Effect.provide(HazelRpcLive)) return Effect.runPromise(program, { signal }) } From d90d0c092038bb1c46f4a5621e3f349f84bfc4ec Mon Sep 17 00:00:00 2001 From: Makisuo Date: Sat, 14 Nov 2026 14:39:23 +0100 Subject: [PATCH 5/6] feat(native): a simulator build takes HAZEL_SESSION_TOKEN, for a PR preview without OAuth Co-Authored-By: Claude Opus 5.5 --- apps/native/README.md | 3 ++- apps/native/scripts/ios.ts | 3 +++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/apps/native/README.md b/apps/native/README.md index 592604458..cd3e9d67e 100644 --- a/apps/native/README.md +++ b/apps/native/README.md @@ -147,7 +147,8 @@ finishes at the finger's speed, the runtime drawing where it goes while the page press on the tab bar never waits on a picture: the bar and the page stay live while the tab draws. **Live data** (`HAZEL_DATA=live bun run ios`, with `VITE_APP_URL`/`VITE_BACKEND_URL` for a dev -stack on this Mac) signs in as the Mac app does: the sign-in link opens in the system's sign-in +stack on this Mac, and `HAZEL_SESSION_TOKEN` from `dev:sign-in` for a PR preview, which has no +OAuth) signs in as the Mac app does: the sign-in link opens in the system's sign-in sheet (`ASWebAuthenticationSession`, `host/ios/src/sign_in.rs`), whose callback goes to the runtime as an opened link, and the session lives in the keychain (`hazel_native::sign_in`). The simulator's keychain serves only an app with an identifier and access group, which the diff --git a/apps/native/scripts/ios.ts b/apps/native/scripts/ios.ts index 0a3ceb158..9ffaf596a 100644 --- a/apps/native/scripts/ios.ts +++ b/apps/native/scripts/ios.ts @@ -73,6 +73,9 @@ const environment: Record = release "NATIVE_PATH", "HAZEL_ISLANDS", "HAZEL_FIXTURE_HTML", + // A session bearer for a live run against a stack without OAuth (a PR preview's + // `dev:sign-in`); simulator builds only, it is written into the bundle as is. + "HAZEL_SESSION_TOKEN", ] .flatMap((name) => { const value = process.env[name] From 75828fb8d387219cf8eb007e0872323e756d3021 Mon Sep 17 00:00:00 2001 From: Makisuo Date: Sat, 14 Nov 2026 14:55:59 +0100 Subject: [PATCH 6/6] test(native): the image retry test accepts a retry that failed again at once A missing file fails fast (Windows CI), so the retried download could already be failed again when the test looked; it now checks the failure is a new one. Co-Authored-By: Claude Opus 5.5 --- apps/native/host/src/images.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/apps/native/host/src/images.rs b/apps/native/host/src/images.rs index 6703e59d1..9e36d10a9 100644 --- a/apps/native/host/src/images.rs +++ b/apps/native/host/src/images.rs @@ -916,7 +916,13 @@ mod tests { .unwrap() .insert(url.clone(), Fetched::Failed(long_ago), 0, |_| false); assert!(remote(&url, 16.0).is_none()); - assert_ne!(state(), "failed", "fetched again once the delay passed"); + // Asked for again: pending, or (a missing file fails fast) failed anew, not the old failure. + let retried = match REMOTE.lock().unwrap().peek(&url) { + Some(Fetched::Failed(at)) => *at > long_ago, + Some(Fetched::Pending) => true, + _ => false, + }; + assert!(retried, "fetched again once the delay passed"); } #[test]