diff --git a/crates/weft-appd/src/main.rs b/crates/weft-appd/src/main.rs index 5433b00..3bf2fc9 100644 --- a/crates/weft-appd/src/main.rs +++ b/crates/weft-appd/src/main.rs @@ -27,6 +27,10 @@ struct SessionEntry { bridge_token: Option, } +/// How many stopped sessions stay registered, so their final state can +/// still be queried. +const KEPT_STOPPED: usize = 32; + struct SessionRegistry { next_id: u64, sessions: std::collections::HashMap, @@ -52,6 +56,7 @@ impl Default for SessionRegistry { impl SessionRegistry { fn launch(&mut self, app_id: &str) -> u64 { + self.prune_stopped(); self.next_id += 1; let id = self.next_id; self.sessions.insert( @@ -71,6 +76,24 @@ impl SessionRegistry { id } + /// Forgets the oldest stopped sessions beyond `KEPT_STOPPED`, so the + /// registry does not grow with every launch. + fn prune_stopped(&mut self) { + let mut stopped: Vec = self + .sessions + .iter() + .filter(|(_, e)| matches!(e.state, AppStateKind::Stopped)) + .map(|(&id, _)| id) + .collect(); + if stopped.len() <= KEPT_STOPPED { + return; + } + stopped.sort_unstable(); + for id in &stopped[..stopped.len() - KEPT_STOPPED] { + self.sessions.remove(id); + } + } + pub(crate) fn bridge_token(&self, session_id: u64) -> Option { self.sessions.get(&session_id)?.bridge_token.clone() } @@ -86,10 +109,22 @@ impl SessionRegistry { }) } + /// Asks a session to stop: a running session is closed as a user close + /// would close it, a starting one is stopped at once. The session stays + /// registered, Stopping, until its supervisor settles it. fn terminate(&mut self, session_id: u64) -> bool { - let found = self.sessions.remove(&session_id).is_some(); - self.abort_senders.remove(&session_id); - found + match self.abort_senders.remove(&session_id) { + Some(sender) => { + let _ = sender.send(()); + self.set_state(session_id, AppStateKind::Stopping); + true + } + // A session already closing keeps closing; it stays registered + // until its supervisor settles it. + None if matches!(self.state(session_id), AppStateKind::Stopping) => true, + // A session no supervisor runs has nothing to settle. + None => self.sessions.remove(&session_id).is_some(), + } } pub(crate) fn register_abort(&mut self, session_id: u64) -> tokio::sync::oneshot::Receiver<()> { @@ -109,10 +144,12 @@ impl SessionRegistry { .collect() } + /// The apps to restore at the next start: a session the user asked to + /// close is not among them. fn running_app_ids(&self) -> Vec { self.sessions .values() - .filter(|e| !matches!(e.state, AppStateKind::Stopped)) + .filter(|e| !matches!(e.state, AppStateKind::Stopped | AppStateKind::Stopping)) .map(|e| e.app_id.clone()) .collect() } @@ -530,12 +567,23 @@ pub(crate) async fn dispatch(req: Request, registry: &Registry) -> Response { Response::LaunchAck { session_id, app_id } } Request::TerminateApp { session_id } => { - let found = registry.lock().await.terminate(session_id); + let found = { + let mut reg = registry.lock().await; + let found = reg.terminate(session_id); + if found && matches!(reg.state(session_id), AppStateKind::Stopping) { + // Every client, not only the requester, shows the close. + let _ = reg.broadcast().send(Response::AppState { + session_id, + state: AppStateKind::Stopping, + }); + } + found + }; if found { - tracing::info!(session_id, "terminated"); + tracing::info!(session_id, "stop requested"); Response::AppState { session_id, - state: AppStateKind::Stopped, + state: AppStateKind::Stopping, } } else { Response::Error { @@ -1056,7 +1104,7 @@ mod tests { } #[tokio::test] - async fn dispatch_terminate_known_returns_stopped() { + async fn dispatch_terminate_known_returns_stopping() { let _env = env_lock().lock().await; let reg = make_registry(); let ack = dispatch( @@ -1071,11 +1119,13 @@ mod tests { Response::LaunchAck { session_id, .. } => session_id, _ => panic!("expected LaunchAck"), }; + // The reply says the session is stopping; Stopped is broadcast once + // its supervisor has settled it. let resp = dispatch(Request::TerminateApp { session_id }, ®).await; assert!(matches!( resp, Response::AppState { - state: AppStateKind::Stopped, + state: AppStateKind::Stopping, .. } )); @@ -1490,6 +1540,164 @@ mod tests { ); } + #[tokio::test(flavor = "current_thread")] + async fn an_app_that_ignores_a_close_is_terminated_after_the_timeout() { + 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_close_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let app = dir.join("store/org.example.close"); + write_test_package(&app, "org.example.close", ""); + // Both children report ready and then ignore everything. + let child = dir.join("child.sh"); + std::fs::write( + &child, + "#!/bin/sh\necho READY $WEFT_READY_TOKEN\nexec sleep 30\n", + ) + .unwrap(); + std::fs::set_permissions(&child, std::fs::Permissions::from_mode(0o755)).unwrap(); + let vars = [ + ("WEFT_RUNTIME_BIN", child.clone().into_os_string()), + ("WEFT_APP_SHELL_BIN", child.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, mut 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.close".into(), + surface_id: 0, + }, + ®istry, + ) + .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(); + let reply = dispatch(Request::TerminateApp { session_id }, ®istry).await; + // A second request while the app is closing changes nothing: the + // session stays registered and listed until it settles. + let again = dispatch(Request::TerminateApp { session_id }, ®istry).await; + let closing = { + let reg = registry.lock().await; + ( + reg.state(session_id), + reg.running_sessions() + .iter() + .any(|s| s.session_id == session_id), + reg.running_app_ids(), + ) + }; + let stopped = tokio::time::timeout(std::time::Duration::from_secs(15), async { + while !matches!( + rx.recv().await, + Ok(Response::AppState { + state: AppStateKind::Stopped, + .. + }) + ) {} + }) + .await; + let elapsed = started.elapsed(); + let mut sent = Vec::new(); + while let Ok(out) = compositor.try_recv() { + sent.push(out.msg); + } + + 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!( + matches!( + reply, + Response::AppState { + state: AppStateKind::Stopping, + .. + } + ), + "{reply:?}" + ); + assert!( + matches!( + again, + Response::AppState { + state: AppStateKind::Stopping, + .. + } + ), + "{again:?}" + ); + assert!( + matches!(closing.0, AppStateKind::Stopping), + "{:?}", + closing.0 + ); + assert!(closing.1, "a closing session is no longer listed"); + // An app the user closed is not restored at the next start. + assert!(closing.2.is_empty(), "{:?}", closing.2); + assert!(stopped.is_ok(), "the session did not stop"); + // The app was asked to close, given the timeout, then terminated. + assert!( + sent.iter().any(|m| matches!( + m, + weft_ipc_types::AppdToCompositor::AppCloseRequest { session_id: s } if *s == session_id + )), + "{sent:?}" + ); + assert!(elapsed >= runtime::CLOSE_TIMEOUT, "{elapsed:?}"); + assert!( + elapsed < runtime::CLOSE_TIMEOUT + std::time::Duration::from_secs(5), + "{elapsed:?}" + ); + } + + #[test] + fn only_the_latest_stopped_sessions_stay_registered() { + let mut reg = SessionRegistry::default(); + let first = reg.launch("org.example.a"); + let running = reg.launch("org.example.b"); + reg.set_state(running, AppStateKind::Running); + reg.set_state(first, AppStateKind::Stopped); + for _ in 0..KEPT_STOPPED { + let id = reg.launch("org.example.c"); + reg.set_state(id, AppStateKind::Stopped); + } + let last = reg.launch("org.example.d"); + assert!(matches!(reg.state(first), AppStateKind::NotFound)); + assert!(matches!(reg.state(running), AppStateKind::Running)); + assert!(matches!(reg.state(last - 1), AppStateKind::Stopped)); + assert_eq!(reg.sessions.len(), KEPT_STOPPED + 2); + } + #[tokio::test(flavor = "current_thread")] async fn without_a_connected_compositor_nothing_is_started() { use std::os::unix::fs::PermissionsExt; @@ -1887,9 +2095,10 @@ mod tests { .await .unwrap(); + // The session stays registered until it settles, then is Stopped. assert!(matches!( registry.lock().await.state(session_id), - AppStateKind::NotFound + AppStateKind::Stopped )); let broadcast = rx.try_recv(); diff --git a/crates/weft-appd/src/runtime.rs b/crates/weft-appd/src/runtime.rs index 95e8fbd..8ef2dee 100644 --- a/crates/weft-appd/src/runtime.rs +++ b/crates/weft-appd/src/runtime.rs @@ -449,7 +449,11 @@ pub(crate) async fn supervise( status = session.app_shell.as_mut().expect("app shell spawned").wait() => { format!("app shell exited ({status:?})") } - _ = &mut abort_rx => "terminate requested".to_owned(), + 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() } @@ -457,6 +461,10 @@ pub(crate) async fn supervise( session.settle(®istry, &reason).await } +/// 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); + /// Creates the session's Wayland connection and queues the compositor's end /// for the compositor, returning the app shell's end. fn attach_client( @@ -514,6 +522,50 @@ struct OwnedSession { } impl OwnedSession { + /// Closes a running session as a user close would: the compositor asks + /// 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 { + let asked = self.client_attached + && self.compositor_tx.as_ref().is_some_and(|tx| { + tx.is_connected() + && tx + .try_send(AppdToCompositor::AppCloseRequest { session_id }.into()) + .is_ok() + }); + if !asked { + return "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(); + }; + let wait = async { + tokio::select! { + status = app_shell.wait() => 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(), + } + }; + tokio::time::timeout(CLOSE_TIMEOUT, wait) + .await + .unwrap_or_else(|_| { + format!( + "close requested; the app shell did not exit within {} s and was terminated", + CLOSE_TIMEOUT.as_secs() + ) + }) + } + async fn settle(self, registry: &Registry, reason: &str) -> anyhow::Result<()> { let session_id = self.session_id; tracing::info!(session_id, reason, "stopping session"); diff --git a/crates/weft-compositor/src/appd_ipc.rs b/crates/weft-compositor/src/appd_ipc.rs index f6e85ab..6421ebf 100644 --- a/crates/weft-compositor/src/appd_ipc.rs +++ b/crates/weft-compositor/src/appd_ipc.rs @@ -285,6 +285,10 @@ fn handle_message(state: &mut WeftCompositorState, msg: AppdToCompositor) { .kill_client(client, DisconnectReason::ConnectionClosed); } } + AppdToCompositor::AppCloseRequest { session_id } => { + let closed = state.close_session_windows(session_id); + tracing::info!(session_id, windows = closed, "session asked to close"); + } AppdToCompositor::AppFocusRequest { session_id } => { if state.activate_session(session_id) { tracing::info!(session_id, "session activated"); diff --git a/crates/weft-compositor/src/windows.rs b/crates/weft-compositor/src/windows.rs index 7bfd476..2d7b527 100644 --- a/crates/weft-compositor/src/windows.rs +++ b/crates/weft-compositor/src/windows.rs @@ -83,6 +83,20 @@ impl WeftCompositorState { } } + /// Asks every window of `session_id` to close; returns how many. + pub fn close_session_windows(&mut self, session_id: u64) -> usize { + let mut closed = 0; + for window in self.space.elements() { + if window_session(window) == Some(session_id) + && let Some(toplevel) = window.toplevel() + { + toplevel.send_close(); + closed += 1; + } + } + closed + } + /// Activates the topmost window of `session_id`; returns whether the /// session has one. pub fn activate_session(&mut self, session_id: u64) -> bool { diff --git a/crates/weft-ipc-types/src/lib.rs b/crates/weft-ipc-types/src/lib.rs index 06cddce..b633c6b 100644 --- a/crates/weft-ipc-types/src/lib.rs +++ b/crates/weft-ipc-types/src/lib.rs @@ -29,6 +29,10 @@ pub enum AppdToCompositor { AppFocusRequest { session_id: u64, }, + /// Asks the session's windows to close, as a user close would. + AppCloseRequest { + session_id: u64, + }, } /// Messages sent from weft-compositor to weft-appd. diff --git a/docs/architecture.md b/docs/architecture.md index 06624e6..f5548a0 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -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 ` 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. 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 ` 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. ### weft-runtime diff --git a/infra/shell/system-ui.html b/infra/shell/system-ui.html index dd019a6..25c6157 100644 --- a/infra/shell/system-ui.html +++ b/infra/shell/system-ui.html @@ -320,6 +320,8 @@ } else if (msg.type === 'APP_STATE') { if (msg.state === 'stopped') { removeTaskbarEntry(msg.session_id); + } else if (msg.state === 'stopping') { + markTaskbarEntryClosing(msg.session_id); } } else if (msg.type === 'RUNNING_APPS') { msg.sessions.forEach(function (s) { @@ -391,7 +393,7 @@ var close = document.createElement('span'); close.className = 'task-close'; close.textContent = '×'; - close.title = 'Terminate'; + close.title = 'Close'; close.addEventListener('click', function (e) { e.stopPropagation(); if (ws && ws.readyState === WebSocket.OPEN) { @@ -402,6 +404,7 @@ el.appendChild(close); // Choosing the entry brings the app's window to the front. el.addEventListener('click', function () { + if (el.dataset.closing) { return; } if (ws && ws.readyState === WebSocket.OPEN) { ws.send(JSON.stringify({ type: 'ACTIVATE_APP', session_id: sessionId })); } @@ -411,6 +414,18 @@ taskbar.insertBefore(el, clock); } + // 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) { + var el = document.getElementById('task-' + sessionId); + if (!el || el.dataset.closing) { return; } + el.dataset.closing = '1'; + el.style.opacity = '0.5'; + el.title += ' (closing)'; + var close = el.querySelector('.task-close'); + if (close) { close.remove(); } + } + function removeTaskbarEntry(sessionId) { var el = document.getElementById('task-' + sessionId); if (el) { el.remove(); } diff --git a/tests/frame/check_counter.py b/tests/frame/check_counter.py index 846acb4..71896d6 100644 --- a/tests/frame/check_counter.py +++ b/tests/frame/check_counter.py @@ -227,13 +227,18 @@ def run(args, desktop, xdotool): if states[3] != states[1]: raise AssertionError("count after ArrowDown does not match the count after one ArrowUp") - # Ending the session closes its client in the compositor. + # Ending the session closes the app as a user close would: the + # compositor asks its window to close and the app shell exits by itself. appd.send({"type": "TERMINATE_APP", "session_id": session_id}) deadline = time.monotonic() + 15 - closed = f"closing the client of an ended session session_id={session_id}" - while closed not in desktop.log_text("compositor"): + asked = f"session asked to close session_id={session_id} windows=1" + # appd records "closed on request" only when the app shell exits cleanly. + closed = (f'stopping session session_id={session_id} reason="closed on request; ' + 'app shell exited') + while asked not in desktop.log_text("compositor") or closed not in desktop.log_text("appd"): if time.monotonic() > deadline: - raise AssertionError(f"the compositor did not close the session's client: {closed!r}") + raise AssertionError("the session did not close on request; see compositor.log " + "and appd.log") time.sleep(0.3)