Skip to content

extra: Receive remote notifications on iOS with a new push module - #2729

Merged
madcodelife merged 2 commits into
mainfrom
extra-push
Nov 21, 2026
Merged

madcodelife merged 2 commits into
mainfrom
extra-push

Conversation

@madcodelife

Copy link
Copy Markdown
Member

Description

What

A new module of nsh-extra, push (Push in TSX, nsh_extra::push in Rust): remote notifications on iOS, with any push service.

nsh add nsh-extra --features push
import { Notifications } from "nsh";
import { Push } from "nsh-extra";

if (await Push.available()) {
  await Notifications.requestPermission(); // showing them needs it; background deliveries do not
  const token = await Push.register();     // hex, for the app's push service
  await sendTokenToServer(token);
}

Push.on("token", ({ token }) => sendTokenToServer(token));
Push.on("press", ({ payload }) => openChat(payload));
Push.on("notification", ({ threadId }) => refreshInbox(threadId));
Push.on("background", async ({ payload }) => ((await syncInbox(payload)) ? "newData" : "noData"));
  • register() calls registerForRemoteNotifications and resolves with the device token in hex. It rejects with the system's reason when the device is not registered, for example when the app is signed without aps-environment. The user's permission stays with the existing Notifications.permission / requestPermission. Registering does not need it.
  • on("token") reports a registration whose token differs from the last one of the run. The first token is included. token() reads the last one.
  • on("notification"): a notification arrived while the app is in front. How it shows is decided ahead of time with setForegroundPresentation({ banner, list, sound, badge }), because the system asks at once and the main thread never waits for JS. foregroundPresentation() reads it. By default it shows as it does behind, like Notifications' own.
  • on("press"): the user pressed a notification. The press that launched the app waits for the first listener. At most 16 presses wait.
  • on("background"): a delivery that woke the app or reached it in front (content-available). The system waits for the listeners. A listener returns "newData", "noData" or "failed", or a promise of one, within 25 seconds. Nothing returned counts as "noData", and a throw or a timeout counts as "failed". A delivery that came while nothing listened waits 5 seconds for a listener. After that the system hears noData.
  • closeThread(threadId) removes the delivered notifications grouped in a thread. It reads getDeliveredNotifications and filters by threadIdentifier, then resolves with how many it removed. One notification is removed by its id with the existing Notifications.close(id), which already removes any delivered request with that identifier. No second API does the same.
  • available() is true in a standalone iOS app. On Android, the desktops, the web and Mac Catalyst it is false, and in an app that embeds NSH in its own UIKit app, whose delegate stays its own. There register and closeThread reject with ERR_FEATURE_UNAVAILABLE_ON_PLATFORM and nothing panics.
  • Payloads are the notification's userInfo as JSON, through the shared user_info_json, with the aps dictionary included.

How it is built

The module uses only the hooks already on main. It makes no change outside nsh-extra.

  • The crate's #[native_module] entry runs on the main thread before run_app. There, on the first run only, push calls nsh_platform_ios::on_application_event, for the launch, the token, failures and background deliveries with their FetchCompletion. It also calls nsh_platform_apple::notifications::set_foreign_handler, for foreground presentation and presses, the cold-start press included.
  • Seeing Launched is what makes the module available. An app that embeds NSH never delivers it, so there the module reports itself unavailable. Without that, register() would never resolve.
  • A process-wide hub keeps the token, the waiting registrations, the presentation and the presses and background deliveries no VM listens to yet. Each VM that calls Push.on subscribes once with a channel and says which events it listens to, so presses wait for the first VM that listens to press. A background delivery shares one completion among the VMs listening. The system hears once the last clone goes, with the most significant result (newData > failed > noData).
  • With push on, the module owns the single foreign-notification handler. The iOS guide now says that an app crate listens through nsh_extra::push::on_event rather than setting its own handler, which would replace the module's. The core already warns when that happens.

Packaging

[package.metadata.nsh.features.push.ios.infoPlist] declares UIBackgroundModes = ["remote-notification"], which the CLI joins with the app's own modes.

aps-environment is deliberately not declared. For devices, nsh package --target ios signs with the entitlements the provisioning profile grants (Profile::entitlements starts from them), and a push-enabled profile grants aps-environment for its own environment: development or production. A fixed value in the crate would be checked by grant against every profile and would fail under the profile of the other environment. An app that wants it elsewhere sets ios.entitlements in nsh.json.

Docs: the nshm guide's nsh-extra section gets a Push part, and the iOS guide notes that push owns the foreign handler (English and zh-CN). The crate docs' module table and the repository map are updated too.

Why

The maintainers decided that remote notifications stay out of the core and come as an optional module, with the core providing the generic hooks. This is that module. It is not tied to any push service: a push service's SDK binding can build on the Rust API, which gives it the token's bytes, every event and the raw launch options.

Public API

nsh-extra (feature push), TS:

  • Push.available(): Promise<boolean>: whether remote notifications work here.
  • Push.register(): Promise<string>: registers the device and resolves with its token in hex.
  • Push.token(): string | null: the last token of this run.
  • Push.foregroundPresentation(): PushPresentation / Push.setForegroundPresentation(presentation: PushPresentationOptions): void: how notifications in front show ({ banner, list, sound, badge }; what the options leave out shows).
  • Push.closeThread(threadId: string): Promise<number>: removes a thread's delivered notifications; resolves with the count.
  • Push.on("token", (token: PushToken) => void): () => void: { token }.
  • Push.on("notification" | "press", (notification: PushNotification) => void): () => void: { id, threadId, payload }.
  • Push.on("background", (background: PushBackground) => void | BackgroundResult | Promise<void | BackgroundResult>): () => void: { threadId, payload }; BackgroundResult is "newData" | "noData" | "failed".

nsh_extra::push, Rust:

  • async fn available() -> bool, async fn register() -> Result<DeviceToken, PushError>, fn device_token() -> Option<DeviceToken>: the same from Rust.
  • fn foreground_presentation() -> ForegroundPresentation, fn set_foreground_presentation(ForegroundPresentation): ForegroundPresentation { banner, list, sound, badge } (non-exhaustive, Default/SHOWN all true, builder methods).
  • async fn close_thread(String) -> Result<usize, PushError>: removes a thread's delivered notifications.
  • fn on_event(impl Fn(&PushEvent<'_>) + Send + Sync + 'static): a Rust observer of every event on the main thread. PushEvent (non-exhaustive) is Token(&DeviceToken), RegistrationFailed(&PushError), Notification(&RemoteNotification), Background { notification, completion: &BackgroundCompletion } or Press(&RemoteNotification).
  • #[cfg(target_os = "ios")] fn launch_options() -> Option<NonNull<c_void>>: the launch options' NSDictionary *, kept for the life of the process, for an SDK that takes them as they are.
  • DeviceToken (new, as_bytes, to_hex, Display): the token.
  • RemoteNotification { id, thread_id, payload: JsonValue } (non-exhaustive; new, background(payload), which takes the thread from aps.thread-id).
  • BackgroundResult { NewData, NoData, Failed } (merge), and BackgroundCompletion (new(finish), set_result, Clone, Send): the system hears once the last clone is dropped.
  • PushError { code, message } (failed, unavailable), UNAVAILABLE, BACKGROUND_WAIT (5 s), BACKGROUND_LIMIT (25 s).
  • The module's JS types (Push, PushPresentation, PushPresentationOptions, PushToken, PushNotification, PushBackground) are pub(crate). They are not Rust API.

nsh-extra Cargo.toml:

  • Feature push. [package.metadata.nsh.features.push.ios.infoPlist] UIBackgroundModes = ["remote-notification"].

How to Test

Device not verified. No APNs delivery, token or press was exercised on a device or simulator. Only compile checks ran on this machine. The unit tests are written but were not run.

Ran:

  • cargo check -p nsh-extra with --features push, --features push --tests, --features camera,push --tests and --tests (host).
  • cargo check -p nsh-extra --target aarch64-apple-ios and --target aarch64-apple-ios-macabi, each with --features push, --features push --tests and --features camera,push.
  • cargo check -p nsh-extra --target aarch64-linux-android --features push --tests and --target wasm32-unknown-unknown --features push.
  • cargo +nightly fmt -p nsh-extra --check, python3 .github/ci/paths.py.

Not run (for CI or a maintainer):

  • cargo test -p nsh-extra --features push (also with camera,push): tokens_are_hexadecimal, a_background_delivery_takes_its_thread_from_the_payload, presentation_options_leave_out_what_shows, errors_keep_their_codes, results_combine_by_significance, the_system_hears_once_when_the_last_clone_goes, threads_are_filtered_by_identifier, presses_wait_for_the_first_listener_in_order, at_most_sixteen_presses_wait, notifications_in_front_do_not_wait, a_background_delivery_waits_a_while_for_a_listener, every_listening_vm_shares_a_background_completion, only_vms_listening_to_a_kind_get_it, a_token_is_reported_when_it_changes, rust_observers_hear_every_event, the_foreground_presentation_is_set_before_notifications_come, there_are_no_remote_notifications_off_ios, the_set_declares_push.
  • cargo clippy -p nsh-extra --all-targets --features camera,push, and the Catalyst clippy command with nsh-extra/push added.
  • On a device, with a push-enabled profile: Push.register() returns a token. A push sent with that token shows in front as setForegroundPresentation says and reaches on("notification"). Pressing it from a killed app reaches on("press"). A content-available push reaches on("background"), and the completion is called. closeThread removes only that thread. In the simulator, xcrun simctl push with an .apns file covers the foreground, press and background paths.

CI note: rust-app.yml tests and lints nsh-extra with camera only. Adding push to that feature list would run these tests in CI. This PR leaves the workflow as it is.

Checklist

  • I have read the CONTRIBUTING document and followed the guidelines.
  • Reviewed the changes in this PR and confirmed AI generated code (if any) is accurate.
  • Passed cargo test --workspace, cargo +nightly fmt --all and clippy (including the Catalyst and Android runs for platform code).
  • Changes to what apps use keep what released versions shipped and come with a case in tests/compat/ (cargo xtask compat).
  • Ran the related examples/gallery demos on iOS and Android (if the change is visible or platform-specific).

Some apps need remote notifications, and each push service brings its
own SDK. The runtime keeps only generic hooks for them (application
events and the handler of notifications NSH did not show); this adds
the module apps turn on to use them: `Push` in TSX and
`nsh_extra::push` in Rust, behind the `push` feature of `nsh-extra`.

The module registers the device and resolves with its token, reports a
token that changed, the notifications that arrive in front (shown as
the app decided beforehand, since the system asks at once), the
presses (the one that launched the app waits for the first listener)
and the background deliveries, whose completion the system hears once
the listeners settle, or after a short wait when none listens. It
removes the delivered notifications of a thread; one goes by its id
with `Notifications.close`. Rust code, such as a push service's SDK
binding, hears every event with the token's bytes and gets the launch
options as the system passed them.

The feature adds the `remote-notification` background mode; the
`aps-environment` entitlement comes from the provisioning profile, which
grants it for its own environment. Elsewhere than a standalone iOS app
the module is unavailable.
Review follow-ups for the `push` module:

- The hub's `dispatch` returns only what no VM will get, so a delivery
  that VMs took is no longer reported lost.
- A background delivery carries its arrival: its wait for a listener
  and its listeners' deadline count from it, also when a VM gives it
  back, so the system always hears within the budget.
- `DeviceToken` is opaque (`as_str`, the string the push service takes,
  and `as_bytes`); `register()` and `token()` give `{ token }` in TS,
  and Rust's `device_token()` is `token()`.
- Notifications in front show per thread (`setForegroundPresentation`
  with `{ threadId }`, `set_thread_presentation`), and Rust code can
  decide each one (`set_foreground_presentation_decider`).
- `closeThread` refuses an empty thread, leaves the notifications
  `Notifications` showed, and resolves with nothing.
- `launch_options()` goes: `on_application_event` already gives them.
  The foreign handler is set once the standalone app launches, a
  closing VM gives back what it did not post, and a failed registration
  leaves no waiting answer.
- Narrower public surface; CI tests and lints `push`.
@madcodelife
madcodelife merged commit 0ea512b into main Nov 21, 2026
19 checks passed
@madcodelife
madcodelife deleted the extra-push branch November 21, 2026 02:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant