S002: a restart no longer loses tray icons or freezes the music player

The tray watcher took its bus name before serving its object, and zbus
drops calls that arrive in that gap without a reply. ksni items (Mulberry)
wait for that reply holding their tray lock, so they went missing and the
app's UI froze until the shell exited. The watcher is now served first,
queues for its name, re-scans item names, keeps entries by owner and path,
and the host re-registers with any new watcher; item and player calls time
out. An empty tray keeps its expand state. Fire-and-forget commands are
reaped (services::detach), and Restart Shell stops the last image's helpers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Jacob Ward 2026-11-13 08:45:03 -06:00
commit 17a7774f9c
16 changed files with 257 additions and 99 deletions

View file

@ -15,14 +15,14 @@ Restarting the shell breaks tray icons (missing or dead) and can freeze the user
## Steps
- [x] Set up a private session bus with a stand-in tray app (Python `gi` StatusNotifierItem) and a stand-in MPRIS player; script a shell start, kill and restart against it
- [ ] Reproduce the tray breakage: record what the watcher holds and which items re-register after restart; fix (claim the watcher name with replace/queue rules, re-scan `org.kde.StatusNotifierItem-*` names on start, handle `NameOwnerChanged`)
- [ ] Fix the chevron: the expand state survives an empty-then-refilled item list
- [ ] Reproduce the player freeze with the stand-in player: look for synchronous calls without a timeout, calls to a name owned by the old process, or a flood of `Position` polls; fix with timeouts and owner checks
- [ ] Regression tests for the pure parts (re-registration bookkeeping, owner checks)
- [ ] Prove it on the private bus: five restarts in a row, and after each one every stand-in tray item shows and the stand-in player still answers `Get Position` within 100 ms
- [ ] Mark §2.1, §2.2 fixed or explain what is left; AUDIT.md notes
- [ ] Live checks this plan needs, written in its PROGRESS entry for the orchestrator's batched restart (D-002, D-011)
- [ ] PROGRESS entry, INDEX line, tracker done, commit `S002: …` and push to origin main
- [x] Reproduce the tray breakage: record what the watcher holds and which items re-register after restart; fix (claim the watcher name with replace/queue rules, re-scan `org.kde.StatusNotifierItem-*` names on start, handle `NameOwnerChanged`)
- [x] Fix the chevron: the expand state survives an empty-then-refilled item list
- [x] Reproduce the player freeze with the stand-in player: look for synchronous calls without a timeout, calls to a name owned by the old process, or a flood of `Position` polls; fix with timeouts and owner checks
- [x] Regression tests for the pure parts (re-registration bookkeeping, owner checks)
- [x] Prove it on the private bus: five restarts in a row, and after each one every stand-in tray item shows and the stand-in player still answers `Get Position` within 100 ms
- [x] Mark §2.1, §2.2 fixed or explain what is left; AUDIT.md notes
- [x] Live checks this plan needs, written in its PROGRESS entry for the orchestrator's batched restart (D-002, D-011)
- [x] PROGRESS entry, INDEX line, tracker done, commit `S002: …` and push to origin main
## End criteria
- `cargo test --release` green

View file

@ -10,7 +10,7 @@ Tracker: https://claude.ai/artifact/U7N1biTWurWCSxkAn17xiz
## 02 UX sweep and bugs
- [ ] [S002 — Restart side effects: tray icons and the music player](02%20UX%20sweep%20and%20bugs/S002-restart-tray-mpris.md) · Opus high
- [x] [S002 — Restart side effects: tray icons and the music player](02%20UX%20sweep%20and%20bugs/S002-restart-tray-mpris.md) · Opus high
- [ ] [S026 — Smooth motion everywhere: one frame pace, never under 30 fps](02%20UX%20sweep%20and%20bugs/S026-smooth-frame-rate.md) · Opus high
- [ ] [S003 — Sweep: bar items and bar popouts](02%20UX%20sweep%20and%20bugs/S003-sweep-bar-popouts.md) · Opus medium
- [ ] [S004 — Sweep: dashboard tabs](02%20UX%20sweep%20and%20bugs/S004-sweep-dashboard.md) · Opus medium

View file

@ -928,12 +928,7 @@ fn sibling(name: &str) -> PathBuf {
}
fn cli(args: &[&str]) {
let _ = Command::new(sibling("caelestia"))
.args(args)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn();
let _ = crate::services::detach(Command::new(sibling("caelestia")).args(args).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()));
}
fn spawn(cmd: &[String]) {
@ -941,7 +936,7 @@ fn spawn(cmd: &[String]) {
return;
}
if niri::spawn(cmd).is_err() {
let _ = Command::new(&cmd[0]).args(&cmd[1..]).stdin(Stdio::null()).spawn();
let _ = crate::services::detach(Command::new(&cmd[0]).args(&cmd[1..]).stdin(Stdio::null()));
}
}

View file

@ -209,7 +209,9 @@ pub fn spawn(active: Arc<AtomicBool>, send: impl Fn(Vec<Player>) + Send + 'stati
let (tx, rx) = channel::<(String, Cmd)>();
let _ = CMDS.set(tx);
std::thread::spawn(move || {
let Ok(conn) = Connection::session() else { return };
// A player that stops answering (busy, or dying) costs one poll, not the thread: zbus
// waits for ever by default.
let Ok(conn) = zbus::blocking::connection::Builder::session().and_then(|b| b.method_timeout(Duration::from_secs(1)).build()) else { return };
let mut arts = HashMap::new();
let mut last: Option<Vec<Player>> = None;
loop {

View file

@ -74,7 +74,7 @@ impl ColourPage {
pub(crate) fn cli(args: &[&str]) {
let exe = std::env::current_exe().ok().and_then(|e| e.parent().map(|d| d.join("caelestia"))).filter(|p| p.exists()).map_or("caelestia".to_string(), |p| p.to_string_lossy().into_owned());
let _ = Command::new(exe).args(args).spawn();
let _ = crate::services::detach(Command::new(exe).args(args));
}
/// What a card does.

View file

@ -488,7 +488,7 @@ impl Nexus {
}
} else if let Some(device) = k.strip_prefix("live:mount:") {
let verb = if v.as_bool() == Some(true) { "mount" } else { "unmount" };
let _ = Command::new("udisksctl").args([verb, "-b", device]).stdout(Stdio::null()).stderr(Stdio::null()).spawn();
let _ = crate::services::detach(Command::new("udisksctl").args([verb, "-b", device]).stdout(Stdio::null()).stderr(Stdio::null()));
} else if k == "live:reduceMotion" {
self.store.set("shell:appearance.anim.enabled", json!(v.as_bool() != Some(true)));
} else if let Some(key) = k.strip_prefix("live:sessionCmd:") {
@ -1746,7 +1746,7 @@ impl Nexus {
}
Act::Pop(crate::popouts::PopAct::AutostartRemove(id)) => syspages::autostart_remove(&id),
Act::Pop(crate::popouts::PopAct::DiskEject(device)) => {
let _ = Command::new("udisksctl").args(["power-off", "-b", &device]).stdout(Stdio::null()).stderr(Stdio::null()).spawn();
let _ = crate::services::detach(Command::new("udisksctl").args(["power-off", "-b", &device]).stdout(Stdio::null()).stderr(Stdio::null()));
}
Act::Pop(crate::popouts::PopAct::Export) => {
if let Some(doc) = caelestia_core::config::read_json(&paths::shell_config()) {
@ -2045,13 +2045,7 @@ fn run_cli(args: &[&str]) -> Result<(), String> {
.and_then(|p| p.parent().map(|d| d.join("caelestia")))
.filter(|p| p.is_file())
.unwrap_or_else(|| "caelestia".into());
Command::new(exe)
.args(args)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.map(|_| ())
crate::services::detach(Command::new(exe).args(args).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()))
.map_err(|e| format!("Could not run caelestia: {e}"))
}

View file

@ -307,7 +307,7 @@ pub fn run_autostart(desktop: &str) {
}
let cmd: Vec<String> = e.exec.split_whitespace().filter(|a| !(a.len() == 2 && a.starts_with('%'))).map(str::to_string).collect();
if let Some((first, rest)) = cmd.split_first() {
let _ = std::process::Command::new(first).args(rest).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).spawn();
let _ = crate::services::detach(std::process::Command::new(first).args(rest).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()));
}
}
}

View file

@ -131,7 +131,7 @@ fn cli() -> String {
/// Wallpapers.setWallpaper
pub fn set_wallpaper(path: &str) {
let _ = Command::new(cli()).args(["wallpaper", "-f", path]).spawn();
let _ = crate::services::detach(Command::new(cli()).args(["wallpaper", "-f", path]));
}
#[derive(Clone)]
@ -255,7 +255,7 @@ impl WallPage {
}
pub(super) fn open_folder(&self) {
let _ = Command::new("xdg-open").arg(walls_dir()).spawn();
let _ = crate::services::detach(Command::new("xdg-open").arg(walls_dir()));
}
pub(super) fn browse(&mut self) {

View file

@ -107,10 +107,7 @@ fn run(cmd: &str, args: &[&str]) -> Option<String> {
/// Runs a command without waiting for it.
pub fn spawn(cmd: &str, args: &[&str]) {
// Waited on, or each one stays as a zombie for as long as the shell runs.
if let Ok(mut child) = Command::new(cmd).args(args).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).spawn() {
std::thread::spawn(move || child.wait());
}
let _ = crate::services::detach(Command::new(cmd).args(args).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()));
}
fn nodes(kind: &str) -> Vec<Node> {

View file

@ -263,14 +263,8 @@ pub fn spawn(send: impl Fn(Status) + Send + 'static) {
/// `pactl subscribe`, feeding `wake`, back again if it ends (PipeWire restarting, say).
/// Every one left behind holds one of pipewire-pulse's 64 client slots, and at 64 no app
/// can reach the sound server, so it dies with the shell. A restart in place keeps our pid,
/// which that does not catch: the old watcher is still our child then, and goes first.
/// which that does not catch: `reap_inherited` stops the old watcher then.
fn spawn_audio_watch(wake: mpsc::Sender<()>) -> bool {
let me = std::process::id() as i32;
for (pid, parent) in running("pactl") {
if parent == me {
crate::popdata::spawn("kill", &[&pid.to_string()]);
}
}
let watch = || helper("pactl", &["subscribe".to_string()]).stdout(Stdio::piped()).spawn();
let Ok(first) = watch() else { return false };
thread::Builder::new()
@ -329,6 +323,18 @@ pub fn clipboard_watch() {
}
}
/// Starts a program the shell does not wait for. A thread collects it when it ends, or each
/// one stays a zombie for as long as the shell runs.
pub fn detach(cmd: &mut Command) -> std::io::Result<()> {
let mut child = cmd.spawn()?;
thread::spawn(move || child.wait());
Ok(())
}
/// Marks helpers, so an `exec` restart can tell the last image's (its `pactl subscribe`, which
/// never ends by itself) from the programs it started for the user.
const HELPER_MARK: &str = "CAELESTIA_HELPER";
/// A background program that ends with the shell.
pub fn helper(tool: &str, args: &[String]) -> Command {
use std::os::unix::process::CommandExt;
@ -336,7 +342,7 @@ pub fn helper(tool: &str, args: &[String]) -> Command {
fn prctl(option: std::ffi::c_int, a: std::ffi::c_ulong, b: std::ffi::c_ulong, c: std::ffi::c_ulong, d: std::ffi::c_ulong) -> std::ffi::c_int;
}
let mut cmd = Command::new(tool);
cmd.args(args).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
cmd.args(args).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).env(HELPER_MARK, "1");
// SAFETY: only calls prctl between fork and exec.
unsafe {
cmd.pre_exec(|| {
@ -364,10 +370,12 @@ pub fn running(tool: &str) -> Vec<(i32, i32)> {
/// Children an `exec` restart inherits from the image it replaced (an audio tap's `pw-record`,
/// a sound's `pw-play`): nothing in this image holds them, so a thread reaps each one when it
/// ends, or it stays a zombie for the life of the shell. Call before spawning anything.
/// ends, or it stays a zombie for the life of the shell. The last image's helpers are stopped
/// first. Call before spawning anything.
pub fn reap_inherited() {
unsafe extern "C" {
fn waitpid(pid: i32, status: *mut i32, options: i32) -> i32;
fn kill(pid: i32, sig: i32) -> i32;
}
let me = std::process::id() as i32;
let kids: Vec<i32> = fs::read_dir("/proc").into_iter().flatten().flatten().filter_map(|e| {
@ -378,13 +386,22 @@ pub fn reap_inherited() {
if kids.is_empty() {
return;
}
let _ = std::thread::Builder::new().name("reap".into()).spawn(move || {
for pid in kids {
// The last image's helpers: this one starts its own.
let mark = format!("{HELPER_MARK}=1");
for &pid in &kids {
if fs::read(format!("/proc/{pid}/environ")).is_ok_and(|env| env.split(|&b| b == 0).any(|v| v == mark.as_bytes())) {
// SAFETY: signals one of our own children.
unsafe { kill(pid, 15) };
}
}
// One waiter each: one that runs long (a `ddcutil detect`) must not hold up the rest.
for pid in kids {
let _ = std::thread::Builder::new().name("reap".into()).spawn(move || {
let mut status = 0;
// SAFETY: waits for one of our own children; nothing else in this image knows it.
unsafe { waitpid(pid, &mut status, 0) };
}
});
});
}
}
/// DMS carried its own polkit agent. Without one, apps asking for admin rights cannot show a

View file

@ -19,6 +19,8 @@ const WATCHER: &str = "org.kde.StatusNotifierWatcher";
const WATCHER_PATH: &str = "/StatusNotifierWatcher";
const ITEM_IFACE: &str = "org.kde.StatusNotifierItem";
const MENU_IFACE: &str = "com.canonical.dbusmenu";
/// How long a call to an item may take: one that never answers must not stall the tray.
const CALL_TIMEOUT: Duration = Duration::from_secs(2);
#[derive(Debug, Clone)]
pub struct Item {
@ -75,9 +77,48 @@ pub fn spawn(send: impl Fn(Event) + Send + Sync + 'static) -> Sender<Cmd> {
tx
}
/// What the watcher holds: each item's key and the unique bus name behind it.
type Registry = Arc<Mutex<Vec<(String, String)>>>;
/// The watcher, when this shell is the one providing it.
struct Watcher {
items: Arc<Mutex<Vec<String>>>,
items: Registry,
}
/// The key an item registers as: its bus name and object path. Items pass their bus name,
/// a name with a path, or just their object path.
fn item_key(sender: &str, service: &str) -> String {
if service.starts_with('/') {
format!("{sender}{service}")
} else if service.contains('/') {
service.to_string()
} else {
format!("{service}/StatusNotifierItem")
}
}
/// Adds an item unless it is there already, under this key or under another name of the
/// same process at the same path (an item found by a re-scan that then registers itself).
fn add_item(items: &mut Vec<(String, String)>, key: &str, owner: &str) -> bool {
let path = split_key(key).1;
if items.iter().any(|(k, o)| k == key || (!owner.is_empty() && o == owner && split_key(k).1 == path)) {
return false;
}
items.push((key.to_string(), owner.to_string()));
true
}
/// Drops every item behind a bus name that went away, by the name in its key or its owner.
fn drop_name(items: &mut Vec<(String, String)>, name: &str) -> Vec<String> {
let gone: Vec<String> = items.iter().filter(|(k, o)| split_key(k).0 == name || o == name).map(|(k, _)| k.clone()).collect();
items.retain(|(k, _)| !gone.contains(k));
gone
}
/// The well-known names items take (`org.kde.StatusNotifierItem-<pid>-<n>`), so a watcher
/// that starts after them can find the ones that never register again.
fn is_item_name(name: &str) -> bool {
["org.kde.StatusNotifierItem-", "org.freedesktop.StatusNotifierItem-"].iter().any(|p| name.starts_with(p))
}
#[zbus::interface(name = "org.kde.StatusNotifierWatcher")]
@ -86,26 +127,24 @@ impl Watcher {
&mut self,
service: &str,
#[zbus(header)] hdr: Header<'_>,
#[zbus(connection)] conn: &zbus::Connection,
#[zbus(signal_emitter)] emitter: SignalEmitter<'_>,
) {
let sender = hdr.sender().map(|s| s.to_string()).unwrap_or_default();
// Items pass their bus name or just their object path.
let key = if service.starts_with('/') {
format!("{sender}{service}")
} else if service.contains('/') {
service.to_string()
let key = item_key(&sender, service);
let name = split_key(&key).0;
let owner = if name.starts_with(':') {
name
} else {
format!("{service}/StatusNotifierItem")
};
let added = {
let mut items = self.items.lock().unwrap();
if items.contains(&key) {
false
} else {
items.push(key.clone());
true
match zbus::fdo::DBusProxy::new(conn).await {
Ok(p) => match name.as_str().try_into() {
Ok(n) => p.get_name_owner(n).await.map(|o| o.to_string()).unwrap_or(sender),
Err(_) => sender,
},
Err(_) => sender,
}
};
let added = add_item(&mut self.items.lock().unwrap(), &key, &owner);
if added {
let _ = Self::status_notifier_item_registered(&emitter, &key).await;
}
@ -117,7 +156,7 @@ impl Watcher {
#[zbus(property)]
fn registered_status_notifier_items(&self) -> Vec<String> {
self.items.lock().unwrap().clone()
self.items.lock().unwrap().iter().map(|(k, _)| k.clone()).collect()
}
#[zbus(property)]
@ -148,20 +187,22 @@ fn split_key(key: &str) -> (String, String) {
}
fn run(send: Arc<dyn Fn(Event) + Send + Sync>, cmds: Receiver<Cmd>) -> anyhow::Result<()> {
let conn = Connection::session()?;
let watched: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
// Be the watcher if the name is free.
let watched: Registry = Arc::new(Mutex::new(Vec::new()));
// The watcher is served before its name is asked for. A call that reaches the name before
// the object server is up gets no reply at all, and a ksni item waits for that reply with
// its tray locked: after a restart its app (Mulberry) froze until this shell went away.
let conn = zbus::blocking::connection::Builder::session()?
.method_timeout(CALL_TIMEOUT)
.serve_at(WATCHER_PATH, Watcher { items: watched.clone() })?
.build()?;
let me = conn.unique_name().map(|n| n.to_string()).unwrap_or_default();
// Queued rather than given up: a watcher still on its way out (the last shell) hands the
// name over when it goes.
let own_watcher = conn
.request_name_with_flags(WATCHER, zbus::fdo::RequestNameFlags::DoNotQueue.into())
.map(|r| r == zbus::fdo::RequestNameReply::PrimaryOwner)
.unwrap_or(false);
if own_watcher {
conn.object_server().at(WATCHER_PATH, Watcher { items: watched.clone() })?;
}
.request_name_with_flags(WATCHER, zbus::fdo::RequestNameFlags::AllowReplacement.into())
.is_ok_and(|r| r == zbus::fdo::RequestNameReply::PrimaryOwner);
let host = format!("org.kde.StatusNotifierHost-{}", std::process::id());
let _ = conn.request_name(host.as_str());
let _ = conn.call_method(Some(WATCHER), WATCHER_PATH, Some(WATCHER), "RegisterStatusNotifierHost", &(host.as_str(),));
// Everything that changes the item list or an item funnels into one channel.
let (wake_tx, wake_rx) = channel::<String>();
@ -181,22 +222,19 @@ fn run(send: Arc<dyn Fn(Event) + Send + Sync>, cmds: Receiver<Cmd>) -> anyhow::R
let hdr = msg.header();
let member = hdr.member().map(|m| m.to_string()).unwrap_or_default();
if member == "NameOwnerChanged" {
// An item's process went away: drop its registrations.
if let Ok((name, _old, new)) = msg.body().deserialize::<(String, String, String)>() {
if new.is_empty() {
let gone: Vec<String> = {
let mut w = watched.lock().unwrap();
let gone = w.iter().filter(|k| split_key(k).0 == name).cloned().collect();
w.retain(|k| split_key(k).0 != name);
gone
};
for key in gone {
if let Ok(iface) = conn.object_server().interface::<_, Watcher>(WATCHER_PATH) {
let _ = zbus::block_on(Watcher::status_notifier_item_unregistered(iface.signal_emitter(), &key));
}
}
let _ = wake.send(format!("gone:{name}"));
let Ok((name, _old, new)) = msg.body().deserialize::<(String, String, String)>() else { continue };
if name == WATCHER {
// A new watcher (maybe this shell, next in the queue): register with it.
if !new.is_empty() {
let _ = wake.send(format!("watcher:{new}"));
}
} else if new.is_empty() {
// An item's process went away: drop its registrations.
let gone = drop_name(&mut watched.lock().unwrap(), &name);
for key in gone {
emit(&conn, &key, false);
}
let _ = wake.send(format!("gone:{name}"));
}
continue;
}
@ -205,6 +243,10 @@ fn run(send: Arc<dyn Fn(Event) + Send + Sync>, cmds: Receiver<Cmd>) -> anyhow::R
}
});
}
if own_watcher {
rescan(&conn, &watched);
}
let _ = conn.call_method(Some(WATCHER), WATCHER_PATH, Some(WATCHER), "RegisterStatusNotifierHost", &(host.as_str(),));
let mut items: HashMap<String, Item> = HashMap::new();
let mut order: Vec<String> = Vec::new();
@ -290,7 +332,15 @@ fn run(send: Arc<dyn Fn(Event) + Send + Sync>, cmds: Receiver<Cmd>) -> anyhow::R
events.push(e);
}
}
let structural = events.iter().any(|e| e.starts_with("StatusNotifierItem") || e.starts_with("gone:"));
for e in &events {
if let Some(owner) = e.strip_prefix("watcher:") {
if owner == me {
rescan(&conn, &watched);
}
let _ = conn.call_method(Some(WATCHER), WATCHER_PATH, Some(WATCHER), "RegisterStatusNotifierHost", &(host.as_str(),));
}
}
let structural = events.iter().any(|e| e.starts_with("StatusNotifierItem") || e.starts_with("gone:") || e.starts_with("watcher:"));
if structural {
refresh_all(&mut items, &mut order);
} else {
@ -307,6 +357,33 @@ fn run(send: Arc<dyn Fn(Event) + Send + Sync>, cmds: Receiver<Cmd>) -> anyhow::R
}
}
/// Tells other hosts an item came or went, when this shell is the watcher.
fn emit(conn: &Connection, key: &str, registered: bool) {
if let Ok(iface) = conn.object_server().interface::<_, Watcher>(WATCHER_PATH) {
let e = iface.signal_emitter();
let _ = zbus::block_on(async {
if registered { Watcher::status_notifier_item_registered(e, key).await } else { Watcher::status_notifier_item_unregistered(e, key).await }
});
}
}
/// A watcher that starts after its items finds them by name: an app that registered with the
/// last watcher and does not watch for a new one would be lost otherwise.
fn rescan(conn: &Connection, watched: &Registry) {
let Ok(dbus) = zbus::blocking::fdo::DBusProxy::new(conn) else { return };
for name in dbus.list_names().unwrap_or_default().iter().map(|n| n.to_string()).filter(|n| is_item_name(n)) {
let key = format!("{name}/StatusNotifierItem");
// Only names that serve an item there.
if conn.call_method(Some(name.as_str()), "/StatusNotifierItem", Some("org.freedesktop.DBus.Properties"), "Get", &(ITEM_IFACE, "Id")).is_err() {
continue;
}
let owner = item_owner(conn, &key);
if add_item(&mut watched.lock().unwrap(), &key, &owner) {
emit(conn, &key, true);
}
}
}
/// The unique bus name behind an item key (keys may use well-known names).
fn item_owner(conn: &Connection, key: &str) -> String {
let (svc, _) = split_key(key);
@ -439,3 +516,51 @@ fn entry_from(id: i32, props: HashMap<String, Value>, children: &[Value]) -> Opt
children,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn keys_from_every_registration_form() {
assert_eq!(item_key(":1.5", "/StatusNotifierItem"), ":1.5/StatusNotifierItem");
assert_eq!(item_key(":1.5", "org.kde.StatusNotifierItem-9-1"), "org.kde.StatusNotifierItem-9-1/StatusNotifierItem");
assert_eq!(item_key(":1.5", ":1.7/org/ayatana/NotificationItem/x"), ":1.7/org/ayatana/NotificationItem/x");
}
/// A re-scan finds an item by its name; when the item then registers again by its object
/// path (or the other way round), it stays one icon.
#[test]
fn rescanned_item_that_registers_again_stays_one() {
let mut items = Vec::new();
assert!(add_item(&mut items, "org.kde.StatusNotifierItem-9-1/StatusNotifierItem", ":1.7"));
assert!(!add_item(&mut items, ":1.7/StatusNotifierItem", ":1.7"));
assert!(!add_item(&mut items, "org.kde.StatusNotifierItem-9-1/StatusNotifierItem", ":1.7"));
// Another process, or another path of the same one, is another item.
assert!(add_item(&mut items, ":1.8/StatusNotifierItem", ":1.8"));
assert!(add_item(&mut items, ":1.7/org/ayatana/NotificationItem/x", ":1.7"));
assert_eq!(items.len(), 3);
}
/// An item goes when either its well-known name or its unique name goes, and only it.
#[test]
fn a_name_that_goes_drops_only_its_items() {
let mut items = Vec::new();
add_item(&mut items, "org.kde.StatusNotifierItem-9-1/StatusNotifierItem", ":1.7");
add_item(&mut items, ":1.8/StatusNotifierItem", ":1.8");
assert_eq!(drop_name(&mut items, ":1.7"), vec!["org.kde.StatusNotifierItem-9-1/StatusNotifierItem".to_string()]);
assert!(drop_name(&mut items, ":1.7").is_empty());
add_item(&mut items, "org.kde.StatusNotifierItem-9-1/StatusNotifierItem", ":1.7");
assert_eq!(drop_name(&mut items, "org.kde.StatusNotifierItem-9-1").len(), 1);
assert_eq!(items, vec![(":1.8/StatusNotifierItem".to_string(), ":1.8".to_string())]);
}
#[test]
fn rescan_takes_only_item_names() {
assert!(is_item_name("org.kde.StatusNotifierItem-1021-1"));
assert!(is_item_name("org.freedesktop.StatusNotifierItem-1342-1"));
assert!(!is_item_name("org.kde.StatusNotifierWatcher"));
assert!(!is_item_name("org.kde.StatusNotifierHost-1029"));
assert!(!is_item_name("org.equicord.equibop.StatusNotifierItem"));
}
}

View file

@ -779,7 +779,7 @@ fn spawn_cmd(cmd: &[String]) {
}
// Through niri, so the app gets the compositor's environment and is not our child.
if niri::spawn(cmd).is_err() {
let _ = Command::new(&cmd[0]).args(&cmd[1..]).spawn();
let _ = crate::services::detach(Command::new(&cmd[0]).args(&cmd[1..]));
}
}
@ -930,7 +930,7 @@ impl App {
let ok = std::fs::copy(&path, &face).is_ok();
let short = path.replacen(&caelestia_core::paths::home().to_string_lossy().to_string(), "~", 1);
let (urgency, title, body) = if ok { ("low", "Profile picture changed", format!("Profile picture changed to {short}")) } else { ("critical", "Unable to change profile picture", format!("Failed to change profile picture to {short}")) };
let _ = std::process::Command::new("notify-send").args(["-a", "caelestia-shell", "-u", urgency, title, &body]).spawn();
let _ = crate::services::detach(std::process::Command::new("notify-send").args(["-a", "caelestia-shell", "-u", urgency, title, &body]));
self.shared.reload_pfp();
self.mark_all_dirty();
}
@ -1461,10 +1461,10 @@ impl App {
vol.level = level;
vol.muted = false;
}
let _ = Command::new("wpctl").args(["set-volume", "@DEFAULT_AUDIO_SINK@", &format!("{level:.3}")]).spawn();
let _ = crate::services::detach(Command::new("wpctl").args(["set-volume", "@DEFAULT_AUDIO_SINK@", &format!("{level:.3}")]));
}
crate::osd::Kind::Mic => {
let _ = Command::new("wpctl").args(["set-volume", "@DEFAULT_AUDIO_SOURCE@", &format!("{v:.3}")]).spawn();
let _ = crate::services::detach(Command::new("wpctl").args(["set-volume", "@DEFAULT_AUDIO_SOURCE@", &format!("{v:.3}")]));
}
crate::osd::Kind::Brightness if self.shared.ddc.contains_key(&self.osd_output()) => {
let output = self.osd_output();
@ -1473,7 +1473,7 @@ impl App {
}
crate::osd::Kind::Brightness => {
self.shared.brightness = Some(v);
let _ = Command::new("brightnessctl").args(["-q", "set", &format!("{}%", (v * 100.0).round() as u32)]).spawn();
let _ = crate::services::detach(Command::new("brightnessctl").args(["-q", "set", &format!("{}%", (v * 100.0).round() as u32)]));
}
}
let delay = Duration::from_millis(self.shared.cfg.osd.hide_delay);
@ -4347,7 +4347,9 @@ impl App {
if on_tray && !s.ui.tray_expanded {
s.ui.set_tray_expanded(true);
s.dirty = true;
} else if !on_tray && !in_tray_menu && !menu_open && s.ui.tray_expanded && !s.ui.tray_pinned {
} else if !on_tray && !in_tray_menu && !menu_open && s.ui.tray_expanded && !s.ui.tray_pinned && !crate::ui::tray_items(&self.shared).is_empty() {
// An empty tray has nothing under the pointer: a restart's empty-then-refilled list
// keeps the state it had, so it does not come back collapsed under the pointer.
s.ui.set_tray_expanded(false);
s.dirty = true;
}
@ -4854,7 +4856,7 @@ impl App {
fn nexus_live(&mut self) {
let (acts, commands) = self.nexus.take_live();
for (tool, args) in commands {
let _ = Command::new(tool).args(&args).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).spawn();
let _ = crate::services::detach(Command::new(tool).args(&args).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()));
}
if !self.screens.is_empty() {
for act in acts {

View file

@ -499,3 +499,19 @@ gaps (now it fades first); turning the beat tracker on or off restarted the whol
original's separate BeatTracker and CavaProvider); Restart Shell's `exec` left the old image's children as zombies, and every `pw-play`
sound left one (now reaped). Per-chunk work is `Bars::feed` / `decode`, tested by `audio::tests::sine_lifts_its_own_bar`.
## Restart side effects: tray and the music player (S002, 2026-11-13)
The original gets its tray from Quickshell's SystemTray; ours is its own watcher and host (`tray.rs`), so this is ours alone.
The watcher took `org.kde.StatusNotifierWatcher` and only then put its object on the bus. zbus drops a method call that
arrives before the object server runs, with no reply, and ksni (Mulberry's tray) calls `RegisterStatusNotifierItem` the
moment the name changes owner, holding its tray lock until the reply. So after a restart some items were missing, and an app
whose UI thread updates its tray (Mulberry's play state) froze until that shell exited: 5.2 s blocks in a stand-in, for ever
on the live shell. Now the watcher is served before the name is asked for, the name is queued rather than given up, a new
watcher re-scans `org.kde.StatusNotifierItem-*` / `org.freedesktop.StatusNotifierItem-*` names (items that never
register again), entries are kept by owner and path so a re-scanned item that registers again stays one icon, and the host
registers again with any new watcher. Calls to items time out after 2 s, to players after 1 s (zbus waits for ever by default).
The tray's `>` vanished with the items; hovering an empty tray no longer collapses it, so a list refilled under the pointer
comes back expanded. Restart Shell (`exec`) also stops the last image's helpers (marked by `CAELESTIA_HELPER` in their
environment) and reaps each inherited child on its own, and fire-and-forget commands (`wpctl`, `caelestia`, `udisksctl`,
autostart, ...) go through `services::detach`, which reaps them. Tests: `tray::tests`.

View file

@ -21,3 +21,4 @@ D-016 — 2026-11-13 — While the user sleeps, the orchestrator answers plan se
D-017 — 2026-11-13 — The installer recommends the user's own Hub apps (Mulberry, Nacre, Damson, Audiphi, Islet, Dezio): first on their page, marked, pre-selected, latest release resolved from the Forgejo API — user request — S027, before S022/S023 so the clean-install check covers it
D-018 — 2026-11-13 — Category 01's live check is batched with S002's (restart side effects) so one restart checks both — a restart before S002 would break the tray again — orchestrator
D-019 — 2026-11-13 — Another session codes Nacre (Rust) on this machine at the same time: plan sessions never touch ~/Projects/Nacre* (S027 reads only), run builds with `nice`, and never kill cargo, rustc, niri or test processes they did not start (stop by own PID only) — shared CPU and processes — all plans
D-020 — 2026-11-13 — A program the shell starts and does not wait for goes through `services::detach` (reaped by a thread), a background one that dies with the shell through `services::helper` (marked, so an `exec` restart stops the last image's); never a bare `.spawn()` that drops its `Child` — each left a zombie for the life of the shell (173 `caelestia` on the live one) — S002, all plans

View file

@ -11,8 +11,8 @@ Status words: open, fixed, left out (with why).
## §2 Restart side effects
- §2.1 After a shell restart, tray icons break (missing or dead). StatusNotifierWatcher and host re-registration (`tray.rs`). HANDOFF also notes the tray's `>` chevron vanished once after quick restarts. — open
- §2.2 After a shell restart the user's music player can freeze. Suspects: MPRIS calls blocking on a name owned by the old process, lyrics, or audio taps. Not investigated. — open
- §2.1 After a shell restart, tray icons break (missing or dead). StatusNotifierWatcher and host re-registration (`tray.rs`). HANDOFF also notes the tray's `>` chevron vanished once after quick restarts. Cause: the watcher's object was served after its name was taken, so registrations in that gap got no reply. Fixed with the order, a re-scan of item names and a queued name; an empty tray keeps its expand state. — fixed (S002; private bus and nested niri, not live)
- §2.2 After a shell restart the user's music player can freeze. Cause: the same gap. ksni (Mulberry's tray) waits for the watcher's reply holding its tray lock, so Mulberry's UI thread blocked on its next tray update until the shell exited. MPRIS polling was not involved (Position answers in under 35 ms throughout); its calls now time out anyway. — fixed (S002; stand-in on a private bus, not live)
## §3 UX sweep findings

View file

@ -13,5 +13,14 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done,
- Not done: the live shell still holds 470 `pw-play` and 166 `caelestia` zombies until restart.
- Later: `caelestia` (166) and `wpctl` zombies come from `spawn(...)` calls in wl.rs that never wait; old-image `pactl subscribe` etc. still run after an exec restart until they exit (S002 area).
## S002 — Restart side effects: tray and the music player (2026-11-13)
- Cause of both: the tray watcher took its name before serving its object; zbus drops calls in that gap unanswered. ksni items (Mulberry) call RegisterStatusNotifierItem holding their tray lock, so they went missing and Mulberry's UI froze on its next tray update until the shell exited (stand-in: 5.2 s blocks, live: for ever). Fix: serve first, queued name, re-scan item names, dedupe by owner+path, host re-registers with a new watcher; 2 s item / 1 s player call timeouts.
- Chevron: it vanished with the items; hovering an empty tray no longer collapses it, so a list refilled under the pointer comes back expanded.
- Zombies: fire-and-forget commands go through `services::detach` (wpctl, caelestia, udisksctl, autostart, notify-send); Restart Shell stops the last image's helpers (`CAELESTIA_HELPER` mark) and reaps each inherited child on its own thread (a long `ddcutil` held up the rest).
- Verified on a private bus in nested niri, 2 ksni stand-ins (Mulberry-like) + 2 Gio items (one never re-registers) + Position probe: old build lost 1–3 items and froze both ksni stand-ins; new build 5 kill+start and 5 Restart Shell rounds, 4/4 items each, 0 freezes, Position ≤ 35 ms, no zombies. Tests `tray::tests` (4), `cargo test --release` green, fuzz 854 tried, 0 crashed. Not tested live.
- Live checks for the batched restart: after the restart and after a Restart Shell, every tray icon is back (`busctl --user list | grep StatusNotifierItem`: Mulberry, equibop, Claude, ABDownloadManager) and each one's menu opens; Mulberry keeps playing and its window still responds to play/pause; `ps -o stat=,comm= --ppid $(pgrep -x caelestia-shell)` shows no Z and one `pactl`.
- Note: the user has two Mulberry processes running (711560, 712208, started 11 s apart this morning), maybe a second start after a freeze.
- Later: `notifs.rs` serves then requests its name on a plain connection (same race, smaller window: use the builder); `current_exe()` reads " (deleted)" after `install` replaces the binary, so Restart Shell's `exec` likely fails until a real restart; `sync_idle`'s own swayidle kill is now redundant.
## Later
-