From 0866befc16b6a1cae6b6848edbf4e108f64146ff Mon Sep 17 00:00:00 2001 From: Marco Allegretti Date: Fri, 9 Oct 2026 16:41:30 +0000 Subject: [PATCH] fix(appd): keep a closing session registered until it settles A repeated TERMINATE_APP during the close wait no longer removes the session from the registry. The close wait also watches the runtime and the IPC relay, and reports a failed app shell exit as a failure rather than a close. A session being closed is not saved for restore, only the 32 most recent stopped sessions stay registered, and the taskbar shows an entry as closing until its session stops. --- crates/weft-appd/src/main.rs | 79 ++++++++++++++++++++++++++++++++- crates/weft-appd/src/runtime.rs | 33 ++++++++++---- docs/architecture.md | 2 +- infra/shell/system-ui.html | 15 ++++++- tests/frame/check_counter.py | 3 +- 5 files changed, 120 insertions(+), 12 deletions(-) diff --git a/crates/weft-appd/src/main.rs b/crates/weft-appd/src/main.rs index 3a13d3c..277c40a 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() } @@ -96,6 +119,9 @@ impl SessionRegistry { 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(), } @@ -118,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() } @@ -1416,6 +1444,19 @@ mod tests { .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, @@ -1453,6 +1494,24 @@ mod tests { ), "{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!( @@ -1469,6 +1528,24 @@ mod tests { ); } + #[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; diff --git a/crates/weft-appd/src/runtime.rs b/crates/weft-appd/src/runtime.rs index d0adc53..8ef2dee 100644 --- a/crates/weft-appd/src/runtime.rs +++ b/crates/weft-appd/src/runtime.rs @@ -537,16 +537,33 @@ impl OwnedSession { if !asked { return "terminate requested; the compositor could not ask the app to close".to_owned(); } - let Some(app_shell) = self.app_shell.as_mut() else { + 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(); }; - match tokio::time::timeout(CLOSE_TIMEOUT, app_shell.wait()).await { - Ok(status) => format!("closed on request; app shell exited ({status:?})"), - Err(_) => format!( - "close requested; the app shell did not exit within {} s and was terminated", - CLOSE_TIMEOUT.as_secs() - ), - } + 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<()> { diff --git a/docs/architecture.md b/docs/architecture.md index 7b06432..c600cdc 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. `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, and `stopped` is broadcast once the session has settled. 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 ` 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 the 32 most recently stopped sessions. 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..bf28f85 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) { @@ -411,6 +413,17 @@ 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) { return; } + 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 cb45450..2118376 100644 --- a/tests/frame/check_counter.py +++ b/tests/frame/check_counter.py @@ -225,8 +225,9 @@ def run(args, desktop, xdotool): appd.send({"type": "TERMINATE_APP", "session_id": session_id}) deadline = time.monotonic() + 15 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 (Ok(ExitStatus(unix_wait_status(0))))"') + '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("the session did not close on request; see compositor.log "