A notification's declared actions reach notificationclick, and a background one holds the app until its work ends

showNotification takes a literal list of NotificationAction records.
Names are nonempty, contain neither comma nor equals sign, occur once per
list, and have one definition across the app. A list has at most four
actions. Data code may post only a declared list; omitted optional fields
and null compare equally, including through the generated Rust binding.

The Apple host registers current live sessions' categories before data
starts. It preserves embedder definitions, refuses collisions and forgets
ownership when the last declaration is removed. Authorization requires the
destination's current registered declarations and the definition revision
in the system's action identifier, checked after data activation. A stale
button cannot inherit a new unlock requirement under an unchanged category
name. Saved categories establish ownership for removal, never authorization.
A push names its category through aps.category and supplies no actions. It
reaches the selected session if that session declares the action, otherwise
the first matching live session. A waiting response carries its hold to the
declaring session. notificationclick receives the identifier, chosen action
and typed reply, with no other payload data.

A background action runs with the person's activation for its declared
handler and cannot open foreground-only UI, even in a visible session.
Auth requests from origin action answer 403 before any session opens or is
held. The 30-second deadline covers storage drainage after the handler
completes. Its invocation owns requests, native statement replies and storage work.
Ordinary wakes keep their native statements fire-and-forget. Both iOS
adapters boot the selected session without a drawn view, retaining whether
it was cold when the response arrived. Before boot or data activation, the
host reads its AfterFirstUnlock Keychain marker. An inaccessible marker
refuses the response without booting or delivering it; locking after the
first unlock does not refuse it. macOS has no notification-specific
cold-launch path and may show its ordinary startup window.

A successful runner replacement releases the old generation's actions as
superseded and preserves responses still waiting for declarations or data.
Background activation follows the current generation even without another
draw. Completion is processed when work ends, including batches that skip
presentation. The runner retains endings of host-held actions until the
host drains them. Simulated actions enter only the bounded diagnostic
history. Completion releases the delegate and background task; expiry
drops held events and prevents later delivery, including expiration during
task creation. An action with no handler settles immediately as unheard.
Under the agent, tap @ref <action>[=<reply>] chooses an action.

The LLP 1133.004 stage 2 amendment draft records these rules and the macOS
cold-launch limitation for publication before landing. Regression tests
cover notification clicks, category ownership transitions, delayed
registration, stale definitions, replacement completion, cold provenance,
ordinary wake completion, first-unlock refusal, locked-after-unlock
activation and repeated agent actions without a host drain.

Not run on a device or through APNs.

Part of #127.

Co-authored-by: Christopher Sarkissian <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: GPT-6 Astra <[email protected]>
This commit is contained in:
committed 2026-11-12 17:33:11 -08:00
1 parent bfb2cd29cf
commit ac741eca19
35 files changed
+3197 -127

No files matched your search

+1
View File
@@ -25,6 +25,7 @@
- **Linux's `showPicker` and `saveFile` can ask the desktop portal too** (2026-11-12). The document pickers now ask `org.freedesktop.portal.FileChooser` (`host/linux/src/portal.rs`), while `input type=file`'s `showPicker` (LLP 1069.002 D8, which rules the portal) and `saveFile` (LLP 1069.010 D3) still refuse outside the agent. Their agent answers (`answer_picker`, `answer_save` in `presenter/picker.rs`) already copy a file in or out given a path, which is what `portal::choose` returns.
- **EAS worker qualification (#48).** Run the app-owned native build recipes on a real EAS worker with distribution signing, upload and store submission. Local artifact checks do not establish these.
- **Notification actions: what LLP 1133.004 stage 2 left unbuilt or unrun** (2026-11-12, expo/exact#127). Not built: actions on Android (no local notifications there yet; the same plan lists become `Notification.Action`s, a text action a `RemoteInput`, a foreground action a `PendingIntent` to `ExactActivity`, a background one a host-owned `BroadcastReceiver` that hands expedited work the headless session LLP 1133.017 stage 3 still owes; `authenticationRequired` is `setAuthenticationRequired`, `destructive` has no counterpart), Windows and the web; the dismissal (`customDismissAction`, the web's `close`); `requireInteraction`; a category a push-only app declares without writing a post; a macOS notification-specific cold launch that opens no window (ordinary startup still shows its window); D6's first-unlock rule for ordinary wake carriers (notification responses check the Keychain marker before boot). Not run: a background action on a phone, through APNs, from the Lock Screen with `authenticationRequired`, and with a request that outlives the system's time; macOS's actions through Notification Center (the delegate and runner are covered by XCTest).
- **`difftest explore … --js-only` drives every program and 18 diverge** (2026-11-12). Run over `contract/corpus apps/*/app.contract`, these remain undiagnosed. A module call is refused for a missing grant, which the runner answers as `prompt` (`contacts-calendar-fixture`, `geofence-fixture`, `photo-editor`, `photos-fixture`, `recorder`). The oracle has no answer for a source the runner never called (`bench` `portList`, `lights` `lights`). The driver's DOM has no `getBoundingClientRect` (`native-fixture`). The rest have no diagnosis yet: `agents`, `auth-fixture`, `expose`, `metronome`, `orientation-fixture`, `shelf`, `unsaid`, `grouped-touch`, `inline-image` and `share`. Each is either the driver's gap or the JS target's defect; tell which before fixing.
- **The workers publish an `exactBodyTo` file when an abort or a deadline lands between the body's end and the rename** (2026-11-12, read, not run). `host/executor/src/body_to.rs` checks for an abort around each read and not between the last one and `staged.publish()`. The asynchronous machine admits the publish under the executor's lock (`async_body_to.rs`); the workers could do the same.
- **The workers' retirement leaves a retired completion's accounting standing** (2026-11-12, read, not run). `complete` in `host/executor/src/lib.rs` returns at `state.retired` before it releases the run's bytes and counts, so they stay in the shared state for as long as a waker or a clone holds it. The asynchronous machine now applies physical ends after retirement (`async_retire.rs`).
+10
View File
@@ -854,6 +854,16 @@ fn substitute(entry: &Value, interface: &Value) -> Result<String, String> {
if !literal.is_empty() {
out.insert("literal".into(), Value::Array(literal));
}
// The options whose literals are the app's declarations, a list of
// records each named by its `declares` field (LLP 1133.004 stage 2: the
// actions a notification category shows, registered at launch).
let declares: Map<String, Value> = (object(&entry["options"]).iter())
.filter(|(_, ty)| ty["literal"] == true)
.filter_map(|(option, ty)| Some((option.clone(), ty["declares"].as_str()?.into())))
.collect();
if !declares.is_empty() {
out.insert("declares".into(), Value::Object(declares));
}
// The options that name a handler, each a string literal (LLP 1133.034 D5).
let handlers: Vec<Value> = (object(&entry["options"]).iter())
.filter(|(_, ty)| ty.as_str().is_some_and(|t| bare(t).0 == "handler"))
+170 -14
View File
@@ -38,6 +38,7 @@ pub(crate) fn desugar(file: &mut File, scopes: &[Scope]) -> Result<(), Vec<Compi
file.shapes.extend(records(m));
}
let mut errors = Vec::new();
declare(file, &modules, &mut errors);
let surfaces = Known {
surfaces: surfaces(file),
shapes: file
@@ -504,27 +505,182 @@ fn bounded(
/// A computed value where the declaration requires a literal (LLP 1133.026
/// D19 item 4): the Android manifest and the Play Console name each
/// permission a `read` list can ask, so the list is written out.
/// permission a `read` list can ask, so the list is written out. An option
/// that `declares` is a list of records written out (LLP 1133.004 stage 2):
/// the platform registers them at launch, before any post.
fn literal(m: &ModuleDecl, option: &str, value: &Expr) -> Option<CompileError> {
let sub: serde_json::Value = serde_json::from_str(&m.substitute).unwrap_or_default();
let required = (sub["literal"].as_array().into_iter().flatten()).any(|o| o == option);
let plain = |e: &Expr| matches!(e, Expr::Str(..) | Expr::Number(..) | Expr::Bool(..));
let written = match value {
Expr::List(items, _) => items.iter().all(plain),
other => plain(other),
};
(required && !written).then(|| {
error(
"contract-module-literal",
format!(
"`{}`'s `{option}` is written out, a list of literals: the permissions it asks are derived from it at bake",
m.declared
),
value.span(),
let declares = sub["declares"][option].is_string();
if !required || written_out(value).is_some() {
return None;
}
let why = if declares {
format!(
"`{}`'s `{option}` is written out, a list of records of literals: the app's declarations are read from it at build",
m.declared
)
} else {
format!(
"`{}`'s `{option}` is written out, a list of literals: the permissions it asks are derived from it at bake",
m.declared
)
};
Some(error("contract-module-literal", why, value.span()))
}
/// A value written out as JSON: a literal, `some` of one or `none`, a
/// record of them (`Shape(field=…)`), or a list of these; `None` for one
/// that computes anything.
fn written_out(value: &Expr) -> Option<serde_json::Value> {
use serde_json::Value as J;
Some(match value {
Expr::Str(s, _) => J::String(s.clone()),
Expr::Number(n, _) => serde_json::json!(n),
Expr::Bool(b, _) => J::Bool(*b),
Expr::None(_) => J::Null,
Expr::Some(inner, _) => written_out(inner)?,
Expr::List(items, _) => J::Array(items.iter().map(written_out).collect::<Option<_>>()?),
Expr::Call(_, args, _) if !args.is_empty() => {
let mut fields = serde_json::Map::new();
for arg in args {
let Expr::NamedArg(name, v, _) = arg else {
return None;
};
fields.insert(name.clone(), written_out(v)?);
}
J::Object(fields)
}
_ => return None,
})
}
/// The app's declarations (LLP 1133.004 stage 2): every value written for
/// an option that `declares`, kept on the name's row as `"declared":
/// {option: [value, …]}`, each value once, in the order first written. A
/// record is named by its `declares` field, and one name means one record
/// across the app: two records of one name that differ are refused, since
/// the platform keeps one definition of each.
fn declare(file: &mut File, modules: &HashMap<String, ModuleDecl>, errors: &mut Vec<CompileError>) {
let mut found: HashMap<String, Vec<(String, serde_json::Value, Span)>> = HashMap::new();
fn walk(
body: &[Stmt],
modules: &HashMap<String, ModuleDecl>,
found: &mut HashMap<String, Vec<(String, serde_json::Value, Span)>>,
) {
for stmt in body {
let (name, args) = match stmt {
Stmt::Command { name, args, .. } => (name, args),
Stmt::Send { source, args, .. } => (source, args),
Stmt::If {
then, otherwise, ..
} => {
walk(then, modules, found);
walk(otherwise, modules, found);
continue;
}
Stmt::Match { some, none, .. } => {
walk(&some.1, modules, found);
walk(none, modules, found);
continue;
}
Stmt::Call { body, .. } => {
walk(body, modules, found);
continue;
}
_ => continue,
};
let Some(m) = modules.get(name.as_str()) else {
continue;
};
let sub: serde_json::Value = serde_json::from_str(&m.substitute).unwrap_or_default();
let Some(declares) = sub["declares"].as_object() else {
continue;
};
for arg in args {
let Expr::NamedArg(option, value, at) = arg else {
continue;
};
if declares.contains_key(option) {
if let Some(v) = written_out(value) {
found
.entry(m.name.clone())
.or_default()
.push((option.clone(), v, *at));
}
}
}
}
}
for c in &file.components {
for a in &c.actions {
walk(&a.body, modules, &mut found);
}
}
for (name, values) in found {
let m = &modules[&name];
let sub: serde_json::Value = serde_json::from_str(&m.substitute).unwrap_or_default();
let mut declared = serde_json::Map::new();
let mut defined: HashMap<(String, String), serde_json::Value> = HashMap::new();
for (option, value, at) in values {
let key = sub["declares"][&option].as_str().unwrap_or_default();
if m.package == "@exact/notifications" && option == "actions" {
let actions = value.as_array().map(Vec::as_slice).unwrap_or_default();
// UNNotificationCategory supports four actions; banners show the first two.
// https://developer.apple.com/documentation/usernotifications/unnotificationcategory/actions
if actions.len() > 4 {
errors.push(error(
"contract-module-declared",
"a notification declares at most four actions".into(),
at,
));
}
let mut names = std::collections::HashSet::new();
for action in actions {
if let Some(name) = action["action"].as_str() {
if name.is_empty() || name.contains([',', '=']) || !names.insert(name) {
errors.push(error("contract-module-declared", "notification action names must be nonempty, contain neither `,` nor `=`, and be unique within their list".into(), at));
}
}
}
}
for record in value.as_array().into_iter().flatten() {
let Some(id) = record[key].as_str() else {
continue;
};
match defined.get(&(option.clone(), id.to_owned())) {
Some(before) if before != record => errors.push(error(
"contract-module-declared",
format!(
"`{}`'s `{option}` declares `{id}` twice, differently: an {key} means one thing in the app, so write it the same way each time: first {before}, here {record}",
m.declared
),
at,
)),
Some(_) => {}
None => {
defined.insert((option.clone(), id.to_owned()), record.clone());
}
}
}
let list = declared
.entry(option)
.or_insert_with(|| serde_json::Value::Array(Vec::new()));
if let Some(list) = list.as_array_mut() {
if !value.is_null() && !list.contains(&value) {
list.push(value);
}
}
}
for decl in file.modules.iter_mut().filter(|d| d.name == name) {
let mut sub: serde_json::Value =
serde_json::from_str(&decl.substitute).unwrap_or_default();
sub["declared"] = serde_json::Value::Object(declared.clone());
decl.substitute = sub.to_string();
}
}
}
/// A handler named by anything but a string literal (LLP 1133.034 D5): the
/// runner admits the module's call back by the name the call wrote.
fn handler(m: &ModuleDecl, option: &str, value: &Expr) -> Option<CompileError> {
+1 -1
View File
@@ -837,7 +837,7 @@ const MIDI_SOURCE: &str = "reserved source, `resource midi = exactMIDI() as shap
/// `@exact/notifications`' names (LLP 1133.004), which a package declares and
/// no table of the compiler's holds.
const NOTIFICATIONS: &str = "a name of the standard module `@exact/notifications` (LLP 1133.004): `bun exact.mjs add notifications`, then `use showNotification, notificationclick, NotificationEvent from \"@exact/notifications\"` and the grant `device.notifications purpose.notifications`. A post is a statement in an action, `showNotification(title=\"Build finished\", tag=t, silent=true, data=\"/thread/3\")`; `closeNotification(tag=t)` takes it away. Its click is `notificationclick=opened` on the root component's outermost node (`action opened(tag: string, e: NotificationEvent)`, `e.data`); with `navigate=\"/thread/3\"` the click opens that route. `setAppBadge(contents=3)`, `setAppBadge()` (a flag) and `clearAppBadge()` set the app icon's badge; `notificationStatus()` reads the permission and `requestNotificationPermission()` asks. Data code calls the same names through the package's binding. Under the agent `state.notifications` lists each post, `tap @ref` clicks one, and `state.badge` is the badge (docs/reference.md#notifications)";
const NOTIFICATIONS: &str = "a name of the standard module `@exact/notifications` (LLP 1133.004): `bun exact.mjs add notifications`, then `use showNotification, notificationclick, NotificationEvent from \"@exact/notifications\"` and the grant `device.notifications purpose.notifications`. A post is a statement in an action, `showNotification(title=\"Build finished\", tag=t, silent=true, data=\"/thread/3\")`; `closeNotification(tag=t)` takes it away. Its click is `notificationclick=opened` on the root component's outermost node (`action opened(tag: string, e: NotificationEvent)`, `e.data`); with `navigate=\"/thread/3\"` the click opens that route. `actions=[NotificationAction(action=\"approve\", title=\"Approve\", foreground=false, destructive=false, authenticationRequired=true, placeholder=none)]`, written out, gives a post its buttons (a push names the list by `aps.category`, \"approve\"); a choice is the click with `e.action` and `e.reply`, and one with `foreground=false` runs its handler in the background, its work held to completion. `setAppBadge(contents=3)`, `setAppBadge()` (a flag) and `clearAppBadge()` set the app icon's badge; `notificationStatus()` reads the permission and `requestNotificationPermission()` asks. Data code calls the same names through the package's binding. Under the agent `state.notifications` lists each post, `tap @ref` clicks one (`tap @ref approve` chooses an action), and `state.badge` is the badge (docs/reference.md#notifications)";
/// A host command: an action statement, never a value.
fn command_text(name: &str) -> String {
+1
View File
@@ -146,6 +146,7 @@ mod navigation_detent;
mod navigation_split;
mod negative_margin;
mod notify;
mod notify_actions;
mod observe_commands;
mod orientationlock;
mod overlay;
+722
View File
@@ -0,0 +1,722 @@
//! `@exact/notifications`' actions (LLP 1133.004 stage 2, as amended
//! 2026-11-12): a post declares its actions as a literal, which the plan
//! keeps as the app's categories; a chosen action is `notificationclick`
//! with the action's name and a typed reply; a background action
//! (`foreground=false`) runs its handler as an invocation of origin
//! `action`, which owns its work until that work ends or the platform's
//! time does.
use exact_runner::{agent, Runner, Value, WakeHow};
use std::path::PathBuf;
struct App(PathBuf);
impl App {
fn new(name: &str) -> Self {
static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let path =
std::env::temp_dir().join(format!("exact-actions-{name}-{}-{n}", std::process::id()));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(path.join("node_modules/@exact")).unwrap();
let package =
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../packages/notifications");
std::os::unix::fs::symlink(
package.canonicalize().unwrap(),
path.join("node_modules/@exact/notifications"),
)
.unwrap();
Self(path.canonicalize().unwrap())
}
fn compile(&self, body: &str) -> Result<exact_plan::Plan, Vec<contract::CompileError>> {
let path = self.0.join("app.contract");
std::fs::write(&path, format!("{HEAD}{body}")).unwrap();
contract::compile_path_all(&path, false).map(|(plan, _)| plan)
}
}
impl Drop for App {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
const HEAD: &str = "use showNotification, requestNotificationPermission, notificationclick, NotificationEvent, NotificationAction, NotificationStatus from \"@exact/notifications\"\n";
const APPROVE: &str = r#"NotificationAction(action="approve", title="Approve", foreground=false, destructive=false, authenticationRequired=true, placeholder=none)"#;
const NOTE: &str = r#"NotificationAction(action="note", title="Add a note", foreground=true, destructive=false, authenticationRequired=false, placeholder=some("Note"))"#;
fn app_text() -> String {
format!(
r#"shape Approved
n: number
component App
state acted = ""
state origin = ""
mutation approved as shape Approved
mutation asked as shape NotificationStatus
action clicked(tag: string, e: NotificationEvent)
match e.action
case some(a)
match e.reply
case some(r)
acted = `${{tag}} ${{a}} ${{r}}`
case none
acted = `${{tag}} ${{a}}`
send approved = approve(tag)
send asked = requestNotificationPermission()
copyText(tag)
case none
acted = tag
action review
showNotification(title="Coffee, $4.50", tag="p1", actions=[{APPROVE}, {NOTE}])
action plain
showNotification(title="Delayed", tag="d1")
view
column notificationclick=clicked
text acted
"#
)
}
/// `approve` answers later, as a server would: the action's owned work
/// until the test fulfills it.
struct Later;
impl exact_runner::DataSource for Later {
fn query(&mut self, source: &str, _: &[Value]) -> Result<Value, exact_runner::DataError> {
Err(exact_runner::DataError::UnknownSource(source.into()))
}
fn answer(
&mut self,
_: &mut exact_runner::Store,
_: &str,
_: &[Value],
) -> Result<exact_runner::Answer, exact_runner::DataError> {
Ok(exact_runner::Answer::Later(exact_runner::Request::native(
b"{}".to_vec(),
)))
}
fn parse(
&mut self,
_: &mut exact_runner::Store,
_: &str,
_: &[Value],
outcome: exact_runner::Outcome,
) -> Result<exact_runner::Answer, exact_runner::DataError> {
match outcome {
exact_runner::Outcome::Response(_) => {
Ok(exact_runner::Answer::Now(Value::record(vec![
Value::Number(7.0),
])))
}
other => Err(exact_runner::DataError::Unavailable(format!("{other:?}"))),
}
}
fn grants(&self) -> &str {
"device.notifications purpose.notifications\n"
}
}
fn boot(app: &App) -> Runner<Later> {
let plan = app.compile(&app_text()).unwrap_or_else(|e| panic!("{e:?}"));
let mut r = Runner::boot(
plan,
Later,
exact_kernel::Kernel::with_monospace(),
Default::default(),
"/",
)
.unwrap();
r.set_module_target("ios");
by(&mut r, 0.0);
r.apply_announced();
r
}
fn by(r: &mut Runner<Later>, ms: f64) {
let at = r.now_ms() + ms;
r.advance(at).unwrap();
}
fn state(r: &Runner<Later>) -> serde_json::Value {
serde_json::from_str(&agent::handle(r, r#"{"op":"state"}"#)).unwrap()
}
fn logs(r: &Runner<Later>) -> String {
agent::handle(r, r#"{"op":"logs"}"#)
}
fn tap(r: &mut Runner<Later>, ticket: u64, choice: Option<&str>) -> String {
let mut request = serde_json::json!({ "op": "tap", "ticket": ticket });
if let Some(c) = choice {
request["choice"] = c.into();
}
agent::answer(r, &request.to_string()).unwrap().0
}
/// A post, allowed at the permission's ticket, and its listed entry.
fn posted(r: &mut Runner<Later>) -> serde_json::Value {
r.act("review", Vec::new()).unwrap();
let ticket = (r.device_holds().iter())
.find(|h| h.capability == "permission")
.unwrap_or_else(|| panic!("no permission ticket: {}", logs(r)))
.ticket;
tap(r, ticket, Some("allow"));
state(r)["notifications"][0].clone()
}
fn acted(r: &Runner<Later>) -> String {
format!("{:?}", r.slot("acted"))
}
#[test]
fn a_posts_literal_actions_are_the_apps_declared_categories() {
let app = App::new("declared");
let plan = app.compile(&app_text()).unwrap_or_else(|e| panic!("{e:?}"));
let row = (plan.modules.iter())
.find(|m| plan.str(m.declared) == "showNotification")
.unwrap();
let declared: serde_json::Value = serde_json::from_str(plan.str(row.substitute)).unwrap();
let lists = declared["declared"]["actions"].clone();
assert_eq!(lists.as_array().map(Vec::len), Some(1), "{declared}");
assert_eq!(lists[0][0]["action"], "approve", "{lists}");
assert_eq!(lists[0][0]["foreground"], false);
assert_eq!(lists[0][1]["placeholder"], "Note");
// An app with no actions declares none.
let plain = App::new("plain");
let plan = plain
.compile("component App\n action go\n showNotification(title=\"x\")\n view\n button press=go\n text \"go\"\n")
.unwrap_or_else(|e| panic!("{e:?}"));
let row = (plan.modules.iter())
.find(|m| plan.str(m.declared) == "showNotification")
.unwrap();
assert!(!plan.str(row.substitute).contains("declared"));
}
#[test]
fn actions_are_written_out_and_an_action_means_one_thing() {
let refused = |body: String| -> Vec<String> {
let app = App::new("refused");
match app.compile(&body) {
Ok(_) => panic!("compiled:\n{body}"),
Err(all) => all
.into_iter()
.map(|e| format!("{} {}", e.id, e.message))
.collect(),
}
};
let go = |call: &str, state: &str| {
format!("component App\n{state} action go\n {call}\n view\n button press=go\n text \"go\"\n")
};
let computed = refused(go(
"showNotification(title=\"x\", actions=[NotificationAction(action=name, title=\"Approve\", foreground=false, destructive=false, authenticationRequired=false, placeholder=none)])",
" state name = \"approve\"\n",
));
assert!(
computed
.iter()
.any(|e| e.contains("contract-module-literal")),
"{computed:?}"
);
let twice = refused(go(
&format!(
"showNotification(title=\"x\", actions=[{APPROVE}])\n showNotification(title=\"y\", actions=[NotificationAction(action=\"approve\", title=\"OK\", foreground=true, destructive=false, authenticationRequired=false, placeholder=none)])"
),
"",
));
assert!(
twice
.iter()
.any(|e| e.contains("contract-module-declared") && e.contains("approve")),
"{twice:?}"
);
}
/// §7 under the agent: the listed entry carries its actions; `tap @ref
/// note=…` is a foreground action, `notificationclick` with the action and
/// the reply, a person's; the plain click carries neither.
#[test]
fn a_foreground_action_is_the_click_with_the_actions_name_and_reply() {
let app = App::new("foreground");
let mut r = boot(&app);
let entry = posted(&mut r);
assert_eq!(entry["actions"][1]["action"], "note", "{entry}");
let reference = entry["ref"].as_u64().unwrap();
let unknown = tap(&mut r, reference, Some("share"));
assert!(unknown.contains("no action `share`"), "{unknown}");
let reply = tap(&mut r, reference, Some("note=On my way"));
assert!(reply.contains("notificationclick"), "{reply}");
r.apply_announced();
assert!(acted(&r).contains("p1 note On my way"), "{}", logs(&r));
assert!(
logs(&r).contains("notifications.notificationclick: heard by clicked"),
"{}",
logs(&r)
);
}
/// The background action (`foreground=false`): the handler runs as an
/// invocation of origin `action`, the page hidden; it owns the request it
/// sends until the reply lands; what opens UI is refused (a permission's
/// prompt, `copyText`); then it completes and the page shows again.
#[test]
fn a_background_action_owns_its_work_until_it_lands() {
let app = App::new("background");
let mut r = boot(&app);
let entry = posted(&mut r);
let reference = entry["ref"].as_u64().unwrap();
// The person changed the permission back meanwhile: a request now
// would prompt, which a background action cannot show.
let prompt = r#"{"op":"prefer","permission":{"notifications":"prompt"}}"#;
r.extension_agent(prompt).unwrap().1.unwrap();
let reply = tap(&mut r, reference, Some("approve"));
assert!(reply.contains(r#""as":"action""#), "{reply}");
by(&mut r, 0.0);
assert!(acted(&r).contains("p1 approve"), "{}", logs(&r));
let running = state(&r)["wake"].clone();
assert_eq!(running["invocations"][0]["state"], "running", "{running}");
assert_eq!(running["origin"], "action", "{running}");
assert!(r.page().hidden, "no view sees a background action");
let journal = logs(&r);
for line in [
"action notificationclick p1: heard by clicked",
"requestNotificationPermission: refused, person-required (action origin)",
"copyText: refused: during a background action",
] {
assert!(journal.contains(line), "{line} in {journal}");
}
let out = r.take_requests();
assert_eq!(out.len(), 1, "the approval in flight: {}", logs(&r));
let ok = exact_runner::Outcome::Response(exact_runner::Response {
status: 200,
headers: Vec::new(),
body: b"7".to_vec(),
});
r.fulfill(out[0].ticket, ok).unwrap();
by(&mut r, 0.0);
assert!(
logs(&r).contains("action notificationclick p1: completed"),
"{}",
logs(&r)
);
assert!(format!("{:?}", r.slot("approved")).contains('7'));
assert!(!r.page().hidden, "the page the action hid is shown again");
}
/// The host raises a chosen background action (`raise_action`), with its
/// own id for it; the runner says when it ended, and the host may expire it
/// first, when the platform's time is up: its request then fails.
#[test]
fn the_host_raises_a_background_action_and_reads_its_end() {
let app = App::new("host");
let mut r = boot(&app);
let args = r#"["p1",{"tag":"p1","data":null,"title":"Coffee","body":null,"action":"approve","reply":null}]"#;
let how = WakeHow {
id: 0,
cold: true,
hidden: true,
};
r.raise_action("notifications", "notificationclick", args, how, "n-1")
.unwrap();
by(&mut r, 0.0);
assert_eq!(r.take_requests().len(), 1, "{}", logs(&r));
let ended = |r: &Runner<Later>| -> serde_json::Value {
serde_json::from_str(&agent::handle(r, r#"{"op":"actions"}"#)).unwrap()
};
assert_eq!(ended(&r)["ended"], serde_json::json!([]));
r.expire_action("n-1");
by(&mut r, 0.0);
assert_eq!(
ended(&r)["ended"],
serde_json::json!([{ "id": "n-1", "outcome": "expired" }]),
"{}",
logs(&r)
);
assert!(!format!("{:?}", r.slot("approved")).contains('7'));
// A plain click's event is not an action's: raised as one, it is refused.
let refused = r
.raise_action("notifications", "nothing", "[]", how, "n-2")
.unwrap_err();
assert!(refused.contains("no event"), "{refused}");
}
/// Data code's post whose actions no literal declared is refused
/// `TypeError`: the platform shows only the categories declared at build.
/// One the Contract declared goes out.
#[test]
fn data_codes_post_naming_undeclared_actions_is_refused() {
let app = App::new("undeclared");
let mut r = boot(&app);
let granted = r#"{"op":"prefer","permission":{"notifications":"granted"}}"#;
r.extension_agent(granted).unwrap().1.unwrap();
let mut post = |actions: serde_json::Value| -> String {
let body = serde_json::json!({ "extension": "notifications", "send": "showNotification",
"args": { "title": "Coffee", "tag": "p2", "actions": actions } });
let request = exact_runner::Request::native(body.to_string().into_bytes());
let exact_runner::Dispatch::Run(work) = r.native_work(&request) else {
panic!("a module call is work");
};
let outcome = match work {
exact_runner::Work::Now(work) => work(),
exact_runner::Work::Later(work) => {
let (tx, rx) = std::sync::mpsc::channel();
work(exact_runner::Reply::new(move |o| tx.send(o).unwrap()));
rx.recv().unwrap()
}
};
match outcome {
exact_runner::Outcome::Response(r) => String::from_utf8_lossy(&r.body).into_owned(),
other => format!("{other:?}"),
}
};
let undeclared = post(serde_json::json!([{ "action": "delete", "title": "Delete",
"foreground": false, "destructive": true, "authenticationRequired": true, "placeholder": null }]));
assert!(undeclared.contains("TypeError"), "{undeclared}");
let declared = post(serde_json::json!([
{ "action": "approve", "title": "Approve", "foreground": false, "destructive": false,
"authenticationRequired": true, "placeholder": null },
{ "action": "note", "title": "Add a note", "foreground": true, "destructive": false,
"authenticationRequired": false, "placeholder": "Note" } ]));
assert!(!declared.contains("error"), "{declared}: {}", logs(&r));
assert!(
logs(&r).contains("showNotification: refused, actions not declared"),
"{}",
logs(&r)
);
}
#[test]
fn notify_action_names_and_list_lengths_are_unambiguous() {
let app = App::new("names");
let mut accepted = Vec::new();
for names in [
vec![""],
vec!["approve,note"],
vec!["note=later"],
vec!["approve", "approve"],
vec!["a", "b", "c", "d", "e"],
] {
let actions = names
.iter()
.map(|name| APPROVE.replace("approve", name))
.collect::<Vec<_>>()
.join(",");
let body = format!("component App\n action go\n showNotification(title=\"x\", actions=[{actions}])\n view\n button press=go\n text \"go\"\n");
if app.compile(&body).is_ok() {
accepted.push(names);
}
}
assert!(accepted.is_empty(), "invalid lists compiled: {accepted:?}");
let four = ["a", "b", "c", "d"]
.map(|name| APPROVE.replace("approve", name))
.join(",");
app.compile(&format!("component App\n action go\n showNotification(title=\"x\", actions=[{four}])\n view\n text \"x\"\n")).unwrap();
}
#[test]
fn notify_generated_rust_binding_posts_a_declared_list_with_no_placeholder() {
let app = App::new("rust-binding");
let mut r = boot(&app);
let plan = app.compile(&app_text()).unwrap();
let mut source = contract::module_rust(&plan).unwrap();
source.push_str(r#"
fn main() {
use exact_data::modules::ModuleValue;
let options = notifications::ShowNotificationOptions::decode(&exact_data::modules::serde_json::json!({
"title":"Coffee", "actions":[
{"action":"approve","title":"Approve","foreground":false,"destructive":false,"authenticationRequired":true},
{"action":"note","title":"Add a note","foreground":true,"destructive":false,"authenticationRequired":false,"placeholder":"Note"}
]
})).unwrap();
assert!(options.actions.as_ref().unwrap()[0].placeholder.is_none());
let request = notifications::show_notification(&options).unwrap();
println!("{}", String::from_utf8(request.body).unwrap());
}
"#);
let src = app.0.join("binding.rs");
let exe = app.0.join("binding");
std::fs::write(&src, source).unwrap();
let deps = std::env::current_exe()
.unwrap()
.parent()
.unwrap()
.to_owned();
let mut command = std::process::Command::new("rustc");
command
.arg("--edition=2021")
.arg(&src)
.arg("-o")
.arg(&exe)
.arg("-L")
.arg(format!("dependency={}", deps.display()));
// Match the libraries this test linked; Apple builds may leave another
// copy with different rustflags beside them.
let exe_name = std::env::current_exe()
.unwrap()
.file_stem()
.unwrap()
.to_string_lossy()
.into_owned();
let fingerprint = deps.parent().unwrap().join(".fingerprint");
let test: serde_json::Value = serde_json::from_slice(
&std::fs::read(
fingerprint
.join(exe_name.replacen("it-", "contract-", 1))
.join("test-integration-test-it.json"),
)
.unwrap(),
)
.unwrap();
for name in ["exact_data", "exact_runner"] {
let hash = test["deps"]
.as_array()
.unwrap()
.iter()
.find(|d| d[1] == name)
.unwrap()[3]
.as_u64()
.unwrap();
let expected = hash.to_le_bytes().map(|b| format!("{b:02x}")).concat();
let prefix = format!("{}-", name.replace('_', "-"));
let dir = std::fs::read_dir(&fingerprint)
.unwrap()
.filter_map(Result::ok)
.map(|e| e.path())
.find(|p| {
p.file_name()
.unwrap()
.to_string_lossy()
.starts_with(&prefix)
&& std::fs::read_to_string(p.join(format!("lib-{name}")))
.is_ok_and(|s| s == expected)
})
.unwrap();
let suffix = dir
.file_name()
.unwrap()
.to_string_lossy()
.strip_prefix(&prefix)
.unwrap()
.to_owned();
let lib = deps.join(format!("lib{name}-{suffix}.rlib"));
command
.arg("--extern")
.arg(format!("{name}={}", lib.display()));
}
let compiled = command.output().unwrap();
assert!(
compiled.status.success(),
"{}",
String::from_utf8_lossy(&compiled.stderr)
);
let output = std::process::Command::new(&exe).output().unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let request = exact_runner::Request::native(output.stdout);
r.extension_agent(r#"{"op":"prefer","permission":{"notifications":"granted"}}"#)
.unwrap()
.1
.unwrap();
let exact_runner::Dispatch::Run(exact_runner::Work::Now(work)) = r.native_work(&request) else {
panic!("substitute answers the post now")
};
let exact_runner::Outcome::Response(response) = work() else {
panic!("the post answers")
};
let body: serde_json::Value = serde_json::from_slice(&response.body).unwrap();
assert!(body.get("error").is_none(), "{body}");
}
#[test]
fn simulated_actions_keep_only_bounded_diagnostics_without_a_host_drain() {
let app = App::new("simulated-endings");
let mut r = boot(&app);
r.extension_agent(r#"{"op":"prefer","permission":{"notifications":"granted"}}"#)
.unwrap()
.1
.unwrap();
for i in 0..256 {
r.act("review", Vec::new()).unwrap();
let reference = state(&r)["notifications"][0]["ref"].as_u64().unwrap();
let reply = tap(&mut r, reference, Some("approve"));
assert!(reply.contains(r#""as":"action""#), "{reply}");
by(&mut r, 0.0);
let requests = r.take_requests();
assert_eq!(requests.len(), 1);
r.fulfill(
requests[0].ticket,
exact_runner::Outcome::Response(exact_runner::Response {
status: 200,
headers: Vec::new(),
body: b"7".to_vec(),
}),
)
.unwrap();
by(&mut r, 0.0);
let diagnostic = r.ended_actions();
assert_eq!(diagnostic.as_array().unwrap().len(), (i + 1).min(32));
assert_eq!(
diagnostic.as_array().unwrap().last().unwrap()["outcome"],
"completed"
);
}
assert_eq!(
r.take_ended_actions(),
serde_json::json!([]),
"no host held these simulated actions"
);
}
/// A notification handler either signs in or leaves a storage write in flight.
struct ActionWork {
callback: Option<&'static str>,
storage: bool,
storage_sent: bool,
}
impl exact_runner::DataSource for ActionWork {
fn query(&mut self, _: &str, _: &[Value]) -> Result<Value, exact_runner::DataError> {
unreachable!("the fixture implements answer")
}
fn answer(
&mut self,
_: &mut exact_runner::Store,
_: &str,
_: &[Value],
) -> Result<exact_runner::Answer, exact_runner::DataError> {
if let Some(callback) = self.callback {
return Ok(exact_runner::Answer::Later(
exact_data::auth::open_auth_session(
"https://as.test/authorize",
callback,
"s1",
false,
),
));
}
self.storage = true;
Ok(exact_runner::Answer::Now(Value::record(vec![
Value::Number(200.0),
])))
}
fn parse(
&mut self,
_: &mut exact_runner::Store,
_: &str,
_: &[Value],
outcome: exact_runner::Outcome,
) -> Result<exact_runner::Answer, exact_runner::DataError> {
let exact_runner::Outcome::Response(response) = outcome else {
panic!("expected an auth response")
};
assert_eq!(response.status, 403);
Ok(exact_runner::Answer::Now(Value::record(vec![
Value::Number(response.status as f64),
])))
}
fn grants(&self) -> &str {
"device.notifications purpose.notifications\nauth.session https://as.test\nauth.callback app.test:/cb\nauth.callback http://127.0.0.1/cb"
}
fn background(&mut self, _: &exact_runner::Store) -> Option<exact_runner::Request> {
if !self.storage || self.storage_sent {
return None;
}
self.storage_sent = true;
Some(exact_runner::Request::continuation(
exact_runner::BACKGROUND,
))
}
fn background_state(&self) -> Option<exact_runner::BackgroundState> {
Some(exact_runner::BackgroundState {
in_flight: u64::from(self.storage),
..Default::default()
})
}
}
fn action_work(app: &App, callback: Option<&'static str>, hidden: bool) -> Runner<ActionWork> {
let plan = app.compile(&app_text()).unwrap();
let mut r = Runner::boot(
plan,
ActionWork {
callback,
storage: false,
storage_sent: false,
},
exact_kernel::Kernel::with_monospace(),
Default::default(),
"/",
)
.unwrap();
r.set_module_target("ios");
r.advance(0.0).unwrap();
r.apply_announced();
r.raise_action(
"notifications", "notificationclick",
r#"["p1",{"tag":"p1","data":null,"title":"Coffee","body":null,"action":"approve","reply":null}]"#,
WakeHow { id: 0, cold: hidden, hidden }, "n-work",
).unwrap();
r.advance(r.now_ms()).unwrap();
r
}
#[test]
fn a_background_notification_action_cannot_open_or_hold_auth() {
use exact_runner::auth::{self, Arm, Browser};
let app = App::new("auth");
for hidden in [false, true] {
for callback in ["app.test:/cb", "http://127.0.0.1:4401/cb"] {
for agent in [false, true] {
let mut r = action_work(&app, Some(callback), hidden);
assert_eq!(r.page().hidden, hidden);
let out = r
.take_requests()
.into_iter()
.find(|o| o.request.is_auth())
.unwrap();
assert_eq!(out.request.reach.origin, exact_runner::CallOrigin::Action);
assert_eq!(
auth::arm(&mut r, &out, agent, Browser::Native, None),
Arm::Settled
);
let (ticket, outcome) = r.take_request_refusal(true).unwrap();
r.fulfill(ticket, outcome).unwrap();
r.advance(r.now_ms()).unwrap();
assert!(format!("{:?}", r.slot("approved")).contains("403"));
assert!(r.device_holds().is_empty());
assert_eq!(
r.take_ended_actions(),
serde_json::json!([{"id":"n-work","outcome":"completed"}])
);
}
}
}
}
#[test]
fn a_completed_notification_handler_keeps_its_deadline_while_storage_drains() {
let app = App::new("storage-deadline");
let mut r = action_work(&app, None, true);
let out = r.take_requests();
assert_eq!(out.len(), 1);
assert_eq!(out[0].target, "background");
r.advance(r.now_ms()).unwrap();
let state: serde_json::Value =
serde_json::from_str(&agent::handle(&r, r#"{"op":"state"}"#)).unwrap();
assert_eq!(state["wake"]["invocations"][0]["state"], "completed");
assert_eq!(r.background_operations(), 1);
assert_eq!(r.take_ended_actions(), serde_json::json!([]));
r.advance(r.now_ms() + 30_001.0).unwrap();
assert_eq!(
r.take_ended_actions(),
serde_json::json!([{"id":"n-work","outcome":"expired"}])
);
assert!(!r.page().hidden);
assert_eq!(
r.background_operations(),
1,
"expiry does not roll back storage"
);
}
+70 -6
View File
@@ -2357,9 +2357,60 @@ grant beside this one: see [Push](#push).
it starts the app. `navigate=` is reduced by the router's `location_of`
(`app://thread/42` becomes `/thread/42`).
- A click without `navigate=` is `notificationclick` on the root component's
outermost node: the tag and the notification's `{tag, data, title, body}`,
delivered once, in order, after first pixel; one that starts the app (macOS,
iOS) is held until then. A click always brings the app forward.
outermost node: the tag and the notification's `{tag, data, title, body,
action, reply}`, delivered once, in order, after first pixel; one that
starts the app (macOS, iOS) is held until then. A click always brings the
app forward. `action` and `reply` are none for a click.
- `actions=[NotificationAction(action=, title=, foreground=, destructive=,
authenticationRequired=, placeholder=)]` (macOS, iOS) gives a post the
buttons the system shows when the notification is pressed and held, on the
Lock Screen too. The list is written out, a literal (`contract-module-literal`):
the build reads each list the app writes, and the host registers each as a
category at launch, named by its actions' names joined by commas
(`approve,note`). An action name means one thing in the app: one written
twice differently is refused (`contract-module-declared`). Names must be
nonempty, contain neither `,` nor `=`, and occur once per list. A list has
at most four actions; Apple's banners show only the first two
([Apple's category guidance](https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/SupportingNotificationsinYourApp.html)).
Exact registers the union of live sessions' declared categories, preserving
an embedder's own categories. Replacing or ending one session does not remove
another's categories. Conflicting definitions of one category are neither
registered nor authorized until the conflict ends. An embedder's existing
category wins a name collision; Exact refuses its own conflicting category.
Removing Exact's last declaration releases its ownership of the name.
The host registers categories before data code starts. Responses wait for the
destination's current declarations, registration and data activation after a
cold launch or plan replacement. The system's action identifier includes its definition's
revision: an old button cannot satisfy a changed unlock requirement, even
when the category name stays the same. `e.action` remains the authored name.
Data code's
post may name only a list the app's Contract writes (`TypeError`
otherwise). `placeholder=some("Note")` makes the action a text field;
`destructive` and `authenticationRequired` are the platform's flags (the
device must be unlocked first). Choosing one is `notificationclick` with
`action` its name and `reply` what the person typed; it never opens the
post's `navigate=`.
- An action with `foreground=true` brings the app forward, as a click does.
With `foreground=false`, a running app is not brought forward. On iOS a
terminated app starts with no view; macOS has no notification-specific
cold-launch path and may show its ordinary startup window. Before the first
unlock after a device restart, iOS refuses the response before booting or
activating data. Locking again after that first unlock does not refuse it.
The handler runs as a background action (LLP 1133.004 stage 2), and the app
is kept running until the work the handler started has ended (its requests
and native statements answered, its storage written) or the system's time
for it, about 30 seconds, runs out. It is the person's
act: it may make the request the action exists for, with the app's kept
credentials. It shows nothing: a permission prompt is refused
`person-required`, a name only the foreground may call is refused, and so
are the host commands a wake may not run (`copyText`, `share`,
`playSound`, …). A session that needs a sign-in it does not have cannot
sign in there; post a notification that asks the person to open the app.
An expired action is discarded even if the session has not booted yet;
opening the app later does not run it. An action with no handler settles
immediately as unheard. Replacing its runner releases an action's held
completion as superseded; a response still awaiting declarations waits for
the replacement.
- A remote notification's click opens its payload's `navigate` and nothing
else ([Push](#push)).
- `setAppBadge(contents=)` sets the app icon's badge, best effort: a number, no
@@ -2389,7 +2440,9 @@ posted (`{title, body, tag, silent, data, showTrigger, navigate, delivered,
ref}`, a tag replacing its older one, `closeNotification` removing it, an
entry for later `delivered: false` until `clock` passes it); `state.badge` is
the badge (a number, `"flag"` or `null`). `tap @ref` on a delivered entry is
its click; `--notification '<entry>'` relaunches the app with one, as the
its click; `tap @ref <action>` chooses one of its `actions`, `tap @ref
'<action>=<text>'` with a typed reply, a background action running hidden
as `state.wake` shows it (`origin` `action`); `--notification '<entry>'` relaunches the app with one, as the
system hands a closed app its click. Scheduling is one time per call: a daily
reminder posts the next one when the app runs.
@@ -2463,8 +2516,19 @@ or origin, never through the app's `protocol_handlers`. Nothing else of the
payload is read and no event is raised; without `navigate` the app only comes
forward. A server writes that string, so a route must not act on being opened.
No app code runs when a push arrives: `content-available` does nothing (the
`remote-notification` background mode is refused), `mutable-content` changes
nothing (no service extension is built), and a `category` shows no actions.
`remote-notification` background mode is refused), and `mutable-content`
changes nothing (no service extension is built).
`aps.category` names one of the categories the app declares with
`@exact/notifications`' `actions=` (above), by its actions' names joined by
commas (`"category": "approve,note"`); a name the app did not declare shows
no actions. A chosen action is `notificationclick` with the tag the
notification's identifier (`apns-collapse-id` when the server set one), the
action's name and the typed reply; `data`, `title` and `body` are empty, and
nothing else of the payload reaches the app, so the app looks up what the
action is about by that identifier. An explicitly selected session receives the
push action if it declares it; otherwise the first matching live session does.
A background action runs as a local post's does.
The system answers a registration on the app delegate. When the package
loads, the app delegate is given the two methods that carry the answer where
+1 -1
View File
@@ -230,7 +230,7 @@ final class AppDelegate: UIResponder, UIApplicationDelegate {
a = exact.makeSession(delegate: delegate, label: "a")
b = exact.makeSession(delegate: delegate, label: "b")
#if !os(tvOS)
exact.installNotificationClicks()
exact.installNotificationClicks(boot: { $0.bootForWake() }, activate: nil)
#endif
if ExactEnv.agentFreezes { a.clock = 0; b.clock = 0 }
sessions = [("a", a), ("b", b)]
+2 -2
View File
@@ -201,11 +201,11 @@ if ExactEnv.environment["EXACT_HOST_CONTROL"] != nil {
final class Delegate: NSObject, NSApplicationDelegate, NSWindowDelegate {
func applicationWillFinishLaunching(_ notification: Notification) {
exact.installNotificationClicks { _ in
exact.installNotificationClicks(boot: nil, activate: { _ in
guard launched else { return } // finishLaunching presents a cold click.
app.windows.first?.makeKeyAndOrderFront(nil)
app.activate(ignoringOtherApps: true)
}
})
}
func applicationDidFinishLaunching(_ notification: Notification) {
readControls() // A launching notification can arrive after willFinish, before the views boot.
+2 -1
View File
@@ -202,7 +202,8 @@ final class AppDelegate: UIResponder, UIApplicationDelegate {
}
session = exact.makeSession(delegate: adapter, label: "main")
#if !os(tvOS)
exact.installNotificationClicks()
// A notification's background action that launched the app with no scene boots it with none (LLP 1133.004 stage 2).
exact.installNotificationClicks(boot: { $0.bootForWake() }, activate: nil)
// A wake that launched the app with no scene boots it with none (LLP 1133.017 D7).
exact.installWakes { session.bootForWake() }
// A tool call that launched the app with no scene boots it the same way (LLP 1133.023 D7).
+74 -25
View File
@@ -8,7 +8,9 @@
// posted it, held until that session can hear it. A remote notification's
// payload is its sender's: its click opens the payload's top-level
// `navigate` as a local notification's opens, and nothing else of the
// payload is read (LLP 1133.004 §9 P5). A notification shows with the app in front
// payload is read (LLP 1133.004 §9 P5). A chosen action is the app's
// declared action, read against its declarations (NotifyActions.swift).
// A notification shows with the app in front
// too, as a browser shows a page's, and sounds only when its content has a
// sound (a silent post has none).
import Foundation
@@ -32,19 +34,61 @@ final class NotificationPresenter: NSObject, UNUserNotificationCenterDelegate {
}
weak var app: ExactApp?
var activate: ((ExactSession) -> Void)?
/// Boots a session with no view for a background action that launched
/// the app with none (iOS: `bootForWake`).
var boot: ((ExactSession) -> Void)?
/// A background boot must be able to read AfterFirstUnlock secrets (LLP 1133.017 D6).
var firstUnlockAvailable: () -> Bool = {
#if os(iOS)
NotificationFirstUnlock.available()
#else
true
#endif
}
/// The background actions held open, by session (NotifyActions.swift).
var opened: [ObjectIdentifier: [OpenAction]] = [:]
/// The centre's registered categories, read and replaced; a test stands
/// in for them, since an XCTest process has no notification centre.
var categories: (read: (@escaping (Set<UNNotificationCategory>) -> Void) -> Void, write: (Set<UNNotificationCategory>) -> Void) = (
read: { reply in
guard NotificationPresenter.available else { return reply([]) }
UNUserNotificationCenter.current().getNotificationCategories { categories in
DispatchQueue.main.async { reply(categories) }
}
},
write: {
guard NotificationPresenter.available else { return }
UNUserNotificationCenter.current().setNotificationCategories($0)
})
/// Each session's declarations belong to one plan generation, never to defaults.
var currentCategories: [ObjectIdentifier: (generation: Int, categories: [String: [DeclaredAction]], ready: Bool)] = [:]
var registeredCategories: [String: [DeclaredAction]] = [:]
var categoryUpdates: [() -> Void] = []
var reconcilingCategories = false
private var delivered = Set<String>()
private var order: [String] = []
func install(on app: ExactApp, activate: ((ExactSession) -> Void)?) {
func install(on app: ExactApp, activate: ((ExactSession) -> Void)?, boot: ((ExactSession) -> Void)?) {
self.app = app
self.activate = activate
self.boot = boot
#if os(iOS)
_ = firstUnlockAvailable() // Keep the marker even in an app with no secrets.
#endif
guard Self.available else { return }
let center = UNUserNotificationCenter.current()
if center.delegate == nil || center.delegate === self { center.delegate = self }
}
func deliver(_ response: UNNotificationResponse, to chosen: ExactSession? = nil) {
guard response.actionIdentifier == UNNotificationDefaultActionIdentifier else { return }
/// `done` once the app may be suspended: at once, or when a background
/// action has ended.
func deliver(_ response: UNNotificationResponse, to chosen: ExactSession? = nil, done: @escaping () -> Void = {}) {
switch response.actionIdentifier {
case UNNotificationDefaultActionIdentifier: break
case UNNotificationDismissActionIdentifier: return done()
default: return chose(response, to: chosen, done: done)
}
defer { done() }
let notification = response.notification
let request = notification.request
// A remote notification's `userInfo` could name any session and
@@ -78,7 +122,7 @@ final class NotificationPresenter: NSObject, UNUserNotificationCenterDelegate {
/// Whether this is the first delivery of a notification: the delegate
/// and a scene's launch options may both hand over one tap.
private func firstDelivery(_ id: String, _ date: Date) -> Bool {
func firstDelivery(_ id: String, _ date: Date) -> Bool {
let key = "\(id):\(date.timeIntervalSince1970)"
guard delivered.insert(key).inserted else { return false }
order.append(key)
@@ -92,21 +136,9 @@ final class NotificationPresenter: NSObject, UNUserNotificationCenterDelegate {
// A notification an older build scheduled carries its session fields
// and `navigate` at the top level of `userInfo`.
guard let entry = info["exact"] as? [AnyHashable: Any] ?? (info["navigate"] != nil ? info : nil),
let label = entry["session"] as? String,
let owner = entry["owner"] as? String else { return }
entry["session"] is String, entry["owner"] is String else { return }
let location = (entry["navigate"] as? String).flatMap { $0.isEmpty ? nil : $0 }
guard firstDelivery(id, date) else { return }
let sessions = app?.sessions.filter { $0.state != .destroyed } ?? []
let sameProcess = (entry["process"] as? String).map { $0 == app?.notificationProcessID } ?? true
let session: ExactSession?
if sameProcess { session = sessions.first { $0.notificationOwnerID == owner } }
else { session = sessions.first { $0.label == label } ?? sessions.first }
guard let session else {
let line = "notification click refused: session \(label) is gone"
sessions.forEach { $0.log(line) }
if sessions.isEmpty { FileHandle.standardError.write(Data("\(line)\n".utf8)) }
return
}
guard firstDelivery(id, date), let session = postingSession(entry) else { return }
if let location { session.openLocation(location) }
else if let name = entry["extension"] as? String, let event = entry["event"] as? String {
session.raiseModuleEvent(extension: name, event: event, args: entry["args"] as? String ?? "[]", activation: true)
@@ -114,6 +146,24 @@ final class NotificationPresenter: NSObject, UNUserNotificationCenterDelegate {
activate?(session)
}
/// The session that posted the entry: by its owner identity in this
/// process; by its label, else the first live one, for a post of a
/// previous process. Nil, journaled, when it is gone.
func postingSession(_ entry: [AnyHashable: Any]) -> ExactSession? {
guard let label = entry["session"] as? String, let owner = entry["owner"] as? String else { return nil }
let sessions = app?.sessions.filter { $0.state != .destroyed } ?? []
let sameProcess = (entry["process"] as? String).map { $0 == app?.notificationProcessID } ?? true
let session: ExactSession?
if sameProcess { session = sessions.first { $0.notificationOwnerID == owner } }
else { session = sessions.first { $0.label == label } ?? sessions.first }
if session == nil {
let line = "notification click refused: session \(label) is gone"
sessions.forEach { $0.log(line) }
if sessions.isEmpty { FileHandle.standardError.write(Data("\(line)\n".utf8)) }
}
return session
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
receive(response, then: completionHandler)
@@ -123,10 +173,7 @@ final class NotificationPresenter: NSObject, UNUserNotificationCenterDelegate {
/// here, on the main thread: a session's navigation reaches its views, and
/// the record of what was delivered is read and written on one thread.
func receive(_ response: UNNotificationResponse, to session: ExactSession? = nil, then done: (() -> Void)? = nil) {
let handle = {
self.deliver(response, to: session)
done?()
}
let handle = { self.deliver(response, to: session) { done?() } }
if Thread.isMainThread { handle() } else { DispatchQueue.main.async(execute: handle) }
}
@@ -139,8 +186,10 @@ final class NotificationPresenter: NSObject, UNUserNotificationCenterDelegate {
extension ExactApp {
/// Install at launch, before the system can deliver a launching tap.
public func installNotificationClicks(activate: ((ExactSession) -> Void)? = nil) {
NotificationPresenter.shared.install(on: self, activate: activate)
/// `boot` receives the selected session and boots it with no view for a
/// background launch (LLP 1133.017 D7; iOS's `bootForWake`).
public func installNotificationClicks(boot: ((ExactSession) -> Void)? = nil, activate: ((ExactSession) -> Void)? = nil) {
NotificationPresenter.shared.install(on: self, activate: activate, boot: boot)
PushRegistration.listen()
}
@@ -0,0 +1,466 @@
// A notification's actions (LLP 1133.004 stage 2, as amended 2026-11-12).
//
// - Categories. The app declares its actions as literals on its posts; the
// plan keeps each list (`declared`, the runner's), and the host registers
// one category per list once the session has booted, its identifier the
// actions' names joined by commas: what a post's content names, and what
// a push's `aps.category` names. The lists are also kept in the app's
// defaults only to identify categories Exact owns when reconciling a
// later plan. Responses wait for the current plan's declarations.
// Categories an embedder registered itself are kept.
// - A chosen action is read only against those declarations: a category
// that is not the app's, or an action it does not declare, raises
// nothing. A push's payload contributes nothing but its identifier as the
// tag; which action the person chose and what they typed are the system's
// report (§9 P5 holds for the rest of the payload).
// - A foreground action is `notificationclick` with the action's name and
// the reply, a person's activation, and brings the app forward. A
// background action (`foreground: false`) is raised as a background
// action: the session boots with no view if it has not (iOS, LLP 1133.017
// D7), the runner runs the handler as an invocation that owns its work,
// and the host keeps the app running, the delegate's completion handler
// and a background task held, until the runner says the invocation ended
// or the system's time runs out; then it expires the action and lets the
// app be suspended at once.
import Foundation
import CryptoKit
import Security
#if canImport(UIKit)
import UIKit
#endif
#if !os(tvOS)
import UserNotifications
/// One declared action, as the plan's literal writes it.
struct DeclaredAction: Equatable {
let action: String, title: String, foreground: Bool, destructive: Bool, authenticationRequired: Bool
let placeholder: String?
init?(_ json: [String: Any]) {
guard let action = json["action"] as? String, !action.isEmpty else { return nil }
self.action = action
title = json["title"] as? String ?? action
foreground = json["foreground"] as? Bool ?? true
destructive = json["destructive"] as? Bool ?? false
authenticationRequired = json["authenticationRequired"] as? Bool ?? false
placeholder = json["placeholder"] as? String
}
/// The system returns this revision, not just the authored name. An old
/// button cannot borrow a new definition's authentication or foreground flags.
var identifier: String {
let fields: [Any] = [action, title, foreground, destructive, authenticationRequired, placeholder as Any? ?? NSNull()]
let data = try! JSONSerialization.data(withJSONObject: fields, options: [.sortedKeys])
return action + "=" + SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
}
/// The platform's action: a text field's for one with a placeholder.
var platform: UNNotificationAction {
var options: UNNotificationActionOptions = []
if foreground { options.insert(.foreground) }
if destructive { options.insert(.destructive) }
if authenticationRequired { options.insert(.authenticationRequired) }
guard let placeholder else { return UNNotificationAction(identifier: identifier, title: title, options: options) }
return UNTextInputNotificationAction(identifier: identifier, title: title, options: options,
textInputButtonTitle: title, textInputPlaceholder: placeholder)
}
}
/// The app's declared categories, by identifier.
enum DeclaredCategories {
static let key = "exact.notifications.categories"
/// A list's category: the identifier a post and a push name it by.
static func identifier(_ actions: [DeclaredAction]) -> String { actions.map(\.action).joined(separator: ",") }
/// The lists the runner's `declared` op answers, read from its JSON.
static func lists(_ declared: String) -> [[DeclaredAction]] {
guard let json = try? JSONSerialization.jsonObject(with: Data(declared.utf8)) as? [String: Any],
let lists = (json["notifications.showNotification"] as? [String: Any])?["actions"] as? [[[String: Any]]] else { return [] }
return lists.map { $0.compactMap(DeclaredAction.init) }.filter { !$0.isEmpty }
}
/// The last registered Exact definitions, kept for ownership reconciliation.
static var kept: [String: [DeclaredAction]] {
guard let data = UserDefaults.standard.data(forKey: key),
let json = try? JSONSerialization.jsonObject(with: data) as? [String: [[String: Any]]] else { return [:] }
return json.mapValues { $0.compactMap(DeclaredAction.init) }
}
static func keep(_ categories: [String: [DeclaredAction]]) {
let json = categories.mapValues { $0.map { a -> [String: Any] in
var o: [String: Any] = ["action": a.action, "title": a.title, "foreground": a.foreground,
"destructive": a.destructive, "authenticationRequired": a.authenticationRequired]
if let p = a.placeholder { o["placeholder"] = p }
return o
} }
if let data = try? JSONSerialization.data(withJSONObject: json) { UserDefaults.standard.set(data, forKey: key) }
}
}
/// LLP 1133.017 D6's marker tests first unlock, unlike protected-data availability,
/// which becomes false again each time the person locks the device.
enum NotificationFirstUnlock {
static func available(
read: (CFDictionary) -> OSStatus = { SecItemCopyMatching($0, nil) },
add: (CFDictionary) -> OSStatus = { SecItemAdd($0, nil) }
) -> Bool {
let item: [CFString: Any] = [
kSecClass: kSecClassGenericPassword,
kSecAttrService: (Bundle.main.bundleIdentifier ?? "exact") + ".exact.first-unlock",
kSecAttrAccount: "marker",
kSecUseDataProtectionKeychain: true,
]
var query = item
query[kSecReturnData] = true
query[kSecMatchLimit] = kSecMatchLimitOne
query[kSecUseAuthenticationUI] = kSecUseAuthenticationUIFail
let status = read(query as CFDictionary)
if status == errSecSuccess { return true }
guard status == errSecItemNotFound else { return false }
var marker = item
marker[kSecAttrAccessible] = kSecAttrAccessibleAfterFirstUnlock
marker[kSecValueData] = Data([1])
let added = add(marker as CFDictionary)
guard added == errSecSuccess || added == errSecDuplicateItem else { return false }
return read(query as CFDictionary) == errSecSuccess
}
}
/// A background action the host holds open: the delegate's completion
/// handler and the background task, until the runner says it ended.
final class OpenAction {
let id: String
var cold: Bool
weak var session: ExactSession?
private var done: (() -> Void)?
var waiting: (() -> Void)?
var raised = false
var generation: Int?
#if canImport(UIKit)
var task = UIBackgroundTaskIdentifier.invalid
static var beginTask: (@escaping () -> Void) -> UIBackgroundTaskIdentifier = {
UIApplication.shared.beginBackgroundTask(withName: "exact.notification-action", expirationHandler: $0)
}
#endif
init(id: String, cold: Bool, done: @escaping () -> Void) { self.id = id; self.cold = cold; self.done = done }
/// Once: the system may suspend the app.
func finish() {
let d = done
done = nil
waiting = nil
#if canImport(UIKit)
if task != .invalid { UIApplication.shared.endBackgroundTask(task); task = .invalid }
#endif
d?()
}
var finished: Bool { done == nil }
}
extension NotificationPresenter {
/// Register the union of live sessions' current declarations. Conflicting
/// definitions of a category are neither registered nor authorized.
func declare(_ lists: [[DeclaredAction]], for session: ExactSession, ready: @escaping () -> Void = {}) {
var mine: [String: [DeclaredAction]] = [:]
for list in lists { mine[DeclaredCategories.identifier(list)] = list }
currentCategories[ObjectIdentifier(session)] = (session.generation, mine, false)
updateCategories(ready)
}
private func declarations(for session: ExactSession, registered: Bool = false) -> [String: [DeclaredAction]]? {
guard session.state != .destroyed, let current = currentCategories[ObjectIdentifier(session)],
current.generation == session.generation, !registered || current.ready else { return nil }
return current.categories
}
private var combinedCategories: [String: [DeclaredAction]] {
var combined: [String: [DeclaredAction]] = [:]
var conflicts = Set<String>()
for session in app?.sessions ?? [] {
for (id, actions) in declarations(for: session) ?? [:] {
if let prior = combined[id], prior != actions { conflicts.insert(id) }
combined[id] = actions
}
}
for id in conflicts { combined[id] = nil }
return combined
}
private func updateCategories(_ ready: @escaping () -> Void = {}) {
categoryUpdates.append(ready)
reconcileCategories()
}
// Category state, confined to main:
// - A live session declares (generation, lists). Only its current generation
// participates; it becomes ready after the centre's write, before data starts.
// - `kept` owns exactly the last written Exact definitions, across launches.
// A registered definition not matching that ownership belongs to the embedder:
// preserve it and refuse an Exact claim of its identifier. Conflicting live
// declarations are refused too. Removal forgets ownership, permitting reuse.
// - A response needs its destination's ready declaration and the registered
// union to agree after data activation, including the definition revision in
// the system's action ID.
// Saved ownership never authorizes a response. A changed definition refuses old
// buttons even when the category ID is unchanged or the process has restarted.
// - Replacement supersedes actions already assigned to the old runner, but keeps
// responses awaiting declarations. Teardown removes that session's declarations
// and releases its responses; another session's equal declaration keeps ownership.
private func reconcileCategories() {
guard !reconcilingCategories, !categoryUpdates.isEmpty else { return }
reconcilingCategories = true
let centre = categories
centre.read { [self] registered in
let updates = categoryUpdates
categoryUpdates = []
let owned = DeclaredCategories.kept
let others = registered.filter { category in
guard let prior = owned[category.identifier] else { return true }
return !category.isEqual(Self.category(category.identifier, prior))
}
let foreign = Set(others.map(\.identifier))
let ours = combinedCategories.filter { !foreign.contains($0.key) }
centre.write(others.union(ours.map { Self.category($0.key, $0.value) }))
DeclaredCategories.keep(ours)
registeredCategories = ours
for session in app?.sessions ?? [] where declarations(for: session) != nil {
currentCategories[ObjectIdentifier(session)]?.ready = true
}
reconcilingCategories = false
updates.forEach { $0() }
for session in app?.sessions ?? [] { deliverWaiting(session) }
reconcileCategories()
}
}
func deliverWaiting(_ session: ExactSession) {
guard declarations(for: session, registered: true) != nil,
!session.booted || session.dataActivated else { return }
for open in opened[ObjectIdentifier(session)] ?? [] {
let waiting = open.waiting
open.waiting = nil
waiting?()
}
}
private static func category(_ id: String, _ actions: [DeclaredAction]) -> UNNotificationCategory {
UNNotificationCategory(identifier: id, actions: actions.map(\.platform), intentIdentifiers: [], options: [])
}
/// The declared action the person chose on a notification of category
/// `category`; nil for a category or an action the app did not declare.
func declared(_ action: String, in category: String, for session: ExactSession) -> DeclaredAction? {
guard let own = declarations(for: session, registered: true)?[category],
combinedCategories[category] == own, registeredCategories[category] == own else { return nil }
return own.first { $0.action == action }
}
/// A chosen action (anything but the default and the dismissal):
/// raised as the declarations say, `done` called when the app may be
/// suspended. A local post carries its activation entry; a push's
/// identifier is its tag.
func chose(_ response: UNNotificationResponse, to chosen: ExactSession?, held: OpenAction? = nil, done: @escaping () -> Void) {
let notification = response.notification
let request = notification.request
let push = request.trigger is UNPushNotificationTrigger
let session: ExactSession?
if push {
let candidates = ([chosen].compactMap { $0 } + (app?.sessions ?? [])).filter { $0.state != .destroyed }
let category = request.content.categoryIdentifier
let action = registeredCategories[category]?.first { $0.identifier == response.actionIdentifier }
session = candidates.first { target in
action.map { declared($0.action, in: category, for: target) == $0 } ?? false
} ?? candidates.first { declarations(for: $0, registered: true) == nil } ?? candidates.first
}
else { session = (request.content.userInfo["exact"] as? [AnyHashable: Any]).flatMap(postingSession) }
guard let session, session.state != .destroyed else { return done() }
guard session.dataActivated || firstUnlockAvailable() else {
session.log("notification action refused: AfterFirstUnlock Keychain marker is inaccessible")
return done()
}
if let held, held.session !== session {
if let prior = held.session {
let key = ObjectIdentifier(prior)
opened[key]?.removeAll { $0 === held }
if opened[key]?.isEmpty == true { opened[key] = nil }
}
held.session = session
held.cold = !session.booted
opened[ObjectIdentifier(session), default: []].append(held)
}
if declarations(for: session, registered: true) == nil || (session.booted && !session.dataActivated) {
let open = held ?? hold(session, done: done)
guard !open.finished else { return }
open.waiting = { [weak self, weak chosen, weak open] in
guard let self, let open, !open.finished else { return }
chose(response, to: chosen, held: open) {
guard let target = open.session else { return open.finish() }
self.settle(target, ended: [open.id])
}
}
boot?(session)
return
}
guard let action = registeredCategories[request.content.categoryIdentifier]?.first(where: { $0.identifier == response.actionIdentifier }),
declared(action.action, in: request.content.categoryIdentifier, for: session) == action,
firstDelivery(request.identifier + "#" + response.actionIdentifier, notification.date) else {
FileHandle.standardError.write(Data("notification action refused: \(response.actionIdentifier) is not declared in \(request.content.categoryIdentifier)\n".utf8))
return done()
}
let reply = action.placeholder == nil ? nil : (response as? UNTextInputNotificationResponse)?.userText ?? ""
let raised: (session: ExactSession, extension: String, event: String, args: String)?
if push { raised = pushAction(id: request.identifier, action: action.action, reply: reply, to: session) }
else { raised = localAction(info: request.content.userInfo, action: action.action, reply: reply) }
guard let raised else { return done() }
guard !action.foreground else {
raised.session.raiseModuleEvent(extension: raised.extension, event: raised.event, args: raised.args, activation: true)
activate?(raised.session)
return done()
}
background(raised.session, extension: raised.extension, event: raised.event, args: raised.args, held: held, done: done)
}
/// A push's action: `notificationclick` of `@exact/notifications` with
/// the request's identifier as the tag, the action and the reply, and
/// nothing else of the payload.
private func pushAction(id: String, action: String, reply: String?, to chosen: ExactSession?)
-> (session: ExactSession, extension: String, event: String, args: String)? {
guard let session = chosen ?? app?.sessions.first(where: { $0.state != .destroyed }), session.state != .destroyed else { return nil }
let event: [String: Any] = ["tag": id, "data": NSNull(), "title": "", "body": NSNull(), "action": action, "reply": reply ?? NSNull()]
guard let data = try? JSONSerialization.data(withJSONObject: [id, event]) else { return nil }
return (session, "notifications", "notificationclick", String(decoding: data, as: UTF8.self))
}
/// A local post's action: its activation entry's event, on the session
/// that posted it, with the action and the reply written into the
/// argument the entry names (`chosen`). Never its `navigate`.
private func localAction(info: [AnyHashable: Any], action: String, reply: String?)
-> (session: ExactSession, extension: String, event: String, args: String)? {
guard let entry = info["exact"] as? [AnyHashable: Any], let name = entry["extension"] as? String,
let event = entry["event"] as? String, let session = postingSession(entry) else { return nil }
let args = Self.choosing(action, reply: reply, in: entry["args"] as? String ?? "[]", at: entry["chosen"] as? Int)
return (session, name, event, args)
}
/// `args` with `action` and `reply` written into the argument at
/// `index`, an object; unchanged when the entry names none.
static func choosing(_ action: String, reply: String?, in args: String, at index: Int?) -> String {
guard let index, var list = (try? JSONSerialization.jsonObject(with: Data(args.utf8))) as? [Any],
list.indices.contains(index), var event = list[index] as? [String: Any] else { return args }
event["action"] = action
event["reply"] = reply ?? NSNull()
list[index] = event
return (try? JSONSerialization.data(withJSONObject: list)).map { String(decoding: $0, as: UTF8.self) } ?? args
}
/// Hold the response while the session boots or its action runs.
private func hold(_ session: ExactSession, done: @escaping () -> Void) -> OpenAction {
let open = OpenAction(id: UUID().uuidString, cold: !session.booted, done: done)
open.session = session
opened[ObjectIdentifier(session), default: []].append(open)
#if os(iOS)
open.task = OpenAction.beginTask { [weak self, weak open] in
guard let open else { return }
guard let session = open.session else { return open.finish() }
self?.expire(open, in: session)
}
// UIKit may expire inline, before it returns the task identifier.
if open.finished { open.finish() }
#endif
return open
}
func background(_ session: ExactSession, extension name: String, event: String, args: String,
held: OpenAction? = nil, done: @escaping () -> Void) {
let open = held ?? hold(session, done: done)
guard !open.finished else { return }
#if os(iOS)
let hidden = UIApplication.shared.applicationState == .background
#else
let hidden = false
#endif
open.generation = session.booted ? session.generation : nil
session.raiseModuleEvent(extension: name, event: event, args: args, activation: true,
background: (id: open.id, cold: open.cold, hidden: hidden))
if !session.booted { boot?(session) }
}
/// The system's time is up: the runner expires the action, failing its
/// requests in flight, and the app is let go at once, inside the
/// expiration handler, as UIKit requires.
func expire(_ open: OpenAction, in session: ExactSession) {
guard !open.finished else { return }
session.heldModuleEvents.removeAll { json in
let event = (try? JSONSerialization.jsonObject(with: Data(json.utf8))) as? [String: Any]
return event?["background"] as? String == open.id
}
if open.raised && open.generation == session.generation { session.expireBackgroundAction(open.id) }
settle(session, ended: [open.id])
}
func replaced(_ session: ExactSession) {
for open in opened[ObjectIdentifier(session)] ?? [] {
if let generation = open.generation, generation != session.generation { expire(open, in: session) }
}
}
/// Drain endings when work lands, including batches that skip presentation.
func applied(_ session: ExactSession) {
guard let open = opened[ObjectIdentifier(session)], !open.isEmpty else { return }
let reply = session.agent("{\"op\":\"actions\",\"drain\":true}")
let ended = ((try? JSONSerialization.jsonObject(with: Data(reply.utf8))) as? [String: Any])?["ended"] as? [[String: Any]] ?? []
settle(session, ended: Set(ended.compactMap { $0["id"] as? String }))
}
/// Let go of `ended`, or of every action when the session ends.
func settle(_ session: ExactSession, ended: Set<String>, all: Bool = false) {
let key = ObjectIdentifier(session)
for open in opened[key] ?? [] where all || ended.contains(open.id) { open.finish() }
opened[key] = (opened[key] ?? []).filter { !$0.finished }
if opened[key]?.isEmpty == true { opened[key] = nil }
if all, currentCategories.removeValue(forKey: key) != nil {
updateCategories()
}
}
}
extension ExactSession {
/// Registration precedes data code and delivery of launching actions.
func declareNotificationCategories(ready: @escaping () -> Void) {
NotificationPresenter.shared.declare(DeclaredCategories.lists(agent("{\"op\":\"declared\"}")), for: self, ready: ready)
}
func replaceBackgroundActions() { NotificationPresenter.shared.replaced(self) }
func deliverNotificationResponses() { NotificationPresenter.shared.deliverWaiting(self) }
/// The platform's time for background action `id` ran out.
func expireBackgroundAction(_ id: String) {
guard booted, let data = try? JSONSerialization.data(withJSONObject: ["expire": id]) else { return }
apply(runtime.moduleEvent(String(decoding: data, as: UTF8.self)))
}
/// An event copied out of the preboot queue may have expired meanwhile.
func beginBackgroundAction(_ id: String) -> Bool {
guard let open = NotificationPresenter.shared.opened[ObjectIdentifier(self)]?.first(where: { $0.id == id }), !open.finished else { return false }
open.raised = true
open.generation = generation
return true
}
/// After work lands: a background action it ended lets the app go.
func backgroundActionsApplied() { NotificationPresenter.shared.applied(self) }
/// The session ends: every background action it held lets the app go.
func endBackgroundActions() { NotificationPresenter.shared.settle(self, ended: [], all: true) }
}
#else
extension ExactSession {
func declareNotificationCategories(ready: @escaping () -> Void) { ready() }
func replaceBackgroundActions() {}
func deliverNotificationResponses() {}
func beginBackgroundAction(_ id: String) -> Bool { false }
func backgroundActionsApplied() {}
func endBackgroundActions() {}
}
#endif
+2 -2
View File
@@ -898,7 +898,7 @@ public final class ExactSession {
sampler?.reset(); frameHealth.reset() // a new runner numbers its transactions afresh (LLP 1079 D3)
// A fresh boot over a running app (the dev menu's reload from the baked plan) starts the views over; the library already replaced its host.
routerOp = nil
generation += 1
generation += 1; replaceBackgroundActions()
if booted { awaitingTree = true; resetHeld(); viewsEpoch += 1; forgetAppearances(); presenter.launchAutofocusReleased = false } // a fresh boot's autofocus waits again
booted = true; app.liveBooted(self)
text.commitFonts()
@@ -996,7 +996,7 @@ public final class ExactSession {
text = candidate.text
text.commitFonts()
updateToken = candidate.token
generation += 1
generation += 1; replaceBackgroundActions()
return batch
}
@@ -15,13 +15,18 @@ extension ExactSession {
activatedGeneration = drawnGeneration
DispatchQueue.main.async { [weak self] in
guard let self, state != .destroyed, generation == drawnGeneration else { return }
// Prepare before any source calls the module (LLP 1067.000 D8).
let started = CACurrentMediaTime()
natives.prepareAppModule()
ExactLaunch.shared.modulePrepared(self, seconds: CACurrentMediaTime() - started)
presenter.releaseLaunchAutofocus() // the next turn, never waiting on a loading source
restoreKeptDocuments() // before any answer reads a kept document (LLP 1069.010.000 D4)
if preparedGeneration != drawnGeneration { prepareData(drawnGeneration, token: token) } else { activateData(drawnGeneration, token: token) }
dataPreparing = true
declareNotificationCategories { [weak self] in
guard let self, state != .destroyed, generation == drawnGeneration else { return }
dataPreparing = false
// Prepare before any source calls the module (LLP 1067.000 D8).
let started = CACurrentMediaTime()
natives.prepareAppModule()
ExactLaunch.shared.modulePrepared(self, seconds: CACurrentMediaTime() - started)
presenter.releaseLaunchAutofocus() // the next turn, never waiting on a loading source
restoreKeptDocuments() // before any answer reads a kept document (LLP 1069.010.000 D4)
if preparedGeneration != drawnGeneration { prepareData(drawnGeneration, token: token) } else { activateData(drawnGeneration, token: token) }
}
}
}
@@ -78,6 +83,7 @@ extension ExactSession {
}
storeRefresh.record(batch)
retryStoreActivation()
deliverNotificationResponses()
deliverModuleEvents() // a launching activation, once the module and the data are up (LLP 1133.004 D6)
NotificationCenter.default.post(name: Self.dataActivated, object: self)
canvases.loadIfNeeded()
@@ -117,28 +123,36 @@ extension ExactSession {
/// D6): held from launch until first pixel and the data's activation,
/// then raised into the runner and heard in order, once. `activation` is
/// true only for a platform callback that reports a person's act on its
/// own UI.
func raiseModuleEvent(extension name: String, event: String, args: String, activation: Bool) {
/// own UI. `background` makes it a notification's background action
/// the person chose (LLP 1133.004 stage 2): the host's id for it, whether
/// the session was booted for it, and whether no view is seen.
func raiseModuleEvent(extension name: String, event: String, args: String, activation: Bool,
background: (id: String, cold: Bool, hidden: Bool)? = nil) {
guard state != .destroyed else { return }
let body: [String: Any] = ["extension": name, "event": event, "args": (try? JSONSerialization.jsonObject(with: Data(args.utf8))) ?? [],
var body: [String: Any] = ["extension": name, "event": event, "args": (try? JSONSerialization.jsonObject(with: Data(args.utf8))) ?? [],
"activation": activation, "deliver": false]
if let background { body["background"] = background.id; body["cold"] = background.cold; body["hidden"] = background.hidden }
guard let data = try? JSONSerialization.data(withJSONObject: body) else { return }
if heldModuleEvents.count >= Self.heldModuleEventBound {
heldModuleEvents.removeFirst()
log("\(name).\(event): dropped (held before the session could hear it)")
}
heldModuleEvents.append(String(decoding: data, as: UTF8.self))
if dataGeneration != nil { deliverModuleEvents() }
if dataActivated { deliverModuleEvents() }
}
/// Each held module event raised into the runner, which bounds each
/// event's own; then everything the runner queued is heard, once (an
/// agent's tap of a listed entry too).
func deliverModuleEvents() {
guard state != .destroyed, booted, firstDrawMs != nil, !runtime.holds("deliverModuleEvents()") else { return } // (kept for after: ResetGate)
guard state != .destroyed, booted, dataActivated, firstDrawMs != nil, !runtime.holds("deliverModuleEvents()") else { return } // (kept for after: ResetGate)
let held = heldModuleEvents
heldModuleEvents = []
for json in held { apply(runtime.moduleEvent(json)) }
for json in held {
let event = (try? JSONSerialization.jsonObject(with: Data(json.utf8))) as? [String: Any]
if let id = event?["background"] as? String, !beginBackgroundAction(id) { continue }
apply(runtime.moduleEvent(json))
}
apply(runtime.moduleEvent("{}"))
}
@@ -150,5 +164,6 @@ extension ExactSession {
}
heldModuleEvents = []
if booted { _ = runtime.moduleEvent("{\"unheard\":true}") }
endBackgroundActions()
}
}
@@ -18,11 +18,12 @@ extension ExactSession {
#endif
extension ExactSession {
/// Tells the launch's and a navigation's TTI to read outstanding work
/// Releases completed background actions and tells launch and navigation TTI to read outstanding work
/// again. Work that shows nothing new can end the last of it (a skipped
/// batch, owner work landing, a canvas replay or an SVG picture done), so
/// this follows every end of work, not only an apply.
func workEnded() {
backgroundActionsApplied()
ExactLaunch.shared.workEnded(self)
NavigationMarks.shared.workEnded(self)
}
@@ -12,7 +12,7 @@ extension ExactSession {
/// is attached or drawn later takes the session as it stands, and its
/// next layout tells the runner its size and insets.
///
/// The session's `firstDrawMs` is then this activation's time, and the
/// On first activation, `firstDrawMs` records its time, and the
/// update store's after-pixel check runs in the wake. In front, a wake
/// waits for first pixel, as every event of a launch with a view does.
public func bootForWake() {
@@ -23,7 +23,7 @@ extension ExactSession {
guard booted else { return WakeStore.log("wakes: the boot with no view was refused: \(bootError ?? "?")") }
WakeStore.log("wakes: booted \(view == nil ? "with no view" : "under an undrawn view") in \(Int(ExactEnv.wall() - started)) ms")
}
guard firstDrawMs == nil else { return }
guard activatedGeneration != generation else { return }
WakeStore.log("wakes: the module and the data open for the wake, \(view == nil ? "no view" : "a view") attached")
firstDrawn(generation: generation, token: updateToken)
}
+1 -1
View File
@@ -647,7 +647,7 @@ final class Delegate: NSObject, NSApplicationDelegate {
func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { true }
func applicationWillFinishLaunching(_ notification: Notification) {
LaunchKind.install()
exact.installNotificationClicks { session in windows.first { $0.session === session }?.front() }
exact.installNotificationClicks(boot: nil, activate: { session in windows.first { $0.session === session }?.front() })
exact.installWakes()
exact.installReach()
}
+9 -2
View File
@@ -215,8 +215,15 @@ public final class ExactPackageContext {
/// (LLP 1133.004 D6, D7): the host's notification delegate reads it and
/// raises the event, a person's activation, on the session that posted
/// it. Empty, and a line in the journal, for `args` that are not JSON.
public func activation(_ name: String, _ args: [Any], navigate: String? = nil) -> [AnyHashable: Any] {
activationFn(name, args, navigate)
/// `chosen` is the argument, an object, that a declared action the
/// person chose writes its `action` and `reply` into (stage 2).
public func activation(_ name: String, _ args: [Any], navigate: String? = nil, chosen: Int? = nil) -> [AnyHashable: Any] {
var info = activationFn(name, args, navigate)
if let chosen, var entry = info["exact"] as? [String: Any] {
entry["chosen"] = chosen
info["exact"] = entry
}
return info
}
/// The app's handler `handler` run for the work `handle` names (LLP
+6
View File
@@ -1315,6 +1315,12 @@ impl<D: DataSource> Bridge<D> {
// `tap @t` / `type @t` answer a held device request (LLP 1069.007
// D4) before any view is looked up.
let out = match self.host.as_mut() {
Some(h)
if exact_runner::agent::field_str(&request, "op").as_deref() == Some("actions")
&& exact_runner::agent::field_bool(&request, "drain") =>
{
h.take_ended_actions()
}
Some(h) => h.answer_hold(&request).unwrap_or_else(|| h.agent(&request)),
None => exact_runner::agent::error("not booted"),
};
+5
View File
@@ -16,6 +16,11 @@ impl<D: DataSource> Host<D> {
self.advanced(a)
}
/// Action endings are delivery, separate from the agent's recent history.
pub fn take_ended_actions(&mut self) -> String {
format!("{{\"ended\":{}}}", self.runner.take_ended_actions())
}
/// The agent API's read operations (LLP 1012): `tree`, `state`, and
/// `logs` from the runner; `settle` — the clock at which the last
/// transition in flight ends, milliseconds, `null` when quiescent — from
+37 -1
View File
@@ -49,6 +49,11 @@ impl<D: DataSource> Host<D> {
/// A module event the platform reported (LLP 1133.004 D6): `{"extension",
/// "event", "args", "activation"}`, raised with a person's origin only
/// when an activation callback of the host's reported it, then heard.
/// With `"background": id` it is a notification's background action the
/// person chose (stage 2), run as an invocation that owns its work
/// (`cold` when the host booted the session for it, `hidden` unless
/// the app is in front); `{"expire": id}`
/// says the platform's time for that action ran out.
pub fn module_event(&mut self, json: &str) -> String {
let v: serde_json::Value = serde_json::from_str(json).unwrap_or_default();
// The session ends: what no handler heard is journaled.
@@ -56,6 +61,29 @@ impl<D: DataSource> Host<D> {
self.runner.journal_unheard_events();
return self.finish(Batch::new(), None);
}
if let Some(id) = v["expire"].as_str() {
let (receipts, error) = self.runner.expire_action(id);
return self.timed_commit(receipts, error.map(|e| format!("{e:?}")));
}
if let (Some(id), Some(event), true) = (
v["background"].as_str(),
v["event"].as_str(),
v["activation"] == true,
) {
let how = exact_runner::WakeHow {
id: 0,
cold: v["cold"] == true,
hidden: v["hidden"] != false,
};
let extension = v["extension"].as_str().unwrap_or_default();
if let Err(e) =
(self.runner).raise_action(extension, event, &v["args"].to_string(), how, id)
{
return self.finish(Batch::new(), Some(e));
}
let (receipts, error) = self.runner.apply_announced();
return self.timed_commit(receipts, error.map(|e| format!("{e:?}")));
}
let origin = if v["activation"] == true {
exact_runner::CallOrigin::App
} else {
@@ -78,12 +106,20 @@ impl<D: DataSource> Host<D> {
}
}
let (receipts, error) = self.runner.apply_announced();
self.timed_commit(receipts, error.map(|e| format!("{e:?}")))
}
fn timed_commit(
&mut self,
receipts: Vec<exact_kernel::CommitReceipt>,
error: Option<String>,
) -> String {
let at_ms = self.now_ms;
let timed: Vec<Timed> = receipts
.into_iter()
.map(|receipt| Timed { at_ms, receipt })
.collect();
self.commit(&timed, error.map(|e| format!("{e:?}")))
self.commit(&timed, error)
}
/// The batch of a host that replaces `old` (a boot, a new generation):
@@ -41,7 +41,7 @@ final class LaunchURLMacTests: XCTestCase {
guard Bundle.main.bundleURL.pathExtension != "app" else { return }
let presenter = NotificationPresenter.shared
defer { presenter.app = nil; presenter.activate = nil }
presenter.install(on: ExactApp.shared, activate: nil)
presenter.install(on: ExactApp.shared, activate: nil, boot: nil)
XCTAssertTrue(presenter.app === ExactApp.shared)
}
@@ -0,0 +1,800 @@
#if !os(tvOS)
import Foundation
import Security
import ObjectiveC
import CExact
import ExactCore
import XCTest
import UserNotifications
#if os(iOS)
import UIKit
#endif
@testable import ExactKit
#if os(iOS)
private extension UIApplication {
@objc var notificationActionBackgroundState: UIApplication.State { .background }
@objc var notificationActionProtectedDataUnavailable: Bool { false }
}
#endif
private final class ActionRequest: UNNotificationRequest {
static var triggerValue: UNNotificationTrigger?
override var trigger: UNNotificationTrigger? { Self.triggerValue }
}
private final class ActionNotification: UNNotification {
static var requestValue: UNNotificationRequest!
override var request: UNNotificationRequest { Self.requestValue }
static var dateValue = Date()
override var date: Date { Self.dateValue }
}
private final class ActionResponse: UNTextInputNotificationResponse {
static var notificationValue: UNNotification!
static var actionValue = ""
static var textValue = ""
override var notification: UNNotification { Self.notificationValue }
override var actionIdentifier: String { Self.actionValue }
override var userText: String { Self.textValue }
}
/// A notification's declared actions (LLP 1133.004 stage 2): the plan's
/// lists registered as categories; a chosen action read against them,
/// through the delegate with the system's response stood in; a foreground
/// action raised as the click with its name and reply, a background one held
/// open until the runner says its invocation ended or the system's time ran
/// out.
final class NotificationActionTests: XCTestCase {
private var sessions: [ExactSession] = []
private var kept: Data?
private var restorePresenter: (() -> Void)?
private let declared = """
{"notifications.showNotification":{"actions":[[\
{"action":"approve","title":"Approve","foreground":false,"destructive":false,"authenticationRequired":true,"placeholder":null},\
{"action":"note","title":"Add a note","foreground":true,"destructive":false,"authenticationRequired":false,"placeholder":"Note"}]]}}
"""
/// The centre's categories as the host registers them.
private var registered: Set<UNNotificationCategory> = []
override func setUp() {
super.setUp()
let presenter = NotificationPresenter.shared
let categories = presenter.categories, current = presenter.currentCategories, priorRegistered = presenter.registeredCategories
let firstUnlock = presenter.firstUnlockAvailable
restorePresenter = {
presenter.categories = categories; presenter.currentCategories = current
presenter.registeredCategories = priorRegistered; presenter.firstUnlockAvailable = firstUnlock
}
// Bare XCTest has no app Keychain identity. Unlock tests supply the marker's statuses.
presenter.firstUnlockAvailable = { true }
presenter.currentCategories = [:]
presenter.registeredCategories = [:]
// An XCTest process has no notification centre (`current()` traps): the categories are held here.
NotificationPresenter.shared.categories = (read: { [unowned self] in $0(registered) }, write: { [unowned self] in registered = $0 })
kept = UserDefaults.standard.data(forKey: DeclaredCategories.key)
DeclaredCategories.keep(["approve,note": DeclaredCategories.lists(declared)[0]])
}
override func tearDown() {
for session in sessions { session.destroy() }
sessions = []
NotificationPresenter.shared.app = nil
NotificationPresenter.shared.activate = nil
NotificationPresenter.shared.boot = nil
restorePresenter?()
UserDefaults.standard.set(kept, forKey: DeclaredCategories.key)
super.tearDown()
}
/// The system's response to a chosen action; a push trigger has no
/// public initializer.
private func response(_ info: [AnyHashable: Any], category: String, action: String, text: String = "",
push: Bool = false, definition: DeclaredAction? = nil) -> UNNotificationResponse {
let content = UNMutableNotificationContent()
content.userInfo = info
content.categoryIdentifier = category
let request = UNNotificationRequest(identifier: "req-\(UUID().uuidString)", content: content, trigger: nil)
ActionRequest.triggerValue = push ? class_createInstance(UNPushNotificationTrigger.self, 0) as? UNPushNotificationTrigger : nil
object_setClass(request, ActionRequest.self)
ActionNotification.dateValue = Date()
ActionNotification.requestValue = request
ActionResponse.notificationValue = class_createInstance(ActionNotification.self, 0) as? ActionNotification
ActionResponse.actionValue = (definition ?? DeclaredCategories.lists(declared).flatMap { $0 }.first { $0.action == action })?.platform.identifier ?? action
ActionResponse.textValue = text
return class_createInstance(ActionResponse.self, 0) as! ActionResponse
}
/// The response as the delegate receives it; whether its completion
/// handler was called.
@discardableResult
private func choose(_ response: UNNotificationResponse) -> () -> Bool {
let center = class_createInstance(UNUserNotificationCenter.self, 0) as! UNUserNotificationCenter
var completed = false
NotificationPresenter.shared.userNotificationCenter(center, didReceive: response) { completed = true }
return { completed }
}
private func session(label: String = "actions") -> (ExactSession, () -> Int) {
let session = ExactApp.shared.makeSession(label: "\(label)-\(UUID().uuidString)")
sessions.append(session)
NotificationPresenter.shared.app = ExactApp.shared
NotificationPresenter.shared.declare(DeclaredCategories.lists(declared), for: session)
var activations = 0
NotificationPresenter.shared.activate = { if $0 === session { activations += 1 } }
return (session, { activations })
}
/// A local post's activation entry, as the package writes it.
private func entry(_ session: ExactSession) -> [AnyHashable: Any] {
["exact": ["session": session.label, "owner": session.notificationOwnerID, "process": ExactApp.shared.notificationProcessID,
"extension": "notifications", "event": "notificationclick", "chosen": 1,
"args": #"["p1",{"tag":"p1","data":"/p/1","title":"Coffee","body":null}]"#]]
}
private func held(_ session: ExactSession) -> [[String: Any]] {
session.heldModuleEvents.compactMap { (try? JSONSerialization.jsonObject(with: Data($0.utf8))) as? [String: Any] }
}
#if os(macOS)
func testTheNotificationInstallerBindsAnActivationClosure() {
let (session, _) = self.session()
var activated = false
ExactApp.shared.installNotificationClicks(boot: nil, activate: { target in activated = target === session })
NotificationPresenter.shared.activate?(session)
XCTAssertTrue(activated)
XCTAssertNil(NotificationPresenter.shared.boot)
activated = false
choose(response(entry(session), category: "", action: UNNotificationDefaultActionIdentifier))
XCTAssertTrue(activated, "the notification body activates the Mac adapter")
activated = false
choose(response(entry(session), category: "approve,note", action: "note", text: "Reply"))
XCTAssertTrue(activated, "a foreground action activates the Mac adapter")
activated = false
NotificationPresenter.shared.currentCategories = [:]
choose(response(entry(session), category: "approve,note", action: "approve"))
XCTAssertFalse(activated, "waiting for declarations never activates the app")
}
#endif
func testAReplacementWaitsForItsOwnDeclarations() throws {
let (session, _) = self.session()
try boot(session)
waitForActivation(session)
let candidate = try XCTUnwrap(session.prepare(try fixturePlan("NOTIFICATION_NO_ACTIONS"), resolver: ExactApp.shared.resolver, size: CGSize(width: 390, height: 844)))
let batch = try XCTUnwrap(session.commit(candidate))
session.presentCommitted(batch, label: "notification declarations")
let completed = choose(response(entry(session), category: "approve,note", action: "approve"))
XCTAssertFalse(completed(), "authorization waits for the replacement's declarations")
XCTAssertFalse(acted(session).contains("p1 approve"), acted(session))
session.raiseModuleEvent(extension: "notifications", event: "notificationclick",
args: #"["plain",{"tag":"plain","data":null,"title":"","body":null,"action":null,"reply":null}]"#, activation: true)
XCTAssertFalse(acted(session).contains("plain"), "a previous data generation cannot receive a module event")
session.drawReceipt().drawn()
waitForActivation(session)
XCTAssertTrue(completed())
XCTAssertFalse(acted(session).contains("p1 approve"), acted(session))
XCTAssertTrue(acted(session).contains("plain"), acted(session))
}
func testARegisteredResponseWaitsForDataAndRevalidatesAfterReplacement() throws {
let (session, activations) = self.session()
XCTAssertNil(session.boot(plan: try fixturePlan("NOTIFICATION_ACTIONS"), size: CGSize(width: 390, height: 844)).error)
NotificationPresenter.shared.declare(DeclaredCategories.lists(declared), for: session)
let completed = choose(response(entry(session), category: "approve,note", action: "note", text: "Old"))
XCTAssertFalse(completed(), "registration alone does not deliver before data activation")
XCTAssertEqual(activations(), 0)
let candidate = try XCTUnwrap(session.prepare(try fixturePlan("NOTIFICATION_NO_ACTIONS"), resolver: ExactApp.shared.resolver, size: CGSize(width: 390, height: 844)))
let batch = try XCTUnwrap(session.commit(candidate))
session.presentCommitted(batch, label: "replace before action delivery")
session.drawReceipt().drawn()
waitForActivation(session)
XCTAssertTrue(completed())
XCTAssertEqual(activations(), 0)
XCTAssertFalse(acted(session).contains("p1 note Old"), "a response must be checked against the generation that hears it")
}
func testAnotherSessionCannotRemoveThePostingSessionsCategories() throws {
let (a, _) = self.session(label: "a")
let (b, _) = self.session(label: "b")
try boot(a)
waitForActivation(a)
XCTAssertNil(b.boot(plan: try fixturePlan("NOTIFICATION_NO_ACTIONS"), size: CGSize(width: 390, height: 844)).error)
b.drawReceipt().drawn()
waitForActivation(b)
XCTAssertEqual(Set(registered.map(\.identifier)), ["approve,note"])
let completed = choose(response(entry(a), category: "approve,note", action: "approve"))
waitFor("the posting session's action ends") { completed() }
XCTAssertTrue(acted(a).contains("p1 approve"), acted(a))
choose(response(entry(b), category: "approve,note", action: "approve"))
XCTAssertFalse(acted(b).contains("p1 approve"), acted(b))
a.destroy()
XCTAssertTrue(registered.isEmpty, "ending a session removes only its categories")
}
func testAPushActionFindsTheFirstSessionThatDeclaresIt() throws {
let (a, _) = self.session(label: "without-actions")
let (b, _) = self.session(label: "declaring")
XCTAssertNil(a.boot(plan: try fixturePlan("NOTIFICATION_NO_ACTIONS"), size: CGSize(width: 390, height: 844)).error)
a.drawReceipt().drawn()
waitForActivation(a)
try boot(b)
waitForActivation(b)
let push = response(["aps": ["category": "approve,note"]], category: "approve,note", action: "approve", push: true)
let completed = choose(push)
waitFor("the push action ends") { completed() }
XCTAssertFalse(acted(a).contains("approve"), acted(a))
XCTAssertTrue(acted(b).contains(push.notification.request.identifier + " approve"), acted(b))
XCTAssertNil(NotificationPresenter.shared.opened[ObjectIdentifier(b)])
}
func testAWaitingPushMovesItsHoldToTheDeclaringSession() throws {
let (a, _) = self.session(label: "first")
let (b, _) = self.session(label: "declaring")
XCTAssertNil(a.boot(plan: try fixturePlan("NOTIFICATION_NO_ACTIONS"), size: CGSize(width: 390, height: 844)).error)
XCTAssertNil(b.boot(plan: try fixturePlan("NOTIFICATION_ACTIONS"), size: CGSize(width: 390, height: 844)).error)
NotificationPresenter.shared.currentCategories = [:]
let push = response([:], category: "approve,note", action: "approve", push: true)
var completed = false
NotificationPresenter.shared.chose(push, to: a) { completed = true }
XCTAssertNotNil(NotificationPresenter.shared.opened[ObjectIdentifier(a)])
a.drawReceipt().drawn()
waitForActivation(a)
XCTAssertFalse(completed)
XCTAssertNil(NotificationPresenter.shared.opened[ObjectIdentifier(a)])
XCTAssertNotNil(NotificationPresenter.shared.opened[ObjectIdentifier(b)])
b.drawReceipt().drawn()
waitForActivation(b)
XCTAssertTrue(completed)
XCTAssertTrue(acted(b).contains(push.notification.request.identifier + " approve"), acted(b))
XCTAssertNil(NotificationPresenter.shared.opened[ObjectIdentifier(b)])
}
func testAnInvisibleContinuationReleasesTheBackgroundAction() throws {
let (session, _) = self.session()
try boot(session)
waitForActivation(session)
var reply: UnsafeMutableRawPointer?
let later: ExactAppLaterFn = { ctx, _, _, pending in
ctx?.assumingMemoryBound(to: UnsafeMutableRawPointer?.self).pointee = pending
}
withUnsafeMutablePointer(to: &reply) { pointer in
Owner.shared.sync { exact_set_app_module(session.runtime.rt, later, nil, pointer) }
session.runtime.bindExtensions(["quick-actions"])
var completed = false
NotificationPresenter.shared.background(session, extension: "notifications", event: "notificationclick",
args: #"["quiet",{"tag":"quiet","data":null,"title":"","body":null,"action":"approve","reply":null}]"#) { completed = true }
waitFor("the action request") { pointer.pointee != nil }
XCTAssertFalse(completed)
if let pending = pointer.pointee {
Data(#"{"state":"unsupported"}"#.utf8).withUnsafeBytes {
exact_app_reply(pending, 200, $0.bindMemory(to: UInt8.self).baseAddress, $0.count)
}
}
waitFor("the continuation ends") { session.agent("{\"op\":\"actions\"}").contains("completed") }
session.drainFill()
XCTAssertTrue(completed, "an ending with no presentation change still releases the delegate")
XCTAssertNil(NotificationPresenter.shared.opened[ObjectIdentifier(session)])
}
}
func testConflictingCategoriesAreRefusedUntilTheConflictEnds() throws {
let (a, _) = self.session(label: "a")
let (b, _) = self.session(label: "b")
let presenter = NotificationPresenter.shared
var conflicting = DeclaredCategories.lists(declared)[0]
conflicting[0] = try XCTUnwrap(DeclaredAction(["action": "approve", "title": "Other approval", "foreground": true]))
presenter.declare([conflicting], for: b)
XCTAssertTrue(registered.isEmpty)
XCTAssertNil(presenter.declared("approve", in: "approve,note", for: a))
XCTAssertNil(presenter.declared("approve", in: "approve,note", for: b))
b.destroy()
XCTAssertEqual(Set(registered.map(\.identifier)), ["approve,note"])
XCTAssertNotNil(presenter.declared("approve", in: "approve,note", for: a))
}
func testThePlansListsAreRegisteredAsCategories() throws {
let (session, _) = self.session()
let lists = DeclaredCategories.lists(declared)
XCTAssertEqual(lists.count, 1)
XCTAssertEqual(DeclaredCategories.identifier(lists[0]), "approve,note")
let approve = lists[0][0].platform, note = lists[0][1].platform
XCTAssertEqual(approve.identifier, lists[0][0].identifier)
XCTAssertEqual(approve.options, [.authenticationRequired], "a background action brings nothing forward")
XCTAssertFalse(approve is UNTextInputNotificationAction)
XCTAssertEqual(note.options, [.foreground])
XCTAssertEqual((note as? UNTextInputNotificationAction)?.textInputPlaceholder, "Note")
let destructive = try XCTUnwrap(DeclaredAction(["action": "delete", "title": "Delete", "foreground": false, "destructive": true]))
XCTAssertEqual(destructive.platform.options, [.destructive])
XCTAssertTrue(DeclaredCategories.lists("{}").isEmpty)
// An embedder's own category stays beside the app's.
registered = [UNNotificationCategory(identifier: "embedder", actions: [], intentIdentifiers: [], options: [])]
NotificationPresenter.shared.declare(lists, for: session)
let ids = Set(registered.map(\.identifier))
let approveNote = try XCTUnwrap(registered.first { $0.identifier == "approve,note" })
XCTAssertEqual(approveNote.actions.map(\.identifier), lists[0].map(\.identifier))
XCTAssertEqual(ids, ["approve,note", "embedder"])
}
func testRemovedCategoriesAreReconciledIncludingAnEmptyPlan() throws {
let (session, _) = self.session()
let lists = DeclaredCategories.lists(declared)
let old = UNNotificationCategory(identifier: "approve,note", actions: lists[0].map(\.platform), intentIdentifiers: [], options: [])
let embedder = UNNotificationCategory(identifier: "embedder", actions: [], intentIdentifiers: [], options: [])
registered = [old, embedder]
NotificationPresenter.shared.declare([[lists[0][0]]], for: session)
XCTAssertEqual(Set(registered.map(\.identifier)), ["approve", "embedder"])
XCTAssertNil(NotificationPresenter.shared.declared("approve", in: "approve,note", for: session))
NotificationPresenter.shared.declare([], for: session)
XCTAssertEqual(Set(registered.map(\.identifier)), ["embedder"])
XCTAssertNil(NotificationPresenter.shared.declared("approve", in: "approve", for: session))
}
func testCategoryOwnershipTransitionsPreserveEmbedderDefinitions() throws {
let (a, _) = session(label: "owner")
let presenter = NotificationPresenter.shared
let lists = DeclaredCategories.lists(declared)
presenter.declare([], for: a)
XCTAssertTrue(DeclaredCategories.kept.isEmpty, "removal relinquishes ownership")
let embedder = UNNotificationCategory(identifier: "approve,note", actions: [], intentIdentifiers: [], options: [])
registered = [embedder]
presenter.declare([], for: a)
XCTAssertEqual(registered, [embedder], "a released name belongs to its new owner")
DeclaredCategories.keep([:])
registered = [embedder]
presenter.declare(lists, for: a)
XCTAssertEqual(registered, [embedder], "a new claim cannot replace an embedder")
XCTAssertNil(presenter.declared("approve", in: "approve,note", for: a))
a.destroy()
XCTAssertEqual(registered, [embedder], "teardown cannot remove the refused claim")
registered = []
let (b, _) = session(label: "new-owner")
XCTAssertNotNil(presenter.declared("approve", in: "approve,note", for: b))
let (c, _) = session(label: "shared-owner")
b.destroy()
XCTAssertNotNil(presenter.declared("approve", in: "approve,note", for: c))
c.destroy()
XCTAssertTrue(registered.isEmpty)
XCTAssertTrue(DeclaredCategories.kept.isEmpty)
}
func testRegistrationPrecedesDataActivationAndWaitingResponses() throws {
let (session, _) = self.session()
let presenter = NotificationPresenter.shared
presenter.currentCategories = [:]
var read: ((Set<UNNotificationCategory>) -> Void)?
presenter.categories.read = { read = $0 }
let completed = choose(response(entry(session), category: "approve,note", action: "note"))
XCTAssertFalse(completed())
try boot(session)
waitFor("the category read") { read != nil }
XCTAssertNil(session.preparedGeneration, "initial data code cannot post before registration")
XCTAssertFalse(session.dataActivated)
XCTAssertFalse(completed(), "an action that can post also waits for registration")
let finish = try XCTUnwrap(read)
presenter.categories.read = { [unowned self] in $0(registered) }
finish(registered)
waitForActivation(session)
XCTAssertTrue(session.dataActivated)
XCTAssertTrue(completed())
XCTAssertEqual(Set(registered.map(\.identifier)), ["approve,note"])
}
func testReplacementSettlesRaisedActionsButKeepsUnauthorizedResponses() throws {
let (session, _) = self.session()
try boot(session)
waitForActivation(session)
var reply: UnsafeMutableRawPointer?
let later: ExactAppLaterFn = { ctx, _, _, pending in
ctx?.assumingMemoryBound(to: UnsafeMutableRawPointer?.self).pointee = pending
}
try withUnsafeMutablePointer(to: &reply) { pointer in
Owner.shared.sync { exact_set_app_module(session.runtime.rt, later, nil, pointer) }
session.runtime.bindExtensions(["quick-actions"])
var completed = 0
NotificationPresenter.shared.background(session, extension: "notifications", event: "notificationclick",
args: #"["wait",{"tag":"wait","data":null,"title":"","body":null,"action":"approve","reply":null}]"#) { completed += 1 }
waitFor("the action's request") { pointer.pointee != nil }
XCTAssertEqual(completed, 0)
let candidate = try XCTUnwrap(session.prepare(try fixturePlan("NOTIFICATION_ACTIONS"), resolver: ExactApp.shared.resolver, size: CGSize(width: 390, height: 844)))
let batch = try XCTUnwrap(session.commit(candidate))
session.presentCommitted(batch, label: "notification action replacement")
XCTAssertEqual(completed, 1, "the replaced runner cannot report the action's end")
let waiting = choose(response(entry(session), category: "approve,note", action: "note"))
XCTAssertFalse(waiting(), "a response awaiting the new declarations is separate")
session.drawReceipt().drawn()
waitForActivation(session)
XCTAssertTrue(waiting())
XCTAssertEqual(completed, 1)
if let pending = pointer.pointee {
Data("{}".utf8).withUnsafeBytes {
exact_app_reply(pending, 200, $0.bindMemory(to: UInt8.self).baseAddress, $0.count)
}
}
}
}
func testCategoryReconciliationSerializesReads() {
let (session, _) = self.session()
var reads: [(Set<UNNotificationCategory>) -> Void] = []
let read = NotificationPresenter.shared.categories.read
defer { NotificationPresenter.shared.categories.read = read }
NotificationPresenter.shared.categories.read = { reads.append($0) }
let lists = DeclaredCategories.lists(declared)
NotificationPresenter.shared.declare([[lists[0][0]]], for: session)
NotificationPresenter.shared.declare(lists, for: session)
XCTAssertEqual(reads.count, 1, "a second read must wait for the first write")
guard !reads.isEmpty else { return XCTFail("no category read") }
let first = reads.removeFirst()
first([])
if !reads.isEmpty { reads.removeFirst()(registered) }
XCTAssertEqual(Set(registered.map(\.identifier)), ["approve,note"])
}
func testAForegroundActionIsTheClickWithItsNameAndReply() throws {
let (session, activations) = self.session()
let completed = choose(response(entry(session), category: "approve,note", action: "note", text: "On my way"))
XCTAssertTrue(completed(), "a foreground action lets the app go at once")
XCTAssertEqual(activations(), 1)
let event = try XCTUnwrap(held(session).first)
XCTAssertNil(event["background"])
XCTAssertEqual(event["activation"] as? Bool, true)
let args = try XCTUnwrap(event["args"] as? [Any])
let fields = try XCTUnwrap(args.last as? [String: Any])
XCTAssertEqual(fields["action"] as? String, "note")
XCTAssertEqual(fields["reply"] as? String, "On my way")
XCTAssertEqual(fields["data"] as? String, "/p/1", "a local post's own data")
XCTAssertNil(session.launchLocation, "an action never opens a location")
}
/// A push's action carries its identifier as the tag, the action and the
/// reply, and nothing else of the payload: not a forged entry, not its
/// keys, not its `navigate`.
func testAPushsActionCarriesOnlyItsIdentifierTheActionAndTheReply() throws {
let (session, _) = self.session()
var info = entry(session)
info["aps"] = ["alert": ["title": "Coffee", "body": "$4.50"], "category": "approve,note"]
info["proposalId"] = "p9"
info["navigate"] = "/forged"
let chosen = response(info, category: "approve,note", action: "note", text: "Later", push: true)
choose(chosen)
let event = try XCTUnwrap(held(session).first)
XCTAssertEqual(event["extension"] as? String, "notifications")
XCTAssertEqual(event["event"] as? String, "notificationclick")
let args = try XCTUnwrap(event["args"] as? [Any])
let id = chosen.notification.request.identifier
XCTAssertEqual(args.first as? String, id)
let fields = try XCTUnwrap(args.last as? [String: Any])
XCTAssertEqual(fields["tag"] as? String, id)
XCTAssertTrue(fields["data"] is NSNull, "\(fields)")
XCTAssertEqual(fields["title"] as? String, "")
XCTAssertEqual(fields["action"] as? String, "note")
XCTAssertEqual(fields["reply"] as? String, "Later")
XCTAssertNil(session.launchLocation)
}
func testAnActionTheAppDidNotDeclareRaisesNothing() {
let (session, activations) = self.session()
for (category, action) in [("approve,note", "delete"), ("embedder", "approve"), ("", "approve")] {
let completed = choose(response(entry(session), category: category, action: action))
XCTAssertTrue(completed(), "\(category) \(action)")
}
XCTAssertTrue(session.heldModuleEvents.isEmpty)
XCTAssertEqual(activations(), 0)
}
func testTheFirstUnlockMarkerIsCreatedAndReadWithAfterFirstUnlockProtection() {
for added in [errSecSuccess, errSecDuplicateItem, errSecInteractionNotAllowed] {
var reads = 0
let available = NotificationFirstUnlock.available(read: { query in
let q = query as NSDictionary
XCTAssertEqual(q[kSecClass] as? String, kSecClassGenericPassword as String)
XCTAssertEqual(q[kSecReturnData] as? Bool, true)
XCTAssertEqual(q[kSecUseAuthenticationUI] as? String, kSecUseAuthenticationUIFail as String)
reads += 1
return reads == 1 ? errSecItemNotFound : errSecSuccess
}, add: { item in
let q = item as NSDictionary
XCTAssertEqual(q[kSecAttrAccessible] as? String, kSecAttrAccessibleAfterFirstUnlock as String)
XCTAssertEqual(q[kSecValueData] as? Data, Data([1]))
return added
})
XCTAssertEqual(available, added != errSecInteractionNotAllowed)
XCTAssertEqual(reads, available ? 2 : 1)
}
}
func testABeforeFirstUnlockResponseCompletesWithoutBootOrDelivery() {
let presenter = NotificationPresenter.shared
let original = presenter.firstUnlockAvailable
defer { presenter.firstUnlockAvailable = original }
presenter.firstUnlockAvailable = {
NotificationFirstUnlock.available(read: { _ in errSecInteractionNotAllowed }, add: { _ in
XCTFail("an inaccessible marker is not a missing marker")
return errSecInteractionNotAllowed
})
}
let (session, activations) = self.session()
let action = DeclaredAction(["action": "approve", "title": "Approve", "foreground": false,
"authenticationRequired": false])!
var boots = 0
presenter.boot = { _ in boots += 1 }
for hasDeclarations in [false, true] {
presenter.currentCategories = [:]
if hasDeclarations { presenter.declare([[action]], for: session) }
let completed = choose(response(entry(session), category: "approve", action: "approve", definition: action))
XCTAssertTrue(completed(), "a response before first unlock must not wait for data")
XCTAssertEqual(boots, 0)
XCTAssertFalse(session.booted)
XCTAssertFalse(session.dataActivated)
XCTAssertTrue(session.heldModuleEvents.isEmpty)
XCTAssertNil(presenter.opened[ObjectIdentifier(session)])
XCTAssertEqual(activations(), 0)
}
}
func testAColdResponseWaitsForCurrentDeclarations() {
let presenter = NotificationPresenter.shared
let (session, activations) = self.session()
presenter.currentCategories = [:]
var boots = 0
presenter.boot = { _ in boots += 1 }
// Keep the category ID unchanged while the update newly requires an unlock.
var old = DeclaredCategories.lists(declared)[0]
old[0] = DeclaredAction(["action": "approve", "title": "Approve", "foreground": false])!
DeclaredCategories.keep(["approve,note": old])
registered = [UNNotificationCategory(identifier: "approve,note", actions: old.map(\.platform), intentIdentifiers: [], options: [])]
let completed = choose(response(entry(session), category: "approve,note", action: "approve", definition: old[0]))
XCTAssertFalse(completed())
XCTAssertEqual(boots, 1)
XCTAssertTrue(session.heldModuleEvents.isEmpty)
presenter.declare(DeclaredCategories.lists(declared), for: session)
XCTAssertTrue(completed())
XCTAssertEqual(activations(), 0)
XCTAssertTrue(session.heldModuleEvents.isEmpty)
// The old system action stays refused after reconciliation and another launch.
presenter.currentCategories = [:]
presenter.registeredCategories = [:]
let relaunched = choose(response(entry(session), category: "approve,note", action: "approve", definition: old[0]))
presenter.declare(DeclaredCategories.lists(declared), for: session)
XCTAssertTrue(relaunched())
XCTAssertTrue(session.heldModuleEvents.isEmpty)
choose(response(entry(session), category: "approve,note", action: "note", text: "Current"))
XCTAssertEqual(activations(), 1, "a current system action still works")
}
#if os(iOS)
func testALockedAfterFirstUnlockResponseBootsAndDelivers() throws {
guard hostedWindowScene() != nil else { throw missing("scene", "bootForWake needs the host's UIApplication") }
let state = try XCTUnwrap(class_getInstanceMethod(UIApplication.self, #selector(getter: UIApplication.applicationState)))
let background = try XCTUnwrap(class_getInstanceMethod(UIApplication.self, #selector(getter: UIApplication.notificationActionBackgroundState)))
let protected = try XCTUnwrap(class_getInstanceMethod(UIApplication.self, #selector(getter: UIApplication.isProtectedDataAvailable)))
let locked = try XCTUnwrap(class_getInstanceMethod(UIApplication.self, #selector(getter: UIApplication.notificationActionProtectedDataUnavailable)))
method_exchangeImplementations(state, background)
method_exchangeImplementations(protected, locked)
let presenter = NotificationPresenter.shared
let original = presenter.firstUnlockAvailable
defer {
presenter.firstUnlockAvailable = original
method_exchangeImplementations(state, background)
method_exchangeImplementations(protected, locked)
}
XCTAssertFalse(UIApplication.shared.isProtectedDataAvailable)
var reads = 0
presenter.firstUnlockAvailable = {
NotificationFirstUnlock.available(read: { _ in reads += 1; return errSecSuccess }, add: { _ in
XCTFail("the marker already exists")
return errSecDuplicateItem
})
}
let (session, activations) = self.session()
presenter.currentCategories = [:]
let plan = try fixturePlan("NOTIFICATION_ACTIONS")
var boots = 0
presenter.boot = { target in
boots += 1
XCTAssertNil(target.boot(plan: plan, size: CGSize(width: 390, height: 844)).error)
target.bootForWake()
}
let completed = choose(response(entry(session), category: "approve,note", action: "approve"))
spin { completed() }
XCTAssertGreaterThan(reads, 0)
XCTAssertEqual(boots, 1)
XCTAssertTrue(session.dataActivated)
XCTAssertTrue(acted(session).contains("p1 approve"), acted(session))
XCTAssertNil(session.view)
XCTAssertEqual(activations(), 0)
XCTAssertNil(presenter.opened[ObjectIdentifier(session)])
}
func testABackgroundActionActivatesABootedUndrawnSession() throws {
guard hostedWindowScene() != nil else { throw missing("scene", "bootForWake needs the host's UIApplication") }
let state = try XCTUnwrap(class_getInstanceMethod(UIApplication.self, #selector(getter: UIApplication.applicationState)))
let background = try XCTUnwrap(class_getInstanceMethod(UIApplication.self, #selector(getter: UIApplication.notificationActionBackgroundState)))
method_exchangeImplementations(state, background)
defer { method_exchangeImplementations(state, background) }
XCTAssertEqual(UIApplication.shared.applicationState, .background)
let (session, activations) = self.session()
XCTAssertNil(session.boot(plan: try fixturePlan("NOTIFICATION_ACTIONS"), size: CGSize(width: 390, height: 844)).error)
XCTAssertTrue(session.booted)
XCTAssertNil(session.firstDrawMs)
XCTAssertFalse(session.dataActivated)
NotificationPresenter.shared.boot = { $0.bootForWake() }
let completed = choose(response(entry(session), category: "approve,note", action: "approve"))
spin { completed() }
XCTAssertTrue(completed())
XCTAssertTrue(session.dataActivated)
XCTAssertNil(session.view, "background activation needs no drawn view")
XCTAssertEqual(activations(), 0)
XCTAssertTrue(acted(session).contains("p1 approve"), acted(session))
let facts = try XCTUnwrap(try JSONSerialization.jsonObject(with: Data(session.agent("{\"op\":\"state\"}").utf8)) as? [String: Any])
XCTAssertEqual((facts["wake"] as? [String: Any])?["cold"] as? Bool, false)
XCTAssertNil(NotificationPresenter.shared.opened[ObjectIdentifier(session)])
}
func testABackgroundActionActivatesAReplacementWithoutAnotherDraw() throws {
guard hostedWindowScene() != nil else { throw missing("scene", "bootForWake needs the host's UIApplication") }
let state = try XCTUnwrap(class_getInstanceMethod(UIApplication.self, #selector(getter: UIApplication.applicationState)))
let background = try XCTUnwrap(class_getInstanceMethod(UIApplication.self, #selector(getter: UIApplication.notificationActionBackgroundState)))
method_exchangeImplementations(state, background)
defer { method_exchangeImplementations(state, background) }
let (session, activations) = self.session()
try boot(session)
waitForActivation(session)
let firstDraw = session.firstDrawMs
let candidate = try XCTUnwrap(session.prepare(try fixturePlan("NOTIFICATION_ACTIONS"), resolver: ExactApp.shared.resolver, size: CGSize(width: 390, height: 844)))
session.presentCommitted(try XCTUnwrap(session.commit(candidate)), label: "background replacement")
XCTAssertFalse(session.dataActivated)
NotificationPresenter.shared.boot = { $0.bootForWake() }
let completed = choose(response(entry(session), category: "approve,note", action: "approve"))
waitForMainQueue()
waitForActivation(session)
XCTAssertTrue(session.dataActivated, "the current generation activates without another draw")
XCTAssertTrue(completed())
XCTAssertEqual(session.firstDrawMs, firstDraw)
XCTAssertEqual(activations(), 0)
XCTAssertTrue(acted(session).contains("p1 approve"), acted(session))
}
func testInlineExpiryDoesNotQueueOrBootTheAction() throws {
let original = OpenAction.beginTask
defer { OpenAction.beginTask = original }
var began = false
OpenAction.beginTask = { expire in
began = true
expire()
return .invalid
}
let (session, _) = self.session()
var boots = 0
NotificationPresenter.shared.boot = { _ in boots += 1 }
let completed = choose(response(entry(session), category: "approve,note", action: "approve"))
XCTAssertTrue(completed())
XCTAssertTrue(began)
XCTAssertEqual(boots, 0)
XCTAssertTrue(session.heldModuleEvents.isEmpty)
}
func testExpiryAfterBootBeforeDataActivationDoesNotRun() throws {
let (session, _) = self.session()
XCTAssertNil(session.boot(plan: try fixturePlan("NOTIFICATION_ACTIONS"), size: CGSize(width: 390, height: 844)).error)
let completed = choose(response(entry(session), category: "approve,note", action: "approve"))
let open = try XCTUnwrap(NotificationPresenter.shared.opened[ObjectIdentifier(session)]?.first)
NotificationPresenter.shared.expire(open, in: session)
XCTAssertTrue(completed())
XCTAssertTrue(session.heldModuleEvents.isEmpty)
session.drawReceipt().drawn()
waitForActivation(session)
XCTAssertFalse(acted(session).contains("p1 approve"), acted(session))
}
#endif
/// Boot `session` on the fixture and draw its first pixel, which
/// activates its data.
private func boot(_ session: ExactSession) throws {
XCTAssertNil(session.boot(plan: try fixturePlan("NOTIFICATION_ACTIONS"), size: CGSize(width: 390, height: 844)).error)
session.drawReceipt().drawn()
}
/// The tree, which shows what the root's handler heard.
private func acted(_ session: ExactSession) -> String { session.agent("{\"op\":\"tree\"}") }
private func spin(until done: () -> Bool, seconds: TimeInterval = 10) {
waitFor("the notification action completes", cap: seconds, done)
}
/// The background action: raised as one (`background`), heard by the
/// root's handler with the action's name, and the delegate's completion
/// called only once the runner says the invocation ended.
func testABackgroundActionHoldsTheAppUntilTheRunnerSaysItEnded() throws {
let (session, activations) = self.session()
try boot(session)
spin { session.dataActivated }
XCTAssertTrue(session.dataActivated)
let completed = choose(response(entry(session), category: "approve,note", action: "approve"))
spin { completed() }
XCTAssertTrue(completed(), "the runner said it ended: \(session.agent("{\"op\":\"actions\"}"))")
XCTAssertEqual(activations(), 0, "a background action brings nothing forward")
XCTAssertTrue(acted(session).contains("p1 approve"), acted(session))
let journal = session.agent("{\"op\":\"logs\"}")
XCTAssertTrue(journal.contains("action notificationclick p1: completed"), journal)
}
func testAnActionWithoutAHandlerReleasesTheApp() throws {
let (session, _) = self.session()
try boot(session)
waitForActivation(session)
var completions = 0
NotificationPresenter.shared.background(session, extension: "missing", event: "notificationclick", args: "[]") { completions += 1 }
XCTAssertEqual(completions, 1)
XCTAssertNil(NotificationPresenter.shared.opened[ObjectIdentifier(session)])
XCTAssertTrue(session.agent("{\"op\":\"actions\"}").contains("unheard"))
}
/// A background action that finds no booted session (the system launched
/// the app for it): the host boots one with no view, the action is
/// delivered once its data is up, and the app is let go after.
func testABackgroundActionBootsAColdSession() throws {
let (session, _) = self.session()
NotificationPresenter.shared.currentCategories = [:]
var booted = 0
NotificationPresenter.shared.boot = { target in
XCTAssertTrue(target === session)
booted += 1
try? self.boot(target)
}
let completed = choose(response(entry(session), category: "approve,note", action: "approve"))
XCTAssertEqual(booted, 1)
XCTAssertFalse(completed(), "held until the session has heard it and its work ended")
spin { completed() }
XCTAssertTrue(completed())
XCTAssertTrue(acted(session).contains("p1 approve"), acted(session))
let state = try XCTUnwrap(try JSONSerialization.jsonObject(with: Data(session.agent("{\"op\":\"state\"}").utf8)) as? [String: Any])
XCTAssertEqual((state["wake"] as? [String: Any])?["cold"] as? Bool, true)
let journal = session.agent("{\"op\":\"logs\"}")
XCTAssertTrue(journal.contains("action notificationclick p1: raised"), journal)
}
func testAnEmbedderBootsOnlyThePostingSession() throws {
let (a, _) = self.session(label: "a")
let (b, _) = self.session(label: "b")
NotificationPresenter.shared.currentCategories = [:]
var booted: [String] = []
NotificationPresenter.shared.boot = { target in
booted.append(target.label)
try? self.boot(target)
}
let completed = choose(response(entry(b), category: "approve,note", action: "approve"))
spin { completed() }
XCTAssertTrue(completed())
XCTAssertEqual(booted, [b.label])
XCTAssertFalse(a.booted)
XCTAssertTrue(acted(b).contains("p1 approve"), acted(b))
}
/// The system's time ran out before the action ended (here, its session
/// never booted): the action expires and the app is let go.
func testExpiryLetsTheAppGo() throws {
let (session, _) = self.session()
let completed = choose(response(entry(session), category: "approve,note", action: "approve"))
XCTAssertFalse(completed())
let copied = session.heldModuleEvents
let open = try XCTUnwrap(NotificationPresenter.shared.opened[ObjectIdentifier(session)]?.first)
NotificationPresenter.shared.expire(open, in: session)
XCTAssertTrue(completed(), "let go inside the expiration handler")
XCTAssertNil(NotificationPresenter.shared.opened[ObjectIdentifier(session)])
XCTAssertTrue(session.heldModuleEvents.isEmpty, "expired actions must leave the preboot queue")
try boot(session)
waitForActivation(session)
XCTAssertFalse(acted(session).contains("p1 approve"), acted(session))
session.heldModuleEvents = copied
session.deliverModuleEvents()
XCTAssertFalse(acted(session).contains("p1 approve"), "a copy taken before expiry must also be refused")
}
}
#endif
+34
View File
@@ -0,0 +1,34 @@
// NotificationActionTests' app: a post that declares a background action
// and a text action (LLP 1133.004 stage 2), and the root's handler, which
// shows what it heard.
use showNotification, notificationclick, NotificationEvent, NotificationAction from "@exact/notifications"
use clearAppShortcuts, requestPinShortcut, ShortcutItem, PinShortcutResult from "@exact/quick-actions"
component App
state acted = "none"
state finished = false
mutation status as shape PinShortcutResult then finish
action finish
finished = true
action clicked(tag: string, e: NotificationEvent)
if tag == "wait"
clearAppShortcuts()
if tag == "quiet"
send status = requestPinShortcut(shortcut=ShortcutItem(name="quiet", short_name=none, description=none, url="/", icons=none, apple=none, android=none))
match e.action
case some(a)
match e.reply
case some(r)
acted = `${tag} ${a} ${r}`
case none
acted = `${tag} ${a}`
case none
acted = tag
action review
showNotification(title="Coffee, $4.50", tag="p1", actions=[NotificationAction(action="approve", title="Approve", foreground=false, destructive=false, authenticationRequired=true, placeholder=none), NotificationAction(action="note", title="Add a note", foreground=true, destructive=false, authenticationRequired=false, placeholder=some("Note"))])
view
column notificationclick=clicked
text testId="acted" acted
button testId="review" press=review
text "Review"
+5
View File
@@ -55,6 +55,11 @@ export function compileFixtures(root, run, env, dir, prefix, appId) {
contract([resolve(root, 'host/apple/tests/fixtures/nested-panel-tabs.contract'), '-o', env[`${prefix}_NESTED_PANEL_TABS_PLAN`] = resolve(dir, 'nested-panel-tabs.plan')]);
// NavigationMoreIOSTests': more tabs than an iPhone's tab bar shows, so UIKit lists some under More.
contract([resolve(root, 'host/apple/tests/fixtures/more-tabs.contract'), '-o', env[`${prefix}_MORE_TABS_PLAN`] = resolve(dir, 'more-tabs.plan')]);
// NotificationActionTests': a post's declared actions and the root's handler.
contract([resolve(root, 'host/apple/tests/fixtures/notification-actions.contract'), '-o', env[`${prefix}_NOTIFICATION_ACTIONS_PLAN`] = resolve(dir, 'notification-actions.plan')]);
const noActions = resolve(dir, 'notification-no-actions.contract');
writeFileSync(noActions, readFileSync(resolve(root, 'host/apple/tests/fixtures/notification-actions.contract'), 'utf8').replace(/, actions=\[.*\]/, ''));
contract([noActions, '-o', env[`${prefix}_NOTIFICATION_NO_ACTIONS_PLAN`] = resolve(dir, 'notification-no-actions.plan')]);
contract([resolve(root, 'host/apple/tests/fixtures/feedback-race.contract'), '-o', env[`${prefix}_FEEDBACK_RACE_PLAN`] = resolve(dir, 'feedback-race.plan')]);
contract([resolve(root, 'host/apple/tests/fixtures/async-advance.contract'), '-o', env[`${prefix}_ASYNC_ADVANCE_PLAN`] = resolve(dir, 'async-advance.plan')]);
contract([resolve(root, 'host/apple/tests/fixtures/save-text.contract'), '-o', env[`${prefix}_SAVE_TEXT_PLAN`] = resolve(dir, 'save-text.plan')]);
@@ -17,6 +17,8 @@
// the app becomes active, announced when it changes.
// - An unbundled process has no notification centre (`current()` traps), so
// there `available` is false and every call refuses `NotSupportedError`.
// - `actions` (stage 2) names the category the host registered at launch
// from the plan's literal lists; the host's delegate hears the choice.
import ExactPackage
import Foundation
#if os(macOS)
@@ -100,7 +102,12 @@ public final class NotificationsModule: NSObject, ExactPackage {
// The platform's sound unless `silent` (D2): a hand-built app sets it, as this does.
content.sound = silent ? nil : .default
let event: [String: Any] = ["tag": tag, "data": args["data"] ?? NSNull(), "title": title, "body": args["body"] ?? NSNull()]
content.userInfo = context.activation("notificationclick", [tag, event], navigate: args["navigate"] as? String)
// A chosen action writes its name and reply into the event, argument 1 (stage 2).
content.userInfo = context.activation("notificationclick", [tag, event], navigate: args["navigate"] as? String, chosen: 1)
// The category the host registered from this literal list: its actions' names, joined by commas.
if let actions = args["actions"] as? [[String: Any]], !actions.isEmpty {
content.categoryIdentifier = actions.compactMap { $0["action"] as? String }.joined(separator: ",")
}
if let words = args["apple"] as? [String: Any] { apply(words, to: content) }
let at = (args["showTrigger"] as? NSNumber)?.doubleValue
let center = UNUserNotificationCenter.current()
+22 -4
View File
@@ -22,7 +22,17 @@
"tag": "string",
"data": "option<string>",
"title": "string",
"body": "option<string>"
"body": "option<string>",
"action": "option<string>",
"reply": "option<string>"
},
"NotificationAction": {
"action": "string",
"title": "string",
"foreground": "bool",
"destructive": "bool",
"authenticationRequired": "bool",
"placeholder": "option<string>"
}
},
"names": [
@@ -39,7 +49,12 @@
"silent": "option<bool>",
"data": "option<string>",
"showTrigger": "option<number>",
"navigate": "option<string>"
"navigate": "option<string>",
"actions": {
"type": "option<NotificationAction[]>",
"literal": true,
"declares": "action"
}
},
"answers": null,
"substitute": {
@@ -63,10 +78,13 @@
"tag": "tag",
"data": "data",
"title": "title",
"body": "body"
"body": "body",
"action": "action",
"reply": "reply"
}
],
"navigate": "navigate"
"navigate": "navigate",
"actions": "actions"
}
}
}
+12 -1
View File
@@ -864,7 +864,18 @@ names no take; `:focus-within` remains out.
(Declarative Web Push or a host worker). Still refused: push-to-start; a
data-only push as a wake's trigger (`content-available`, the
`remote-notification` background mode); a notification service extension; an
event raised by a push.
event raised by a push, but for a declared action the person chose (below).
**Expanded (Charlie, 2026-11-12, "build the ideal end state now", after a
design panel; expo/exact#127; LLP 1133.004 stage 2):** a notification's
actions on macOS and iOS: a post declares them as a literal list, which the
host registers as a category, and a push names one by `aps.category`; a
chosen action, and a typed reply, reach `notificationclick`. One that leaves
the app in the background runs its handler with no view, as the person's act
for that one action, held until its work has ended or the system's time has
run out. Consumer: expo/exact#127's app, whose pushes carry Approve. Unblocks
a notification's Snooze, Reply and Approve without app Swift. Take: none
named; the ruling stands as its own waiver. Not built: actions on Android,
Windows and the web; the dismissal; `requireInteraction`.
**Components** — roughly 15 built-in tags, not 40; roughly 12 Facet components, not 47.
+6
View File
@@ -51,6 +51,12 @@ pub fn handle<D: DataSource>(runner: &Runner<D>, request: &str) -> String {
// Whether the app must finish work an answer started (`must_finish`):
// what a host's quit waits for, cheaper than `state`.
Some("background") => format!("{{\"mustFinish\":{}}}", runner.must_finish()),
// Recent background action endings for diagnostics (LLP 1133.004
// stage 2). A host drains delivery through `take_ended_actions`.
Some("actions") => format!("{{\"ended\":{}}}", runner.ended_actions()),
// What the app's literals declare (LLP 1133.004 stage 2): the
// notification categories a host registers at launch.
Some("declared") => runner.declared_values().to_string(),
// A polled module source's ask in flight (LLP 1133.009 D10 item 7):
// what a jump waits for before it replies.
Some("polls") => format!("{{\"asking\":{}}}", runner.polls_asking()),
+9
View File
@@ -690,6 +690,15 @@ pub fn arm<D: DataSource>(
web_origin: Option<&str>,
) -> Arm {
let ticket = out.ticket;
if out.request.reach.origin == crate::CallOrigin::Action {
settle(
runner,
ticket,
403,
"auth sessions are refused during a background action",
);
return Arm::Settled;
}
let body = String::from_utf8_lossy(&out.request.body).into_owned();
let session = match Session::from_json(&body) {
Ok(s) => s,
+69 -5
View File
@@ -56,6 +56,13 @@ pub enum CallOrigin {
Wake,
/// A tool invocation (LLP 1111).
Tool,
/// A notification's background action the person chose (LLP 1133.004
/// stage 2, as amended 2026-11-12): the person's act for that one
/// declared action, run with no view. It may call a name held to the
/// app (`"origin": "app"`) that shows nothing; it opens no UI, so a
/// prompt, a presence check, a name only the foreground may call and
/// the host commands a wake may not run are refused, as for a wake.
Action,
/// A person's input, or the app's own code in a foreground session.
#[default]
App,
@@ -68,6 +75,7 @@ impl CallOrigin {
CallOrigin::Device => "device",
CallOrigin::Wake => "wake",
CallOrigin::Tool => "tool",
CallOrigin::Action => "action",
CallOrigin::App => "app",
}
}
@@ -231,9 +239,15 @@ impl<D: DataSource> Runner<D> {
}
/// Whether invocation `id` owns work in flight: a request, an armed
/// `then`, a held call or a queued send stamped with it.
/// `then`, a native statement, a held call or a queued send stamped with it.
pub(in crate::runner) fn invocation_owns(&self, id: u64) -> bool {
!self.invocation_tickets(id).is_empty()
self.extensions
.declared
.statements
.lock()
.unwrap_or_else(|e| e.into_inner())
.contains_key(&id)
|| !self.invocation_tickets(id).is_empty()
|| (self.extensions.origins.then_ids.iter())
.any(|(m, i)| *i == id && self.then_due[*m].is_finite())
|| (self.extensions.held.iter()).any(|h| h.id == id)
@@ -656,6 +670,9 @@ impl<D: DataSource> Runner<D> {
self.log(format!("{}: refused, {why}", self.key(row)));
return Decision::Now(json!({ "error": code, "message": why }));
}
if let Some(refused) = self.undeclared(row, args) {
return Decision::Now(refused);
}
if let Err(why) = self.admit(row, args, origin) {
self.log(format!("{}: refused, {why}", self.key(row)));
if why.starts_with("person-required") {
@@ -743,6 +760,45 @@ impl<D: DataSource> Runner<D> {
decision
}
/// An option whose values are the app's declarations takes one of them
/// (LLP 1133.004 stage 2): the platform shows only what was registered
/// at launch, so data code cannot add to it. The refusal, journaled.
pub(super) fn undeclared(&mut self, row: &ModulesRow, args: &Json) -> Option<Json> {
let sub = self.substitute(row);
let declares = sub["declares"].as_object()?;
let source = &self.plan.sources[row.source.0 as usize];
let shape = self
.plan
.source_params
.get(source.params.start as usize)
.and_then(|p| exact_js_value::Shape::from_plan(&self.plan, p.ty).ok());
let option = declares.iter().find(|(option, _)| {
let field = match &shape {
Some(exact_js_value::Shape::Record(fields)) => fields
.iter()
.find(|(name, _)| name == *option)
.map(|(_, field)| field),
_ => None,
};
let normalize = |value: &Json| {
let mut value = value.clone();
if let Some(field) = field {
super::absent_is_none(&mut value, field);
}
value
};
let given = normalize(&args[option.as_str()]);
let declared = sub["declared"][option.as_str()].as_array();
!given.is_null() && !declared.is_some_and(|d| d.iter().any(|v| normalize(v) == given))
})?;
let why = format!(
"{} not declared: only a literal the app's Contract writes declares them",
option.0
);
self.log(format!("{}: refused, {why}", self.key(row)));
Some(json!({ "error": "TypeError", "message": why }))
}
/// The permission a call of `row` with `args` asks: its declared one,
/// or, where its interface declares several and the name's grants are a
/// line per argument (`permissionBy`), the one of the arguments it was
@@ -1054,7 +1110,11 @@ impl<D: DataSource> Runner<D> {
// (LLP 1133.036 D3).
let joins = (sub["samples"]["stream"].as_str()).is_some_and(|s| self.app_rate(s).is_some())
|| self.joins_running(row, args);
if applies && app_only && origin != CallOrigin::App && !joins {
// A background action is the person's act: it may call a name held
// to the app, which shows nothing there (the foreground rule below
// refuses one that would).
let persons = matches!(origin, CallOrigin::App | CallOrigin::Action);
if applies && app_only && !persons && !joins {
return Err(format!("person-required ({} origin)", origin.word()));
}
// A call the app holds admits a capture's start while hidden on iOS
@@ -1066,7 +1126,10 @@ impl<D: DataSource> Runner<D> {
&& origin == CallOrigin::App
&& self.in_call()
};
if applies && sub["foreground"] == true && self.page.in_background() && !calling() {
if applies
&& sub["foreground"] == true
&& (origin == CallOrigin::Action || (self.page.in_background() && !calling()))
{
return Err("not in the foreground".into());
}
Ok(())
@@ -1109,10 +1172,11 @@ fn fetch_refusal(grants: &str, at: &str, given: &str) -> Option<String> {
}
/// Every origin, least privileged first.
pub(in crate::runner) const ORIGINS: [CallOrigin; 4] = [
pub(in crate::runner) const ORIGINS: [CallOrigin; 5] = [
CallOrigin::Device,
CallOrigin::Wake,
CallOrigin::Tool,
CallOrigin::Action,
CallOrigin::App,
];
+114 -4
View File
@@ -65,6 +65,8 @@ pub(in crate::runner) struct Declared {
app: Option<AppState>,
/// Effects held on a permission ticket.
held: Vec<HeldEffect>,
/// Native statements still awaiting the platform, counted by invocation.
pub(super) statements: Arc<Mutex<BTreeMap<u64, usize>>>,
/// What a bound implementation's refusals said, for the journal.
lines: Arc<Mutex<Vec<String>>>,
/// What a registration a wake runs for keeps beside its options, by `ref`.
@@ -173,6 +175,9 @@ impl<D: DataSource> Runner<D> {
self.log(format!("{}: refused, {why}", self.key(row)));
return Effect::Now(json!({ "error": code, "message": why }));
}
if let Some(refused) = self.undeclared(row, &args) {
return Effect::Now(refused);
}
if let Err(why) = self.admit(row, &args, origin) {
self.log(format!("{}: refused, {why}", self.key(row)));
let message = why
@@ -196,10 +201,21 @@ impl<D: DataSource> Runner<D> {
let Some(handler) = slot.handler() else {
return Effect::Now(json!({ "error": "NotSupportedError" }));
};
// A data-code call settles from the implementation's reply, so
// it is the caller's work until the platform has the effect (LLP
// 1133.004 D5; LLP 1133.021 §9 item 10): a wake does not end on
// the handoff. A Contract statement answers nothing to wait for.
// A background action owns a native statement until its reply;
// ordinary wakes keep fire-and-forget statements (LLP 1133.004 stage 2).
let owner = if reply.is_none() && origin == CallOrigin::Action {
self.invocation_id()
} else {
0
};
let statements = self.extensions.declared.statements.clone();
if owner != 0 {
*statements
.lock()
.unwrap_or_else(|e| e.into_inner())
.entry(owner)
.or_default() += 1;
}
let pending = reply.clone();
handler(
request.body,
@@ -220,6 +236,17 @@ impl<D: DataSource> Runner<D> {
if let Some(pending) = &pending {
Pending::complete(pending, outcome);
}
if owner != 0 {
let mut owned = statements.lock().unwrap_or_else(|e| e.into_inner());
if let Some(count) = owned.get_mut(&owner) {
*count -= 1;
if *count == 0 {
owned.remove(&owner);
}
}
drop(owned);
slot.changed("");
}
}),
);
return match reply {
@@ -781,6 +808,11 @@ impl<D: DataSource> Runner<D> {
if self.substitute(&row)["list"]["tap"]["as"] == "wake" {
return self.tap_wake(&state, at);
}
if let Some(choice) =
choice.filter(|_| self.substitute(&row)["list"]["tap"]["actions"].is_string())
{
return self.tap_action(&row, &state, at, choice);
}
let entry = self
.extensions
.declared
@@ -793,6 +825,84 @@ impl<D: DataSource> Runner<D> {
self.activate_entry(&row, &Json::Object(entry.fields), reference)
}
/// `tap @ref <action>[=<reply>]` on an entry that shows actions (LLP
/// 1133.004 stage 2): the person chose one of the entry's actions, and
/// typed `reply` into a text action. The event carries the action's
/// name and the reply, and never opens the entry's `navigate`. A
/// foreground action is the click's activation; one with `foreground`
/// false runs as a background action, as the host raises it.
fn tap_action(
&mut self,
row: &ModulesRow,
state: &str,
at: usize,
choice: &str,
) -> Result<String, String> {
let entry = &self.extensions.declared.lists[state][at];
let reference = entry.reference;
let tap = self.substitute(row)["list"]["tap"].clone();
let field = tap["actions"].as_str().unwrap_or_default();
let actions = entry.fields.get(field).cloned().unwrap_or(Json::Null);
let (name, typed) = match choice.split_once('=') {
Some((name, typed)) => (name, Some(typed)),
None => (choice, None),
};
let names: Vec<&str> = (actions.as_array().into_iter().flatten())
.filter_map(|a| a["action"].as_str())
.collect();
let Some(action) = (actions.as_array().into_iter().flatten()).find(|a| a["action"] == name)
else {
let shows = match names.is_empty() {
true => "it shows none".to_owned(),
false => format!("it shows {}", names.join(", ")),
};
return Err(format!("@{reference}: no action `{name}`; {shows}"));
};
let reply = match (action["placeholder"].is_string(), typed) {
(true, typed) => json!(typed.unwrap_or_default()),
(false, None) => Json::Null,
(false, Some(_)) => return Err(format!("@{reference}: `{name}` takes no typed reply")),
};
let foreground = action["foreground"] != false;
let mut fields = self
.extensions
.declared
.lists
.get_mut(state)
.expect("found above")
.remove(at)
.fields;
fields.remove("navigate");
fields.insert("action".into(), json!(name));
fields.insert("reply".into(), reply);
self.log(format!("{state} @{reference}: {name} chosen"));
if foreground {
return self.activate_entry(row, &Json::Object(fields), reference);
}
let Some(event) = tap["event"].as_str() else {
return Err(format!("@{reference}: its list raises no event"));
};
let args = Json::Array(entry_args(&tap, &Json::Object(fields))).to_string();
let extension = self.plan.str(row.extension).to_owned();
let how = super::WakeHow {
id: 0,
cold: false,
hidden: true,
};
self.queue_action(
&extension,
event,
&args,
how,
&format!("@{reference}"),
false,
)?;
Ok(
json!({ "ref": reference, "event": event, "as": "action", "delivery": "substituted" })
.to_string(),
)
}
/// A relaunched app's launch flag (`--notification '<entry>'`): the
/// entry as the agent's state printed it, delivered as its tap would be
/// (LLP 1133.004 §7), held until the session can hear it.
+1
View File
@@ -126,6 +126,7 @@ impl<D: DataSource> Runner<D> {
Some("device") => CallOrigin::Device,
Some("wake") => CallOrigin::Wake,
Some("tool") => CallOrigin::Tool,
Some("action") => CallOrigin::Action,
_ => CallOrigin::App,
};
let extension = self.plan.str(row.extension).to_owned();
@@ -433,3 +433,271 @@ fn a_dropped_bound_member_reply_retires_its_provisional_request() {
.iter()
.all(|b| b.get("dispose").is_none()));
}
#[test]
fn a_background_action_refuses_foreground_calls_even_in_a_visible_session() {
let mut b = PlanBuilder::new(exact_kernel::SCHEMA_DIGEST, 1);
let string = b.primitive(TypeKind::String);
let source = b.source("openBrowser", &[], string);
b.module(
source,
("browser", "@fixture/browser"),
"openBrowser",
true,
false,
"never",
"",
r#"{"origin":"app","foreground":true}"#,
);
b.node(NodeType::View as u8, None, None, 0, &[], &[], None);
let mut r = boot(b.finish().unwrap());
let row = r.plan.modules[0].clone();
for hidden in [false, true] {
r.page.hidden = hidden;
assert!(
r.admit(&row, &serde_json::json!({}), super::CallOrigin::Action)
.is_err(),
"hidden={hidden}"
);
}
}
#[test]
fn an_action_without_a_handler_has_a_terminal_outcome() {
let mut r = boot(plan("never"));
assert!(r
.raise_action(
"notifications",
"notificationclick",
"[]",
crate::WakeHow {
id: 0,
cold: false,
hidden: false
},
"unheard"
)
.is_err());
assert_eq!(
r.ended_actions(),
serde_json::json!([{"id":"unheard","outcome":"unheard"}])
);
}
#[test]
fn a_native_statement_is_owned_until_its_reply_or_expiry() {
use std::sync::{Arc, Mutex};
let mut b = PlanBuilder::new(exact_kernel::SCHEMA_DIGEST, 1);
let string = b.primitive(TypeKind::String);
let source = b.source("showNotification", &[], string);
b.module(
source,
("notifications", "@fixture/notifications"),
"showNotification",
true,
false,
"never",
"",
r#"{"effect":true,"takes":[]}"#,
);
let name = b.str("showNotification");
let mut body = Asm::new();
body.command(name, 0);
let body = b.code(body);
let action = b.action("clicked", &[], &[], body);
b.module_event(
("notifications", "@fixture/notifications"),
"notificationclick",
action,
"activation",
16,
0,
);
b.module_event(
("geofencing", "@fixture/geofencing"),
"geofenceenter",
action,
"wake",
16,
30_000,
);
b.node(NodeType::View as u8, None, None, 0, &[], &[], None);
let mut r = boot(b.finish().unwrap());
let replies: Arc<Mutex<Vec<crate::Reply>>> = Default::default();
let held = replies.clone();
r.native_slot()
.host(Some(Arc::new(move |body: Vec<u8>, reply: crate::Reply| {
let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
if body["send"] != "showNotification" {
return;
}
held.lock().unwrap().push(reply);
})));
r.bind_extensions(&["notifications"], &[]);
for (id, outcome, expired) in [
("success", serde_json::json!(null), false),
(
"failure",
serde_json::json!({"error":"NotAllowedError"}),
false,
),
("expired", serde_json::json!(null), true),
] {
r.raise_action(
"notifications",
"notificationclick",
"[]",
crate::WakeHow::default(),
id,
)
.unwrap();
assert!(r.step_wakes().1.is_none());
assert!(
!r.ended_actions()
.as_array()
.unwrap()
.iter()
.any(|a| a["id"] == id),
"the native reply has not arrived"
);
if expired {
assert!(r.expire_action(id).1.is_none());
assert_eq!(
r.ended_actions().as_array().unwrap().last().unwrap()["outcome"],
"expired"
);
}
replies
.lock()
.unwrap()
.pop()
.expect("the handler posted a notification")
.send(super::response(&outcome));
r.apply_announced();
assert!(r.step_wakes().1.is_none());
let ended = r.ended_actions();
let mine: Vec<_> = ended
.as_array()
.unwrap()
.iter()
.filter(|a| a["id"] == id)
.collect();
assert_eq!(mine.len(), 1, "{ended}");
assert_eq!(
mine[0]["outcome"],
if expired { "expired" } else { "completed" }
);
}
r.raise_wake(
"geofencing",
"geofenceenter",
"[]",
crate::WakeHow {
id: 1,
cold: false,
hidden: true,
},
)
.unwrap();
assert!(r.step_wakes().1.is_none());
assert_eq!(
replies.lock().unwrap().len(),
1,
"the wake posted a notification"
);
let ended = r.take_ended_wakes();
assert_eq!(
ended.len(),
1,
"a wake's statement does not wait for its native reply"
);
assert!(ended[0].contains("completed"), "{ended:?}");
replies
.lock()
.unwrap()
.pop()
.unwrap()
.send(super::response(&serde_json::json!(null)));
r.apply_announced();
assert!(r.step_wakes().1.is_none());
assert!(
r.take_ended_wakes().is_empty(),
"a late statement reply cannot end the wake twice"
);
}
#[test]
fn every_action_ending_survives_a_single_turn_until_the_host_drains_it() {
use std::sync::{Arc, Mutex};
let mut b = PlanBuilder::new(exact_kernel::SCHEMA_DIGEST, 1);
let string = b.primitive(TypeKind::String);
let source = b.source("post", &[], string);
b.module(
source,
("notifications", "@fixture/notifications"),
"post",
true,
false,
"never",
"",
r#"{"effect":true,"takes":[]}"#,
);
let name = b.str("post");
let mut body = Asm::new();
body.command(name, 0);
let body = b.code(body);
let clicked = b.action("clicked", &[], &[], body);
b.module_event(
("notifications", "@fixture/notifications"),
"notificationclick",
clicked,
"activation",
16,
0,
);
b.node(NodeType::View as u8, None, None, 0, &[], &[], None);
let mut r = boot(b.finish().unwrap());
let replies: Arc<Mutex<Vec<crate::Reply>>> = Default::default();
let held = replies.clone();
r.native_slot()
.host(Some(Arc::new(move |_: Vec<u8>, reply: crate::Reply| {
held.lock().unwrap().push(reply);
})));
r.bind_extensions(&["notifications"], &[]);
for id in 0..40 {
r.raise_action(
"notifications",
"notificationclick",
"[]",
crate::WakeHow::default(),
&id.to_string(),
)
.unwrap();
}
assert!(r.step_wakes().1.is_none());
assert!(r.ended_actions().as_array().unwrap().is_empty());
r.native_slot()
.host(Some(Arc::new(|_: Vec<u8>, reply: crate::Reply| {
reply.send(super::response(&serde_json::json!(null)));
})));
replies
.lock()
.unwrap()
.pop()
.unwrap()
.send(super::response(&serde_json::json!(null)));
r.apply_announced();
assert!(r.step_wakes().1.is_none());
let ended = r.take_ended_actions();
assert_eq!(
ended.as_array().unwrap().len(),
40,
"no ending may be evicted before the host reads it"
);
assert!(r.take_ended_actions().as_array().unwrap().is_empty());
assert_eq!(r.ended_actions().as_array().unwrap().len(), 32);
for id in 0..40 {
assert_eq!(ended[id]["id"], id.to_string());
assert_eq!(ended[id]["outcome"], "completed");
}
}
+236 -39
View File
@@ -41,6 +41,15 @@
//! handler hears the event. When the platform's time runs out first (a
//! `BGTask`'s expiration handler), the implementation says so ([`EXPIRED`]):
//! that wake expires now, or, not yet begun, ends `expired` unrun.
//! - **A background action** (LLP 1133.004 stage 2, as amended 2026-11-12):
//! the person chose a notification's declared action that leaves the app
//! in the background. The host raises it ([`Runner::raise_action`]) with
//! an id of its own; it runs as a wake does, owning its work, its page
//! hidden and its timers stopped, but with origin [`CallOrigin::Action`]:
//! the person's act, for that one action. What opens UI is refused, since
//! nothing is shown. Its end is read by the host (`actions`, the agent
//! op), which then lets the platform suspend the app; when the platform's
//! time runs out first the host expires it ([`Runner::expire_action`]).
use super::super::{CommitReceipt, DataSource, Runner, RunnerError};
use super::{CallOrigin, Json, Route};
@@ -71,6 +80,11 @@ const REFUSED: &[&str] = &[
/// raises, `{"extension", "event", "args", "id"}` after it (module doc).
pub(in crate::runner) const TOLD: &str = "exact-wake:";
/// A background action's time, iOS's for a notification action's
/// background launch (about 30 s, which the platform may cut): the most a
/// background action's invocation may run before it expires.
const ACTION_BUDGET: f64 = 30_000.0;
/// The prefix of a `changed` topic by which a bound implementation says the
/// platform expired a wake it raised, `{"extension", "id"}` after it.
pub(in crate::runner) const EXPIRED: &str = "exact-wake-expired:";
@@ -128,6 +142,11 @@ struct Invocation {
pub(super) entry: Option<u64>,
}
struct Action {
id: String,
host_delivery: bool,
}
struct Wake {
how: WakeHow,
/// The first delivery, on the session's clock.
@@ -139,6 +158,34 @@ struct Wake {
hid: bool,
/// The implementation that raised it and its id for it, told the end.
told: Option<(String, String)>,
/// `Wake`, or `Action` for a background action (module doc).
origin: CallOrigin,
/// A background action and whether the host holds its completion.
action: Option<Action>,
}
impl Wake {
fn new(how: WakeHow, origin: CallOrigin, action: Option<Action>) -> Self {
Wake {
how,
started: None,
budget: 0.0,
invocations: Vec::new(),
expired: false,
hid: false,
told: None,
origin,
action,
}
}
/// The journal's word for it.
fn word(&self) -> &'static str {
match self.origin {
CallOrigin::Action => "action",
_ => "wake",
}
}
}
#[derive(Default)]
@@ -151,6 +198,10 @@ pub(in crate::runner) struct Wakes {
last: Option<Json>,
/// Whether the page showed before the running wake hid it.
shown: bool,
/// Action endings awaiting the host's drain, never evicted.
actions: Vec<(String, &'static str)>,
/// The last 32 endings for diagnostics, independent of host delivery.
recent_actions: VecDeque<(String, &'static str)>,
}
impl<D: DataSource> Runner<D> {
@@ -186,6 +237,145 @@ impl<D: DataSource> Runner<D> {
Ok(())
}
/// The host raises activation event `name` of `extension` for a
/// background action the person chose (module doc), `id` the host's own
/// for it, which [`Self::take_ended_actions`] names when it ends. `Err` for
/// an event the plan does not declare as an activation, or arguments
/// that are not an array.
pub fn raise_action(
&mut self,
extension: &str,
name: &str,
args: &str,
how: WakeHow,
id: &str,
) -> Result<(), String> {
self.queue_action(extension, name, args, how, id, true)
}
pub(super) fn queue_action(
&mut self,
extension: &str,
name: &str,
args: &str,
how: WakeHow,
id: &str,
host_delivery: bool,
) -> Result<(), String> {
let action = Action {
id: id.to_owned(),
host_delivery,
};
let key = format!("{extension}.{name}");
let args: Vec<Json> = match serde_json::from_str(args) {
Ok(Json::Array(args)) => args,
_ => {
self.action_ended(action, "refused");
return Err(format!("{key}: the arguments are a JSON array"));
}
};
let row = (self.plan.module_events.iter()).position(|e| {
self.plan.str(e.extension) == extension
&& self.plan.str(e.declared) == name
&& self.plan.str(e.raised) == "activation"
});
let Some(row) = row else {
self.action_ended(action, "unheard");
return Err(format!("{key}: no event a person's action raises"));
};
// One wake per action: the host's id, hashed as a told wake's is,
// the top two bits set.
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
for byte in id.bytes() {
hash = (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3);
}
let how = WakeHow {
id: hash | 3 << 62,
..how
};
let w = &mut self.extensions.wakes;
w.waiting
.push_back(Wake::new(how, CallOrigin::Action, Some(action)));
self.wake_invocation(Some(row), args, how, None);
Ok(())
}
/// The platform's time for background action `id` ran out: it expires
/// now, or, not yet begun, ends `expired` unrun. One already ended, or
/// unknown, is left.
pub fn expire_action(&mut self, id: &str) -> (Vec<CommitReceipt>, Option<RunnerError>) {
let w = &mut self.extensions.wakes;
let mine = |wake: &Wake| wake.action.as_ref().is_some_and(|a| a.id == id);
if w.current.as_ref().is_some_and(mine) {
self.log(format!("action {id}: the platform's time ran out"));
return self.expire_wake();
}
if let Some(at) = w.waiting.iter().position(mine) {
let action = w
.waiting
.remove(at)
.and_then(|w| w.action)
.expect("an action");
self.log(format!(
"action {id}: the platform's time ran out before it ran"
));
self.action_ended(action, "expired");
}
(Vec::new(), None)
}
fn action_ended(&mut self, action: Action, outcome: &'static str) {
if action.host_delivery {
self.extensions
.wakes
.actions
.push((action.id.clone(), outcome));
}
let ended = &mut self.extensions.wakes.recent_actions;
ended.push_back((action.id, outcome));
if ended.len() > 32 {
ended.pop_front();
}
}
/// What the app's literals declare, by `<extension>.<name>`: each row's
/// `declared` (LLP 1133.004 stage 2), `{option: [value, …]}`.
pub fn declared_values(&self) -> Json {
let mut out = serde_json::Map::new();
for row in &self.plan.modules {
let declared = &self.substitute(row)["declared"];
if declared.is_object() {
let key = format!(
"{}.{}",
self.plan.str(row.extension),
self.plan.str(row.declared)
);
out.insert(key, declared.clone());
}
}
Json::Object(out)
}
/// The background actions that ended, the latest 32, as JSON: `[{"id",
/// "outcome"}]`, the outcome `completed`, `expired`, `superseded`,
/// `refused`, or `unheard`. This diagnostic read consumes no endings.
pub fn ended_actions(&self) -> Json {
let ended = (self.extensions.wakes.recent_actions.iter())
.map(|(id, outcome)| json!({ "id": id, "outcome": outcome }));
Json::Array(ended.collect())
}
/// Consume every host-held action ending since the host's last drain.
/// The host releases its completions even when the final batch is empty.
pub fn take_ended_actions(&mut self) -> Json {
Json::Array(
std::mem::take(&mut self.extensions.wakes.actions)
.into_iter()
.map(|(id, outcome)| json!({ "id": id, "outcome": outcome }))
.collect(),
)
}
/// Queue an invocation of event `row` (none: unheard) in the wake for
/// `how.id`, for the registration `entry` where the substitute keeps one.
pub(super) fn wake_invocation(
@@ -202,15 +392,7 @@ impl<D: DataSource> Runner<D> {
None => match w.waiting.iter().position(|q| q.how.id == how.id) {
Some(i) => &mut w.waiting[i],
None => {
w.waiting.push_back(Wake {
how,
started: None,
budget: 0.0,
invocations: Vec::new(),
expired: false,
hid: false,
told: None,
});
w.waiting.push_back(Wake::new(how, CallOrigin::Wake, None));
w.waiting.back_mut().expect("pushed")
}
},
@@ -220,10 +402,14 @@ impl<D: DataSource> Runner<D> {
return;
};
let event = &self.plan.module_events[row];
let (budget, hold) = (event.budget as f64, event.hold.max(1) as usize);
let (budget, hold) = match wake.origin {
CallOrigin::Action => (ACTION_BUDGET, usize::MAX),
_ => (event.budget as f64, event.hold.max(1) as usize),
};
let name = self.plan.str(event.declared).to_owned();
let tag = args.first().and_then(Json::as_str).unwrap_or_default();
let line = format!("wake {name} {tag}: raised");
let word = wake.word();
let line = format!("{word} {name} {tag}: raised");
wake.budget = wake.budget.max(budget);
wake.invocations.push(Invocation {
id,
@@ -251,7 +437,7 @@ impl<D: DataSource> Runner<D> {
}
self.log(line);
for tag in dropped {
self.log(format!("wake {name} {tag}: dropped"));
self.log(format!("{word} {name} {tag}: dropped"));
}
self.native_slot().changed("");
}
@@ -335,6 +521,7 @@ impl<D: DataSource> Runner<D> {
let now = self.now_ms;
let wake = self.extensions.wakes.current.as_mut().expect("a wake");
wake.started.get_or_insert(now);
let (origin, word) = (wake.origin, wake.word());
let inv = &mut wake.invocations[i];
inv.state = State::Running;
inv.delivered = true;
@@ -362,10 +549,8 @@ impl<D: DataSource> Runner<D> {
self.wake_entry_delivered(i);
let name = self.plan.str(action.name).to_owned();
let (event_name, tag) = self.invocation_words(i);
self.log(format!("wake {event_name} {tag}: heard by {name}"));
let result = self.as_invocation(CallOrigin::Wake, id, |r| {
r.run_action(event.action, args, &[])
});
self.log(format!("{word} {event_name} {tag}: heard by {name}"));
let result = self.as_invocation(origin, id, |r| r.run_action(event.action, args, &[]));
match result {
Ok(receipt) => Ok(Some(receipt)),
Err(e) => {
@@ -389,7 +574,8 @@ impl<D: DataSource> Runner<D> {
let inv = &mut wake.invocations[i];
inv.state = state;
let (entry, delivered) = (inv.entry, inv.delivered);
self.log(format!("wake {event} {tag}: {}", state.word()));
let word = wake.word();
self.log(format!("{word} {event} {tag}: {}", state.word()));
if let Some(entry) = entry {
self.wake_entry_ended(entry, state.word(), delivered);
}
@@ -427,27 +613,30 @@ impl<D: DataSource> Runner<D> {
"completed"
};
let described = self.describe_wake(&wake, Some(outcome));
self.log(format!("wake: {outcome}"));
self.log(format!("{}: {outcome}", wake.word()));
let w = &mut self.extensions.wakes;
if wake.told.is_none() {
if wake.told.is_none() && wake.action.is_none() {
w.ended.push(described.clone());
}
w.last = Some(described);
let state = |s: State| wake.invocations.iter().any(|i| i.state == s);
let told = if wake.invocations.is_empty() {
"unheard"
} else if wake.expired || state(State::Expired) {
"expired"
} else if state(State::Superseded) {
"superseded"
} else if state(State::Refused) {
"refused"
} else {
"completed"
};
if let Some((extension, id)) = &wake.told {
let state = |s: State| wake.invocations.iter().any(|i| i.state == s);
let told = if wake.invocations.is_empty() {
"unheard"
} else if wake.expired || state(State::Expired) {
"expired"
} else if state(State::Superseded) {
"superseded"
} else if state(State::Refused) {
"refused"
} else {
"completed"
};
self.tell_woke(extension, id, told);
}
if let Some(action) = wake.action {
self.action_ended(action, told);
}
self.native_slot().changed("");
if wake.hid {
return self.wake_page(false);
@@ -473,6 +662,7 @@ impl<D: DataSource> Runner<D> {
json!({
"id": wake.how.id,
"kind": kind,
"origin": wake.origin.word(),
"cold": wake.how.cold,
"started": wake.started.map(|s| epoch + s),
"deadline": wake.started.map(|s| epoch + s + wake.budget),
@@ -484,9 +674,7 @@ impl<D: DataSource> Runner<D> {
/// The wake's deadline on the session's clock, while one runs unexpired.
pub(in crate::runner) fn wake_deadline(&self) -> Option<f64> {
let wake = self.extensions.wakes.current.as_ref()?;
(!wake.expired)
.then_some(wake.started? + wake.budget)
.filter(|_| wake.invocations.iter().any(|i| !i.state.ended()))
(!wake.expired).then_some(wake.started? + wake.budget)
}
/// When the host should next advance for the wakes: now while one can
@@ -527,6 +715,12 @@ impl<D: DataSource> Runner<D> {
_ => return (receipts, None),
}
let id = self.running_wake().unwrap_or(0);
self.extensions
.declared
.statements
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(&id);
for ticket in self.invocation_tickets(id) {
let failed = Outcome::Failed {
kind: FailureKind::Network,
@@ -586,11 +780,14 @@ impl<D: DataSource> Runner<D> {
}
/// Take off this commit's host commands from `first` that a wake may
/// not run, when the commit is the wake's.
/// not run, when the commit is the wake's or a background action's
/// (origin `action`: the person's act, but nothing is shown).
pub(in crate::runner) fn refuse_in_wake(&mut self, first: usize) {
if self.call_origin() != CallOrigin::Wake {
return;
}
let during = match self.call_origin() {
CallOrigin::Wake => "during a wake",
CallOrigin::Action => "during a background action",
_ => return,
};
let mut i = first;
while i < self.commands.len() {
// Bare `focus()` brings the window forward, which a wake never
@@ -599,7 +796,7 @@ impl<D: DataSource> Runner<D> {
let window = command.name == "focus" && command.args.is_empty();
if REFUSED.contains(&command.name.as_str()) || window {
let name = self.commands.remove(i).name;
self.log(format!("{name}: refused: during a wake"));
self.log(format!("{name}: refused: {during}"));
} else {
i += 1;
}