From d509513e0a8868a08586bd8e06b1cbd438d0746c Mon Sep 17 00:00:00 2001 From: Marco Allegretti Date: Fri, 9 Oct 2026 17:16:42 +0000 Subject: [PATCH] fix(appd): stop a session whose stop request races its readiness A stop requested while a session was starting could still be queued when the app shell reported ready. The session was then shown as running and asked to close, instead of being stopped. The supervisor now checks for that request before it marks the session running. Stop requests use a small bounded queue. A repeated request on a stopping session is neither queued nor broadcast again; only a forced one is sent. The taskbar's Force quit returns to a normal close when the entry is activated, or 20 s after it is offered. --- crates/weft-appd/src/main.rs | 129 +++++++++++++++++++++++++++++++- crates/weft-appd/src/runtime.rs | 12 ++- docs/architecture.md | 2 +- infra/shell/system-ui.html | 17 ++++- 4 files changed, 153 insertions(+), 7 deletions(-) diff --git a/crates/weft-appd/src/main.rs b/crates/weft-appd/src/main.rs index 808a6e3..644a6fe 100644 --- a/crates/weft-appd/src/main.rs +++ b/crates/weft-appd/src/main.rs @@ -117,8 +117,17 @@ impl SessionRegistry { fn terminate(&mut self, session_id: u64, force: bool) -> Option { let state = self.state(session_id); match self.abort_senders.get(&session_id) { + // Already ending; a forced request still ends it without waiting. + Some(sender) if matches!(state, AppStateKind::Stopping) => { + if force { + let _ = sender.try_send(runtime::Stop::Force); + } + Some(AppStateKind::Stopping) + } Some(sender) => { - let _ = sender.send(if force { + // A full queue already holds a request; a forced one that + // does not fit is preceded by one the supervisor acts on. + let _ = sender.try_send(if force { runtime::Stop::Force } else { runtime::Stop::Close @@ -138,7 +147,7 @@ impl SessionRegistry { } pub(crate) fn register_abort(&mut self, session_id: u64) -> runtime::StopReceiver { - let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); + let (tx, rx) = tokio::sync::mpsc::channel(runtime::STOP_QUEUE); self.abort_senders.insert(session_id, tx); rx } @@ -579,8 +588,11 @@ pub(crate) async fn dispatch(req: Request, registry: &Registry) -> Response { Request::TerminateApp { session_id, force } => { let state = { let mut reg = registry.lock().await; + let before = reg.state(session_id); let state = reg.terminate(session_id, force); - if matches!(state, Some(AppStateKind::Stopping)) { + if matches!(state, Some(AppStateKind::Stopping)) + && !matches!(before, AppStateKind::Stopping) + { let _ = reg.broadcast().send(Response::AppState { session_id, state: AppStateKind::Stopping, @@ -1748,6 +1760,117 @@ mod tests { ); } + #[tokio::test(flavor = "current_thread")] + async fn a_forced_stop_ends_a_close_in_progress() { + 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_force_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let app = dir.join("store/org.example.force"); + write_test_package(&app, "org.example.force", ""); + // 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, 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.force".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; + dispatch( + Request::TerminateApp { + session_id, + force: false, + }, + ®istry, + ) + .await; + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + let forced_at = std::time::Instant::now(); + let reply = dispatch( + Request::TerminateApp { + session_id, + force: true, + }, + ®istry, + ) + .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; + let elapsed = forced_at.elapsed(); + drop(compositor); + + 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!(stopped.is_ok(), "the forced stop did not stop the session"); + // The forced stop does not wait out the close timeout. + assert!(elapsed < std::time::Duration::from_secs(3), "{elapsed:?}"); + } + #[test] fn only_the_latest_stopped_sessions_stay_registered() { let mut reg = SessionRegistry::default(); diff --git a/crates/weft-appd/src/runtime.rs b/crates/weft-appd/src/runtime.rs index cd2f864..f07bfb6 100644 --- a/crates/weft-appd/src/runtime.rs +++ b/crates/weft-appd/src/runtime.rs @@ -272,9 +272,11 @@ pub(crate) enum Stop { Force, } -pub(crate) type StopSender = tokio::sync::mpsc::UnboundedSender; +/// Repeated requests carry nothing new, so a few queued ones are enough. +pub(crate) const STOP_QUEUE: usize = 2; +pub(crate) type StopSender = tokio::sync::mpsc::Sender; /// Ends when appd shuts down and drops the sender. -pub(crate) type StopReceiver = tokio::sync::mpsc::UnboundedReceiver; +pub(crate) type StopReceiver = tokio::sync::mpsc::Receiver; pub(crate) async fn supervise( session_id: u64, @@ -456,6 +458,12 @@ pub(crate) async fn supervise( { let mut reg = registry.lock().await; + // A stop requested while starting can still be queued here, or lose + // the race with READY; the session is then stopped, not shown. + if matches!(reg.state(session_id), AppStateKind::Stopping) || abort_rx.try_recv().is_ok() { + drop(reg); + return session.settle(®istry, "startup aborted").await; + } reg.set_state(session_id, AppStateKind::Running); let _ = reg.broadcast().send(Response::AppReady { session_id, diff --git a/docs/architecture.md b/docs/architecture.md index 871592a..1207cd4 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 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 session stays `running` while the application answers (appd replies with that state), and enters `stopping` only once it is ending. An application that declares the `ask` close policy may decline the close (see [Closing an application](#closing-an-application)); its window is brought to the front and the session keeps running. A repeated request while the application answers changes nothing. `TERMINATE_APP` with `"force": true` terminates the session without asking; the taskbar offers it, as Force quit, for an app still running once it has had time to answer. The stop reason records what happened: a close on request with a clean exit, a failure while closing, the timeout, or a forced stop; `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. appd keeps the final state of at most 32 stopped sessions, forgetting those launched earliest. 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 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 session stays `running` while the application answers (appd replies with that state), and enters `stopping` only once it is ending. An application that declares the `ask` close policy may decline the close (see [Closing an application](#closing-an-application)); its window is brought to the front and the session keeps running. A repeated request while the application answers changes nothing, and a session being asked to close is still restored at the next start if appd stops meanwhile. `TERMINATE_APP` with `"force": true` terminates the session without asking; the taskbar offers it, as Force quit, for an app still running once it has had time to answer. The stop reason records what happened: a close on request with a clean exit, a failure while closing, the timeout, or a forced stop; `stopped` is broadcast once the session has settled. A session still starting is stopped at once, also when the request races its readiness, and when appd itself shuts down its sessions are terminated without a close. appd keeps the final state of at most 32 stopped sessions, forgetting those launched earliest. 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 31ea941..4d0b5eb 100644 --- a/infra/shell/system-ui.html +++ b/infra/shell/system-ui.html @@ -382,6 +382,7 @@ // Longer than weft-appd's close timeout, so an app that neither closes // nor declines has already been terminated. var FORCE_QUIT_DELAY = 6000; + var FORCE_QUIT_OFFER = 20000; function ensureTaskbarEntry(sessionId, appId) { var id = 'task-' + sessionId; @@ -401,6 +402,7 @@ // The first click asks the app to close; it may decline, for example // to offer saving. An app still running once it has had time to // answer can then be force quit, losing what it has not saved. + var closeTimer = null; close.addEventListener('click', function (e) { e.stopPropagation(); if (!ws || ws.readyState !== WebSocket.OPEN) { return; } @@ -408,19 +410,32 @@ ws.send(JSON.stringify({ type: 'TERMINATE_APP', session_id: sessionId, force: force })); if (force || close.dataset.asked) { return; } close.dataset.asked = '1'; - setTimeout(function () { + closeTimer = setTimeout(function () { if (!document.getElementById(el.id) || el.dataset.closing) { return; } close.dataset.force = '1'; close.textContent = 'Force quit'; close.title = 'Force quit: changes the app has not saved are lost'; close.style.color = '#ff6b6b'; + // Offered only for a while: an app that declined to let the user + // keep working is closed normally next time. + closeTimer = setTimeout(resetClose, FORCE_QUIT_OFFER); }, FORCE_QUIT_DELAY); }); + function resetClose() { + clearTimeout(closeTimer); + closeTimer = null; + delete close.dataset.asked; + delete close.dataset.force; + close.textContent = '×'; + close.title = 'Close'; + close.style.color = ''; + } el.appendChild(span); el.appendChild(close); // Choosing the entry brings the app's window to the front. el.addEventListener('click', function () { if (el.dataset.closing) { return; } + resetClose(); if (ws && ws.readyState === WebSocket.OPEN) { ws.send(JSON.stringify({ type: 'ACTIVATE_APP', session_id: sessionId })); }