feat: let an application decline a close to keep unsaved changes

A package declares its unsaved-change policy in [ui].close. With
"ask", the app shell dispatches a cancelable weftclose event before
the window closes and waits up to 2 s for the page. A page that
cancels the close keeps running, and the app shell reports this to
weft-appd with its readiness token, which returns the session to
running. The page closes itself later with window.close().

Notes declares "ask". With unsaved changes it offers Save and close,
Close without saving, and Cancel. It closes after a save only once the
save is acknowledged. The taskbar shows a declined close as running
again.
This commit is contained in:
Marco Allegretti 2026-10-09 17:00:08 +00:00
parent e72c55c87c
commit 551df84562
No known key found for this signature in database
12 changed files with 589 additions and 45 deletions

View file

@ -68,6 +68,33 @@ struct FrameSignals {
content: AtomicBool,
/// The document has loaded and Servo reports its rendering is up to date.
settled: AtomicBool,
/// The page closed itself with `window.close()`.
page_closed: AtomicBool,
/// The page's answer to the pending close request; see `CloseAnswer`.
close_answer: std::sync::atomic::AtomicU8,
}
/// The page's answer to a close request, as stored in `close_answer`.
#[derive(Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
enum CloseAnswer {
Pending = 0,
Close = 1,
Cancel = 2,
}
/// How long a page with the `ask` close policy has to answer a close
/// request; a page that does not answer in time is closed.
const CLOSE_ANSWER_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
/// Asks the page whether it may close: dispatches a cancelable `weftclose`
/// event on the top-level window. The page cancels the close by calling
/// `preventDefault()` and closes itself later with `window.close()`.
const ASK_CLOSE_SCRIPT: &str = "window.dispatchEvent(new Event('weftclose', { cancelable: true }))";
/// The application's declared close policy, from `WEFT_APP_CLOSE`.
fn close_policy_asks() -> bool {
std::env::var("WEFT_APP_CLOSE").is_ok_and(|v| v == "ask")
}
struct WeftWebViewDelegate {
@ -87,6 +114,12 @@ impl WebViewDelegate for WeftWebViewDelegate {
self.signals.redraw.store(true, Ordering::Relaxed);
}
/// The application page called `window.close()`, which Servo allows for
/// a top-level document with a single history entry.
fn notify_closed(&self, _webview: servo::WebView) {
self.signals.page_closed.store(true, Ordering::Relaxed);
}
/// The webview carries the session's bridge, so it stays within the
/// application's own UI files.
fn request_navigation(&self, _webview: servo::WebView, request: NavigationRequest) {
@ -368,6 +401,10 @@ struct App {
modifiers: ModifiersState,
cursor_pos: DevicePoint,
shell_client: Option<crate::shell_client::ShellClient>,
/// Whether the page is asked before its window closes.
ask_before_close: bool,
/// When the pending close request is closed regardless of the page.
close_deadline: Option<std::time::Instant>,
}
impl App {
@ -394,9 +431,70 @@ impl App {
modifiers: ModifiersState::default(),
cursor_pos: DevicePoint::origin(),
shell_client: None,
ask_before_close: close_policy_asks(),
close_deadline: None,
}
}
/// Handles a request to close the window. Under the `ask` policy the
/// page answers first; otherwise, or without a page, the app closes.
fn request_close(&mut self, event_loop: &ActiveEventLoop) {
if self.close_deadline.is_some() {
return;
}
let Some(webview) = self.webview.as_ref().filter(|_| self.ask_before_close) else {
self.shut_down();
event_loop.exit();
return;
};
self.signals
.close_answer
.store(CloseAnswer::Pending as u8, Ordering::Relaxed);
self.close_deadline = Some(std::time::Instant::now() + CLOSE_ANSWER_TIMEOUT);
let signals = Arc::clone(&self.signals);
webview.evaluate_javascript(ASK_CLOSE_SCRIPT, move |result| {
// dispatchEvent returns false when the page cancelled the event.
let answer = match result {
Ok(servo::JSValue::Boolean(false)) => CloseAnswer::Cancel,
Ok(_) => CloseAnswer::Close,
Err(e) => {
tracing::warn!(?e, "the page could not be asked to close; closing");
CloseAnswer::Close
}
};
signals.close_answer.store(answer as u8, Ordering::Relaxed);
});
}
/// Acts on the page's answer to a pending close request, or on its
/// absence once the answer is due. Returns whether the app is closing.
fn settle_close_request(&mut self) -> bool {
let Some(deadline) = self.close_deadline else {
return false;
};
let answer = self.signals.close_answer.load(Ordering::Relaxed);
if answer == CloseAnswer::Cancel as u8 {
self.close_deadline = None;
tracing::info!("the page cancelled the close");
// weft-appd learns that the session keeps running; the token
// keeps page output from forging this report.
if let Ok(token) = std::env::var("WEFT_READY_TOKEN") {
use std::io::Write;
println!("CLOSE_CANCELLED {token}");
let _ = std::io::stdout().flush();
}
return false;
}
if answer == CloseAnswer::Close as u8 {
return true;
}
if std::time::Instant::now() >= deadline {
tracing::warn!("the page did not answer the close request in time; closing");
return true;
}
false
}
/// Paints and presents once Servo has requested its first repaint.
///
/// Nothing is presented before that request; the first frames can still be
@ -546,6 +644,17 @@ impl ApplicationHandler<ServoWake> for App {
if let Some(servo) = &self.servo {
servo.spin_event_loop();
}
// The page answers a close request while Servo spins.
if self.signals.page_closed.load(Ordering::Relaxed) || self.settle_close_request() {
self.shut_down();
event_loop.exit();
return;
}
// Wake for the close answer's deadline even when nothing else happens.
event_loop.set_control_flow(match self.close_deadline {
Some(deadline) => winit::event_loop::ControlFlow::WaitUntil(deadline),
None => winit::event_loop::ControlFlow::Wait,
});
if self.signals.redraw.swap(false, Ordering::Relaxed)
&& let Some(w) = &self.window
{
@ -605,10 +714,7 @@ impl ApplicationHandler<ServoWake> for App {
)));
}
}
WindowEvent::CloseRequested => {
self.shut_down();
event_loop.exit();
}
WindowEvent::CloseRequested => self.request_close(event_loop),
_ => {}
}
}

View file

@ -6,7 +6,7 @@
use std::path::{Path, PathBuf};
use weft_ipc_types::manifest::{MANIFEST_FILE, Manifest, ManifestError, entry_path};
use weft_ipc_types::manifest::{ClosePolicy, MANIFEST_FILE, Manifest, ManifestError, entry_path};
use weft_ipc_types::package::{ImageFiles, is_valid_app_id};
use crate::grants::Refusal;
@ -20,6 +20,8 @@ pub(crate) struct LaunchPackage {
pub(crate) module: PathBuf,
/// The UI document, from `[ui].entry`.
pub(crate) ui_entry: PathBuf,
/// What a user close does, from `[ui].close`.
pub(crate) close: ClosePolicy,
pub(crate) capabilities: Vec<String>,
/// The image the package root is mounted from, held for as long as the
/// session runs.
@ -110,6 +112,7 @@ fn from_root(app_id: &str, root: PathBuf, image: Option<Mount>) -> Result<Launch
capabilities: manifest.capabilities().to_vec(),
module,
ui_entry,
close: manifest.ui.close,
root,
image,
})
@ -125,6 +128,7 @@ impl LaunchPackage {
root: PathBuf::from("/nonexistent"),
module: PathBuf::from("/nonexistent/app.wasm"),
ui_entry: PathBuf::from("/nonexistent/ui/index.html"),
close: ClosePolicy::Immediate,
capabilities: Vec::new(),
image: None,
}

View file

@ -1399,6 +1399,129 @@ mod tests {
);
}
#[tokio::test(flavor = "current_thread")]
async fn an_app_that_cancels_a_close_keeps_running() {
use std::os::unix::fs::PermissionsExt;
let _env = env_lock().lock().await;
use_test_runtime_dir();
let dir = std::env::temp_dir().join(format!("weft_test_cancel_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let app = dir.join("store/org.example.cancel");
write_test_package(&app, "org.example.cancel", "");
let runtime = dir.join("runtime.sh");
std::fs::write(
&runtime,
"#!/bin/sh\necho READY $WEFT_READY_TOKEN\nexec sleep 30\n",
)
.unwrap();
// The app shell declines the close once, after a forged report.
let shell = dir.join("shell.sh");
std::fs::write(
&shell,
"#!/bin/sh\necho READY $WEFT_READY_TOKEN\nsleep 1\n\
echo CLOSE_CANCELLED 00000000000000000000000000000000\nsleep 1\n\
echo CLOSE_CANCELLED $WEFT_READY_TOKEN\nexec sleep 30\n",
)
.unwrap();
for script in [&runtime, &shell] {
std::fs::set_permissions(script, std::fs::Permissions::from_mode(0o755)).unwrap();
}
let vars = [
("WEFT_RUNTIME_BIN", runtime.clone().into_os_string()),
("WEFT_APP_SHELL_BIN", shell.clone().into_os_string()),
("WEFT_DISABLE_CGROUP", "1".into()),
("WEFT_APP_STORE", dir.join("store").into_os_string()),
];
let prior: Vec<_> = vars
.iter()
.map(|(k, _)| (*k, std::env::var_os(k)))
.collect();
for (key, value) in &vars {
// SAFETY: env_lock is held on a current_thread runtime.
unsafe { std::env::set_var(key, value) };
}
let registry = make_registry();
let (tx, _compositor) = tokio::sync::mpsc::channel(8);
registry.lock().await.compositor_tx = Some(compositor_client::CompositorSender::new(
tx,
std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true)),
));
let mut rx = registry.lock().await.subscribe();
let ack = dispatch(
Request::LaunchApp {
app_id: "org.example.cancel".into(),
surface_id: 0,
},
&registry,
)
.await;
let Response::LaunchAck { session_id, .. } = ack else {
panic!("{ack:?}");
};
let ready = tokio::time::timeout(std::time::Duration::from_secs(10), async {
while !matches!(rx.recv().await, Ok(Response::AppReady { .. })) {}
})
.await;
let started = std::time::Instant::now();
dispatch(Request::TerminateApp { session_id }, &registry).await;
// The session is running again once the genuine report arrives.
let resumed = tokio::time::timeout(std::time::Duration::from_secs(5), async {
loop {
match rx.recv().await {
Ok(Response::AppState {
state: AppStateKind::Running,
..
}) => return true,
Ok(Response::AppState {
state: AppStateKind::Stopped,
..
}) => return false,
_ => {}
}
}
})
.await;
let resumed_after = started.elapsed();
let state = registry.lock().await.state(session_id);
// A second request asks again; this time nothing declines it.
dispatch(Request::TerminateApp { session_id }, &registry).await;
let stopped = tokio::time::timeout(std::time::Duration::from_secs(10), async {
while !matches!(
rx.recv().await,
Ok(Response::AppState {
state: AppStateKind::Stopped,
..
})
) {}
})
.await;
for (key, value) in prior {
// SAFETY: as above.
unsafe {
match value {
Some(v) => std::env::set_var(key, v),
None => std::env::remove_var(key),
}
}
}
let _ = std::fs::remove_dir_all(&dir);
assert!(ready.is_ok(), "the session did not become ready");
assert_eq!(
resumed,
Ok(true),
"the cancelled close did not resume the session"
);
// The forged report one second in did not count.
assert!(
resumed_after >= std::time::Duration::from_millis(1500),
"{resumed_after:?}"
);
assert!(matches!(state, AppStateKind::Running), "{state:?}");
assert!(stopped.is_ok(), "the second close did not stop the session");
}
#[tokio::test(flavor = "current_thread")]
async fn an_app_that_ignores_a_close_is_terminated_after_the_timeout() {
use std::os::unix::fs::PermissionsExt;

View file

@ -116,6 +116,8 @@ const READY_TIMEOUT: Duration = Duration::from_secs(30);
/// runtime passes the guest only the variables it names and pages cannot read
/// the host process environment.
const READY_TOKEN_ENV: &str = "WEFT_READY_TOKEN";
/// The application's close policy, `immediate` or `ask`, for the app shell.
const CLOSE_POLICY_ENV: &str = "WEFT_APP_CLOSE";
/// Environment variable carrying the session's application bridge credential
/// to weft-app-shell.
@ -222,6 +224,7 @@ fn spawn_app_shell(
.arg("--ui")
.arg(&package.ui_entry)
.env(READY_TOKEN_ENV, token)
.env(CLOSE_POLICY_ENV, package.close.as_str())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.kill_on_drop(true)
@ -430,7 +433,13 @@ pub(crate) async fn supervise(
Ok(reader) => reader,
Err(reason) => return session.settle(&registry, &reason).await,
};
tokio::spawn(drain_stdout(shell_stdout, session_id));
let (cancel_tx, mut cancelled) = tokio::sync::mpsc::channel(1);
tokio::spawn(watch_app_shell_stdout(
shell_stdout,
session_id,
token.clone(),
cancel_tx,
));
{
let mut reg = registry.lock().await;
@ -442,25 +451,76 @@ pub(crate) async fn supervise(
}
tracing::info!(session_id, %app_id, "app ready");
let reason = tokio::select! {
status = session.runtime.as_mut().expect("runtime spawned").wait() => {
format!("runtime exited ({status:?})")
}
status = session.app_shell.as_mut().expect("app shell spawned").wait() => {
format!("app shell exited ({status:?})")
}
requested = &mut abort_rx => match requested {
Ok(()) => session.close(session_id).await,
// The sender is dropped only when appd shuts down.
Err(_) => "appd is shutting down".to_owned(),
},
_ = session.relay.as_mut().expect("relay opened").ended() => {
"component closed its IPC connection".to_owned()
let reason = loop {
tokio::select! {
status = session.runtime.as_mut().expect("runtime spawned").wait() => {
break format!("runtime exited ({status:?})");
}
status = session.app_shell.as_mut().expect("app shell spawned").wait() => {
break format!("app shell exited ({status:?})");
}
requested = &mut abort_rx => match requested {
Ok(()) => match session.close(session_id, &mut cancelled).await {
Close::Settle(reason) => break reason,
// The application kept running, as its close policy
// allows; a later request asks again.
Close::Cancelled => {
let mut reg = registry.lock().await;
abort_rx = reg.register_abort(session_id);
reg.set_state(session_id, AppStateKind::Running);
let _ = reg.broadcast().send(Response::AppState {
session_id,
state: AppStateKind::Running,
});
tracing::info!(session_id, "the application cancelled the close");
}
},
// The sender is dropped only when appd shuts down.
Err(_) => break "appd is shutting down".to_owned(),
},
_ = session.relay.as_mut().expect("relay opened").ended() => {
break "component closed its IPC connection".to_owned();
}
}
};
session.settle(&registry, &reason).await
}
/// How a close request ended.
enum Close {
/// The session ends, for this reason.
Settle(String),
/// The application declined the close and keeps running.
Cancelled,
}
/// The app shell's report that its page declined a close, followed by the
/// session's readiness token so page output cannot fake it.
const CLOSE_CANCELLED: &str = "CLOSE_CANCELLED";
/// Passes the app shell's close reports on to the supervisor and logs
/// everything else it prints.
async fn watch_app_shell_stdout(
mut reader: BufReader<tokio::process::ChildStdout>,
session_id: u64,
token: String,
cancelled: tokio::sync::mpsc::Sender<()>,
) {
while let Ok(Some(line)) = read_child_line(&mut reader).await {
if line
.strip_prefix(CLOSE_CANCELLED)
.and_then(|rest| rest.strip_prefix(' '))
.is_some_and(|t| crate::ws::tokens_match(&token, t))
{
// One pending report is enough; the supervisor drops stale ones
// before it asks again.
let _ = cancelled.try_send(());
} else {
tracing::debug!(session_id, stdout = %line, "child stdout");
}
}
}
/// How long an application may take to close after being asked, for
/// example to save, before its processes are terminated.
pub(crate) const CLOSE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
@ -526,7 +586,14 @@ impl OwnedSession {
/// its windows to close and the app shell gets `CLOSE_TIMEOUT` to exit by
/// itself. Returns the terminal reason; settling terminates whatever is
/// still running.
async fn close(&mut self, session_id: u64) -> String {
async fn close(
&mut self,
session_id: u64,
cancelled: &mut tokio::sync::mpsc::Receiver<()>,
) -> Close {
// A report from an earlier close, for example one the user started
// in the compositor, does not answer this one.
while cancelled.try_recv().is_ok() {}
let asked = self.client_attached
&& self.compositor_tx.as_ref().is_some_and(|tx| {
tx.is_connected()
@ -535,34 +602,41 @@ impl OwnedSession {
.is_ok()
});
if !asked {
return "terminate requested; the compositor could not ask the app to close".to_owned();
return Close::Settle(
"terminate requested; the compositor could not ask the app to close".to_owned(),
);
}
let (Some(app_shell), Some(runtime), Some(relay)) = (
self.app_shell.as_mut(),
self.runtime.as_mut(),
self.relay.as_mut(),
) else {
return "terminate requested".to_owned();
return Close::Settle("terminate requested".to_owned());
};
let wait = async {
tokio::select! {
status = app_shell.wait() => match status {
status = app_shell.wait() => Close::Settle(match status {
Ok(status) if status.success() => {
format!("closed on request; app shell exited ({status:?})")
}
status => format!("app shell failed while closing ({status:?})"),
},
status = runtime.wait() => format!("runtime exited while closing ({status:?})"),
_ = relay.ended() => "component closed its IPC connection while closing".to_owned(),
}),
status = runtime.wait() => {
Close::Settle(format!("runtime exited while closing ({status:?})"))
}
_ = relay.ended() => Close::Settle(
"component closed its IPC connection while closing".to_owned(),
),
Some(()) = cancelled.recv() => Close::Cancelled,
}
};
tokio::time::timeout(CLOSE_TIMEOUT, wait)
.await
.unwrap_or_else(|_| {
format!(
Close::Settle(format!(
"close requested; the app shell did not exit within {} s and was terminated",
CLOSE_TIMEOUT.as_secs()
)
))
})
}

View file

@ -38,6 +38,31 @@ pub struct RuntimeMeta {
pub struct UiMeta {
/// The UI document, relative to the package root.
pub entry: String,
/// What happens when the user asks the application's window to close.
#[serde(default)]
pub close: ClosePolicy,
}
/// An application's declared unsaved-change policy: what a user close does.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ClosePolicy {
/// The window closes at once; the application keeps no unsaved state.
#[default]
Immediate,
/// The page is asked first and may cancel the close, for example to
/// offer saving unsaved changes; it then closes itself when done.
Ask,
}
impl ClosePolicy {
/// The value weft-appd passes to the app shell in `WEFT_APP_CLOSE`.
pub fn as_str(self) -> &'static str {
match self {
Self::Immediate => "immediate",
Self::Ask => "ask",
}
}
}
/// Why a manifest could not be read.
@ -212,6 +237,24 @@ mod tests {
let manifest = Manifest::read(&dir).unwrap();
assert_eq!(manifest.package.id, "org.weft.test");
assert_eq!(manifest.capabilities(), ["sys:notifications"]);
assert_eq!(manifest.ui.close, ClosePolicy::Immediate);
std::fs::write(
dir.join(MANIFEST_FILE),
"[package]\nid = \"org.weft.test\"\nname = \"T\"\nversion = \"1.0.0\"\n\
[runtime]\nmodule = \"app.wasm\"\n[ui]\nentry = \"ui/index.html\"\nclose = \"ask\"\n",
)
.unwrap();
assert_eq!(Manifest::read(&dir).unwrap().ui.close, ClosePolicy::Ask);
std::fs::write(
dir.join(MANIFEST_FILE),
"[package]\nid = \"org.weft.test\"\nname = \"T\"\nversion = \"1.0.0\"\n\
[runtime]\nmodule = \"app.wasm\"\n[ui]\nentry = \"ui/index.html\"\nclose = \"later\"\n",
)
.unwrap();
assert!(matches!(
Manifest::read(&dir),
Err(ManifestError::Parse(..))
));
std::fs::write(dir.join(MANIFEST_FILE), "[package]\nid = \"x\"\n").unwrap();
assert!(matches!(
Manifest::read(&dir),

View file

@ -20,7 +20,7 @@ Per-application Servo host. Spawned by `weft-appd` after the Wasm runtime signal
### weft-appd
Session supervisor. Listens on a Unix socket (MessagePack protocol) and a WebSocket port (JSON). Before a session exists, appd resolves the package once (see [Package resolution](#package-resolution)) and derives its grants from that package's manifest; the runtime and the app shell receive the resolved component and UI document and do not search the stores themselves. For each session: spawns `weft-runtime` and waits for its READY, spawns `weft-app-shell` (`WEFT_APP_SHELL_BIN` is required) and waits for its READY, and only then reports the session running (`APP_READY`). A child reports readiness by printing `READY <token>` on stdout, where the token is a random per-session value appd passes in `WEFT_READY_TOKEN`; Wasm guests and pages share those stdout streams but cannot read the token, so their output cannot fake readiness. Each wait times out after 30 seconds. `TERMINATE_APP` on a running session closes it as a user close would: appd replies `stopping`, asks the compositor to close the session's windows, and gives the app shell 5 seconds to exit by itself, for example after saving, before terminating it; the stop reason records which happened (a clean exit, a failure while closing, or the timeout), and `stopped` is broadcast once the session has settled. A repeated `TERMINATE_APP` while the app is closing changes nothing; the timeout is the only forced termination, and a session being closed is not restored at the next start. appd keeps the final state of at most 32 stopped sessions, forgetting those launched earliest. A session still starting is stopped at once, and when appd itself shuts down its sessions are terminated without a close. If either child fails to start, fails to become ready or exits, or the session is terminated, the whole session is stopped: both children, the IPC relay (its task, socket and registered sender), the file portal, the compositor association and any image mount are released. The IPC relay is created with the session in `$XDG_RUNTIME_DIR/weft` (a session cannot start without it); its socket is accessible only to the user and accepts a single connection, which the session's runtime makes before it starts the component. If that connection closes while the session runs, the session is stopped. `IPC_FORWARD` on the Unix socket never waits: it reports an error when the session has no relay or its queue is full. appd applies cgroup resource limits to the runtime via systemd-run when available.
Session supervisor. Listens on a Unix socket (MessagePack protocol) and a WebSocket port (JSON). Before a session exists, appd resolves the package once (see [Package resolution](#package-resolution)) and derives its grants from that package's manifest; the runtime and the app shell receive the resolved component and UI document and do not search the stores themselves. For each session: spawns `weft-runtime` and waits for its READY, spawns `weft-app-shell` (`WEFT_APP_SHELL_BIN` is required) and waits for its READY, and only then reports the session running (`APP_READY`). A child reports readiness by printing `READY <token>` on stdout, where the token is a random per-session value appd passes in `WEFT_READY_TOKEN`; Wasm guests and pages share those stdout streams but cannot read the token, so their output cannot fake readiness. Each wait times out after 30 seconds. `TERMINATE_APP` on a running session closes it as a user close would: appd replies `stopping`, asks the compositor to close the session's windows, and gives the app shell 5 seconds to exit by itself, for example after saving, before terminating it; the stop reason records which happened (a clean exit, a failure while closing, or the timeout), and `stopped` is broadcast once the session has settled. An application that declares the `ask` close policy may decline the close (see [Closing an application](#closing-an-application)); the session is then `running` again. A repeated `TERMINATE_APP` while the app is closing changes nothing; the timeout is the only forced termination, and a session being closed is not restored at the next start. appd keeps the final state of at most 32 stopped sessions, forgetting those launched earliest. A session still starting is stopped at once, and when appd itself shuts down its sessions are terminated without a close. If either child fails to start, fails to become ready or exits, or the session is terminated, the whole session is stopped: both children, the IPC relay (its task, socket and registered sender), the file portal, the compositor association and any image mount are released. The IPC relay is created with the session in `$XDG_RUNTIME_DIR/weft` (a session cannot start without it); its socket is accessible only to the user and accepts a single connection, which the session's runtime makes before it starts the component. If that connection closes while the session runs, the session is stopped. `IPC_FORWARD` on the Unix socket never waits: it reports an error when the session has no relay or its queue is full. appd applies cgroup resource limits to the runtime via systemd-run when available.
### weft-runtime
@ -121,6 +121,17 @@ The package root must be a directory and its manifest a regular file, neither a
A directory install can still be changed by its owner while a session runs, and nothing verifies its content at launch.
## Closing an application
A user closes an application from the taskbar, which sends `TERMINATE_APP`, or with Alt+F4 in the compositor; both ask the application's window to close. What happens next is the application's declared unsaved-change policy, `[ui].close` in `wapp.toml`:
- `immediate` (the default): the app shell exits at once.
- `ask`: the app shell dispatches a cancelable `weftclose` event on the page's top-level window and waits up to 2 seconds for it to be handled. If no listener calls `preventDefault()`, or the page does not answer in time, the app shell exits. Otherwise the close is cancelled: the app shell reports this to weft-appd with its readiness token on standard output, so page output cannot forge it, and the session stays running. The page then lets the user decide, and closes itself with `window.close()`, which Servo allows while the top-level document has a single history entry.
Notes uses `ask`: with unsaved changes it offers "Save and close", which closes only after the save is acknowledged and stays open with the error shown when the save fails, "Close without saving", and Cancel.
The close timeout of weft-appd still applies to a close that is not declined: an app shell that neither exits nor declines within 5 seconds is terminated, and the stop reason says so. A terminated session, a crash and appd's own shutdown are never reported as a close on request, and say nothing about whether the application saved.
## App data
Each app's private data lives in `$XDG_DATA_HOME/weft/app-data/<id>` (`~/.local/share/weft/app-data/<id>` by default), apart from installed packages. Installing, updating or uninstalling a package never removes it. `weft-appd` creates the directory when a session with an app-data capability starts and makes it accessible only to the user (mode 0700); a symbolic link in its place is refused rather than followed. `weft-appd` and `weft-pack` must run with the same `HOME` and `XDG_DATA_HOME` to agree on this location; the systemd unit allows `weft-appd` to write under `~/.local/share/weft`.

View file

@ -85,7 +85,7 @@ same nested desktop and drive the demo apps with real keyboard input:
```sh
python3 tests/frame/check_counter.py # Counter round trip through the session bridge
python3 tests/frame/check_notes.py # Notes stores exactly what is typed, refuses stale saves
python3 tests/frame/check_notes.py # Notes stores exactly what is typed, refuses stale saves, asks before closing unsaved text
python3 tests/frame/check_app_data.py # Notes data from the earlier layout is moved and kept
python3 tests/frame/check_confinement.py # an app page reaches only its UI files and its session bridge
python3 tests/frame/check_activation.py # apps fill the work area above the taskbar; launch and ACTIVATE_APP raise and focus

View file

@ -1 +1 @@
e8c10750b142b9df4405fd33ea0c060e63d44b5293e7f9ffa5b076989146b05e81f716e9b92aaeeb139ce1dc9b13ed26f356385d6a61a19c7f3dcaf6e95d2d03
6bd7b2df26ef619b20c73aa42ed92438d8b0c8515e35f47fd4be346cd90875b53e83374413a3b6008b2b0a718ba1da28497532f04a54b673ebc074db94ce730c

View file

@ -80,6 +80,15 @@
font-size: 12px;
color: #444;
}
#closing {
display: none;
align-items: center;
gap: 8px;
flex-shrink: 0;
font-size: 13px;
}
#closing.shown { display: flex; }
#closing span { flex: 1; }
#charcount {
font-size: 12px;
color: #444;
@ -95,6 +104,12 @@
<button class="primary" id="save">Save</button>
</div>
</header>
<div id="closing" role="alertdialog" aria-label="Unsaved changes">
<span>These notes have unsaved changes.</span>
<button class="primary" id="close-save">Save and close</button>
<button id="close-discard">Close without saving</button>
<button id="close-cancel">Cancel</button>
</div>
<textarea id="editor" placeholder="Start typing…" spellcheck="false"></textarea>
<footer>
<span id="status">connecting…</span>
@ -121,6 +136,8 @@
var lastSent = null;
var loading = null; // timer of the outstanding load, if any
var encoder = new TextEncoder();
var closing = document.getElementById('closing');
var closeAfterSave = false;
function setStatus(msg) { statusEl.textContent = msg; }
function countChars() { charEl.textContent = editor.value.length + ' chars'; }
@ -138,6 +155,40 @@
setLoaded(rev !== null);
}
// Close policy ("ask" in wapp.toml): when the window is asked to close
// with unsaved changes, the close is cancelled and the user chooses to
// save first, close without saving, or keep editing. The window closes
// after a save only once the save is acknowledged; a failed save keeps
// it open with the error shown.
function unsaved() {
return pending !== null || (rev !== null && editor.value !== saved);
}
function hideClosing() {
closing.classList.remove('shown');
closeAfterSave = false;
}
window.addEventListener('weftclose', function (e) {
if (!unsaved()) return;
e.preventDefault();
closeAfterSave = false;
closing.classList.add('shown');
});
document.getElementById('close-save').addEventListener('click', function () {
closeAfterSave = true;
if (!pending) saveButton.click();
// The save could not start (status says why): stay open.
if (!pending) hideClosing();
});
document.getElementById('close-discard').addEventListener('click', function () {
window.close();
});
document.getElementById('close-cancel').addEventListener('click', hideClosing);
saveButton.addEventListener('click', function () {
if (!window.weftIpc || pending) return;
if (rev === null) {
@ -162,6 +213,7 @@
text: request.text,
timer: setTimeout(function () {
finishSave();
hideClosing();
setStatus('not saved: no reply; try again');
}, REPLY_TIMEOUT),
};
@ -225,8 +277,15 @@
rev = msg.rev;
finishSave();
setStatus(editor.value === saved ? 'saved' : 'saved; newer changes are not saved yet');
if (closeAfterSave) {
if (editor.value === saved) window.close();
else hideClosing();
}
} else if (msg.op === 'error') {
if (pending && msg.seq === pending.seq) finishSave();
if (pending && msg.seq === pending.seq) {
finishSave();
hideClosing();
}
if (loading && msg.seq === undefined) finishLoad();
setStatus(msg.conflict
? 'not saved: changed in another window. Copy your text, then Discard to reload.'

View file

@ -11,3 +11,4 @@ module = "app.wasm"
[ui]
entry = "ui/index.html"
close = "ask"

View file

@ -321,7 +321,10 @@
if (msg.state === 'stopped') {
removeTaskbarEntry(msg.session_id);
} else if (msg.state === 'stopping') {
markTaskbarEntryClosing(msg.session_id);
setTaskbarEntryClosing(msg.session_id, true);
} else if (msg.state === 'running') {
// The app declined the close, for example to save first.
setTaskbarEntryClosing(msg.session_id, false);
}
} else if (msg.type === 'RUNNING_APPS') {
msg.sessions.forEach(function (s) {
@ -415,15 +418,16 @@
}
// The app has been asked to close and may take a few seconds, for
// example to save; the entry stays until the session has stopped.
function markTaskbarEntryClosing(sessionId) {
// example to save; the entry stays until the session has stopped. An
// app that declines the close is shown as running again.
function setTaskbarEntryClosing(sessionId, closing) {
var el = document.getElementById('task-' + sessionId);
if (!el || el.dataset.closing) { return; }
el.dataset.closing = '1';
el.style.opacity = '0.5';
el.title += ' (closing)';
if (!el || Boolean(el.dataset.closing) === closing) { return; }
if (closing) { el.dataset.closing = '1'; } else { delete el.dataset.closing; }
el.style.opacity = closing ? '0.5' : '';
el.classList.toggle('closing', closing);
var close = el.querySelector('.task-close');
if (close) { close.remove(); }
if (close) { close.style.display = closing ? 'none' : ''; }
}
function removeTaskbarEntry(sessionId) {

View file

@ -19,6 +19,12 @@ sequence, quotes, a tab and non-ASCII characters, launches
5. A load that fails (the stored notes are not valid UTF-8) leaves Discard
usable: after the file is repaired, Discard loads it and it can be edited
and saved again.
6. Notes declares the `ask` close policy. With unsaved changes, a close
request (TERMINATE_APP or Alt+F4) is cancelled and a prompt is shown: the
session keeps running and Cancel keeps the text; "Save and close" stores
the text before the app shell exits cleanly; "Close without saving"
leaves the stored notes unchanged. Without unsaved changes, Notes closes
at once.
Requires Xvfb, xwd, ImageMagick's convert and xdotool.
"""
@ -45,6 +51,8 @@ PAGE = (15, 15, 15) # The Notes page's background, #0f0f0f.
# The Discard button, right-aligned in the header: its offset from the
# window's right edge, and its height on the desktop.
DISCARD_FROM_RIGHT, DISCARD_Y = 137, 68
# The row through the close prompt's buttons, below the header.
PROMPT_Y = DISCARD_Y + 48
def runtime_pid():
@ -66,6 +74,118 @@ def wait_for_file(path, expected, timeout=15):
raise AssertionError(f"stored notes {actual!r}, expected {expected!r}")
def prompt_buttons(desktop, page):
"""The close prompt's buttons, left to right, as (left, right) columns,
or None when the prompt is not shown."""
width, _, pixels = parse_ppm(desktop.capture())
runs, start = [], None
for x in range(page[0], page[2] + 2):
i = (PROMPT_Y * width + x) * 3
background = x > page[2] or tuple(pixels[i:i + 3]) == PAGE
if not background and start is None:
start = x
elif background and start is not None:
runs.append((start, x - 1))
start = None
buttons = [r for r in runs if r[1] - r[0] >= 40]
# Shown, the row holds the prompt's text and its three buttons, with the
# page between them; hidden, it crosses the editor from edge to edge.
if len(buttons) < 3 or buttons[-1][1] - buttons[0][0] > (page[2] - page[0]) * 0.8:
return None
return buttons[-3:]
def wait_for_prompt(desktop, page, shown, timeout=10):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
buttons = prompt_buttons(desktop, page)
if (buttons is not None) == shown:
return buttons
time.sleep(0.3)
raise AssertionError("the close prompt was " + ("not shown" if shown else "not dismissed"))
def launch(appd):
appd.send({"type": "LAUNCH_APP", "app_id": APP_ID, "surface_id": 0})
reply = appd.wait_for(lambda m: m.get("type") in ("APP_READY", "ERROR"), 120)
if reply.get("type") != "APP_READY":
raise AssertionError(f"Notes did not start: {reply}")
return reply["session_id"]
def wait_for_state(appd, session_id, state, timeout):
try:
appd.wait_for(lambda m: m.get("type") == "APP_STATE" and m.get("state") == state
and m.get("session_id") == session_id, timeout)
except TimeoutError:
raise AssertionError(f"session {session_id} did not become {state}")
def stop_reason(desktop, session_id):
marker = f"stopping session session_id={session_id} reason=\""
for line in desktop.log_text("appd").splitlines():
if marker in line:
return line.split(marker, 1)[1].rsplit('"', 1)[0]
return None
def check_close_policy(desktop, appd, page, act, notes, session_id):
"""Step 6, from a running Notes session whose text is saved."""
def click(column):
act("mousemove", "--sync", str((column[0] + column[1]) // 2), str(PROMPT_Y))
act("click", "1")
def type_at_end(text):
act("mousemove", "--sync", "100", "400")
act("click", "1")
act("key", "ctrl+End")
act("type", "--delay", "40", text)
stored = notes.read_text(encoding="utf-8")
type_at_end(" unsaved")
# The page cancels the close: the session is running again.
appd.send({"type": "TERMINATE_APP", "session_id": session_id})
wait_for_state(appd, session_id, "running", 10)
buttons = wait_for_prompt(desktop, page, True)
click(buttons[2]) # Cancel
wait_for_prompt(desktop, page, False)
# The compositor's close (Alt+F4) asks the page the same way.
act("key", "alt+F4")
buttons = wait_for_prompt(desktop, page, True)
time.sleep(1)
if stop_reason(desktop, session_id) is not None:
raise AssertionError("the session stopped although the close was cancelled")
click(buttons[0]) # Save and close
wait_for_state(appd, session_id, "stopped", 20)
if notes.read_text(encoding="utf-8") != stored + " unsaved":
raise AssertionError("Save and close did not store the text before closing")
reason = stop_reason(desktop, session_id)
if reason is None or not reason.startswith("app shell exited (") or "(0)" not in reason:
raise AssertionError(f"Notes did not exit cleanly after saving: {reason}")
# Close without saving keeps the stored notes.
session_id = launch(appd)
time.sleep(2)
act("search", "--class", "weft-compositor", "windowfocus", "--sync")
type_at_end(" dropped")
appd.send({"type": "TERMINATE_APP", "session_id": session_id})
wait_for_state(appd, session_id, "running", 10)
buttons = wait_for_prompt(desktop, page, True)
click(buttons[1]) # Close without saving
wait_for_state(appd, session_id, "stopped", 20)
if notes.read_text(encoding="utf-8") != stored + " unsaved":
raise AssertionError("closing without saving changed the stored notes")
# Without unsaved changes, a close request closes Notes at once.
session_id = launch(appd)
time.sleep(2)
appd.send({"type": "TERMINATE_APP", "session_id": session_id})
wait_for_state(appd, session_id, "stopped", 10)
reason = stop_reason(desktop, session_id)
if reason is None or not reason.startswith("closed on request; app shell exited"):
raise AssertionError(f"Notes without changes did not close on request: {reason}")
def run(args, desktop, home, xdotool):
data_home = home / "share"
notes = data_home / "weft/app-data" / APP_ID / "notes.txt"
@ -84,10 +204,7 @@ def run(args, desktop, home, xdotool):
})
port, token = read_endpoint(desktop.runtime, 30)
appd = AppdClient(port, token)
appd.send({"type": "LAUNCH_APP", "app_id": APP_ID, "surface_id": 0})
reply = appd.wait_for(lambda m: m.get("type") in ("APP_READY", "ERROR"), 120)
if reply.get("type") != "APP_READY":
raise AssertionError(f"Notes did not start: {reply}")
session_id = launch(appd)
time.sleep(2)
width, height, pixels = parse_ppm(desktop.capture())
page = bounding_box(width, height, pixels, PAGE)
@ -173,6 +290,8 @@ def run(args, desktop, home, xdotool):
if leftovers:
raise AssertionError(f"files left beside the notes: {leftovers}")
check_close_policy(desktop, appd, page, act, notes, session_id)
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__,