mirror of
https://github.com/marcoallegretti/WEFT_OS.git
synced 2026-11-22 08:13:59 +00:00
fix(appd): keep a session running while it answers a close, and add a forced stop
An application with the ask close policy could decline every close, and nothing could end it. TERMINATE_APP now takes force, which terminates the session without asking. The taskbar offers it as Force quit once an app has had longer than the close timeout to answer. The close interaction now comes before Running -> Stopping, as blueprint 6.2 requires. The session stays running while the application answers, and a declined close no longer moves Stopping back to Running. Stop requests reach the supervisor on a channel, so a repeated or forced request during the close wait is seen without registering again. A declining window is brought to the front, so its prompt is visible. A clean exit after a close request is recorded as a close on request. A decline report is recognised after page output that lacks a newline. Notes keeps a pending Save and close when asked again. It saves text typed during that save before closing, and reports when it cannot save because it is not connected.
This commit is contained in:
parent
551df84562
commit
ddd79f6ab1
8 changed files with 356 additions and 149 deletions
|
|
@ -8,8 +8,12 @@ pub enum Request {
|
|||
app_id: String,
|
||||
surface_id: u64,
|
||||
},
|
||||
/// Asks a running session to close as a user close would, or with
|
||||
/// `force`, terminates it without asking.
|
||||
TerminateApp {
|
||||
session_id: u64,
|
||||
#[serde(default)]
|
||||
force: bool,
|
||||
},
|
||||
/// Brings the session's window to the front with keyboard focus.
|
||||
ActivateApp {
|
||||
|
|
@ -215,10 +219,19 @@ mod tests {
|
|||
|
||||
#[test]
|
||||
fn terminate_app_request_roundtrip() {
|
||||
let req = Request::TerminateApp { session_id: 42 };
|
||||
let req = Request::TerminateApp {
|
||||
session_id: 42,
|
||||
force: false,
|
||||
};
|
||||
let bytes = rmp_serde::to_vec(&req).unwrap();
|
||||
let decoded: Request = rmp_serde::from_slice(&bytes).unwrap();
|
||||
assert!(matches!(decoded, Request::TerminateApp { session_id: 42 }));
|
||||
assert!(matches!(
|
||||
decoded,
|
||||
Request::TerminateApp {
|
||||
session_id: 42,
|
||||
force: false
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ struct SessionRegistry {
|
|||
next_id: u64,
|
||||
sessions: std::collections::HashMap<u64, SessionEntry>,
|
||||
broadcast: tokio::sync::broadcast::Sender<Response>,
|
||||
abort_senders: std::collections::HashMap<u64, tokio::sync::oneshot::Sender<()>>,
|
||||
abort_senders: std::collections::HashMap<u64, runtime::StopSender>,
|
||||
compositor_tx: Option<compositor_client::CompositorSender>,
|
||||
ipc_senders: std::collections::HashMap<u64, tokio::sync::mpsc::Sender<String>>,
|
||||
}
|
||||
|
|
@ -109,26 +109,36 @@ 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 {
|
||||
match self.abort_senders.remove(&session_id) {
|
||||
/// Asks a session to stop and returns the state to report, or `None`
|
||||
/// when there is no such session. A running session is asked to close
|
||||
/// as a user close would, and stays running while the application
|
||||
/// answers; a forced stop or a session still starting is stopped at
|
||||
/// once and is Stopping until its supervisor settles it.
|
||||
fn terminate(&mut self, session_id: u64, force: bool) -> Option<AppStateKind> {
|
||||
let state = self.state(session_id);
|
||||
match self.abort_senders.get(&session_id) {
|
||||
Some(sender) => {
|
||||
let _ = sender.send(());
|
||||
self.set_state(session_id, AppStateKind::Stopping);
|
||||
true
|
||||
let _ = sender.send(if force {
|
||||
runtime::Stop::Force
|
||||
} else {
|
||||
runtime::Stop::Close
|
||||
});
|
||||
if !force && matches!(state, AppStateKind::Running) {
|
||||
return Some(AppStateKind::Running);
|
||||
}
|
||||
self.set_state(session_id, AppStateKind::Stopping);
|
||||
Some(AppStateKind::Stopping)
|
||||
}
|
||||
// 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(),
|
||||
None => self
|
||||
.sessions
|
||||
.remove(&session_id)
|
||||
.map(|_| AppStateKind::Stopped),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn register_abort(&mut self, session_id: u64) -> tokio::sync::oneshot::Receiver<()> {
|
||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||
pub(crate) fn register_abort(&mut self, session_id: u64) -> runtime::StopReceiver {
|
||||
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
|
||||
self.abort_senders.insert(session_id, tx);
|
||||
rx
|
||||
}
|
||||
|
|
@ -154,7 +164,7 @@ impl SessionRegistry {
|
|||
.collect()
|
||||
}
|
||||
|
||||
fn state(&self, session_id: u64) -> AppStateKind {
|
||||
pub(crate) fn state(&self, session_id: u64) -> AppStateKind {
|
||||
self.sessions
|
||||
.get(&session_id)
|
||||
.map(|e| e.state.clone())
|
||||
|
|
@ -566,30 +576,27 @@ pub(crate) async fn dispatch(req: Request, registry: &Registry) -> Response {
|
|||
});
|
||||
Response::LaunchAck { session_id, app_id }
|
||||
}
|
||||
Request::TerminateApp { session_id } => {
|
||||
let found = {
|
||||
Request::TerminateApp { session_id, force } => {
|
||||
let state = {
|
||||
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 state = reg.terminate(session_id, force);
|
||||
if matches!(state, Some(AppStateKind::Stopping)) {
|
||||
let _ = reg.broadcast().send(Response::AppState {
|
||||
session_id,
|
||||
state: AppStateKind::Stopping,
|
||||
});
|
||||
}
|
||||
found
|
||||
state
|
||||
};
|
||||
if found {
|
||||
tracing::info!(session_id, "stop requested");
|
||||
Response::AppState {
|
||||
session_id,
|
||||
state: AppStateKind::Stopping,
|
||||
match state {
|
||||
Some(state) => {
|
||||
tracing::info!(session_id, force, "stop requested");
|
||||
Response::AppState { session_id, state }
|
||||
}
|
||||
} else {
|
||||
Response::Error {
|
||||
None => Response::Error {
|
||||
code: 1,
|
||||
message: format!("session {session_id} not found"),
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
Request::ActivateApp { session_id } => {
|
||||
|
|
@ -963,7 +970,7 @@ mod tests {
|
|||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dispatch_terminate_known_returns_stopping() {
|
||||
async fn dispatch_terminate_forgets_a_stopped_session() {
|
||||
let _env = env_lock().lock().await;
|
||||
let reg = make_registry();
|
||||
let ack = dispatch(
|
||||
|
|
@ -978,22 +985,43 @@ 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!(
|
||||
// Without a configured runtime the session stopped at once; a
|
||||
// terminate forgets it.
|
||||
let resp = dispatch(
|
||||
Request::TerminateApp {
|
||||
session_id,
|
||||
force: false,
|
||||
},
|
||||
®,
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
matches!(
|
||||
resp,
|
||||
Response::AppState {
|
||||
state: AppStateKind::Stopping,
|
||||
state: AppStateKind::Stopped,
|
||||
..
|
||||
}
|
||||
),
|
||||
"{resp:?}"
|
||||
);
|
||||
assert!(matches!(
|
||||
reg.lock().await.state(session_id),
|
||||
AppStateKind::NotFound
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dispatch_terminate_unknown_returns_error() {
|
||||
let reg = make_registry();
|
||||
let resp = dispatch(Request::TerminateApp { session_id: 999 }, ®).await;
|
||||
let resp = dispatch(
|
||||
Request::TerminateApp {
|
||||
session_id: 999,
|
||||
force: false,
|
||||
},
|
||||
®,
|
||||
)
|
||||
.await;
|
||||
assert!(matches!(resp, Response::Error { .. }));
|
||||
}
|
||||
|
||||
|
|
@ -1104,14 +1132,14 @@ mod tests {
|
|||
fn registry_terminate_known_session() {
|
||||
let mut reg = SessionRegistry::default();
|
||||
let id = reg.launch("com.example.app");
|
||||
assert!(reg.terminate(id));
|
||||
assert!(reg.terminate(id, false).is_some());
|
||||
assert!(matches!(reg.state(id), AppStateKind::NotFound));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_terminate_unknown_returns_false() {
|
||||
let mut reg = SessionRegistry::default();
|
||||
assert!(!reg.terminate(999));
|
||||
assert!(reg.terminate(999, false).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -1126,7 +1154,7 @@ mod tests {
|
|||
assert_eq!(sessions[0].app_id, "com.example.a");
|
||||
assert_eq!(sessions[1].session_id, id2);
|
||||
assert_eq!(sessions[1].app_id, "com.example.b");
|
||||
reg.terminate(id1);
|
||||
reg.terminate(id1, false);
|
||||
assert_eq!(reg.running_sessions().len(), 1);
|
||||
assert_eq!(reg.running_sessions()[0].session_id, id2);
|
||||
}
|
||||
|
|
@ -1442,7 +1470,7 @@ mod tests {
|
|||
}
|
||||
|
||||
let registry = make_registry();
|
||||
let (tx, _compositor) = tokio::sync::mpsc::channel(8);
|
||||
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)),
|
||||
|
|
@ -1464,28 +1492,46 @@ mod tests {
|
|||
})
|
||||
.await;
|
||||
let started = std::time::Instant::now();
|
||||
dispatch(Request::TerminateApp { session_id }, ®istry).await;
|
||||
// The session is running again once the genuine report arrives.
|
||||
dispatch(
|
||||
Request::TerminateApp {
|
||||
session_id,
|
||||
force: false,
|
||||
},
|
||||
®istry,
|
||||
)
|
||||
.await;
|
||||
// Once the genuine report arrives, the declining window is brought
|
||||
// to the front, and the session never left Running.
|
||||
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,
|
||||
_ => {}
|
||||
match compositor.recv().await.map(|out| out.msg) {
|
||||
Some(weft_ipc_types::AppdToCompositor::AppFocusRequest { session_id: s })
|
||||
if s == session_id =>
|
||||
{
|
||||
return true;
|
||||
}
|
||||
Some(_) => {}
|
||||
None => return false,
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
let mut broadcasts = Vec::new();
|
||||
while let Ok(message) = rx.try_recv() {
|
||||
broadcasts.push(message);
|
||||
}
|
||||
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 }, ®istry).await;
|
||||
// A forced stop does not ask, so nothing can decline it.
|
||||
let forced_at = std::time::Instant::now();
|
||||
let forced = 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,
|
||||
|
|
@ -1519,7 +1565,28 @@ mod tests {
|
|||
"{resumed_after:?}"
|
||||
);
|
||||
assert!(matches!(state, AppStateKind::Running), "{state:?}");
|
||||
assert!(stopped.is_ok(), "the second close did not stop the session");
|
||||
assert!(
|
||||
!broadcasts
|
||||
.iter()
|
||||
.any(|m| matches!(m, Response::AppState { .. })),
|
||||
"{broadcasts:?}"
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
forced,
|
||||
Response::AppState {
|
||||
state: AppStateKind::Stopping,
|
||||
..
|
||||
}
|
||||
),
|
||||
"{forced:?}"
|
||||
);
|
||||
assert!(stopped.is_ok(), "a forced stop did not stop the session");
|
||||
assert!(
|
||||
forced_at.elapsed() < std::time::Duration::from_secs(3),
|
||||
"{:?}",
|
||||
forced_at.elapsed()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
|
|
@ -1577,10 +1644,24 @@ 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 reply = dispatch(
|
||||
Request::TerminateApp {
|
||||
session_id,
|
||||
force: false,
|
||||
},
|
||||
®istry,
|
||||
)
|
||||
.await;
|
||||
// While the application is asked, the session is still running; a
|
||||
// second request changes nothing and does not ask again.
|
||||
let again = dispatch(
|
||||
Request::TerminateApp {
|
||||
session_id,
|
||||
force: false,
|
||||
},
|
||||
®istry,
|
||||
)
|
||||
.await;
|
||||
let closing = {
|
||||
let reg = registry.lock().await;
|
||||
(
|
||||
|
|
@ -1622,7 +1703,7 @@ mod tests {
|
|||
matches!(
|
||||
reply,
|
||||
Response::AppState {
|
||||
state: AppStateKind::Stopping,
|
||||
state: AppStateKind::Running,
|
||||
..
|
||||
}
|
||||
),
|
||||
|
|
@ -1632,27 +1713,32 @@ mod tests {
|
|||
matches!(
|
||||
again,
|
||||
Response::AppState {
|
||||
state: AppStateKind::Stopping,
|
||||
state: AppStateKind::Running,
|
||||
..
|
||||
}
|
||||
),
|
||||
"{again:?}"
|
||||
);
|
||||
assert!(
|
||||
matches!(closing.0, AppStateKind::Stopping),
|
||||
matches!(closing.0, AppStateKind::Running),
|
||||
"{:?}",
|
||||
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!(
|
||||
closing.1,
|
||||
"a session being asked to close is no longer listed"
|
||||
);
|
||||
assert_eq!(closing.2, ["org.example.close"]);
|
||||
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!(
|
||||
assert_eq!(
|
||||
sent.iter()
|
||||
.filter(|m| matches!(
|
||||
m,
|
||||
weft_ipc_types::AppdToCompositor::AppCloseRequest { session_id: s } if *s == session_id
|
||||
)),
|
||||
))
|
||||
.count(),
|
||||
1,
|
||||
"{sent:?}"
|
||||
);
|
||||
assert!(elapsed >= runtime::CLOSE_TIMEOUT, "{elapsed:?}");
|
||||
|
|
@ -2018,6 +2104,11 @@ mod tests {
|
|||
Ok(Ok(Response::AppReady { session_id: sid, .. })) if sid == session_id
|
||||
));
|
||||
|
||||
let stopping = tokio::time::timeout(std::time::Duration::from_millis(200), rx.recv()).await;
|
||||
assert!(matches!(
|
||||
stopping,
|
||||
Ok(Ok(Response::AppState { session_id: sid, state: AppStateKind::Stopping })) if sid == session_id
|
||||
));
|
||||
let stopped = tokio::time::timeout(std::time::Duration::from_millis(200), rx.recv()).await;
|
||||
assert!(matches!(
|
||||
stopped,
|
||||
|
|
@ -2062,7 +2153,7 @@ mod tests {
|
|||
let session_id = registry.lock().await.launch("test.abort.startup");
|
||||
let abort_rx = registry.lock().await.register_abort(session_id);
|
||||
|
||||
registry.lock().await.terminate(session_id);
|
||||
registry.lock().await.terminate(session_id, false);
|
||||
|
||||
use_test_runtime_dir();
|
||||
|
||||
|
|
|
|||
|
|
@ -263,12 +263,25 @@ fn spawn_file_portal(
|
|||
Some((socket, child))
|
||||
}
|
||||
|
||||
/// A request to end a session, from `TERMINATE_APP`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Stop {
|
||||
/// Close as a user close would; the application may decline.
|
||||
Close,
|
||||
/// Terminate without asking.
|
||||
Force,
|
||||
}
|
||||
|
||||
pub(crate) type StopSender = tokio::sync::mpsc::UnboundedSender<Stop>;
|
||||
/// Ends when appd shuts down and drops the sender.
|
||||
pub(crate) type StopReceiver = tokio::sync::mpsc::UnboundedReceiver<Stop>;
|
||||
|
||||
pub(crate) async fn supervise(
|
||||
session_id: u64,
|
||||
mut package: LaunchPackage,
|
||||
grants: crate::grants::SessionGrants,
|
||||
registry: Registry,
|
||||
abort_rx: tokio::sync::oneshot::Receiver<()>,
|
||||
abort_rx: StopReceiver,
|
||||
compositor_tx: Option<CompositorSender>,
|
||||
) -> anyhow::Result<()> {
|
||||
let mut abort_rx = abort_rx;
|
||||
|
|
@ -451,32 +464,40 @@ pub(crate) async fn supervise(
|
|||
}
|
||||
tracing::info!(session_id, %app_id, "app ready");
|
||||
|
||||
// Whether the user asked the application to close, so that a clean exit
|
||||
// afterwards, also one the application makes after declining, is a
|
||||
// close on request.
|
||||
let mut close_asked = false;
|
||||
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:?})");
|
||||
break match status {
|
||||
Ok(status) if close_asked && status.success() => {
|
||||
format!("closed on request; app shell exited ({status:?})")
|
||||
}
|
||||
requested = &mut abort_rx => match requested {
|
||||
Ok(()) => match session.close(session_id, &mut cancelled).await {
|
||||
status => format!("app shell exited ({status:?})"),
|
||||
};
|
||||
}
|
||||
stop = abort_rx.recv() => match stop {
|
||||
Some(Stop::Force) => break "terminated by force".to_owned(),
|
||||
Some(Stop::Close) => {
|
||||
close_asked = true;
|
||||
match session.close(session_id, &mut cancelled, &mut abort_rx).await {
|
||||
Close::Settle(reason) => break reason,
|
||||
// The application kept running, as its close policy
|
||||
// allows; a later request asks again.
|
||||
// The application keeps running, as its close
|
||||
// policy allows; its window comes to the front so
|
||||
// the user sees why. 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");
|
||||
tracing::info!(session_id, "the application declined the close");
|
||||
session.focus(session_id);
|
||||
}
|
||||
},
|
||||
// The sender is dropped only when appd shuts down.
|
||||
Err(_) => break "appd is shutting down".to_owned(),
|
||||
}
|
||||
}
|
||||
// The senders are dropped only when appd shuts down.
|
||||
None => break "appd is shutting down".to_owned(),
|
||||
},
|
||||
_ = session.relay.as_mut().expect("relay opened").ended() => {
|
||||
break "component closed its IPC connection".to_owned();
|
||||
|
|
@ -507,11 +528,11 @@ async fn watch_app_shell_stdout(
|
|||
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))
|
||||
{
|
||||
// Earlier output without a trailing newline can precede the
|
||||
// report, as it can precede READY; the token alone establishes it.
|
||||
if line.rsplit_once(' ').is_some_and(|(head, t)| {
|
||||
head.ends_with(CLOSE_CANCELLED) && crate::ws::tokens_match(&token, t)
|
||||
}) {
|
||||
// One pending report is enough; the supervisor drops stale ones
|
||||
// before it asks again.
|
||||
let _ = cancelled.try_send(());
|
||||
|
|
@ -590,9 +611,13 @@ impl OwnedSession {
|
|||
&mut self,
|
||||
session_id: u64,
|
||||
cancelled: &mut tokio::sync::mpsc::Receiver<()>,
|
||||
stops: &mut StopReceiver,
|
||||
) -> Close {
|
||||
// A report from an earlier close, for example one the user started
|
||||
// in the compositor, does not answer this one.
|
||||
// A report already read from an earlier close, for example one the
|
||||
// user started in the compositor, does not answer this one. One
|
||||
// still in the pipe can: the session then reads as declined while
|
||||
// the app shell is still asking, and the app shell's own answer
|
||||
// timeout still closes a page that does not answer.
|
||||
while cancelled.try_recv().is_ok() {}
|
||||
let asked = self.client_attached
|
||||
&& self.compositor_tx.as_ref().is_some_and(|tx| {
|
||||
|
|
@ -614,20 +639,31 @@ impl OwnedSession {
|
|||
return Close::Settle("terminate requested".to_owned());
|
||||
};
|
||||
let wait = async {
|
||||
loop {
|
||||
tokio::select! {
|
||||
status = app_shell.wait() => Close::Settle(match status {
|
||||
status = app_shell.wait() => break 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() => {
|
||||
Close::Settle(format!("runtime exited while closing ({status:?})"))
|
||||
break Close::Settle(format!("runtime exited while closing ({status:?})"));
|
||||
}
|
||||
_ = relay.ended() => Close::Settle(
|
||||
_ = relay.ended() => break Close::Settle(
|
||||
"component closed its IPC connection while closing".to_owned(),
|
||||
),
|
||||
Some(()) = cancelled.recv() => Close::Cancelled,
|
||||
Some(()) = cancelled.recv() => break Close::Cancelled,
|
||||
stop = stops.recv() => match stop {
|
||||
// Asking again while the application answers changes
|
||||
// nothing.
|
||||
Some(Stop::Close) => {}
|
||||
Some(Stop::Force) => {
|
||||
break Close::Settle("terminated by force while closing".to_owned());
|
||||
}
|
||||
None => break Close::Settle("appd is shutting down".to_owned()),
|
||||
},
|
||||
}
|
||||
}
|
||||
};
|
||||
tokio::time::timeout(CLOSE_TIMEOUT, wait)
|
||||
|
|
@ -640,9 +676,28 @@ impl OwnedSession {
|
|||
})
|
||||
}
|
||||
|
||||
/// Brings the session's window to the front with keyboard focus.
|
||||
fn focus(&self, session_id: u64) {
|
||||
if self.client_attached
|
||||
&& let Some(tx) = &self.compositor_tx
|
||||
{
|
||||
let _ = tx.try_send(AppdToCompositor::AppFocusRequest { session_id }.into());
|
||||
}
|
||||
}
|
||||
|
||||
async fn settle(self, registry: &Registry, reason: &str) -> anyhow::Result<()> {
|
||||
let session_id = self.session_id;
|
||||
tracing::info!(session_id, reason, "stopping session");
|
||||
{
|
||||
let mut reg = registry.lock().await;
|
||||
if !matches!(reg.state(session_id), AppStateKind::Stopping) {
|
||||
reg.set_state(session_id, AppStateKind::Stopping);
|
||||
let _ = reg.broadcast().send(Response::AppState {
|
||||
session_id,
|
||||
state: AppStateKind::Stopping,
|
||||
});
|
||||
}
|
||||
}
|
||||
kill_child(self.app_shell).await;
|
||||
kill_child(self.runtime).await;
|
||||
if self.client_attached
|
||||
|
|
@ -689,7 +744,7 @@ async fn kill_child(child: Option<tokio::process::Child>) {
|
|||
async fn wait_for_child_ready(
|
||||
stdout: tokio::process::ChildStdout,
|
||||
token: &str,
|
||||
abort_rx: &mut tokio::sync::oneshot::Receiver<()>,
|
||||
abort_rx: &mut StopReceiver,
|
||||
) -> Result<BufReader<tokio::process::ChildStdout>, String> {
|
||||
tokio::select! {
|
||||
r = tokio::time::timeout(READY_TIMEOUT, wait_for_ready(stdout, token)) => match r {
|
||||
|
|
@ -697,7 +752,8 @@ async fn wait_for_child_ready(
|
|||
Ok(Err(e)) => Err(format!("did not become ready: {e}")),
|
||||
Err(_) => Err(format!("not ready after {}s", READY_TIMEOUT.as_secs())),
|
||||
},
|
||||
_ = abort_rx => Err("startup aborted".to_owned()),
|
||||
// Any stop request, or appd shutting down, ends a startup.
|
||||
_ = abort_rx.recv() => Err("startup aborted".to_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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. 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.
|
||||
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 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.
|
||||
|
||||
### weft-runtime
|
||||
|
||||
|
|
@ -126,11 +126,11 @@ A directory install can still be changed by its owner while a session runs, and
|
|||
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.
|
||||
- `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 declined: the app shell reports this to weft-appd with its readiness token on standard output, so page output cannot forge it, and the session keeps 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. A clean exit after a close request, including one the page makes after declining, is recorded as a close on request. A report still unread when a new request arrives can answer that request early; the app shell still closes a page that does not answer.
|
||||
|
||||
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.
|
||||
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. An application can decline every close, so a forced stop never asks it: it is the user's way to end an application that will not close. A forced stop, the timeout, 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
|
||||
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
6bd7b2df26ef619b20c73aa42ed92438d8b0c8515e35f47fd4be346cd90875b53e83374413a3b6008b2b0a718ba1da28497532f04a54b673ebc074db94ce730c
|
||||
3c5155af4973c453e5c09b04aa0eaf71e943b6564d9aaa81a5fb023fe3ebea091a793ef493234a5a862b9752acf7cafbb0d11a2ec9c962331606ebde75c7b803
|
||||
|
|
@ -158,8 +158,10 @@
|
|||
// 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.
|
||||
// after a save only once the save is acknowledged, saving again first if
|
||||
// the text changed meanwhile; a failed save keeps it open with the error
|
||||
// shown. Text typed while the notes are not loaded cannot be saved, so it
|
||||
// does not hold the window open.
|
||||
function unsaved() {
|
||||
return pending !== null || (rev !== null && editor.value !== saved);
|
||||
}
|
||||
|
|
@ -172,7 +174,7 @@
|
|||
window.addEventListener('weftclose', function (e) {
|
||||
if (!unsaved()) return;
|
||||
e.preventDefault();
|
||||
closeAfterSave = false;
|
||||
// Asked again while the prompt is up, keep the user's choice so far.
|
||||
closing.classList.add('shown');
|
||||
});
|
||||
|
||||
|
|
@ -190,7 +192,11 @@
|
|||
document.getElementById('close-cancel').addEventListener('click', hideClosing);
|
||||
|
||||
saveButton.addEventListener('click', function () {
|
||||
if (!window.weftIpc || pending) return;
|
||||
if (pending) return;
|
||||
if (!window.weftIpc) {
|
||||
setStatus('not saved: not connected');
|
||||
return;
|
||||
}
|
||||
if (rev === null) {
|
||||
setStatus('the notes have not loaded; use Discard to reload them');
|
||||
return;
|
||||
|
|
@ -279,7 +285,9 @@
|
|||
setStatus(editor.value === saved ? 'saved' : 'saved; newer changes are not saved yet');
|
||||
if (closeAfterSave) {
|
||||
if (editor.value === saved) window.close();
|
||||
else hideClosing();
|
||||
// Text typed after this save began is saved before closing.
|
||||
else saveButton.click();
|
||||
if (!pending && editor.value !== saved) hideClosing();
|
||||
}
|
||||
} else if (msg.op === 'error') {
|
||||
if (pending && msg.seq === pending.seq) {
|
||||
|
|
|
|||
|
|
@ -321,10 +321,7 @@
|
|||
if (msg.state === 'stopped') {
|
||||
removeTaskbarEntry(msg.session_id);
|
||||
} else if (msg.state === 'stopping') {
|
||||
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);
|
||||
setTaskbarEntryClosing(msg.session_id);
|
||||
}
|
||||
} else if (msg.type === 'RUNNING_APPS') {
|
||||
msg.sessions.forEach(function (s) {
|
||||
|
|
@ -382,6 +379,10 @@
|
|||
});
|
||||
}
|
||||
|
||||
// Longer than weft-appd's close timeout, so an app that neither closes
|
||||
// nor declines has already been terminated.
|
||||
var FORCE_QUIT_DELAY = 6000;
|
||||
|
||||
function ensureTaskbarEntry(sessionId, appId) {
|
||||
var id = 'task-' + sessionId;
|
||||
if (document.getElementById(id)) { return; }
|
||||
|
|
@ -397,11 +398,23 @@
|
|||
close.className = 'task-close';
|
||||
close.textContent = '×';
|
||||
close.title = 'Close';
|
||||
// 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.
|
||||
close.addEventListener('click', function (e) {
|
||||
e.stopPropagation();
|
||||
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify({ type: 'TERMINATE_APP', session_id: sessionId }));
|
||||
}
|
||||
if (!ws || ws.readyState !== WebSocket.OPEN) { return; }
|
||||
var force = close.dataset.force === '1';
|
||||
ws.send(JSON.stringify({ type: 'TERMINATE_APP', session_id: sessionId, force: force }));
|
||||
if (force || close.dataset.asked) { return; }
|
||||
close.dataset.asked = '1';
|
||||
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';
|
||||
}, FORCE_QUIT_DELAY);
|
||||
});
|
||||
el.appendChild(span);
|
||||
el.appendChild(close);
|
||||
|
|
@ -417,17 +430,15 @@
|
|||
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. An
|
||||
// app that declines the close is shown as running again.
|
||||
function setTaskbarEntryClosing(sessionId, closing) {
|
||||
// The session is ending; its entry stays until it has stopped.
|
||||
function setTaskbarEntryClosing(sessionId) {
|
||||
var el = document.getElementById('task-' + sessionId);
|
||||
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);
|
||||
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.style.display = closing ? 'none' : ''; }
|
||||
if (close) { close.style.display = 'none'; }
|
||||
}
|
||||
|
||||
function removeTaskbarEntry(sessionId) {
|
||||
|
|
|
|||
|
|
@ -20,11 +20,12 @@ sequence, quotes, a tab and non-ASCII characters, launches
|
|||
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
|
||||
request (TERMINATE_APP or Alt+F4) is declined 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.
|
||||
leaves the stored notes unchanged. A forced TERMINATE_APP ends a session
|
||||
whose close was declined at once, saving nothing. Without unsaved
|
||||
changes, Notes closes at once.
|
||||
|
||||
Requires Xvfb, xwd, ImageMagick's convert and xdotool.
|
||||
"""
|
||||
|
|
@ -121,6 +122,15 @@ def wait_for_state(appd, session_id, state, timeout):
|
|||
raise AssertionError(f"session {session_id} did not become {state}")
|
||||
|
||||
|
||||
def wait_for_decline(desktop, session_id, timeout=10):
|
||||
marker = f"the application declined the close session_id={session_id}"
|
||||
deadline = time.monotonic() + timeout
|
||||
while marker not in desktop.log_text("appd"):
|
||||
if time.monotonic() > deadline:
|
||||
raise AssertionError(f"session {session_id} did not decline the close")
|
||||
time.sleep(0.2)
|
||||
|
||||
|
||||
def stop_reason(desktop, session_id):
|
||||
marker = f"stopping session session_id={session_id} reason=\""
|
||||
for line in desktop.log_text("appd").splitlines():
|
||||
|
|
@ -143,9 +153,9 @@ def check_close_policy(desktop, appd, page, act, notes, session_id):
|
|||
|
||||
stored = notes.read_text(encoding="utf-8")
|
||||
type_at_end(" unsaved")
|
||||
# The page cancels the close: the session is running again.
|
||||
# The page declines the close; the session keeps running.
|
||||
appd.send({"type": "TERMINATE_APP", "session_id": session_id})
|
||||
wait_for_state(appd, session_id, "running", 10)
|
||||
wait_for_decline(desktop, session_id)
|
||||
buttons = wait_for_prompt(desktop, page, True)
|
||||
click(buttons[2]) # Cancel
|
||||
wait_for_prompt(desktop, page, False)
|
||||
|
|
@ -160,7 +170,7 @@ def check_close_policy(desktop, appd, page, act, notes, session_id):
|
|||
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:
|
||||
if reason is None or not reason.startswith("closed on request; app shell exited"):
|
||||
raise AssertionError(f"Notes did not exit cleanly after saving: {reason}")
|
||||
|
||||
# Close without saving keeps the stored notes.
|
||||
|
|
@ -169,13 +179,31 @@ def check_close_policy(desktop, appd, page, act, notes, session_id):
|
|||
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)
|
||||
wait_for_decline(desktop, session_id)
|
||||
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")
|
||||
|
||||
# A forced stop ends a session that declined its close, without asking.
|
||||
session_id = launch(appd)
|
||||
time.sleep(2)
|
||||
act("search", "--class", "weft-compositor", "windowfocus", "--sync")
|
||||
type_at_end(" forced")
|
||||
appd.send({"type": "TERMINATE_APP", "session_id": session_id})
|
||||
wait_for_decline(desktop, session_id)
|
||||
wait_for_prompt(desktop, page, True)
|
||||
forced = time.monotonic()
|
||||
appd.send({"type": "TERMINATE_APP", "session_id": session_id, "force": True})
|
||||
wait_for_state(appd, session_id, "stopped", 10)
|
||||
if time.monotonic() - forced > 3:
|
||||
raise AssertionError("a forced stop waited for the application")
|
||||
if stop_reason(desktop, session_id) != "terminated by force":
|
||||
raise AssertionError(f"a forced stop reported {stop_reason(desktop, session_id)!r}")
|
||||
if notes.read_text(encoding="utf-8") != stored + " unsaved":
|
||||
raise AssertionError("a forced stop changed the stored notes")
|
||||
|
||||
# Without unsaved changes, a close request closes Notes at once.
|
||||
session_id = launch(appd)
|
||||
time.sleep(2)
|
||||
|
|
|
|||
Loading…
Reference in a new issue