diff --git a/.gitattributes b/.gitattributes index 2825521f..8c729b86 100644 --- a/.gitattributes +++ b/.gitattributes @@ -12,6 +12,7 @@ *.ico binary *.gif binary *.webp binary +*.pdf binary *.woff binary *.woff2 binary *.exe binary diff --git a/CHANGELOG.md b/CHANGELOG.md index 530ce9d8..4d786cc9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,18 @@ and listed with their assets on the ### Added +- **A tray icon on Windows, Linux and macOS** (ADR-0060, #1). The hub + starts `devstack tray`: the dashboard's mark in the notification area + (Windows), as a StatusNotifierItem (Linux: KDE, Xfce, GNOME with the + AppIndicator extension; the binary stays static) or in the menu bar + (macOS, from the menu bar client contributed in #248). Green when + something runs, amber while a stack starts or stops, red when something + needs attention, grey when nothing runs. Its menu opens the dashboard, + lists every stack with what needs attention (a click opens that service + in the dashboard), and starts, stops or opens a stack's folder. It is a + client of the hub, which says what it shows (`GET /hub/summary`, the same + as what notifies); quitting it stops nothing. `devstack hub tray off` + keeps it off, `on` brings it back; `DEVSTACK_NO_TRAY` too. - **A profile can leave out containers, whole Compose groups and services** (ADR-0058, #244). `[profiles.] skip = ["compose.search", "compose.app.scanner", "indexer"]` makes a light profile for daily work: diff --git a/Cargo.lock b/Cargo.lock index 83d4fcbe..d6e1cef6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -651,8 +651,12 @@ version = "0.20.0" dependencies = [ "devstack-proc", "libc", + "objc2", + "objc2-app-kit", + "objc2-foundation", "raw-window-handle", "rfd", + "serde", "tempfile", "tokio", "tokio-stream", @@ -1482,6 +1486,7 @@ dependencies = [ "bitflags 2.13.2", "block2", "objc2", + "objc2-core-foundation", "objc2-foundation", ] diff --git a/Cargo.toml b/Cargo.toml index 88cf6063..1a9752e6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,6 +31,37 @@ jiff = "0.2" libc = "0.2" # Mach host and time calls on macOS that libc marks deprecated (ADR-0054). mach2 = "0.7" +# The tray's status item on macOS (ADR-0060), linked on macOS only. +objc2 = "0.6" +objc2-app-kit = { version = "0.3.2", default-features = false, features = [ + "std", + "NSApplication", + "NSButton", + "NSColor", + "NSControl", + "NSEvent", + "NSGraphicsContext", + "NSImage", + "NSMenu", + "NSMenuItem", + "NSResponder", + "NSRunningApplication", + "NSStatusBar", + "NSStatusBarButton", + "NSStatusItem", + "NSView", + "objc2-core-foundation", +] } +objc2-foundation = { version = "0.3.2", default-features = false, features = [ + "std", + "NSData", + "NSDate", + "NSGeometry", + "NSObject", + "NSRunLoop", + "NSString", + "NSTimer", +] } notify = "8" rand = "0.10" raw-window-handle = "0.6" @@ -63,9 +94,10 @@ tar = "0.4" # WinRT toasts (ADR-0045); windows-sys has no WinRT. windows = { version = "0.62", features = ["Data_Xml_Dom", "Foundation", "UI_Notifications"] } # Desktop notifications on Linux over the session bus, pure Rust (ADR-0045). -zbus = { version = "6", default-features = false, features = ["tokio", "proxy"] } +zbus = { version = "6", default-features = false, features = ["tokio", "proxy", "service"] } windows-sys = { version = "0.61", features = [ "Win32_Foundation", + "Win32_Graphics_Gdi", "Win32_NetworkManagement_IpHelper", "Win32_Security", "Win32_Storage_FileSystem", @@ -76,6 +108,7 @@ windows-sys = { version = "0.61", features = [ "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", + "Win32_System_LibraryLoader", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell", diff --git a/README.md b/README.md index 94cbaa4d..9d6bb6d0 100644 --- a/README.md +++ b/README.md @@ -218,6 +218,7 @@ Every command and flag: `devstack --help`, `devstack --help`. | `devstack lane list\|start\|stop\|reset\|prune\|move\|share` | the lanes (worktrees), see above; `reset` throws a stopped lane's data away, `prune` removes what gone lanes left behind | | `devstack ui [--lane ] [--browser ] [--link\|--print]` | open and pair the dashboard, on this stack (in a worktree on its lane, or on `--lane`); the browser is `--browser`, else `DEVSTACK_BROWSER`, else `BROWSER`, else the system's default. `--link` prints the lasting links to the stack or lane instead (the page, and the `devstack://open` link that pairs first); `--print` the one-time pairing link. `status`, `up` and `lane start` end with the page as `dashboard: ` | | `devstack hub [status\|stop\|start\|install\|uninstall]` | the hub that serves the dashboard: without an action in the foreground; `stop` leaves the stacks running; `install` registers it at logon and the `devstack://` link (`--no-autostart`: the link only), `uninstall` removes both, and `devstack up` then leaves them alone | +| `devstack hub tray [on\|off]` | the tray icon ([ADR-0060](docs/adr/0060-the-tray-is-a-client-of-the-hub.md)): the state of every stack in the icon's colour, a menu to open the dashboard, start or stop a stack and open its folder. The hub starts it (`devstack tray`); `off` ends it and keeps it off, `on` brings it back. Windows, Linux (a StatusNotifierItem: KDE, Xfce, GNOME with the AppIndicator extension) and macOS | | `devstack skills install [--dir] [--force]`, `skills check` | write the agent skills; check that they match this devstack and stack file (exits 1 when not) | | `devstack mcp` | the MCP server (above) | | `devstack join --fingerprint [--name] [--pool] [--telemetry] [--no-wait]` | ask a pool to admit this machine ([pool.md](docs/pool.md#join-a-pool)) | @@ -254,6 +255,7 @@ dashboard ─────┘ one per repo, └── services: main slot (f | `DEVSTACK_HUB_PORT` | the hub's port (default 4250) | | `DEVSTACK_NO_HUB` | `devstack up` does not start the dashboard hub | | `DEVSTACK_NO_HUB_INTEGRATION` | the installer registers no hub at logon and no `devstack://` link (and records that); `devstack up` registers neither while it is set | +| `DEVSTACK_NO_TRAY` | the hub does not start the tray icon (`devstack hub tray off` keeps it off for good) | | `DEVSTACK_NO_NOTIFY` | the hub shows no desktop notifications (they are set per kind with `devstack hub notify` or the bell in the dashboard) | | `DEVSTACK_NO_UPDATE_CHECK` | no check for a newer release | | `DEVSTACK_OTLP_ENDPOINT` | devstack's own diagnostic log also to this OTLP/HTTP collector | diff --git a/crates/devstack-desktop/Cargo.toml b/crates/devstack-desktop/Cargo.toml index 8212fc83..132f48a5 100644 --- a/crates/devstack-desktop/Cargo.toml +++ b/crates/devstack-desktop/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "devstack-desktop" -description = "The desktop devstack runs on, one module per operating system: the hub at logon, the devstack:// link, notifications, the folder dialog, browsers and programs, starting Docker, how devstack was installed (ADR-0054)" +description = "The desktop devstack runs on, one module per operating system: the hub at logon, the devstack:// link, notifications, the tray, the folder dialog, browsers and programs, starting Docker, how devstack was installed (ADR-0054)" version.workspace = true license.workspace = true edition.workspace = true @@ -22,12 +22,18 @@ windows-sys.workspace = true # uses osascript there. [target.'cfg(target_os = "linux")'.dependencies] rfd.workspace = true +serde.workspace = true tokio-stream.workspace = true zbus.workspace = true [target.'cfg(unix)'.dependencies] libc.workspace = true +[target.'cfg(target_os = "macos")'.dependencies] +objc2.workspace = true +objc2-app-kit.workspace = true +objc2-foundation.workspace = true + [dev-dependencies] tempfile.workspace = true diff --git a/crates/devstack-desktop/src/lib.rs b/crates/devstack-desktop/src/lib.rs index c3bd51c7..81eb0fc3 100644 --- a/crates/devstack-desktop/src/lib.rs +++ b/crates/devstack-desktop/src/lib.rs @@ -19,6 +19,7 @@ pub mod channel; #[cfg_attr(not(target_os = "macos"), allow(dead_code))] mod mac; pub mod notify; +pub mod tray; #[cfg(target_os = "linux")] mod linux; diff --git a/crates/devstack-desktop/src/tray/assets/devstack-template.pdf b/crates/devstack-desktop/src/tray/assets/devstack-template.pdf new file mode 100644 index 00000000..552be675 Binary files /dev/null and b/crates/devstack-desktop/src/tray/assets/devstack-template.pdf differ diff --git a/crates/devstack-desktop/src/tray/assets/devstack-template.svg b/crates/devstack-desktop/src/tray/assets/devstack-template.svg new file mode 100644 index 00000000..56eb6d5c --- /dev/null +++ b/crates/devstack-desktop/src/tray/assets/devstack-template.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/crates/devstack-desktop/src/tray/icon.rs b/crates/devstack-desktop/src/tray/icon.rs new file mode 100644 index 00000000..67bd7230 --- /dev/null +++ b/crates/devstack-desktop/src/tray/icon.rs @@ -0,0 +1,172 @@ +//! The tray's icon on Windows and Linux: the dashboard's mark (`ui/public/ +//! favicon.svg`, three strokes and a dot on a dark rounded square), drawn +//! at the size the platform asks for, with the middle stroke and the dot in +//! the state's colour and both larger than in the favicon, so the state +//! shows at 16 pixels. macOS takes a template image instead (`macos.rs`). + +use super::Tone; + +/// In the favicon's 512-unit square. +const BACKGROUND: [u8; 3] = [0x0f, 0x11, 0x15]; +const BLUE: [u8; 3] = [0x5b, 0x8c, 0xff]; + +fn colour(tone: Tone) -> [u8; 3] { + match tone { + Tone::Ok => [0x3e, 0xcf, 0x8e], + Tone::Busy => [0xf5, 0xa5, 0x24], + Tone::Attention => [0xf0, 0x52, 0x4f], + Tone::Idle => [0x8b, 0x92, 0x9e], + } +} + +/// One shape: how much of the point `(x, y)` (512 units) it covers. +enum Shape { + /// A rounded square over the whole icon, corner radius. + Square(f32), + /// A line from `x0` to `x1` at `y`, with round caps of radius `r`. + Stroke { + x0: f32, + x1: f32, + y: f32, + r: f32, + }, + Dot { + x: f32, + y: f32, + r: f32, + }, +} + +impl Shape { + fn inside(&self, x: f32, y: f32) -> bool { + match *self { + Shape::Square(r) => { + let cx = x.clamp(r, 512.0 - r); + let cy = y.clamp(r, 512.0 - r); + (x - cx).powi(2) + (y - cy).powi(2) <= r * r + } + Shape::Stroke { x0, x1, y: sy, r } => { + let cx = x.clamp(x0, x1); + (x - cx).powi(2) + (y - sy).powi(2) <= r * r + } + Shape::Dot { x: dx, y: dy, r } => (x - dx).powi(2) + (y - dy).powi(2) <= r * r, + } + } +} + +/// The icon as `size`×`size` pixels, RGBA with straight alpha, rows from +/// the top. +pub fn rgba(size: u32, tone: Tone) -> Vec { + let state = colour(tone); + // Painted in order, each over the last: (shape, colour, opacity). + let shapes = [ + (Shape::Square(112.0), BACKGROUND, 1.0), + ( + Shape::Stroke { + x0: 120.0, + x1: 392.0, + y: 150.0, + r: 30.0, + }, + BLUE, + 1.0, + ), + ( + Shape::Stroke { + x0: 120.0, + x1: 248.0, + y: 256.0, + r: 30.0, + }, + state, + 1.0, + ), + ( + Shape::Stroke { + x0: 120.0, + x1: 392.0, + y: 362.0, + r: 30.0, + }, + BLUE, + 0.55, + ), + ( + Shape::Dot { + x: 352.0, + y: 256.0, + r: 62.0, + }, + state, + 1.0, + ), + ]; + const SAMPLES: u32 = 4; + let unit = 512.0 / size as f32; + let mut out = Vec::with_capacity((size * size * 4) as usize); + for py in 0..size { + for px in 0..size { + // Straight colour and alpha, composited per sample, averaged. + let (mut r, mut g, mut b, mut a) = (0.0f32, 0.0f32, 0.0f32, 0.0f32); + for sy in 0..SAMPLES { + for sx in 0..SAMPLES { + let x = (px as f32 + (sx as f32 + 0.5) / SAMPLES as f32) * unit; + let y = (py as f32 + (sy as f32 + 0.5) / SAMPLES as f32) * unit; + let mut c = [0.0f32; 3]; + let mut alpha = 0.0f32; + for (shape, col, op) in &shapes { + if shape.inside(x, y) { + let k = *op; + for (ci, &cc) in c.iter_mut().zip(col) { + *ci = *ci * (1.0 - k) + cc as f32 * k; + } + alpha = alpha * (1.0 - k) + k; + } + } + // Premultiplied while summing, so edges do not darken. + r += c[0] * alpha; + g += c[1] * alpha; + b += c[2] * alpha; + a += alpha; + } + } + let n = (SAMPLES * SAMPLES) as f32; + if a > 0.0 { + out.extend([ + (r / a).round() as u8, + (g / a).round() as u8, + (b / a).round() as u8, + (a / n * 255.0).round() as u8, + ]); + } else { + out.extend([0, 0, 0, 0]); + } + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn pixel(img: &[u8], size: u32, x: u32, y: u32) -> [u8; 4] { + let i = ((y * size + x) * 4) as usize; + [img[i], img[i + 1], img[i + 2], img[i + 3]] + } + + #[test] + fn the_dot_has_the_states_colour_and_the_corners_are_clear() { + for size in [16, 22, 32, 48] { + for tone in [Tone::Idle, Tone::Ok, Tone::Busy, Tone::Attention] { + let img = rgba(size, tone); + assert_eq!(img.len(), (size * size * 4) as usize); + assert_eq!(pixel(&img, size, 0, 0)[3], 0, "corner at {size}"); + // The dot's centre, (352, 256) of 512. + let p = pixel(&img, size, size * 352 / 512, size / 2); + assert_eq!(p[..3], colour(tone), "{tone:?} at {size}"); + assert_eq!(p[3], 255); + } + } + } +} diff --git a/crates/devstack-desktop/src/tray/linux.rs b/crates/devstack-desktop/src/tray/linux.rs new file mode 100644 index 00000000..ede8fdcd --- /dev/null +++ b/crates/devstack-desktop/src/tray/linux.rs @@ -0,0 +1,561 @@ +//! Linux: a StatusNotifierItem (`org.kde.StatusNotifierItem`) with its menu +//! as `com.canonical.dbusmenu`, both on the session bus in pure Rust, so +//! the binary stays static (ADR-0060). KDE, Xfce, Cinnamon, and GNOME with +//! the AppIndicator extension show it. Without a StatusNotifierWatcher on +//! the bus (GNOME without it) the item waits and registers when one comes. + +use super::{Entry, Menu, QUIT, Tone}; +use serde::Serialize; +use std::collections::HashMap; +use std::path::Path; +use std::sync::mpsc::{Receiver, Sender, TryRecvError}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; +use tokio_stream::StreamExt; +use zbus::object_server::SignalEmitter; +use zbus::{OwnedObjectPath, OwnedVariant, Type, Variant, interface}; + +const ITEM_PATH: &str = "/StatusNotifierItem"; +const MENU_PATH: &str = "/MenuBar"; +const WATCHER: &str = "org.kde.StatusNotifierWatcher"; + +/// The sizes the icon is offered in; the host picks. +const SIZES: [u32; 5] = [16, 22, 24, 32, 48]; + +pub fn unavailable() -> Option { + let address = std::env::var_os("DBUS_SESSION_BUS_ADDRESS").is_some_and(|v| !v.is_empty()); + let socket = std::env::var_os("XDG_RUNTIME_DIR") + .is_some_and(|d| !d.is_empty() && Path::new(&d).join("bus").exists()); + (!address && !socket).then(|| "no desktop session (no D-Bus session bus)".into()) +} + +/// What both objects read: the menu shown, and its layout's revision. +struct Shared { + menu: Menu, + revision: u32, +} + +/// The icon, in ARGB32 with the bytes in network order, as the spec wants. +type Pixmap = (i32, i32, Vec); + +fn pixmaps(tone: Tone) -> Vec { + SIZES + .iter() + .map(|&size| { + let rgba = super::rgba(size, tone); + let argb = rgba + .as_chunks::<4>() + .0 + .iter() + .flat_map(|p| [p[3], p[0], p[1], p[2]]) + .collect(); + (size as i32, size as i32, argb) + }) + .collect() +} + +struct Item { + shared: Arc>, + actions: Mutex>, +} + +#[interface(name = "org.kde.StatusNotifierItem")] +impl Item { + #[zbus(property)] + fn category(&self) -> &str { + "ApplicationStatus" + } + #[zbus(property)] + fn id(&self) -> &str { + "devstack" + } + #[zbus(property)] + fn title(&self) -> &str { + "devstack" + } + #[zbus(property)] + fn status(&self) -> &str { + "Active" + } + #[zbus(property)] + fn window_id(&self) -> u32 { + 0 + } + #[zbus(property)] + fn icon_name(&self) -> &str { + "" + } + #[zbus(property)] + fn icon_theme_path(&self) -> &str { + "" + } + #[zbus(property)] + fn icon_pixmap(&self) -> Vec { + pixmaps(self.shared.lock().unwrap().menu.tone) + } + #[zbus(property)] + fn overlay_icon_name(&self) -> &str { + "" + } + #[zbus(property)] + fn overlay_icon_pixmap(&self) -> Vec { + Vec::new() + } + #[zbus(property)] + fn attention_icon_name(&self) -> &str { + "" + } + #[zbus(property)] + fn attention_icon_pixmap(&self) -> Vec { + Vec::new() + } + #[zbus(property)] + fn attention_movie_name(&self) -> &str { + "" + } + /// Icon name, icon, title, text. + #[zbus(property)] + fn tool_tip(&self) -> (String, Vec, String, String) { + let tip = self.shared.lock().unwrap().menu.tooltip.clone(); + (String::new(), Vec::new(), "devstack".into(), tip) + } + /// A click shows the menu; `Activate` is not needed then. + #[zbus(property)] + fn item_is_menu(&self) -> bool { + true + } + #[zbus(property)] + fn menu(&self) -> OwnedObjectPath { + OwnedObjectPath::try_from(MENU_PATH).expect("a valid path") + } + + /// A host that activates anyway (KDE's left click): the dashboard. + fn activate(&self, _x: i32, _y: i32) { + let _ = self.actions.lock().unwrap().send("dashboard".into()); + } + fn secondary_activate(&self, _x: i32, _y: i32) {} + fn context_menu(&self, _x: i32, _y: i32) {} + fn scroll(&self, _delta: i32, _orientation: &str) {} + + #[zbus(signal)] + async fn new_icon(emitter: &SignalEmitter<'_>) -> zbus::Result<()>; + #[zbus(signal)] + async fn new_tool_tip(emitter: &SignalEmitter<'_>) -> zbus::Result<()>; +} + +/// A node of the menu's layout: `(ia{sv}av)`. +#[derive(Debug, Serialize, Type)] +struct Layout { + id: i32, + props: HashMap, + children: Vec, +} + +/// A menu item as the layout has it, with the action it sends. +struct Node { + id: i32, + props: HashMap, + action: Option, + children: Vec, +} + +fn owned<'a>(v: impl Into>) -> OwnedVariant { + OwnedVariant::try_from(v.into()).expect("no file descriptors in a menu") +} + +/// `_` marks an access key in a dbusmenu label. +fn label(text: &str) -> OwnedVariant { + owned(text.replace('_', "__")) +} + +/// The menu as a tree of nodes, numbered depth first from 1 (the root is +/// 0), the same numbers for the same menu. +fn tree(entries: &[Entry], next: &mut i32) -> Vec { + entries + .iter() + .map(|e| { + *next += 1; + let id = *next; + let mut props = HashMap::new(); + let mut action = None; + let mut children = Vec::new(); + match e { + Entry::Separator => { + props.insert("type".into(), owned("separator")); + } + Entry::Label(text) => { + props.insert("label".into(), label(text)); + props.insert("enabled".into(), owned(false)); + } + Entry::Action { + label: text, + id: action_id, + enabled, + } => { + props.insert("label".into(), label(text)); + props.insert("enabled".into(), owned(*enabled)); + action = Some(action_id.clone()); + } + Entry::Submenu { + label: text, + entries, + } => { + props.insert("label".into(), label(text)); + props.insert("children-display".into(), owned("submenu")); + children = tree(entries, next); + } + } + Node { + id, + props, + action, + children, + } + }) + .collect() +} + +fn root(menu: &Menu) -> Node { + let mut props = HashMap::new(); + props.insert("children-display".into(), owned("submenu")); + Node { + id: 0, + props, + action: None, + children: tree(&menu.entries, &mut 0), + } +} + +fn find(node: &Node, id: i32) -> Option<&Node> { + if node.id == id { + return Some(node); + } + node.children.iter().find_map(|c| find(c, id)) +} + +/// `depth`: how many levels of children; `-1` all. +fn layout(node: &Node, depth: i32) -> Layout { + let children = if depth == 0 { + Vec::new() + } else { + node.children + .iter() + .map(|c| { + let l = layout(c, depth - 1); + owned(Variant::from(zbus::Structure::from(( + l.id, l.props, l.children, + )))) + }) + .collect() + }; + Layout { + id: node.id, + props: node.props.clone(), + children, + } +} + +struct DbusMenu { + shared: Arc>, + actions: Mutex>, + stop: Arc, +} + +impl DbusMenu { + fn clicked(&self, id: i32) { + let action = { + let s = self.shared.lock().unwrap(); + find(&root(&s.menu), id).and_then(|n| n.action.clone()) + }; + let Some(action) = action else { + return; + }; + let quit = action == QUIT; + let sent = self.actions.lock().unwrap().send(action).is_ok(); + if quit || !sent { + self.stop.notify_one(); + } + } +} + +#[interface(name = "com.canonical.dbusmenu")] +impl DbusMenu { + #[zbus(property)] + fn version(&self) -> u32 { + 3 + } + #[zbus(property)] + fn text_direction(&self) -> &str { + "ltr" + } + #[zbus(property)] + fn status(&self) -> &str { + "normal" + } + #[zbus(property)] + fn icon_theme_path(&self) -> Vec { + Vec::new() + } + + #[zbus(out_args("revision", "layout"))] + fn get_layout( + &self, + parent_id: i32, + recursion_depth: i32, + _property_names: Vec, + ) -> zbus::fdo::Result<(u32, Layout)> { + let s = self.shared.lock().unwrap(); + let root = root(&s.menu); + let node = find(&root, parent_id) + .ok_or_else(|| zbus::fdo::Error::InvalidArgs(format!("no item {parent_id}")))?; + Ok((s.revision, layout(node, recursion_depth))) + } + + fn get_group_properties( + &self, + ids: Vec, + _property_names: Vec, + ) -> Vec<(i32, HashMap)> { + let s = self.shared.lock().unwrap(); + let root = root(&s.menu); + ids.into_iter() + .filter_map(|id| find(&root, id).map(|n| (id, n.props.clone()))) + .collect() + } + + fn get_property(&self, id: i32, name: &str) -> zbus::fdo::Result { + let s = self.shared.lock().unwrap(); + find(&root(&s.menu), id) + .and_then(|n| n.props.get(name).cloned()) + .ok_or_else(|| zbus::fdo::Error::InvalidArgs(format!("no {name} on item {id}"))) + } + + fn event(&self, id: i32, event_id: &str, _data: OwnedVariant, _timestamp: u32) { + if event_id == "clicked" { + self.clicked(id); + } + } + + fn event_group(&self, events: Vec<(i32, String, OwnedVariant, u32)>) -> Vec { + for (id, event_id, _, _) in &events { + if event_id == "clicked" { + self.clicked(*id); + } + } + Vec::new() + } + + fn about_to_show(&self, _id: i32) -> bool { + false + } + + #[zbus(out_args("updates_needed", "id_errors"))] + fn about_to_show_group(&self, _ids: Vec) -> (Vec, Vec) { + (Vec::new(), Vec::new()) + } + + #[zbus(signal)] + async fn layout_updated( + emitter: &SignalEmitter<'_>, + revision: u32, + parent: i32, + ) -> zbus::Result<()>; +} + +pub fn run(initial: Menu, updates: Receiver, actions: Sender) -> Result<(), String> { + if let Some(why) = unavailable() { + return Err(why); + } + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .map_err(|e| e.to_string())?; + rt.block_on(serve(initial, updates, actions)) +} + +async fn serve( + initial: Menu, + updates: Receiver, + actions: Sender, +) -> Result<(), String> { + let shared = Arc::new(Mutex::new(Shared { + menu: initial, + revision: 1, + })); + let stop = Arc::new(tokio::sync::Notify::new()); + let name = format!("org.kde.StatusNotifierItem-{}-1", std::process::id()); + let conn = zbus::connection::Builder::session() + .name(name.as_str()) + .serve_at( + ITEM_PATH, + Item { + shared: shared.clone(), + actions: Mutex::new(actions.clone()), + }, + ) + .serve_at( + MENU_PATH, + DbusMenu { + shared: shared.clone(), + actions: Mutex::new(actions), + stop: stop.clone(), + }, + ) + .build() + .await + .map_err(|e| format!("no desktop session (D-Bus session bus: {e})"))?; + register(&conn, &name).await; + let watcher = tokio::spawn(follow_watcher(conn.clone(), name.clone())); + + let item = conn + .object_server() + .interface::<_, Item>(ITEM_PATH) + .await + .map_err(|e| e.to_string())?; + let menu = conn + .object_server() + .interface::<_, DbusMenu>(MENU_PATH) + .await + .map_err(|e| e.to_string())?; + let mut tick = tokio::time::interval(Duration::from_millis(200)); + loop { + tokio::select! { + _ = stop.notified() => break, + _ = tick.tick() => {} + } + let mut next = None; + loop { + match updates.try_recv() { + Ok(m) => next = Some(m), + Err(TryRecvError::Empty) => break, + Err(TryRecvError::Disconnected) => { + watcher.abort(); + return Ok(()); + } + } + } + let Some(next) = next else { + continue; + }; + let (icon, tip, layout, revision) = { + let mut s = shared.lock().unwrap(); + if s.menu == next { + continue; + } + let icon = s.menu.tone != next.tone; + let tip = s.menu.tooltip != next.tooltip; + let layout = s.menu.entries != next.entries; + if layout { + s.revision += 1; + } + s.menu = next; + (icon, tip, layout, s.revision) + }; + let emitter = item.signal_emitter(); + if icon { + let _ = Item::new_icon(emitter).await; + } + if tip { + let _ = Item::new_tool_tip(emitter).await; + } + if layout { + let _ = DbusMenu::layout_updated(menu.signal_emitter(), revision, 0).await; + } + } + watcher.abort(); + Ok(()) +} + +/// Tell the watcher about the item; quiet when there is none (yet). +async fn register(conn: &zbus::Connection, name: &str) { + let _ = conn + .call_method( + Some(WATCHER), + "/StatusNotifierWatcher", + Some(WATCHER), + "RegisterStatusNotifierItem", + &(name,), + ) + .await; +} + +/// Register again whenever a watcher appears: the desktop's shell restarted, +/// or the AppIndicator extension was switched on. +async fn follow_watcher(conn: zbus::Connection, name: String) { + let Ok(dbus) = zbus::fdo::DBusProxy::new(&conn).await else { + return; + }; + let Ok(mut changes) = dbus.receive_name_owner_changed().await else { + return; + }; + while let Some(change) = changes.next().await { + let Ok(args) = change.args() else { + continue; + }; + if args.name().as_str() == WATCHER && args.new_owner().is_some() { + register(&conn, &name).await; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn menu() -> Menu { + Menu { + tone: Tone::Ok, + tooltip: "devstack".into(), + entries: vec![ + Entry::Label("devstack: 1 stack running".into()), + Entry::Separator, + Entry::Submenu { + label: "shop_app".into(), + entries: vec![Entry::Action { + label: "Stop".into(), + id: "stop:ab12".into(), + enabled: true, + }], + }, + Entry::Action { + label: "Quit".into(), + id: QUIT.into(), + enabled: true, + }, + ], + } + } + + #[test] + fn items_are_numbered_depth_first_and_find_their_action() { + let root = root(&menu()); + assert_eq!( + find(&root, 4).and_then(|n| n.action.as_deref()), + Some("stop:ab12") + ); + assert_eq!(find(&root, 5).and_then(|n| n.action.as_deref()), Some(QUIT)); + assert!(find(&root, 1).unwrap().action.is_none()); + let sub = find(&root, 3).unwrap(); + assert_eq!( + sub.props["label"], + OwnedVariant::try_from(Variant::from("shop__app")).unwrap() + ); + assert_eq!(layout(&root, -1).children.len(), 4); + assert!(layout(&root, 0).children.is_empty()); + } + + #[test] + fn the_layout_has_the_dbusmenu_signature() { + assert_eq!(Layout::SIGNATURE.to_string(), "(ia{sv}av)"); + assert_eq!(>::SIGNATURE.to_string(), "a(iiay)"); + } + + #[test] + fn the_icon_is_argb_in_network_order() { + let p = pixmaps(Tone::Attention); + assert_eq!(p.len(), SIZES.len()); + let (w, h, bytes) = &p[0]; + assert_eq!((*w, *h, bytes.len()), (16, 16, 16 * 16 * 4)); + assert_eq!(bytes[0], 0, "a clear corner: alpha first"); + } +} diff --git a/crates/devstack-desktop/src/tray/macos.rs b/crates/devstack-desktop/src/tray/macos.rs new file mode 100644 index 00000000..6f32795e --- /dev/null +++ b/crates/devstack-desktop/src/tray/macos.rs @@ -0,0 +1,325 @@ +//! macOS: a status item in the menu bar (ADR-0060), from the menu bar client +//! contributed in #248. AppKit is confined to the main thread; no request +//! of the owner runs from a delegate or timer callback. The process makes +//! itself an accessory application, so it has no Dock icon. The icon is a +//! template image, so it follows the menu bar's appearance, tinted in the +//! state's colour. + +use std::cell::{Cell, RefCell}; +use std::sync::mpsc::{Receiver, Sender, TryRecvError}; + +use objc2::rc::{Retained, autoreleasepool}; +use objc2::runtime::{NSObject, NSObjectProtocol, ProtocolObject}; +use objc2::{ + AnyThread, DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, sel, +}; +use objc2_app_kit::{ + NSApplication, NSApplicationActivationPolicy, NSColor, NSEvent, NSEventModifierFlags, + NSEventType, NSImage, NSMenu, NSMenuDelegate, NSMenuItem, NSStatusBar, NSStatusItem, +}; +use objc2_foundation::{ + NSData, NSPoint, NSRunLoop, NSRunLoopCommonModes, NSSize, NSString, NSTimer, ns_string, +}; + +use super::{Entry, Menu, QUIT, Tone}; + +pub fn unavailable() -> Option { + None +} + +struct Ivars { + updates: Receiver, + actions: Sender, + status_item: Retained, + shown: RefCell>, + pending: RefCell>, + tracking: Cell, +} + +define_class!( + // SAFETY: NSObject has no subclassing requirements. Every callback and + // field is confined to the AppKit main thread; this class has no Drop. + #[unsafe(super(NSObject))] + #[thread_kind = MainThreadOnly] + #[ivars = Ivars] + struct MenuTarget; + + unsafe impl NSObjectProtocol for MenuTarget {} + + // SAFETY: The optional protocol callbacks have AppKit's declared signatures. + unsafe impl NSMenuDelegate for MenuTarget { + #[unsafe(method(menuWillOpen:))] + fn menu_will_open(&self, _menu: &NSMenu) { + self.ivars().tracking.set(true); + } + + #[unsafe(method(menuDidClose:))] + fn menu_did_close(&self, _menu: &NSMenu) { + // The next timer tick applies a pending snapshot, after AppKit has + // finished dispatching the action for the selected menu item. + self.ivars().tracking.set(false); + } + } + + impl MenuTarget { + #[unsafe(method(performMenuAction:))] + fn perform_menu_action(&self, item: &NSMenuItem) { + let Some(object) = item.representedObject() else { + return; + }; + let Some(id) = object.downcast_ref::() else { + return; + }; + let id = id.to_string(); + let quitting = id == QUIT; + if self.ivars().actions.send(id).is_err() || quitting { + self.stop(); + } + } + + #[unsafe(method(pollUpdates:))] + fn poll_updates(&self, _timer: &NSTimer) { + autoreleasepool(|_| self.poll()); + } + } +); + +impl MenuTarget { + fn new( + mtm: MainThreadMarker, + status_item: Retained, + updates: Receiver, + actions: Sender, + ) -> Retained { + let this = Self::alloc(mtm).set_ivars(Ivars { + updates, + actions, + status_item, + shown: RefCell::new(None), + pending: RefCell::new(None), + tracking: Cell::new(false), + }); + // SAFETY: The superclass is NSObject and the instance's fields have + // been initialized before invoking its designated initializer. + unsafe { msg_send![super(this), init] } + } + + fn poll(&self) { + // Coalesce snapshots and bound work per event even if a producer sends + // faster than AppKit can draw. There is never a blocking channel read. + for _ in 0..32 { + match self.ivars().updates.try_recv() { + Ok(menu) => *self.ivars().pending.borrow_mut() = Some(menu), + Err(TryRecvError::Empty) => break, + Err(TryRecvError::Disconnected) => { + self.stop(); + return; + } + } + } + // Keep the open menu and its action IDs stable under the pointer. + // The timer runs in common modes, including menu tracking, but only + // replaces a menu once its tracking session has ended. + if !self.ivars().tracking.get() { + let pending = self.ivars().pending.borrow_mut().take(); + if let Some(menu) = pending { + self.apply(menu); + } + } + } + + fn apply(&self, snapshot: Menu) { + if self.ivars().shown.borrow().as_ref() == Some(&snapshot) { + return; + } + if let Some(button) = self.ivars().status_item.button(self.mtm()) { + button.setToolTip(Some(&NSString::from_str(&snapshot.tooltip))); + // A template image takes the tint; none follows the menu bar. + let tint = match snapshot.tone { + Tone::Idle | Tone::Ok => None, + Tone::Busy => Some(NSColor::systemOrangeColor()), + Tone::Attention => Some(NSColor::systemRedColor()), + }; + button.setContentTintColor(tint.as_deref()); + } + let menu = build_menu(self, &snapshot.entries); + // NSMenu's delegate and NSMenuItem's target are weak; `run` retains + // this object until the menu is detached and its timer invalidated. + menu.setDelegate(Some(ProtocolObject::from_ref(self))); + self.ivars().status_item.setMenu(Some(&menu)); + *self.ivars().shown.borrow_mut() = Some(snapshot); + } + + fn stop(&self) { + if let Some(menu) = self.ivars().status_item.menu(self.mtm()) { + menu.cancelTracking(); + } + let app = NSApplication::sharedApplication(self.mtm()); + app.stop(None); + // A timer can stop NSApplication while it waits for the next event. + // Wake that wait so `run` returns and its retained objects are cleaned + // up, without using `terminate:` or exiting the owning process. + if let Some(event) = NSEvent::otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2( + NSEventType::ApplicationDefined, + NSPoint::new(0.0, 0.0), + NSEventModifierFlags::empty(), + 0.0, + 0, + None, + 0, + 0, + 0, + ) { + app.postEvent_atStart(&event, true); + } + } +} + +fn build_menu(target: &MenuTarget, entries: &[Entry]) -> Retained { + let menu = NSMenu::new(target.mtm()); + // AppKit's automatic validation would otherwise re-enable explicitly + // disabled items or disable submenu parents with no action of their own. + menu.setAutoenablesItems(false); + for entry in entries { + let item = match entry { + Entry::Separator => NSMenuItem::separatorItem(target.mtm()), + Entry::Label(label) => { + let item = new_item(target.mtm(), label, false); + item.setEnabled(false); + item + } + Entry::Action { label, id, enabled } => { + let item = new_item(target.mtm(), label, true); + // SAFETY: The fixed selector is implemented by MenuTarget with + // the NSMenuItem argument AppKit sends. The immutable action + // ID is an NSString retained by this item's representedObject. + // The target remains retained throughout the native run loop. + unsafe { + item.setTarget(Some(target)); + item.setRepresentedObject(Some(&NSString::from_str(id))); + } + item.setEnabled(*enabled); + if id == QUIT { + item.setKeyEquivalent(ns_string!("q")); + } + item + } + Entry::Submenu { label, entries } => { + let item = new_item(target.mtm(), label, false); + item.setSubmenu(Some(&build_menu(target, entries))); + item.setEnabled(true); + item + } + }; + menu.addItem(&item); + } + menu +} + +fn new_item(mtm: MainThreadMarker, label: &str, actionable: bool) -> Retained { + // SAFETY: The only selector is our MenuTarget method, set on action items + // immediately after creation. Other items have no action. + unsafe { + NSMenuItem::initWithTitle_action_keyEquivalent( + NSMenuItem::alloc(mtm), + &NSString::from_str(label), + actionable.then(|| sel!(performMenuAction:)), + ns_string!(""), + ) + } +} + +pub(super) fn run( + initial: Menu, + updates: Receiver, + actions: Sender, +) -> Result<(), String> { + let mtm = MainThreadMarker::new() + .ok_or("The macOS menu bar must be started on the process's main thread.")?; + autoreleasepool(|_| { + let app = NSApplication::sharedApplication(mtm); + // An LSUIElement app already starts as Accessory. AppKit may refuse + // setting that same policy again, even though it is ready to run. + if app.activationPolicy() != NSApplicationActivationPolicy::Accessory + && !app.setActivationPolicy(NSApplicationActivationPolicy::Accessory) + && app.activationPolicy() != NSApplicationActivationPolicy::Accessory + { + return Err(format!( + "macOS could not make devstack a menu bar application (activation policy: {:?}).", + app.activationPolicy() + )); + } + let status_bar = NSStatusBar::systemStatusBar(); + let status_item = status_bar.statusItemWithLength(28.0); + let Some(button) = status_item.button(mtm) else { + status_bar.removeStatusItem(&status_item); + return Err("macOS could not create the devstack menu bar item.".into()); + }; + // The dashboard favicon's three strokes and dot, with no background. + // A vector PDF stays sharp at every display scale; template rendering + // follows macOS's light/dark menu bar and selected-item appearance. + let icon_data = NSData::with_bytes(include_bytes!("assets/devstack-template.pdf")); + if let Some(image) = NSImage::initWithData(NSImage::alloc(), &icon_data) { + image.setSize(NSSize::new(20.0, 18.0)); + image.setTemplate(true); + image.setAccessibilityDescription(Some(ns_string!("devstack"))); + button.setImage(Some(&image)); + } else { + status_item.setLength(76.0); + button.setTitle(ns_string!("devstack")); + } + button.setToolTip(Some(ns_string!("devstack"))); + status_item.setVisible(true); + let target = MenuTarget::new(mtm, status_item.clone(), updates, actions); + target.apply(initial); + // SAFETY: `pollUpdates:` is implemented above with NSTimer's expected + // signature. The retained target and timer live until after `run`. + let timer = unsafe { + NSTimer::timerWithTimeInterval_target_selector_userInfo_repeats( + 0.2, + &target, + sel!(pollUpdates:), + None, + true, + ) + }; + // SAFETY: The timer's callbacks and target are main-thread-only, and + // this is the main run loop. Common modes keep callbacks responsive + // while AppKit is tracking a menu. + unsafe { + NSRunLoop::mainRunLoop().addTimer_forMode(&timer, NSRunLoopCommonModes); + } + app.run(); + timer.invalidate(); + if let Some(menu) = status_item.menu(mtm) { + menu.setDelegate(None); + } + status_item.setMenu(None); + status_bar.removeStatusItem(&status_item); + Ok(()) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rejects_a_worker_thread_before_touching_appkit() { + let result = std::thread::spawn(|| { + let (_updates, receiver) = std::sync::mpsc::channel(); + let (sender, _actions) = std::sync::mpsc::channel(); + run( + Menu { + tooltip: "devstack".into(), + ..Menu::default() + }, + receiver, + sender, + ) + }) + .join() + .unwrap(); + assert!(result.unwrap_err().contains("main thread")); + } +} diff --git a/crates/devstack-desktop/src/tray/mod.rs b/crates/devstack-desktop/src/tray/mod.rs new file mode 100644 index 00000000..0be96efe --- /dev/null +++ b/crates/devstack-desktop/src/tray/mod.rs @@ -0,0 +1,115 @@ +//! The tray (ADR-0060): an icon in the notification area (Windows), a +//! StatusNotifierItem (Linux) or a status item in the menu bar (macOS), with +//! a menu. What it shows is made by its owner (`devstack tray`) as a [`Menu`]; +//! this module only draws it and sends the chosen action's id back. +//! +//! [`run`] takes the calling thread, which must be the process's main thread +//! (AppKit wants it; Windows and Linux do not mind), until the menu's `quit` +//! action, or until the owner drops its end of `updates`. + +use std::sync::mpsc::{Receiver, Sender}; + +mod icon; +#[cfg(target_os = "linux")] +mod linux; +#[cfg(target_os = "macos")] +mod macos; +#[cfg(windows)] +mod windows; + +pub use icon::rgba; + +/// What the icon says, in the state's colour (ADR-0060 point 4). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum Tone { + /// Nothing runs, or the hub does not. + #[default] + Idle, + /// Something runs, and nothing needs attention. + Ok, + /// A stack starts or stops. + Busy, + /// Something needs attention. + Attention, +} + +/// Everything the tray shows: the icon, its tooltip and the menu. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Menu { + pub tone: Tone, + pub tooltip: String, + pub entries: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Entry { + /// Text that cannot be chosen. + Label(String), + Separator, + /// Sends `id` when chosen. + Action { + label: String, + id: String, + enabled: bool, + }, + Submenu { + label: String, + entries: Vec, + }, +} + +/// The action id that ends [`run`] (after it was sent to the owner). +pub const QUIT: &str = "quit"; + +/// Show `initial`, then each menu from `updates`, and send the id of every +/// chosen action to `actions`. Returns when [`QUIT`] is chosen or `updates` +/// is disconnected; `Err` when no tray can be shown here. +pub fn run(initial: Menu, updates: Receiver, actions: Sender) -> Result<(), String> { + os::run(initial, updates, actions) +} + +/// Why no tray can be shown in this session, or `None`: Linux without a +/// session bus (a server, a container, an SSH login). +pub fn unavailable() -> Option { + os::unavailable() +} + +#[cfg(target_os = "linux")] +use self::linux as os; +#[cfg(target_os = "macos")] +use self::macos as os; +#[cfg(windows)] +use self::windows as os; + +/// What a menu's label shows on one line: no control characters, at most +/// `max` characters. +pub fn one_line(text: &str, max: usize) -> String { + let clean: String = text + .chars() + .map(|c| if c.is_control() { ' ' } else { c }) + .collect(); + let clean = clean.trim(); + if clean.chars().count() > max { + format!( + "{}…", + clean + .chars() + .take(max.saturating_sub(1)) + .collect::() + ) + } else { + clean.to_string() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_label_is_one_short_line() { + assert_eq!(one_line(" a\nb\tc ", 10), "a b c"); + assert_eq!(one_line("abcdef", 4), "abc…"); + assert_eq!(one_line("äöü", 3), "äöü"); + } +} diff --git a/crates/devstack-desktop/src/tray/windows.rs b/crates/devstack-desktop/src/tray/windows.rs new file mode 100644 index 00000000..4738ac84 --- /dev/null +++ b/crates/devstack-desktop/src/tray/windows.rs @@ -0,0 +1,346 @@ +//! Windows: an icon in the notification area (`Shell_NotifyIconW`) owned by +//! a hidden window of this thread, with a popup menu on either click +//! (ADR-0060). A timer on that window takes the owner's menus; Explorer's +//! `TaskbarCreated` (it restarted) adds the icon again. + +use super::{Entry, Menu, QUIT, Tone}; +use std::cell::RefCell; +use std::sync::mpsc::{Receiver, Sender, TryRecvError}; +use windows_sys::Win32::Foundation::{HWND, LPARAM, LRESULT, POINT, WPARAM}; +use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW; +use windows_sys::Win32::UI::Shell::{ + NIF_ICON, NIF_MESSAGE, NIF_TIP, NIM_ADD, NIM_DELETE, NIM_MODIFY, NOTIFYICONDATAW, + Shell_NotifyIconW, +}; +use windows_sys::Win32::UI::WindowsAndMessaging::{ + AppendMenuW, CreateIcon, CreatePopupMenu, CreateWindowExW, DefWindowProcW, DestroyIcon, + DestroyMenu, DestroyWindow, DispatchMessageW, GetCursorPos, GetMessageW, GetSystemMetrics, + HICON, HMENU, KillTimer, MF_GRAYED, MF_POPUP, MF_SEPARATOR, MF_STRING, MSG, PostMessageW, + PostQuitMessage, RegisterClassW, RegisterWindowMessageW, SM_CXSMICON, SetForegroundWindow, + SetTimer, TPM_NONOTIFY, TPM_RETURNCMD, TPM_RIGHTBUTTON, TrackPopupMenu, TranslateMessage, + WM_APP, WM_DESTROY, WM_LBUTTONUP, WM_NULL, WM_RBUTTONUP, WM_TIMER, WNDCLASSW, WS_POPUP, +}; + +/// The icon's messages to its window. +const CALLBACK: u32 = WM_APP + 1; +const TIMER: usize = 1; + +pub fn unavailable() -> Option { + None +} + +/// What the window procedure works with; one tray per thread. +struct State { + hwnd: HWND, + menu: Menu, + icon: HICON, + updates: Receiver, + actions: Sender, + taskbar_created: u32, +} + +thread_local! { + static STATE: RefCell> = const { RefCell::new(None) }; +} + +fn wide(s: &str) -> Vec { + s.encode_utf16().chain(Some(0)).collect() +} + +/// The icon at the small-icon size, from the shared drawing. +fn make_icon(tone: Tone) -> HICON { + // SAFETY: plain Win32 calls with buffers that outlive them. + unsafe { + let size = GetSystemMetrics(SM_CXSMICON).clamp(16, 64) as u32; + let rgba = super::rgba(size, tone); + // Windows wants BGRA; straight alpha. + let bgra: Vec = rgba + .as_chunks::<4>() + .0 + .iter() + .flat_map(|p| [p[2], p[1], p[0], p[3]]) + .collect(); + // The mask is unused where the colour has alpha; rows of whole words. + let mask = vec![0u8; (size.div_ceil(16) * 2 * size) as usize]; + CreateIcon( + GetModuleHandleW(std::ptr::null()), + size as i32, + size as i32, + 1, + 32, + mask.as_ptr(), + bgra.as_ptr(), + ) + } +} + +fn data(s: &State) -> NOTIFYICONDATAW { + // SAFETY: an all-zero NOTIFYICONDATAW is valid (no handles, empty strings). + let mut d: NOTIFYICONDATAW = unsafe { std::mem::zeroed() }; + d.cbSize = std::mem::size_of::() as u32; + d.hWnd = s.hwnd; + d.uID = 1; + d.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP; + d.uCallbackMessage = CALLBACK; + d.hIcon = s.icon; + let tip: Vec = super::one_line(&s.menu.tooltip, 127) + .encode_utf16() + .collect(); + let n = tip.len().min(d.szTip.len() - 1); + d.szTip[..n].copy_from_slice(&tip[..n]); + d +} + +fn show(s: &State, how: u32) { + let d = data(s); + // SAFETY: `d` is a valid NOTIFYICONDATAW for our own window. + unsafe { + Shell_NotifyIconW(how, &d); + } +} + +/// `&` marks an access key in a menu's text. +fn menu_text(label: &str) -> Vec { + wide(&super::one_line(label, 120).replace('&', "&&")) +} + +/// The popup menu for `entries`; command ids from 1, their actions in `ids`. +fn build(entries: &[Entry], ids: &mut Vec) -> HMENU { + // SAFETY: plain Win32 calls; the menu is destroyed by the caller (with + // its submenus). + unsafe { + let menu = CreatePopupMenu(); + for e in entries { + match e { + Entry::Separator => { + AppendMenuW(menu, MF_SEPARATOR, 0, std::ptr::null()); + } + Entry::Label(text) => { + AppendMenuW(menu, MF_STRING | MF_GRAYED, 0, menu_text(text).as_ptr()); + } + Entry::Action { label, id, enabled } => { + ids.push(id.clone()); + let flags = if *enabled { + MF_STRING + } else { + MF_STRING | MF_GRAYED + }; + AppendMenuW(menu, flags, ids.len(), menu_text(label).as_ptr()); + } + Entry::Submenu { label, entries } => { + let sub = build(entries, ids); + AppendMenuW( + menu, + MF_STRING | MF_POPUP, + sub as usize, + menu_text(label).as_ptr(), + ); + } + } + } + menu + } +} + +/// Show the menu at the cursor and send what was chosen. +fn popup(hwnd: HWND) { + let Some((entries, actions)) = STATE.with(|s| { + s.borrow() + .as_ref() + .map(|s| (s.menu.entries.clone(), s.actions.clone())) + }) else { + return; + }; + let mut ids = Vec::new(); + let menu = build(&entries, &mut ids); + // SAFETY: our own window and menu. The window must be in front, or the + // menu does not close when the user clicks elsewhere; WM_NULL afterwards + // as Microsoft documents for notification-area menus. + let chosen = unsafe { + let mut at = POINT { x: 0, y: 0 }; + GetCursorPos(&mut at); + SetForegroundWindow(hwnd); + let chosen = TrackPopupMenu( + menu, + TPM_RETURNCMD | TPM_NONOTIFY | TPM_RIGHTBUTTON, + at.x, + at.y, + 0, + hwnd, + std::ptr::null(), + ); + PostMessageW(hwnd, WM_NULL, 0, 0); + DestroyMenu(menu); + chosen + }; + if chosen <= 0 { + return; + } + let Some(id) = ids.get(chosen as usize - 1).cloned() else { + return; + }; + let quit = id == QUIT; + if actions.send(id).is_err() || quit { + // SAFETY: our own window, on its thread. + unsafe { + DestroyWindow(hwnd); + } + } +} + +/// Take the owner's latest menu; the window ends when the owner is gone. +fn poll(hwnd: HWND) { + let mut gone = false; + STATE.with(|s| { + let mut s = s.borrow_mut(); + let Some(s) = s.as_mut() else { + return; + }; + let mut next = None; + loop { + match s.updates.try_recv() { + Ok(m) => next = Some(m), + Err(TryRecvError::Empty) => break, + Err(TryRecvError::Disconnected) => { + gone = true; + break; + } + } + } + let Some(next) = next else { + return; + }; + if next == s.menu { + return; + } + let tone = next.tone != s.menu.tone; + let tip = next.tooltip != s.menu.tooltip; + s.menu = next; + if tone { + let old = s.icon; + s.icon = make_icon(s.menu.tone); + show(s, NIM_MODIFY); + // SAFETY: the icon the notification area no longer uses. + unsafe { + DestroyIcon(old); + } + } else if tip { + show(s, NIM_MODIFY); + } + }); + if gone { + // SAFETY: our own window, on its thread. + unsafe { + DestroyWindow(hwnd); + } + } +} + +unsafe extern "system" fn window_proc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT { + match msg { + CALLBACK => { + let event = (lp & 0xffff) as u32; + if event == WM_LBUTTONUP || event == WM_RBUTTONUP { + popup(hwnd); + } + 0 + } + WM_TIMER if wp == TIMER => { + poll(hwnd); + 0 + } + WM_DESTROY => { + STATE.with(|s| { + if let Some(s) = s.borrow().as_ref() { + show(s, NIM_DELETE); + } + }); + // SAFETY: our own window and timer, on its thread. + unsafe { + KillTimer(hwnd, TIMER); + PostQuitMessage(0); + } + 0 + } + _ => { + let again = STATE.with(|s| { + s.borrow() + .as_ref() + .is_some_and(|s| s.taskbar_created != 0 && msg == s.taskbar_created) + }); + if again { + // Explorer restarted: the icon is gone from the new taskbar. + STATE.with(|s| { + if let Some(s) = s.borrow().as_ref() { + show(s, NIM_ADD); + } + }); + return 0; + } + // SAFETY: the default procedure for our own window. + unsafe { DefWindowProcW(hwnd, msg, wp, lp) } + } + } +} + +pub fn run(initial: Menu, updates: Receiver, actions: Sender) -> Result<(), String> { + let class = wide("devstack-tray"); + // SAFETY: plain Win32 calls; the window, icon and timer are ours and + // released when the message loop ends. + unsafe { + let instance = GetModuleHandleW(std::ptr::null()); + let mut wc: WNDCLASSW = std::mem::zeroed(); + wc.lpfnWndProc = Some(window_proc); + wc.hInstance = instance; + wc.lpszClassName = class.as_ptr(); + // A second registration in the same process fails; the class is the same. + RegisterClassW(&wc); + // A hidden top-level window, not a message-only one: only top-level + // windows hear Explorer's `TaskbarCreated` broadcast. + let hwnd = CreateWindowExW( + 0, + class.as_ptr(), + wide("devstack").as_ptr(), + WS_POPUP, + 0, + 0, + 0, + 0, + std::ptr::null_mut(), + std::ptr::null_mut(), + instance, + std::ptr::null(), + ); + if hwnd.is_null() { + return Err("Windows could not create the tray's window".into()); + } + let state = State { + hwnd, + icon: make_icon(initial.tone), + menu: initial, + updates, + actions, + taskbar_created: RegisterWindowMessageW(wide("TaskbarCreated").as_ptr()), + }; + let d = data(&state); + let added = Shell_NotifyIconW(NIM_ADD, &d) != 0; + let icon = state.icon; + STATE.with(|s| *s.borrow_mut() = Some(state)); + if !added { + DestroyWindow(hwnd); + STATE.with(|s| s.borrow_mut().take()); + DestroyIcon(icon); + return Err("Windows did not add the icon to the notification area".into()); + } + SetTimer(hwnd, TIMER, 200, None); + let mut msg: MSG = std::mem::zeroed(); + while GetMessageW(&mut msg, std::ptr::null_mut(), 0, 0) > 0 { + TranslateMessage(&msg); + DispatchMessageW(&msg); + } + if let Some(s) = STATE.with(|s| s.borrow_mut().take()) { + DestroyIcon(s.icon); + } + } + Ok(()) +} diff --git a/crates/devstack-hub/src/lib.rs b/crates/devstack-hub/src/lib.rs index 6f20d77c..35d1a7de 100644 --- a/crates/devstack-hub/src/lib.rs +++ b/crates/devstack-hub/src/lib.rs @@ -44,6 +44,8 @@ mod prompts; pub mod release; mod share; mod shared; +mod summary; +pub mod tray; mod ws; pub const VERSION: &str = env!("CARGO_PKG_VERSION"); @@ -150,6 +152,8 @@ struct AppState { shutdown: Arc, /// Desktop notifications (ADR-0045). notify: Arc, + /// What the streams `notify` follows show now, for `/hub/summary`. + board: Arc, } fn now_ms() -> u128 { @@ -409,6 +413,7 @@ pub fn serve() -> Result<(), String> { engine_fast_until, shutdown: shutdown.clone(), notify, + board: Arc::default(), }; // The port last: what accepts a connection answers it. Bound before // the setup above (a first `docker version` alone may take 5 s), the @@ -430,6 +435,7 @@ pub fn serve() -> Result<(), String> { ) .map_err(|e| e.to_string())?; notify::start(state.clone()); + tray::start_quietly(); let app = router(state); if let Some(v6) = v6 { let app6 = app.clone(); @@ -476,6 +482,7 @@ fn router(state: AppState) -> axum::Router { .route("/hub/session", get(session)) .route("/hub/ping", get(ping).options(ping_preflight)) .route("/hub/stacks", get(stacks)) + .route("/hub/summary", get(summary::get)) .route("/hub/docker", get(docker)) .route("/hub/docker/start", post(docker_start)) .route("/hub/events", get(events)) diff --git a/crates/devstack-hub/src/notify/mod.rs b/crates/devstack-hub/src/notify/mod.rs index 4323acfe..f1408911 100644 --- a/crates/devstack-hub/src/notify/mod.rs +++ b/crates/devstack-hub/src/notify/mod.rs @@ -446,6 +446,7 @@ async fn follow_stack(s: AppState, id: String, name: String) { let mut lanes = Lanes::default(); let mut scope = Scope::default(); let mut followed: HashMap = HashMap::new(); + let held = s.board.hold(&id, None); if let Some(mut events) = open(&s, &id, "/v1/events").await { if let Some(v) = get_json(&s, &id, "/v1/lanes").await { lanes.baseline(&v); @@ -464,12 +465,14 @@ async fn follow_stack(s: AppState, id: String, name: String) { } _ => scope.apply(&ev), }; + s.board.set(&id, None, scope.glance()); for n in notices { s.notify.deliver(&id, &name, None, n); } } } drop(followed); + drop(held); tokio::time::sleep(wait).await; wait = (wait * 2).min(RETRY_MAX); } @@ -504,6 +507,7 @@ async fn follow_lane(s: AppState, id: String, name: String, lane: String) { let mut wait = RETRY_MIN; loop { let mut scope = Scope::default(); + let held = s.board.hold(&id, Some(&lane)); if let Some(mut events) = open(&s, &id, &path).await { while let Some(text) = events.next().await { wait = RETRY_MIN; @@ -513,11 +517,14 @@ async fn follow_lane(s: AppState, id: String, name: String, lane: String) { if ev["type"] == "usage" { continue; } - for n in scope.apply(&ev) { + let notices = scope.apply(&ev); + s.board.set(&id, Some(&lane), scope.glance()); + for n in notices { s.notify.deliver(&id, &name, Some(&lane), n); } } } + drop(held); tokio::time::sleep(wait).await; wait = (wait * 2).min(RETRY_MAX); } diff --git a/crates/devstack-hub/src/notify/rules.rs b/crates/devstack-hub/src/notify/rules.rs index cdeb06cf..524ead81 100644 --- a/crates/devstack-hub/src/notify/rules.rs +++ b/crates/devstack-hub/src/notify/rules.rs @@ -89,8 +89,13 @@ const CASCADE_PREFIX: &str = "not started: "; struct Svc { /// `status.state`. state: String, + /// `status.reason` and `status.exit_code`, for what the tray shows. + reason: String, + exit_code: Option, /// The candidate's `state` and `build_id`. candidate: Option<(String, Option)>, + /// The candidate's `reason`. + candidate_reason: String, } /// What one event stream (the main tree's, or one lane's) showed last, per @@ -114,7 +119,10 @@ impl Scope { s["name"].as_str()?.to_string(), Svc { state: state_of(&s["status"]), + reason: reason_of(&s["status"]), + exit_code: s["status"]["exit_code"].as_i64(), candidate: candidate_of(&s["candidate"]), + candidate_reason: reason_of(&s["candidate"]), }, )) }) @@ -127,6 +135,8 @@ impl Scope { }; let svc = self.services.entry(name.to_string()).or_default(); let before = std::mem::replace(&mut svc.state, state_of(&event["status"])); + svc.reason = reason_of(&event["status"]); + svc.exit_code = event["status"]["exit_code"].as_i64(); service_notice(name, &before, &event["status"]) .into_iter() .collect() @@ -138,6 +148,7 @@ impl Scope { let svc = self.services.entry(name.to_string()).or_default(); let now = candidate_of(&event["candidate"]); let before = std::mem::replace(&mut svc.candidate, now.clone()); + svc.candidate_reason = reason_of(&event["candidate"]); candidate_notice(name, before, now.as_ref(), &event["candidate"]) .into_iter() .collect() @@ -147,6 +158,62 @@ impl Scope { } } +impl Scope { + /// What this stream shows now, for the hub's summary (ADR-0060 point 3): + /// the services ready of all, whether one starts, and what needs + /// attention, the same as what notifies. + pub fn glance(&self) -> crate::summary::Glance { + let mut g = crate::summary::Glance { + total: self.services.len(), + ..Default::default() + }; + let mut names: Vec<&String> = self.services.keys().collect(); + names.sort(); + for name in names { + let svc = &self.services[name]; + match svc.state.as_str() { + "running" | "healthy" => g.ready += 1, + "completed" if svc.exit_code == Some(0) => g.ready += 1, + "building" | "starting" => g.starting = true, + "failed" + if !svc.reason.starts_with(STOPPED_PREFIX) + && !svc.reason.starts_with(CASCADE_PREFIX) => + { + g.attention.push(attention(name, "failed", &svc.reason)); + } + _ => {} + } + match svc.candidate.as_ref().map(|(s, _)| s.as_str()) { + Some("held") => g.attention.push(attention( + name, + "build held for promote", + &svc.candidate_reason, + )), + Some("failed") => { + g.attention + .push(attention(name, "build failed", &svc.candidate_reason)); + } + _ => {} + } + } + g + } +} + +/// `: `, and the first line of why. +fn attention(service: &str, what: &str, reason: &str) -> crate::summary::Item { + crate::summary::Item { + lane: None, + service: Some(service.to_string()), + text: format!("{service}: {what}"), + detail: first_lines(reason, 1), + } +} + +fn reason_of(v: &Value) -> String { + v["reason"].as_str().unwrap_or("").to_string() +} + fn state_of(status: &Value) -> String { status["state"].as_str().unwrap_or("").to_string() } @@ -382,6 +449,32 @@ mod tests { n.iter().map(|n| n.kind).collect() } + #[test] + fn the_glance_counts_ready_services_and_names_what_needs_attention() { + let mut s = Scope::default(); + s.apply(&snapshot(json!([ + { "name": "api", "status": { "state": "healthy" }, + "candidate": { "state": "held", "build_id": "b1", "reason": "schema\nmore" } }, + { "name": "job", "status": { "state": "completed", "exit_code": 0 } }, + { "name": "web", "status": { "state": "failed", "reason": "not started: api failed" } }, + { "name": "worker", "status": { "state": "starting" } } + ]))); + let g = s.glance(); + assert_eq!((g.ready, g.total, g.starting), (2, 4, true)); + // A service held back by another's failure is not one more thing. + assert_eq!(g.attention.len(), 1); + assert_eq!(g.attention[0].text, "api: build held for promote"); + assert_eq!(g.attention[0].detail, "schema"); + s.apply(&service( + "worker", + json!({ "state": "failed", "reason": "port taken" }), + )); + let g = s.glance(); + assert!(!g.starting); + assert_eq!(g.attention[1].text, "worker: failed"); + assert_eq!(g.attention[1].service.as_deref(), Some("worker")); + } + #[test] fn what_the_snapshot_shows_is_the_baseline() { let mut s = Scope::default(); diff --git a/crates/devstack-hub/src/summary.rs b/crates/devstack-hub/src/summary.rs new file mode 100644 index 00000000..efe6b258 --- /dev/null +++ b/crates/devstack-hub/src/summary.rs @@ -0,0 +1,312 @@ +//! `GET /hub/summary` (ADR-0060 point 3): every registered stack at a glance, +//! and one state over all of them, for the tray. What needs attention is +//! what notifies (ADR-0045), read from the streams the hub follows for that +//! (`notify`): each stream leaves its [`Glance`] on the [`Board`] after every +//! event, and takes it away when it ends. + +use axum::Json; +use axum::extract::State; +use axum::response::{IntoResponse, Response}; +use serde::Serialize; +use std::collections::{BTreeMap, HashMap}; +use std::sync::{Arc, Mutex}; + +use crate::{AppState, Phase, StackEntry}; + +/// Something that needs attention. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] +pub(crate) struct Item { + /// The lane it is in; `None`: the main working tree. + pub lane: Option, + /// The service it is about; `None`: the stack's start. + pub service: Option, + /// One short line: `api: build held for promote`. + pub text: String, + /// The first line of why, or empty. + pub detail: String, +} + +/// What one stream (a stack's main tree, or one of its lanes) shows now. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub(crate) struct Glance { + /// Services running, healthy or done (a job that ended with 0). + pub ready: usize, + pub total: usize, + /// A service builds or starts. + pub starting: bool, + pub attention: Vec, +} + +/// Each followed stream's last [`Glance`], by stack id and lane. +#[derive(Default)] +pub(crate) struct Board { + streams: Mutex, Glance>>>, +} + +impl Board { + pub fn set(&self, stack: &str, lane: Option<&str>, g: Glance) { + self.streams + .lock() + .unwrap() + .entry(stack.to_string()) + .or_default() + .insert(lane.map(str::to_string), g); + } + + fn remove(&self, stack: &str, lane: Option<&str>) { + let mut streams = self.streams.lock().unwrap(); + if let Some(by_lane) = streams.get_mut(stack) { + by_lane.remove(&lane.map(str::to_string)); + if by_lane.is_empty() { + streams.remove(stack); + } + } + } + + /// Takes the stream's glance off the board when dropped: when its + /// stream ends, or its task is aborted (the stack or lane stopped). + pub fn hold(self: &Arc, stack: &str, lane: Option<&str>) -> Held { + Held { + board: self.clone(), + stack: stack.to_string(), + lane: lane.map(str::to_string), + } + } + + fn of(&self, stack: &str) -> BTreeMap, Glance> { + self.streams + .lock() + .unwrap() + .get(stack) + .cloned() + .unwrap_or_default() + } +} + +pub(crate) struct Held { + board: Arc, + stack: String, + lane: Option, +} + +impl Drop for Held { + fn drop(&mut self) { + self.board.remove(&self.stack, self.lane.as_deref()); + } +} + +/// One stack in the summary. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub(crate) struct StackSummary { + pub id: String, + pub name: String, + /// The main working tree (`POST /hub/open` opens it). + pub repo: std::path::PathBuf, + pub running: bool, + /// `stopped`, `starting`, `stopping`, `ok` or `attention`. + pub state: &'static str, + /// The main tree's services ready, of all. + pub ready: usize, + pub total: usize, + /// Lanes whose stream the hub follows: started, here or on a node. + pub lanes: usize, + pub attention: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub(crate) struct Summary { + /// `attention`, `starting` (a stack starts or stops), `ok` (a stack + /// runs) or `idle`: the worst of the stacks. + pub state: &'static str, + pub version: &'static str, + pub stacks: Vec, +} + +fn stack( + e: &StackEntry, + phase: Option, + streams: &BTreeMap, Glance>, +) -> StackSummary { + let main = streams.get(&None).cloned().unwrap_or_default(); + let mut attention = Vec::new(); + if let Some(err) = &e.start_error { + attention.push(Item { + lane: None, + service: None, + text: "the start failed".into(), + detail: err + .lines() + .rev() + .find(|l| !l.trim().is_empty()) + .unwrap_or("") + .trim() + .to_string(), + }); + } + let mut starting = false; + for (lane, g) in streams { + if e.running { + starting |= g.starting; + attention.extend(g.attention.iter().cloned().map(|mut i| { + i.lane = lane.clone(); + i + })); + } + } + let state = match phase { + Some(Phase::Starting) => "starting", + Some(Phase::Stopping) => "stopping", + None if !attention.is_empty() => "attention", + None if !e.running => "stopped", + None if starting => "starting", + None => "ok", + }; + StackSummary { + id: e.id.clone(), + name: e.name.clone(), + repo: e.repo.clone(), + running: e.running, + state, + ready: main.ready, + total: main.total, + lanes: streams.keys().filter(|l| l.is_some()).count(), + attention, + } +} + +fn overall(stacks: &[StackSummary]) -> &'static str { + let any = |s: &[&str]| stacks.iter().any(|x| s.contains(&x.state)); + if any(&["attention"]) { + "attention" + } else if any(&["starting", "stopping"]) { + "starting" + } else if stacks.iter().any(|x| x.running) { + "ok" + } else { + "idle" + } +} + +pub(crate) fn summary(s: &AppState) -> Summary { + let entries = s.stacks.borrow().clone(); + let phases = s.phases.lock().unwrap().clone(); + let stacks: Vec = entries + .iter() + .map(|e| stack(e, phases.get(&e.id).copied(), &s.board.of(&e.id))) + .collect(); + Summary { + state: overall(&stacks), + version: crate::VERSION, + stacks, + } +} + +/// `GET /hub/summary`. +pub(crate) async fn get(State(s): State) -> Response { + Json(summary(&s)).into_response() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn entry(id: &str, running: bool) -> StackEntry { + StackEntry { + id: id.into(), + name: format!("stack {id}"), + file: Default::default(), + repo: Default::default(), + running, + daemon: None, + last_seen: None, + start_error: None, + } + } + + fn held(service: &str) -> Item { + Item { + lane: None, + service: Some(service.into()), + text: format!("{service}: build held for promote"), + detail: String::new(), + } + } + + #[test] + fn a_lanes_attention_is_the_stacks_and_names_the_lane() { + let mut streams = BTreeMap::new(); + streams.insert( + None, + Glance { + ready: 2, + total: 3, + ..Default::default() + }, + ); + streams.insert( + Some("feat-x".to_string()), + Glance { + attention: vec![held("api")], + ..Default::default() + }, + ); + let s = stack(&entry("ab12", true), None, &streams); + assert_eq!(s.state, "attention"); + assert_eq!((s.ready, s.total, s.lanes), (2, 3, 1)); + assert_eq!(s.attention[0].lane.as_deref(), Some("feat-x")); + assert_eq!(overall(&[s]), "attention"); + } + + #[test] + fn a_stopped_stack_shows_its_failed_start_and_nothing_stale() { + let mut e = entry("ab12", false); + e.start_error = Some("Error: port 5432 is taken\n\n".into()); + // A stream not taken off the board yet says nothing for a stopped stack. + let streams = BTreeMap::from([( + None, + Glance { + attention: vec![held("api")], + ..Default::default() + }, + )]); + let s = stack(&e, None, &streams); + assert_eq!(s.state, "attention"); + assert_eq!(s.attention.len(), 1); + assert_eq!(s.attention[0].detail, "Error: port 5432 is taken"); + let s = stack(&entry("cd34", false), None, &BTreeMap::new()); + assert_eq!(s.state, "stopped"); + assert_eq!(overall(&[s]), "idle"); + } + + #[test] + fn a_start_or_stop_under_way_wins_and_the_worst_stack_is_the_whole() { + let ok = stack(&entry("ab12", true), None, &BTreeMap::new()); + assert_eq!(ok.state, "ok"); + let starting = stack( + &entry("cd34", false), + Some(Phase::Starting), + &BTreeMap::new(), + ); + assert_eq!(starting.state, "starting"); + let stopping = stack( + &entry("ef56", true), + Some(Phase::Stopping), + &BTreeMap::new(), + ); + assert_eq!(stopping.state, "stopping"); + assert_eq!(overall(std::slice::from_ref(&ok)), "ok"); + assert_eq!(overall(&[ok, stopping]), "starting"); + } + + #[test] + fn a_held_glance_goes_with_its_stream() { + let board = Arc::new(Board::default()); + { + let _held = board.hold("ab12", Some("feat-x")); + board.set("ab12", Some("feat-x"), Glance::default()); + board.set("ab12", None, Glance::default()); + assert_eq!(board.of("ab12").len(), 2); + } + assert_eq!(board.of("ab12").len(), 1); + } +} diff --git a/crates/devstack-hub/src/tray.rs b/crates/devstack-hub/src/tray.rs new file mode 100644 index 00000000..0d6df8b9 --- /dev/null +++ b/crates/devstack-hub/src/tray.rs @@ -0,0 +1,142 @@ +//! The hub starts the tray (ADR-0060 point 2): `devstack tray` in the +//! background when the hub starts, unless it is switched off (`tray.json` +//! beside the hub's state, `DEVSTACK_NO_TRAY`) or there is no desktop. The +//! tray is its own process and outlives the hub; a second one exits. + +use serde::{Deserialize, Serialize}; +use std::path::PathBuf; + +const FILE: &str = "tray.json"; + +#[derive(Debug, Default, Serialize, Deserialize)] +struct Settings { + #[serde(default)] + off: bool, +} + +fn path() -> PathBuf { + crate::state_dir().join(FILE) +} + +/// Switched off with `devstack hub tray off`. +pub fn is_off() -> bool { + std::fs::read(path()) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()) + .is_some_and(|s| s.off) +} + +/// `devstack hub tray on|off`: kept per machine. +pub fn set_off(off: bool) -> Result<(), String> { + let dir = crate::state_dir(); + std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; + let json = serde_json::to_vec_pretty(&Settings { off }).map_err(|e| e.to_string())?; + std::fs::write(path(), json).map_err(|e| format!("{}: {e}", path().display())) +} + +/// `DEVSTACK_NO_TRAY` is set and not `0` (tests, a machine nobody sits at). +pub fn env_off() -> bool { + std::env::var_os("DEVSTACK_NO_TRAY").is_some_and(|v| !v.is_empty() && v != "0") +} + +/// The lock a running tray holds, so a second one exits. +pub fn lock_path() -> PathBuf { + crate::state_dir().join("tray.lock") +} + +/// The running tray's process id, written once it holds the lock. +pub fn pid_path() -> PathBuf { + crate::state_dir().join("tray.pid") +} + +/// Asks the running tray to end (`devstack hub tray off`, `self uninstall`): +/// it looks every two seconds and removes the file when it goes. +pub fn stop_path() -> PathBuf { + crate::state_dir().join("tray.stop") +} + +/// The process id of the tray that runs, if one does. +pub fn running() -> Option { + let pid: u32 = std::fs::read_to_string(pid_path()) + .ok()? + .trim() + .parse() + .ok()?; + let lock = std::fs::OpenOptions::new() + .read(true) + .write(true) + .open(lock_path()) + .ok()?; + match lock.try_lock() { + Err(std::fs::TryLockError::WouldBlock) => devstack_proc::pid_alive(pid).then_some(pid), + _ => None, + } +} + +/// End the running tray, and wait up to `wait` for it to go. Whether none +/// runs now. +pub fn stop(wait: std::time::Duration) -> bool { + if running().is_none() { + return true; + } + if std::fs::write(stop_path(), b"").is_err() { + return false; + } + let t0 = std::time::Instant::now(); + while t0.elapsed() < wait { + if running().is_none() { + return true; + } + std::thread::sleep(std::time::Duration::from_millis(200)); + } + running().is_none() +} + +/// Why the tray does not start with the hub, or `None`. +pub fn why_not() -> Option { + if env_off() { + return Some("switched off (DEVSTACK_NO_TRAY)".into()); + } + if is_off() { + return Some("switched off (`devstack hub tray on` starts it)".into()); + } + devstack_desktop::tray::unavailable() +} + +/// Start `devstack tray` in the background; its output goes to `tray.out`. +pub fn spawn() -> Result<(), String> { + let exe = crate::devstack_exe().map_err(|e| e.to_string())?; + let dir = crate::state_dir(); + std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; + // Appended: a second tray (it exits) must not wipe what the first said. + let out = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(dir.join("tray.out")) + .map_err(|e| e.to_string())?; + let mut cmd = std::process::Command::new(exe); + cmd.arg("tray") + .current_dir(&dir) + .stdin(std::process::Stdio::null()) + .stdout(out.try_clone().map_err(|e| e.to_string())?) + .stderr(out); + let mut child = + devstack_proc::spawn_detached(&mut cmd).map_err(|e| format!("start the tray: {e}"))?; + // A second tray exits at once; a long-lived hub must not keep it as a + // zombie. + std::thread::spawn(move || { + let _ = child.wait(); + }); + Ok(()) +} + +/// At the hub's start: the tray, unless it is off; a failure is logged. +pub(crate) fn start_quietly() { + if let Some(why) = why_not() { + devstack_daemon::diag::info("tray_not_started", serde_json::json!({ "why": why })); + return; + } + if let Err(e) = spawn() { + devstack_daemon::diag::warn("tray_start_failed", serde_json::json!({ "error": e })); + } +} diff --git a/crates/devstack/src/dispatch/hub.rs b/crates/devstack/src/dispatch/hub.rs index 0d055bc3..b1a60703 100644 --- a/crates/devstack/src/dispatch/hub.rs +++ b/crates/devstack/src/dispatch/hub.rs @@ -1,7 +1,7 @@ //! The hub and the dashboard (ADR-0021): `devstack ui`, `devstack hub`, and //! the `devstack://` links the system hands over. -use crate::{Cmd, HubAction, NotifyAction, hubcmd, integration}; +use crate::{Cmd, HubAction, NotifyAction, TrayAction, hubcmd, integration, tray}; use anyhow::Result; use std::path::Path; @@ -15,6 +15,7 @@ pub(crate) fn run(file: &Path, cmd: Cmd) -> Result<()> { } => hubcmd::ui(file, lane.as_deref(), link, print, browser.as_deref()), Cmd::Hub { action } => hub(action), Cmd::OpenUrl { url } => integration::open_url(&url), + Cmd::Tray => tray::run(), _ => super::misrouted(), } } @@ -49,5 +50,13 @@ fn hub(action: Option) -> Result<()> { Some(NotifyAction::Off { kinds }) => hubcmd::notify_set(&kinds, false), Some(NotifyAction::Test) => hubcmd::notify_test(), }, + Some(HubAction::Tray { action }) => match action { + None => { + println!("{}", hubcmd::tray_text()); + Ok(()) + } + Some(TrayAction::On) => hubcmd::tray_on(), + Some(TrayAction::Off) => hubcmd::tray_off(), + }, } } diff --git a/crates/devstack/src/hubcmd.rs b/crates/devstack/src/hubcmd.rs index 9dc3d3a1..4c3587c0 100644 --- a/crates/devstack/src/hubcmd.rs +++ b/crates/devstack/src/hubcmd.rs @@ -491,6 +491,43 @@ pub fn stop() -> Result<()> { Ok(()) } +/// `devstack hub tray`: whether the tray runs, and why not. +pub fn tray_text() -> String { + use devstack_hub::tray; + match (tray::running(), tray::why_not()) { + (Some(pid), _) => format!("tray running (pid {pid})"), + (None, Some(why)) => format!("tray not running: {why}"), + (None, None) => { + "tray not running; it starts with the hub (`devstack hub tray on` starts it now)".into() + } + } +} + +/// `devstack hub tray on`: with the hub from now on, and now. +pub fn tray_on() -> Result<()> { + use devstack_hub::tray; + tray::set_off(false).map_err(|e| anyhow!(e))?; + if tray::running().is_none() { + if let Some(why) = tray::why_not() { + bail!("the tray cannot start: {why}"); + } + tray::spawn().map_err(|e| anyhow!(e))?; + } + println!("tray on: it starts with the hub"); + Ok(()) +} + +/// `devstack hub tray off`: ended now, and not started with the hub. +pub fn tray_off() -> Result<()> { + use devstack_hub::tray; + tray::set_off(true).map_err(|e| anyhow!(e))?; + if !tray::stop(Duration::from_secs(5)) { + bail!("the tray did not end; it ends within a few seconds, or end it yourself"); + } + println!("tray off: `devstack hub tray on` brings it back"); + Ok(()) +} + /// Start the hub alongside a stack (`devstack up`), unless `DEVSTACK_NO_HUB` /// is set. A failure is a note, never a reason to fail `up`. pub fn ensure_quietly() { diff --git a/crates/devstack/src/main.rs b/crates/devstack/src/main.rs index fc796563..8fe31518 100644 --- a/crates/devstack/src/main.rs +++ b/crates/devstack/src/main.rs @@ -16,6 +16,7 @@ mod integration; mod mcp; mod poolcmd; mod selfcmd; +mod tray; use devstack_skills as skills; mod topcmd; mod update; @@ -219,6 +220,9 @@ enum Cmd { }, /// MCP server on stdio for coding agents; a client of the daemon like the CLI. Mcp, + /// The tray icon: the stacks' state, the dashboard, start and stop + /// (ADR-0060). The hub starts it; `devstack hub tray off` keeps it off. + Tray, /// Open the dashboard: starts the hub if needed and pairs the browser /// (ADR-0021). In a repository it opens on this stack, in a worktree on /// its lane. @@ -595,6 +599,20 @@ enum HubAction { #[command(subcommand)] action: Option, }, + /// The tray icon the hub starts (ADR-0060); without an action, whether + /// it runs. + Tray { + #[command(subcommand)] + action: Option, + }, +} + +#[derive(Subcommand)] +enum TrayAction { + /// Start the tray now and with the hub from now on. + On, + /// End the tray, and do not start it with the hub. + Off, } #[derive(Subcommand)] @@ -701,7 +719,7 @@ fn main() -> Result<()> { cmd @ (Cmd::Node { .. } | Cmd::Join { .. } | Cmd::Pool { .. } | Cmd::Open { .. }) => { dispatch::pool::run(&file, cmd) } - cmd @ (Cmd::Ui { .. } | Cmd::Hub { .. } | Cmd::OpenUrl { .. }) => { + cmd @ (Cmd::Ui { .. } | Cmd::Hub { .. } | Cmd::OpenUrl { .. } | Cmd::Tray) => { dispatch::hub::run(&file, cmd) } cmd @ (Cmd::Update { .. } | Cmd::Myself { .. }) => dispatch::myself::run(cmd), diff --git a/crates/devstack/src/selfcmd.rs b/crates/devstack/src/selfcmd.rs index e22d5de7..ae8ee27c 100644 --- a/crates/devstack/src/selfcmd.rs +++ b/crates/devstack/src/selfcmd.rs @@ -1,7 +1,7 @@ //! `devstack self uninstall`: take devstack off this machine for this user. //! //! Removes what the installer and devstack itself put into the user's profile: -//! the hub (stopped), its autostart (on macOS the LaunchAgent) and +//! the hub and its tray (stopped), its autostart (on macOS the LaunchAgent) and //! `devstack://` link, the name its notifications show under (Windows, //! ADR-0045), the per-user state (token, registry of stacks, hub log and //! sessions), the PATH entry and the installed binary. A binary winget or @@ -41,14 +41,15 @@ fn pool_state(root: &Path) -> (Option, Vec) { (coordinator, memberships) } -/// Other devstack processes of this user, besides this one and the hub -/// (which is stopped): a node agent, a coordinator, an MCP server. They run -/// the binary that is to go, and a running one cannot be deleted (Windows). -fn other_devstack_processes(hub: Option) -> Vec { +/// Other devstack processes of this user, besides this one, the hub and +/// the tray (both are stopped): a node agent, a coordinator, an MCP server. +/// They run the binary that is to go, and a running one cannot be deleted +/// (Windows). +fn other_devstack_processes(hub: Option, tray: Option) -> Vec { let me = std::process::id(); devstack_desktop::devstack_pids() .into_iter() - .filter(|p| *p != me && Some(*p) != hub) + .filter(|p| *p != me && Some(*p) != hub && Some(*p) != tray) .collect() } @@ -70,7 +71,10 @@ pub fn uninstall(yes: bool, with_coordinator: bool) -> Result<()> { list.join("\n") ); } - let others = other_devstack_processes(devstack_hub::read_info().map(|h| h.pid)); + let others = other_devstack_processes( + devstack_hub::read_info().map(|h| h.pid), + devstack_hub::tray::running(), + ); if !others.is_empty() { let list: Vec = others.iter().map(u32::to_string).collect(); bail!( @@ -96,9 +100,9 @@ pub fn uninstall(yes: bool, with_coordinator: bool) -> Result<()> { let brew = devstack_desktop::homebrew_prefix(&exe).is_some(); println!("devstack self uninstall removes:"); if devstack_desktop::LINK_UNAVAILABLE.is_some() { - println!(" - the dashboard hub and its start at logon"); + println!(" - the dashboard hub, its tray and its start at logon"); } else { - println!(" - the dashboard hub, its start at logon and the devstack:// link"); + println!(" - the dashboard hub, its tray, its start at logon and the devstack:// link"); } println!(" - {} (token, list of stacks, hub log)", root.display()); if !memberships.is_empty() { @@ -143,6 +147,7 @@ pub fn uninstall(yes: bool, with_coordinator: bool) -> Result<()> { return Ok(()); } + let _ = devstack_hub::tray::stop(std::time::Duration::from_secs(5)); let _ = crate::hubcmd::stop(); // The hub holds its log and lock open until it has exited (2 s grace). let port = devstack_hub::port(); diff --git a/crates/devstack/src/tray.rs b/crates/devstack/src/tray.rs new file mode 100644 index 00000000..dbcdd64c --- /dev/null +++ b/crates/devstack/src/tray.rs @@ -0,0 +1,499 @@ +//! `devstack tray` (ADR-0060): the tray icon, a client of the hub. The main +//! thread shows it (`devstack_desktop::tray`); a worker reads `/hub/summary` +//! every two seconds, makes the menu from it, and does what is chosen, each +//! action a request to the hub on a thread of its own. It works out no state +//! itself and never talks to a daemon. +//! +//! One per user: the lock beside the hub's state. The hub starts it; it +//! ends when chosen in its menu, when switched off (`devstack hub tray off`, +//! `tray.json`) or asked to (`tray.stop`), and hands over to the tray of a +//! newer devstack the hub runs. + +use anyhow::{Result, anyhow, bail}; +use devstack_desktop::tray::{Entry, Menu, QUIT, Tone, one_line}; +use devstack_hub::{Listener, tray as hubtray}; +use serde_json::Value; +use std::fs::{File, OpenOptions}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +const REFRESH: Duration = Duration::from_secs(2); +/// How long an action's failure stays in the menu. +const SHOW_ERROR: Duration = Duration::from_secs(60); +/// Set for the tray a tray started for the hub's newer devstack, to that +/// version: if it is not that version either, it does not hand over again. +const HANDED_OVER: &str = "DEVSTACK_TRAY_HANDED_OVER"; + +/// What the hub says, or why it says nothing. +#[derive(Debug, Clone, PartialEq)] +enum Hub { + Running(Value), + /// The hub answers, but the summary could not be read. + Unreadable(String), + Stopped, + /// Another program answers on the hub's port. + Foreign, +} + +fn agent() -> ureq::Agent { + ureq::Agent::config_builder() + .timeout_global(Some(Duration::from_secs(5))) + .http_status_as_error(false) + .build() + .new_agent() +} + +fn token() -> Result { + devstack_daemon::token::load() + .filter(|t| !t.is_empty()) + .ok_or_else(|| anyhow!("no token yet")) +} + +fn fetch() -> Hub { + let port = devstack_hub::port(); + match devstack_hub::who_answers(port) { + Listener::Nothing => return Hub::Stopped, + Listener::Foreign => return Hub::Foreign, + Listener::Ours => {} + } + let read = || -> Result { + let mut r = agent() + .get(&format!("http://127.0.0.1:{port}/hub/summary")) + .header("Authorization", &format!("Bearer {}", token()?)) + .call()?; + let text = r.body_mut().read_to_string()?; + if r.status() != 200 { + bail!("the hub answered {}", r.status()); + } + Ok(serde_json::from_str(&text)?) + }; + match read() { + Ok(v) => Hub::Running(v), + Err(e) => Hub::Unreadable(e.to_string()), + } +} + +/// `POST` to the hub, as the dashboard does. +fn post(path: &str, body: Option) -> Result<()> { + let port = devstack_hub::port(); + if devstack_hub::who_answers(port) != Listener::Ours { + bail!("the hub does not run"); + } + let req = agent() + .post(&format!("http://127.0.0.1:{port}{path}")) + .header("Authorization", &format!("Bearer {}", token()?)); + let mut r = match body { + Some(b) => req + .header("Content-Type", "application/json") + .send(b.to_string())?, + None => req.send_empty()?, + }; + if !r.status().is_success() { + let text = r.body_mut().read_to_string().unwrap_or_default(); + let v: Value = serde_json::from_str(&text).unwrap_or(Value::Null); + bail!("{}", v["error"].as_str().unwrap_or(&text)); + } + Ok(()) +} + +fn action(label: &str, id: String, enabled: bool) -> Entry { + Entry::Action { + label: label.into(), + id, + enabled, + } +} + +fn plural(n: u64, one: &str) -> String { + if n == 1 { + format!("1 {one}") + } else { + format!("{n} {one}s") + } +} + +/// `/#/s/?lane=`, and with a service its page. +fn route(stack: &str, lane: Option<&str>, service: Option<&str>) -> String { + let enc = crate::client::enc; + let mut r = format!("/#/s/{}", enc(stack)); + if let Some(s) = service { + r.push_str(&format!("/services/{}", enc(s))); + } + r.push_str(&format!("?lane={}", enc(lane.unwrap_or("")))); + r +} + +/// The tray's menu for what the hub said, and an action's failure. +fn menu(hub: &Hub, error: Option<&str>) -> Menu { + let mut entries = Vec::new(); + let (tone, head) = match hub { + Hub::Stopped => (Tone::Idle, "The dashboard hub does not run".to_string()), + Hub::Foreign => ( + Tone::Attention, + format!("Port {} is taken by another program", devstack_hub::port()), + ), + Hub::Unreadable(e) => (Tone::Attention, format!("The hub does not answer: {e}")), + Hub::Running(v) => { + let stacks = v["stacks"].as_array().map(Vec::as_slice).unwrap_or(&[]); + let running = stacks.iter().filter(|s| s["running"] == true).count() as u64; + let attention: u64 = stacks + .iter() + .map(|s| s["attention"].as_array().map_or(0, |a| a.len() as u64)) + .sum(); + match v["state"].as_str() { + Some("attention") => ( + Tone::Attention, + if attention == 1 { + "1 thing needs attention".to_string() + } else { + format!("{attention} things need attention") + }, + ), + Some("starting") => (Tone::Busy, "A stack starts or stops".to_string()), + Some("ok") => (Tone::Ok, format!("{} running", plural(running, "stack"))), + _ => (Tone::Idle, "No stack runs".to_string()), + } + } + }; + entries.push(Entry::Label(head.clone())); + if let Some(e) = error { + entries.push(Entry::Label(format!("⚠ {}", one_line(e, 100)))); + } + let hub_runs = matches!(hub, Hub::Running(_)); + entries.push(action("Open Dashboard", "dashboard".into(), hub_runs)); + entries.push(Entry::Separator); + if let Hub::Running(v) = hub { + let stacks = v["stacks"].as_array().map(Vec::as_slice).unwrap_or(&[]); + if stacks.is_empty() { + entries.push(Entry::Label( + "No stacks yet: `devstack up` in a repository adds one".into(), + )); + } + for s in stacks { + entries.push(stack_menu(s)); + } + if !stacks.is_empty() { + entries.push(Entry::Separator); + } + } + if *hub == Hub::Stopped { + entries.push(action("Start Dashboard Hub", "hub-start".into(), true)); + entries.push(Entry::Separator); + } + entries.push(action("Quit Tray", QUIT.into(), true)); + Menu { + tone, + tooltip: format!("devstack: {head}"), + entries, + } +} + +fn stack_menu(s: &Value) -> Entry { + let id = s["id"].as_str().unwrap_or(""); + let name = one_line(s["name"].as_str().unwrap_or(id), 60); + let state = s["state"].as_str().unwrap_or(""); + let running = s["running"] == true; + let (mark, said) = match state { + "ok" => ("●", "running"), + "attention" => ("▲", "needs attention"), + "starting" => ("◌", "starting"), + "stopping" => ("◌", "stopping"), + _ => ("○", "stopped"), + }; + let mut children = Vec::new(); + if running { + children.push(Entry::Label(format!( + "Services: {} of {} ready", + s["ready"].as_u64().unwrap_or(0), + s["total"].as_u64().unwrap_or(0) + ))); + let lanes = s["lanes"].as_u64().unwrap_or(0); + if lanes > 0 { + children.push(Entry::Label(format!("{} started", plural(lanes, "lane")))); + } + } + let attention = s["attention"].as_array().map(Vec::as_slice).unwrap_or(&[]); + if !attention.is_empty() { + children.push(Entry::Separator); + } + for a in attention { + let lane = a["lane"].as_str(); + let service = a["service"].as_str(); + let mut label = a["text"].as_str().unwrap_or("needs attention").to_string(); + if let Some(l) = lane { + label.push_str(&format!(" (lane {l})")); + } + children.push(action( + &one_line(&label, 80), + format!("open:{}", route(id, lane, service)), + true, + )); + if let Some(d) = a["detail"].as_str().filter(|d| !d.is_empty()) { + children.push(Entry::Label(format!(" {}", one_line(d, 80)))); + } + } + children.push(Entry::Separator); + children.push(action( + "Open in Dashboard", + format!("open:{}", route(id, None, None)), + true, + )); + match state { + "starting" | "stopping" => {} + _ if running => children.push(action("Stop", format!("stop:{id}"), true)), + _ => children.push(action("Start", format!("start:{id}"), true)), + } + children.push(action("Open Folder", format!("folder:{id}"), true)); + Entry::Submenu { + label: format!("{mark} {name}: {said}"), + entries: children, + } +} + +/// Do what `id` says; `Err` with what to show in the menu. +fn perform(id: &str, hub: &Hub) -> Result<()> { + let (kind, arg) = id.split_once(':').unwrap_or((id, "")); + match kind { + "dashboard" => crate::hubcmd::open_dashboard("/#/"), + "open" if arg.starts_with("/#/") => crate::hubcmd::open_dashboard(arg), + "hub-start" => devstack_hub::ensure_running() + .map(|_| ()) + .map_err(|e| anyhow!(e)), + "start" => post(&format!("/hub/stacks/{}/up", crate::client::enc(arg)), None), + // As the dashboard's Stop: the main tree's services and containers; + // lanes that run keep theirs (ADR-0060 point 5). + "stop" => post( + &format!("/hub/stacks/{}/down?infra=true", crate::client::enc(arg)), + None, + ), + "folder" => { + let Hub::Running(v) = hub else { + bail!("the hub does not run"); + }; + let repo = v["stacks"] + .as_array() + .into_iter() + .flatten() + .find(|s| s["id"] == arg) + .and_then(|s| s["repo"].as_str()) + .ok_or_else(|| anyhow!("no such stack"))?; + post( + "/hub/open", + Some(serde_json::json!({ "stack": arg, "path": repo, "with": "files" })), + ) + } + _ => Ok(()), + } +} + +/// Why the worker ended. +#[derive(Debug, PartialEq)] +enum End { + /// Quit, switched off, asked to stop, or the tray is gone. + Done, + /// The hub runs another devstack: its tray takes over. + HandOver(String), +} + +fn worker( + actions: Receiver, + refresh: Sender, + updates: Sender, + done: Arc, +) -> End { + let error: Arc>> = Arc::default(); + let mut last = None; + loop { + if done.load(Ordering::Acquire) || hubtray::is_off() || hubtray::stop_path().exists() { + return End::Done; + } + let hub = fetch(); + if let Hub::Running(v) = &hub + && let Some(theirs) = v["version"].as_str() + && theirs != devstack_hub::VERSION + && std::env::var(HANDED_OVER).ok().as_deref() != Some(theirs) + { + return End::HandOver(theirs.to_string()); + } + let shown = { + let mut e = error.lock().unwrap(); + if e.as_ref().is_some_and(|(_, at)| at.elapsed() > SHOW_ERROR) { + *e = None; + } + e.as_ref().map(|(text, _)| text.clone()) + }; + let next = menu(&hub, shown.as_deref()); + if last.as_ref() != Some(&next) { + if updates.send(next.clone()).is_err() { + return End::Done; + } + last = Some(next); + } + match actions.recv_timeout(REFRESH) { + Ok(id) if id == QUIT => return End::Done, + Ok(id) if id == "refresh" => {} + Ok(id) => { + let (hub, error, refresh) = (hub.clone(), error.clone(), refresh.clone()); + std::thread::spawn(move || { + let result = perform(&id, &hub); + *error.lock().unwrap() = result.err().map(|e| { + eprintln!("tray: {id}: {e:#}"); + (format!("{e:#}"), Instant::now()) + }); + let _ = refresh.send("refresh".into()); + }); + } + Err(RecvTimeoutError::Timeout) => {} + Err(RecvTimeoutError::Disconnected) => return End::Done, + } + } +} + +/// The lock that makes this the only tray of this user. +fn lock() -> Result> { + let path = hubtray::lock_path(); + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + let file = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(&path)?; + match file.try_lock() { + Ok(()) => Ok(Some(file)), + Err(std::fs::TryLockError::WouldBlock) => Ok(None), + Err(e) => bail!("{}: {e}", path.display()), + } +} + +/// `devstack tray`: the tray, until it is quit. +pub fn run() -> Result<()> { + if let Some(why) = devstack_desktop::tray::unavailable() { + bail!("no tray here: {why}"); + } + let Some(lock) = lock()? else { + println!("the tray runs already"); + return Ok(()); + }; + // A request to stop from before this tray is not for it. + let _ = std::fs::remove_file(hubtray::stop_path()); + std::fs::write(hubtray::pid_path(), std::process::id().to_string())?; + + let (actions_tx, actions_rx) = mpsc::channel(); + let (updates_tx, updates_rx) = mpsc::channel(); + let done = Arc::new(AtomicBool::new(false)); + let refresh = actions_tx.clone(); + let worker = { + let done = done.clone(); + std::thread::Builder::new() + .name("devstack-tray".into()) + .spawn(move || worker(actions_rx, refresh, updates_tx, done))? + }; + let initial = menu(&Hub::Stopped, None); + let shown = devstack_desktop::tray::run( + Menu { + tooltip: "devstack".into(), + entries: vec![Entry::Label("Asking the hub…".into())], + ..initial + }, + updates_rx, + actions_tx.clone(), + ); + done.store(true, Ordering::Release); + let _ = actions_tx.send(QUIT.into()); + let end = worker + .join() + .map_err(|_| anyhow!("the tray's worker panicked"))?; + let _ = std::fs::remove_file(hubtray::pid_path()); + let _ = std::fs::remove_file(hubtray::stop_path()); + drop(lock); + shown.map_err(|e| anyhow!(e))?; + if let End::HandOver(version) = end { + let exe = std::env::current_exe().map(|e| devstack_desktop::stable_exe(&e))?; + let mut cmd = std::process::Command::new(exe); + cmd.arg("tray") + .env(HANDED_OVER, &version) + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()); + devstack_proc::spawn_detached(&mut cmd)?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn find<'a>(entries: &'a [Entry], id: &str) -> Option<&'a Entry> { + entries.iter().find_map(|e| match e { + Entry::Action { id: found, .. } if found == id => Some(e), + Entry::Submenu { entries, .. } => find(entries, id), + _ => None, + }) + } + + fn summary() -> Value { + json!({ + "state": "attention", + "version": devstack_hub::VERSION, + "stacks": [ + { "id": "ab12", "name": "shop", "repo": "/src/shop", "running": true, + "state": "attention", "ready": 2, "total": 3, "lanes": 1, + "attention": [{ "lane": "feat x", "service": "api", + "text": "api: build held for promote", "detail": "schema changed" }] }, + { "id": "cd34", "name": "blog", "repo": "/src/blog", "running": false, + "state": "stopped", "ready": 0, "total": 0, "lanes": 0, "attention": [] } + ] + }) + } + + #[test] + fn the_menu_follows_the_hubs_summary() { + let m = menu(&Hub::Running(summary()), None); + assert_eq!(m.tone, Tone::Attention); + assert_eq!(m.tooltip, "devstack: 1 thing needs attention"); + assert!(find(&m.entries, "stop:ab12").is_some()); + assert!(find(&m.entries, "start:ab12").is_none()); + assert!(find(&m.entries, "start:cd34").is_some()); + assert!(find(&m.entries, "open:/#/s/ab12/services/api?lane=feat%20x").is_some()); + assert!(find(&m.entries, "hub-start").is_none()); + assert!(find(&m.entries, QUIT).is_some()); + } + + #[test] + fn a_stopped_hub_can_be_started_and_nothing_else() { + let m = menu(&Hub::Stopped, None); + assert_eq!(m.tone, Tone::Idle); + assert!(find(&m.entries, "hub-start").is_some()); + assert!(matches!( + find(&m.entries, "dashboard"), + Some(Entry::Action { enabled: false, .. }) + )); + let m = menu(&Hub::Foreign, Some("boom")); + assert_eq!(m.tone, Tone::Attention); + assert!(find(&m.entries, "hub-start").is_none()); + assert!(m.entries.contains(&Entry::Label("⚠ boom".into()))); + } + + #[test] + fn a_stack_starting_or_stopping_offers_neither() { + let mut v = summary(); + v["stacks"][1]["state"] = json!("starting"); + let m = menu(&Hub::Running(v), None); + assert!(find(&m.entries, "start:cd34").is_none()); + assert!(find(&m.entries, "stop:cd34").is_none()); + } + + #[test] + fn only_dashboard_routes_are_opened() { + assert!(perform("open:https://example.invalid", &Hub::Stopped).is_ok()); + assert!(perform("nonsense", &Hub::Stopped).is_ok()); + assert!(perform("folder:ab12", &Hub::Stopped).is_err()); + } +} diff --git a/crates/devstack/tests/hub.rs b/crates/devstack/tests/hub.rs index e8f6bcb5..a5eaab3f 100644 --- a/crates/devstack/tests/hub.rs +++ b/crates/devstack/tests/hub.rs @@ -49,6 +49,8 @@ fn start_env(home: tempfile::TempDir, port: u16, extra: &[(&str, std::ffi::OsStr .env("DEVSTACK_NO_UPDATE_CHECK", "1") // What would notify is logged; nothing shows on the desktop. .env("DEVSTACK_NO_NOTIFY", "1") + // No tray icon on the desktop of whoever runs the tests. + .env("DEVSTACK_NO_TRAY", "1") .stdout(Stdio::null()) .stderr(Stdio::null()) .spawn() @@ -425,6 +427,7 @@ fn a_hub_answers_once_its_port_takes_connections() { .env("LOCALAPPDATA", h.home.path()) .env("XDG_STATE_HOME", h.home.path()) .env("DEVSTACK_NO_UPDATE_CHECK", "1") + .env("DEVSTACK_NO_TRAY", "1") .output() .unwrap(); let text = String::from_utf8_lossy(&out.stdout); @@ -443,6 +446,7 @@ fn the_token_goes_only_to_this_users_hub() { .env("LOCALAPPDATA", h.home.path()) .env("XDG_STATE_HOME", h.home.path()) .env("DEVSTACK_NO_UPDATE_CHECK", "1") + .env("DEVSTACK_NO_TRAY", "1") .output() .unwrap() }; @@ -822,6 +826,25 @@ fn a_failed_start_is_reported() { if let Some(why) = entry["start_error"].as_str() { assert!(why.contains("99.0.0"), "{why}"); assert_eq!(entry["running"], false); + // The tray's summary says it too (ADR-0060), to the token. + let bearer = format!("Authorization: Bearer {}\r\n", token(&h)); + let (s, _, body) = get(p, "/hub/summary", &bearer); + assert_eq!(s, 200, "{body}"); + let v: serde_json::Value = serde_json::from_str(&body).unwrap(); + assert_eq!(v["state"], "attention", "{body}"); + let stack = &v["stacks"][0]; + assert_eq!( + (&stack["id"], &stack["state"]), + (&id.as_str().into(), &"attention".into()) + ); + assert_eq!(stack["attention"][0]["text"], "the start failed"); + assert!( + stack["attention"][0]["detail"] + .as_str() + .unwrap() + .contains("99.0.0"), + "{body}" + ); break; } assert!( diff --git a/docs/adr/0018-dashboard-is-a-browser-page.md b/docs/adr/0018-dashboard-is-a-browser-page.md index 2fd3c687..bfa30238 100644 --- a/docs/adr/0018-dashboard-is-a-browser-page.md +++ b/docs/adr/0018-dashboard-is-a-browser-page.md @@ -1,6 +1,6 @@ # ADR-0018: The dashboard is a browser page; native integration is a tray in the daemon, not a desktop wrapper -- **Status:** Accepted (2026-10-14); who serves the dashboard amended by [ADR-0021](0021-a-hub-serves-the-dashboard.md) (the hub); the tray is not built yet; point 2's notifications come from the hub, without a tray ([ADR-0045](0045-the-hub-notifies-the-desktop.md)) +- **Status:** Accepted (2026-10-14); who serves the dashboard amended by [ADR-0021](0021-a-hub-serves-the-dashboard.md) (the hub); point 2's notifications come from the hub, without a tray ([ADR-0045](0045-the-hub-notifies-the-desktop.md)); point 2's tray is a client process the hub starts ([ADR-0060](0060-the-tray-is-a-client-of-the-hub.md)) - **Date:** 2026-10-14 - **Deciders:** project owner - **Related:** [ADR-0006](0006-dashboard-vue-same-origin.md), [ADR-0007](0007-one-http-api-is-the-control-surface.md), plan §6 @@ -84,3 +84,9 @@ no `--no-tray` yet (plan §13). for the tray: the hub sends them ([ADR-0045](0045-the-hub-notifies-the-desktop.md)), on Windows as a toast and on Linux over the session bus, and a tray, when it comes, adds the icon only. + +*Amended 2026-10-23.* Point 2's tray is built, as a process of its own +that the hub starts, `devstack tray`, on Windows, Linux and macOS +([ADR-0060](0060-the-tray-is-a-client-of-the-hub.md)): a client of the hub, +not part of the daemon. It is switched off with `devstack hub tray off`, +not `--no-tray`, and does not promote candidates. diff --git a/docs/adr/0021-a-hub-serves-the-dashboard.md b/docs/adr/0021-a-hub-serves-the-dashboard.md index 37a8a587..d26bad6c 100644 --- a/docs/adr/0021-a-hub-serves-the-dashboard.md +++ b/docs/adr/0021-a-hub-serves-the-dashboard.md @@ -111,7 +111,9 @@ answered in 2 ms over WebSockets, and not within 8 s once each window held one version. ADR-0018 stands otherwise: a browser page, no desktop wrapper, a tray later. -The tray belongs to the hub, which is the long-lived process now. +The tray belongs to the hub, which is the long-lived process now. (Amended +2026-10-23 by [ADR-0060](0060-the-tray-is-a-client-of-the-hub.md): the hub +starts the tray as a process of its own and tells it what to show.) ## Alternatives considered diff --git a/docs/adr/0060-the-tray-is-a-client-of-the-hub.md b/docs/adr/0060-the-tray-is-a-client-of-the-hub.md new file mode 100644 index 00000000..905c1948 --- /dev/null +++ b/docs/adr/0060-the-tray-is-a-client-of-the-hub.md @@ -0,0 +1,123 @@ +# ADR-0060: The tray is a client of the hub, a process of its own, on every desktop + +- **Status:** Accepted (2026-10-23) +- **Date:** 2026-10-23 +- **Deciders:** project owner +- **Related:** [#1](https://github.com/nuetzliches/devstack/issues/1) (the tray), [#248](https://github.com/nuetzliches/devstack/pull/248) (a macOS menu bar client, which this replaces), [ADR-0007](0007-one-http-api-is-the-control-surface.md), [ADR-0018](0018-dashboard-is-a-browser-page.md) (point 2 amended here), [ADR-0021](0021-a-hub-serves-the-dashboard.md) (where the tray lives, amended here), [ADR-0045](0045-the-hub-notifies-the-desktop.md), [ADR-0054](0054-macos-is-a-developer-platform-in-preview.md) + +## Context + +ADR-0018 point 2 put a tray icon in the daemon: the stack's state as green, +yellow or red, a menu to open the dashboard and stop the stack. ADR-0021 +moved it to the hub, the one long-lived process per user. ADR-0045 gave the +notifications to the hub without a tray, because the usual Rust tray crates +link GTK and AppIndicator, which the static Linux binary cannot carry (#1). +What is left of the tray is the icon: one glance that says whether +something needs attention, and a way to the dashboard and to starting or +stopping a stack without a terminal. + +A contribution for macOS (#248) built that as a separate process, +`devstack menubar`, and showed why it is one. AppKit's status item must +live on the process's main thread, and the hub's main thread runs its +server. It also showed what goes wrong when the client works out a stack's +state for itself: it read each daemon's `/v1/stack` every five seconds and +judged services, containers, exit codes and profile skips on its own, a +third reading of the state beside the dashboard's and the notifications', +which would drift from them. + +The pieces a tray needs exist on every platform without a GUI runtime: + +- Windows: `Shell_NotifyIconW` and a popup menu, in `windows-sys`. +- Linux: `org.kde.StatusNotifierItem` and `com.canonical.dbusmenu` on the + session bus, in pure Rust over `zbus` (already used for ADR-0045), so the + binary stays static. KDE, Xfce, Cinnamon, and GNOME with the AppIndicator + extension (Ubuntu's default) show it. +- macOS: `NSStatusItem` through `objc2`, linked on macOS only. + +## Decision + +1. **The tray is its own process, `devstack tray`, on every platform.** One + per user (a lock beside the hub's state); a second one exits. It is a + client of the hub as the dashboard and the CLI are (ADR-0007): it never + talks to a daemon, starts a stack itself or works out a state. Its main + thread runs the platform's tray; a worker does the requests. +2. **The hub starts it.** When the hub starts it runs `devstack tray` in the + background, unless the tray is switched off (`devstack hub tray off`, + kept per machine as `tray.json` beside the hub's state, or + `DEVSTACK_NO_TRAY`) or there is no desktop (Linux: no session bus). So it + comes at logon with the hub (ADR-0021), with no autostart of its own. The + tray outlives a hub that stops: it then says so and offers to start it. + A tray of an older devstack than the hub's starts the new one and exits. + *Quit* in its menu ends it until the hub's next start; `devstack hub tray + off` ends it for good, `on` starts it again. +3. **The hub says what the tray shows: `GET /hub/summary`.** Per registered + stack whether it runs, a start or stop under way, its services running of + all, its started lanes, and what needs attention; and one state over all + of them: `attention`, `starting`, `ok` (something runs) or `idle`. What + needs attention is what ADR-0045 notifies, read from the same streams the + hub follows already: a service that failed (not one the user stopped, not + one held back by another's failure), a candidate held for `promote` or + whose build failed, in the main tree and in every started lane; and a + failed start from the dashboard. Containers are the dashboard's: the + daemon's stream carries their state only in its snapshot. +4. **The icon is the dashboard's mark, in the state's colour:** green when + something runs and nothing needs attention, amber while a stack starts or + stops, red when something needs attention, grey when nothing runs. On + macOS it is a template image, so it follows the menu bar's light and + dark, tinted orange or red for those two states and plain otherwise, as + menu bar icons are. The tooltip says the same in words. +5. **The menu:** the overall state; *Open Dashboard*; per stack a submenu + with its state, what needs attention (a click opens the dashboard on that + service), *Open in Dashboard*, *Start* or *Stop*, *Open Folder*; *Start + Hub* while the hub does not run; *Quit*. Every action is a request to the + hub: `POST /hub/stacks/{id}/up`, `…/down` (as the dashboard's Stop: + lanes keep running), `POST /hub/open` with `files`, a paired browser as + `devstack ui` opens it. Nothing the menu does stops the hub or a lane. +6. **The model is the same everywhere, the drawing is per platform.** The + menu is a tree of labels, actions, separators and submenus with an icon + state and a tooltip, made once in the CLI; `devstack-desktop` shows it + with one module per operating system (ADR-0054 point 6). + +ADR-0018 point 2 is amended: the tray is a client process the hub starts, +not part of the daemon or the hub; it is on by default and switched off +with `devstack hub tray off` instead of `--no-tray`; it does not promote +candidates (the dashboard does, where the diff is shown). ADR-0021's "the +tray belongs to the hub" now means the hub starts it and tells it what to +show. + +## Alternatives considered + +- **The tray inside the hub (ADR-0021 as written).** One process less, but + on macOS the hub's main thread would have to become AppKit's and its + server move to another thread, and a hub that restarts for an update + takes the icon with it. On Windows and Linux it would work; one model for + all three is simpler. +- **A macOS-only menu bar client (#248).** The same need exists on Windows + first (#1), and its own reading of every daemon's state would differ from + the dashboard's. +- **Its own autostart at logon.** A second entry to register and remove + per platform, for a process that is useless without the hub. +- **A tray crate (`tray-icon`, `ksni`).** `tray-icon` links GTK on Linux; + `ksni` would bring a second `zbus` version. The three platform calls are + small. +- **The tray following `/hub/events` instead of polling `/hub/summary`.** + The summary is cheap and local; a poll every two seconds keeps the client + simple and survives a hub restart without reconnect logic. + +## Consequences + +- A user who never opens a terminal sees whether their stacks run, and + starts one, from the icon. +- GNOME without the AppIndicator extension shows no icon: the tray runs and + says nothing. Notifications (ADR-0045) do not depend on it. +- macOS gets the icon without an app bundle: as in #248, the process makes + itself an accessory application, so it has no Dock icon. + +## Enforced by + +- `crates/devstack-desktop/src/tray/`: the menu model, the icon, and + `windows.rs`, `linux.rs`, `macos.rs`. +- `crates/devstack/src/tray.rs`: `devstack tray`, the menu from + `/hub/summary` and its actions. +- `crates/devstack-hub/src/summary.rs`: `GET /hub/summary`; `tray.rs`: the + start at the hub's start and `tray.json`. diff --git a/docs/adr/README.md b/docs/adr/README.md index 684d06d8..6ffec621 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -66,10 +66,10 @@ stay. | [0015](0015-devstack-is-optional.md) | devstack accelerates a stack, it is never required to run one | Accepted | | [0016](0016-a-daemon-restart-is-a-clean-restart.md) | A daemon restart is a clean restart from the last promoted artifacts | Accepted | | [0017](0017-stack-file-is-toml.md) | The stack file is TOML, without profiles in version 1 | Accepted, amended 2026-10-20 (ADR-0041's profiles are not the environments ruled out) | -| [0018](0018-dashboard-is-a-browser-page.md) | The dashboard is a browser page; native integration is a tray in the daemon, not a desktop wrapper | Accepted; who serves it amended by ADR-0021; the tray is not built; notifications from the hub by ADR-0045 | +| [0018](0018-dashboard-is-a-browser-page.md) | The dashboard is a browser page; native integration is a tray in the daemon, not a desktop wrapper | Accepted; who serves it amended by ADR-0021; notifications from the hub by ADR-0045; the tray a client process the hub starts by ADR-0060 | | [0019](0019-control-api-security.md) | The control API trusts the user's own processes, never a web page | Accepted, amended (own page for reads too; the hub proves itself; IPv4 loopback and `DEVSTACK_LISTEN`; the cookie is the hub's, no `token rotate`) | | [0020](0020-builds-share-one-long-lived-build-job.md) | Builds share one long-lived build job; a cancel ends only the cancelled build's tree | Accepted | -| [0021](0021-a-hub-serves-the-dashboard.md) | A hub on a fixed port serves the dashboard for every stack | Accepted, amended (streams over WebSocket; the pool area polls) | +| [0021](0021-a-hub-serves-the-dashboard.md) | A hub on a fixed port serves the dashboard for every stack | Accepted, amended (streams over WebSocket; the pool area polls); the tray is the hub's client, ADR-0060 | | [0022](0022-network-egress-sandbox.md) | Outbound network calls of supervised services are visible and need an allow rule | Proposed | | [0023](0023-stack-file-compatibility.md) | Stack files stay readable; migrations once devstack has outside users | Accepted | | [0024](0024-a-lane-is-a-supervisor-in-the-main-trees-daemon.md) | A lane is a supervisor in the main working tree's daemon | Accepted, amended twice (lanes are the worktrees, run from a copy); point 4 replaced by ADR-0030; point 1 replaced in part for the hub by ADR-0047; point 7 amended 2026-10-21 (the removal is shown while it runs); point 6 amended by ADR-0052 (a restart carries the lanes over) | @@ -108,3 +108,4 @@ stay. | [0057](0057-a-port-a-container-announces-moves-inside-it-too.md) | A port a container announces moves inside the container too, and Compose is told its number | Accepted | | [0058](0058-a-profile-can-leave-out-containers-and-services.md) | A profile can leave out containers, whole Compose groups and services | Accepted | | [0059](0059-a-services-stop-command-ends-what-its-run-started.md) | A service's `stop` command ends what its `run` started outside its process tree | Accepted | +| [0060](0060-the-tray-is-a-client-of-the-hub.md) | The tray is a client of the hub, a process of its own, on every desktop | Accepted | diff --git a/docs/dashboard-api.md b/docs/dashboard-api.md index 9b803e82..d7324a1d 100644 --- a/docs/dashboard-api.md +++ b/docs/dashboard-api.md @@ -48,6 +48,7 @@ and `Referrer-Policy: no-referrer`. The dashboard has no inline script. | `POST /hub/notify/test` | cookie + Origin | one notification whatever the settings say: `204`, or `503` with why nothing shows. A click opens the dashboard | | `GET /hub/session` | cookie | `200 {"version": "", "link_unavailable": string\|null}`, or `401` (not paired: show "run `devstack ui`"). `link_unavailable` says why this platform has no `devstack://` link (macOS: "not on macOS yet", ADR-0054): the page keeps it and offers `devstack hub start` instead of its "Start hub" link while the hub is down. Older hubs leave it out | | `GET /hub/stacks` | cookie | `[StackEntry]` | +| `GET /hub/summary` | cookie or token | every registered stack at a glance, for the tray ([ADR-0060](adr/0060-the-tray-is-a-client-of-the-hub.md)): `{"state", "version", "stacks": [{id, name, repo, running, state, ready, total, lanes, attention: [{lane, service, text, detail}]}]}`. A stack's `state`: `stopped`, `starting`, `stopping` (a start or stop the hub runs), `ok` or `attention`; the whole `state` is the worst: `attention`, `starting`, `ok` (a stack runs) or `idle`. `ready` of `total`: the main tree's services running, healthy or done. `lanes`: started lanes. `attention`: what notifies (ADR-0045) and is still so, in the main tree and every started lane (`lane` names it): a failed service (not one the user stopped, not one held back by another's failure), a candidate `held` or whose build `failed`; and a failed start from the dashboard (`service` `null`). Containers are not in it. `version`: the hub's devstack | | `GET /hub/ws?path=` | cookie + Origin | WebSocket that carries the server-sent event stream at `` (`/hub/events`, `/hub/stacks/{id}/api/v1/...`, or `/hub/pool/shared/{lease}/api/v1/...[?pool=]` for a lane shared with this machine), one text message per event's `data`; how the dashboard reads every stream (a browser allows six HTTP/1.1 connections per host across all its tabs, WebSockets do not count; ADR-0021). The upstream is opened before the upgrade: `503` for a stack not running, `400` for another path. When the stream ends the socket closes | | `GET /hub/events` | cookie | SSE: `{"type":"stacks","stacks":[StackEntry]}` and `{"type":"docker","docker":DockerEngine}` and `{"type":"release","current","newer":string|null,"error":string|null}` (a newer devstack; checked at start, every 12 h by the clock and when a dashboard connects and the last answer is over an hour old, unless `DEVSTACK_NO_UPDATE_CHECK`; `error` why the last check failed, no network or GitHub's rate limit, tried again after an hour and `null` once one succeeds, while a `newer` found before stays; older hubs leave it out) and `{"type":"update","update":{"running":bool,"error":string|null,"installed":string|null,"finished":ms|null}}` (the dashboard's update; `finished` is when the last one ended, `installed` the version it installed, told by the hub it started) and `{"type":"guests","guests":[Guest]}` (lanes of other members on this machine, every pool: `{pool, lease, member, owner, repo, lane, state: "offered"\|"running", since: unix s, cpus, memory}`, the leases whose node is this machine; read after each share report, every 15 s per pool), each first and on every change | | `POST /hub/update` | cookie + Origin | `202`: `devstack update` in the background (output in `hub/update.log`); on success it restarts the hub on the new version, so the dashboard reconnects to it, and the new hub's `update` event names the installed version (the old hub leaves `hub/update.json` for it; a hub that starts on the old version while the updater runs waits for it and reports a failure); on failure the `update` event carries the end of its output. `409` while one runs (checked and claimed in one step). Running stacks switch at their next restart | diff --git a/docs/macos.md b/docs/macos.md index 4acbcbf0..e30b4688 100644 --- a/docs/macos.md +++ b/docs/macos.md @@ -28,6 +28,7 @@ with a browser is blocked until `xattr -d com.apple.quarantine devstack`. | The hub at login | a LaunchAgent (`~/Library/LaunchAgents/it.nuetzliche.devstack.hub.plist`), for a Homebrew install too, not `brew services` | | Folder picker, "Open in" (Finder, Terminal, editors, GitHub Desktop), browsers | `osascript`, `open`, `open -a` | | Starting Docker | Docker Desktop or OrbStack; Colima: `colima start` yourself | +| The tray ([ADR-0060](adr/0060-the-tray-is-a-client-of-the-hub.md)) | a status item in the menu bar, no Dock icon, started by the hub; not checked on a Mac since it became the tray of every platform | | `devstack update`, the dashboard's update | a Homebrew copy through `brew upgrade` | | Requesting a lane on a Linux node of a pool | expected to work, not checked yet | | Desktop notifications, the `devstack://` link | not yet: both need a signed app bundle | @@ -98,3 +99,22 @@ What CI cannot show. Each step names what to look for; anything else is a bug. 18. With the hub started at login (step 5), joining or using a pool on your LAN works; if macOS asks about Local Network access, say so in the report, with what you answered. + +**The tray** (ADR-0060; the AppKit part comes from #248, the rest is new) + +19. With the hub started (`devstack hub start`), the devstack mark shows in + the menu bar within a few seconds, and nothing in the Dock. + `devstack hub tray` says it runs; a second `devstack tray` says it runs + already. +20. The icon follows the menu bar's light and dark. It turns orange while a + stack starts or stops, red while a service has failed (a stack whose + service exits at once), and plain again once that is gone. +21. Its menu lists every registered stack with its state. *Stop* and + *Start* in a stack's submenu work as in the dashboard; *Open Folder* + opens Finder; *Open in Dashboard* and a line under "needs attention" + open the paired dashboard on that stack or service. +22. *Quit Tray* ends only the icon: stacks and the hub keep running. + `devstack hub tray off` ends it and `devstack hub stop` / `start` + leaves it off; `devstack hub tray on` brings it back. +23. `devstack hub stop` while it runs: the icon stays, says the hub does + not run, and *Start Dashboard Hub* starts it again. diff --git a/docs/plan.md b/docs/plan.md index e7bcc95d..e6b915bf 100644 --- a/docs/plan.md +++ b/docs/plan.md @@ -426,7 +426,9 @@ checks ([ADR-0019](adr/0019-control-api-security.md)). Delivery: a browser page served by the daemon, opened with `devstack ui`; status icon and notifications through a tray in the daemon binary ([ADR-0018](adr/0018-dashboard-is-a-browser-page.md)). The notifications came without the tray, from the hub -([ADR-0045](adr/0045-the-hub-notifies-the-desktop.md)). +([ADR-0045](adr/0045-the-hub-notifies-the-desktop.md)); the tray came as a +client process the hub starts, on every platform +([ADR-0060](adr/0060-the-tray-is-a-client-of-the-hub.md)). - **Overview by group** (§4.4a): one panel per group, ungrouped members under "Other", a member shown in every group it belongs to. Per member: state, @@ -456,7 +458,7 @@ of the current instance (live, filter, pause), service and stack actions, commands with confirmation and their run history, resources, the events timeline, Docker and stack-file banners, container logs, earlier logs of a service, sortable tables, actions per group, the jump to the last failure, a -candidate's console, a build timeline per service, a command palette, the lane switcher. Open (§13): tray. +candidate's console, a build timeline per service, a command palette, the lane switcher, the tray (ADR-0060). ## 7. Phases @@ -957,6 +959,5 @@ What is open, roughly in the order it pays off, and where it comes from. | `devstack migrate`, once devstack has outside users | [ADR-0023](adr/0023-stack-file-compatibility.md) | medium | | A pull request as a lane, by its number: fetched by refspec, no forge API (`refs/pull/N/head` on GitHub and Forgejo/Gitea, `refs/merge-requests/N/head` on GitLab), the forge told by the remote's URL. A feature that needs the API after all takes its token from `git credential fill` (else `gh`, `glab`, `tea`), never from an OAuth flow of devstack's own: a self-hosted instance has no client ID devstack could ship | [ADR-0047](adr/0047-the-dashboard-makes-a-lane-from-a-branch.md) (what it does not say) | medium | | Dead ends link onward, once devstack has outside users: a gap left on purpose names its tracking issue (one per gap, so interest adds up instead of duplicates); an open list (forges, programs to open a tree in) links to a prefilled issue form with the version and the OS only, never hosts or paths. One mechanism for it, such as a notice, not links in every error | [ADR-0023](adr/0023-stack-file-compatibility.md) (the same trigger), [ADR-0050](adr/0050-what-no-request-reports-reaches-the-dashboard-as-a-notice.md) | small | -| Tray icon with status (deferred; the notifications are the hub's since ADR-0045) | §6, ADR-0018, [#1](https://github.com/nuetzliches/devstack/issues/1) | medium | | Network egress sandbox, stage 1 (cooperative proxy) | [ADR-0022](adr/0022-network-egress-sandbox.md) (proposed) | medium | | Confine file writes of services to the repository (deferred) | [#2](https://github.com/nuetzliches/devstack/issues/2) | medium | diff --git a/skills/devstack/SKILL.md b/skills/devstack/SKILL.md index 128ac58c..d98a58e7 100644 --- a/skills/devstack/SKILL.md +++ b/skills/devstack/SKILL.md @@ -78,6 +78,7 @@ Run from the repository root (devstack looks for `{{devstack:stack_file}}` there | `devstack top` | CPU, memory, disk per service, container, group and lane | | `devstack ui` | dashboard in the browser, on this stack (in a worktree on its lane; `--lane ` on another), and pairs the browser once; `--browser chrome\|edge\|firefox\|brave\|`, else `DEVSTACK_BROWSER`, else `BROWSER` picks the browser. `--link` prints the lasting links instead (see "Tell the user where to look"), `--print` the one-time pairing link | | `devstack hub notify` | the desktop notifications the hub shows (a build failed, a candidate held, a service crashed, a lane's start on a node failed) and whether they show; `on\|off …\|all`, `test`. The user's own choice: change it only when asked | +| `devstack hub tray` | whether the tray icon runs (the hub starts it); `on\|off`. The user's own choice: change it only when asked | | `devstack update` | install the newest devstack (`--check` only asks); stacks switch at their next restart | | `devstack down` | stop the services and the daemon; containers keep running. `down --infra` removes them too. In the main tree, lanes that run keep the daemon and the infrastructure (only the main tree's services stop); `down --all` stops the lanes too: ask first, they may be someone else's |