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..83fe56cc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,11 @@ and listed with their assets on the the ones recorded. `docs/stack-file.md` describes a container as a service (`--init`, `--rm`, a name per instance). A file with `stop` says `requires = "0.21.0"`. +- **An optional native macOS menu bar** (`devstack menubar`, proposed + ADR-0060): see the hub and registered stacks, open the paired dashboard, + start or stop the hub or a stack, and open a stack's folder. Lifecycle + actions use the existing CLI; quitting the menu leaves stacks and the hub + running. No login integration is installed by this command. ## [0.20.0] - 2026-10-23 diff --git a/Cargo.lock b/Cargo.lock index 83d4fcbe..58a78466 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -651,6 +651,9 @@ version = "0.20.0" dependencies = [ "devstack-proc", "libc", + "objc2", + "objc2-app-kit", + "objc2-foundation", "raw-window-handle", "rfd", "tempfile", @@ -1482,6 +1485,7 @@ dependencies = [ "bitflags 2.13.2", "block2", "objc2", + "objc2-core-foundation", "objc2-foundation", ] diff --git a/Cargo.toml b/Cargo.toml index 88cf6063..044dc102 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,6 +31,36 @@ jiff = "0.2" libc = "0.2" # Mach host and time calls on macOS that libc marks deprecated (ADR-0054). mach2 = "0.7" +# The optional macOS menu client (ADR-0060), linked on macOS only. +objc2 = "0.6" +objc2-app-kit = { version = "0.3.2", default-features = false, features = [ + "std", + "NSApplication", + "NSButton", + "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" diff --git a/README.md b/README.md index 94cbaa4d..3f45fc76 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 menubar` | optional native macOS menu bar: hub and stack status, open the paired dashboard, start/stop the hub or a registered stack, open its folder. Quitting the menu keeps stacks and the hub running; see [macOS](docs/macos.md#menu-bar) | | `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)) | diff --git a/crates/devstack-desktop/Cargo.toml b/crates/devstack-desktop/Cargo.toml index 8212fc83..5232cdd3 100644 --- a/crates/devstack-desktop/Cargo.toml +++ b/crates/devstack-desktop/Cargo.toml @@ -28,6 +28,11 @@ 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..dd52bac5 100644 --- a/crates/devstack-desktop/src/lib.rs +++ b/crates/devstack-desktop/src/lib.rs @@ -18,6 +18,7 @@ pub mod channel; // The macOS module's text, built and tested everywhere. #[cfg_attr(not(target_os = "macos"), allow(dead_code))] mod mac; +pub mod menubar; pub mod notify; #[cfg(target_os = "linux")] diff --git a/crates/devstack-desktop/src/menubar/assets/devstack-template.pdf b/crates/devstack-desktop/src/menubar/assets/devstack-template.pdf new file mode 100644 index 00000000..552be675 Binary files /dev/null and b/crates/devstack-desktop/src/menubar/assets/devstack-template.pdf differ diff --git a/crates/devstack-desktop/src/menubar/assets/devstack-template.svg b/crates/devstack-desktop/src/menubar/assets/devstack-template.svg new file mode 100644 index 00000000..56eb6d5c --- /dev/null +++ b/crates/devstack-desktop/src/menubar/assets/devstack-template.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/crates/devstack-desktop/src/menubar/macos.rs b/crates/devstack-desktop/src/menubar/macos.rs new file mode 100644 index 00000000..6eafa823 --- /dev/null +++ b/crates/devstack-desktop/src/menubar/macos.rs @@ -0,0 +1,310 @@ +//! AppKit is confined to the main thread. In particular, no status request or +//! child command runs from a delegate or timer callback. + +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, 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}; + +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))); + } + 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(), + entries: vec![], + }, + receiver, + sender, + ) + }) + .join() + .unwrap(); + assert!(result.unwrap_err().contains("main thread")); + } +} diff --git a/crates/devstack-desktop/src/menubar/mod.rs b/crates/devstack-desktop/src/menubar/mod.rs new file mode 100644 index 00000000..d3fc6a34 --- /dev/null +++ b/crates/devstack-desktop/src/menubar/mod.rs @@ -0,0 +1,66 @@ +//! The optional native macOS menu client (ADR-0060). +//! +//! Its owner collects status and performs commands on a worker. This module +//! only presents snapshots and sends action IDs back to that worker. + +use std::sync::mpsc::{Receiver, Sender}; + +/// A complete snapshot, independent of the desktop toolkit. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Menu { + pub tooltip: String, + pub entries: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Entry { + Label(String), + Separator, + Action { + label: String, + id: String, + enabled: bool, + }, + Submenu { + label: String, + entries: Vec, + }, +} + +#[cfg(target_os = "macos")] +mod macos; + +/// Run on the process's main thread until the user exits the menu client or +/// its worker disconnects. The reserved action ID `quit` exits only this +/// client, after sending the action to its owner; it stops no other process. +pub fn run(initial: Menu, updates: Receiver, actions: Sender) -> Result<(), String> { + #[cfg(target_os = "macos")] + { + macos::run(initial, updates, actions) + } + #[cfg(not(target_os = "macos"))] + { + let _ = (initial, updates, actions); + Err("The devstack menu bar is available on macOS only.".into()) + } +} + +#[cfg(all(test, not(target_os = "macos")))] +mod tests { + use super::*; + + #[test] + fn unavailable_without_a_macos_desktop() { + let (_, updates) = std::sync::mpsc::channel(); + let (actions, _) = std::sync::mpsc::channel(); + let result = run( + Menu { + tooltip: "devstack".into(), + entries: vec![], + }, + updates, + actions, + ); + assert!(result.unwrap_err().contains("macOS only")); + } +} diff --git a/crates/devstack/src/dispatch/hub.rs b/crates/devstack/src/dispatch/hub.rs index 0d055bc3..fe05a8b7 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, hubcmd, integration, menubar}; use anyhow::Result; use std::path::Path; @@ -14,6 +14,7 @@ pub(crate) fn run(file: &Path, cmd: Cmd) -> Result<()> { browser, } => hubcmd::ui(file, lane.as_deref(), link, print, browser.as_deref()), Cmd::Hub { action } => hub(action), + Cmd::Menubar => menubar::run(), Cmd::OpenUrl { url } => integration::open_url(&url), _ => super::misrouted(), } diff --git a/crates/devstack/src/main.rs b/crates/devstack/src/main.rs index fc796563..793144aa 100644 --- a/crates/devstack/src/main.rs +++ b/crates/devstack/src/main.rs @@ -14,6 +14,7 @@ mod hubcmd; mod init; mod integration; mod mcp; +mod menubar; mod poolcmd; mod selfcmd; use devstack_skills as skills; @@ -219,6 +220,9 @@ enum Cmd { }, /// MCP server on stdio for coding agents; a client of the daemon like the CLI. Mcp, + /// Show a native macOS menu bar for the dashboard and registered stacks. + /// Optional; quitting the menu leaves the hub and stacks running. + Menubar, /// 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. @@ -701,7 +705,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::Menubar) => { dispatch::hub::run(&file, cmd) } cmd @ (Cmd::Update { .. } | Cmd::Myself { .. }) => dispatch::myself::run(cmd), @@ -738,6 +742,12 @@ mod tests { Cli::command().debug_assert(); } + #[test] + fn the_menu_bar_is_an_explicit_command_without_a_stack_file() { + assert!(matches!(parse(&["menubar"]).cmd, Cmd::Menubar)); + assert_eq!(refused(&["menubar", "--all"]), ErrorKind::UnknownArgument); + } + #[test] fn the_stack_file_defaults_and_is_global() { assert_eq!(parse(&["status"]).file, PathBuf::from("devstack.toml")); diff --git a/crates/devstack/src/menubar.rs b/crates/devstack/src/menubar.rs new file mode 100644 index 00000000..bd1f30fd --- /dev/null +++ b/crates/devstack/src/menubar.rs @@ -0,0 +1,1077 @@ +//! The optional macOS menu is a client of the existing CLI and daemon API +//! (ADR-0060). AppKit stays on the main thread; this worker owns all I/O. + +pub(crate) fn run() -> anyhow::Result<()> { + #[cfg(target_os = "macos")] + return controller::run(); + + #[cfg(not(target_os = "macos"))] + anyhow::bail!("the menu bar client is available on macOS only") +} + +#[cfg(any(target_os = "macos", test))] +mod controller { + #[cfg(target_os = "macos")] + use anyhow::anyhow; + use anyhow::{Context, Result, bail}; + use devstack_daemon::registry; + use devstack_desktop::menubar::{Entry, Menu}; + use serde_json::Value; + use std::collections::BTreeSet; + use std::ffi::OsString; + use std::fs::{File, OpenOptions}; + use std::io::{Read, Seek, SeekFrom}; + use std::path::{Path, PathBuf}; + use std::process::{Command, Stdio}; + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::mpsc::{self, Receiver, Sender}; + use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + + const REFRESH: Duration = Duration::from_secs(5); + const REQUEST_TIMEOUT: Duration = Duration::from_secs(2); + + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + enum Hub { + Checking, + Running, + Stopped, + Foreign, + } + + #[derive(Clone, Debug)] + struct Stack { + entry: registry::Entry, + daemon: bool, + status: String, + details: Vec, + } + + struct Snapshot { + hub: Hub, + stacks: Vec, + message: Option, + busy: bool, + } + + impl Default for Snapshot { + fn default() -> Self { + Self { + hub: Hub::Checking, + stacks: Vec::new(), + message: None, + busy: false, + } + } + } + + fn action(label: &str, id: &str, enabled: bool) -> Entry { + Entry::Action { + label: label.into(), + id: id.into(), + enabled, + } + } + + fn menu(s: &Snapshot) -> Menu { + let hub = match s.hub { + Hub::Checking => "Checking Dashboard Hub…", + Hub::Running => "● Dashboard Hub running", + Hub::Stopped => "○ Dashboard Hub stopped", + Hub::Foreign => "⚠ Dashboard Hub port occupied", + }; + let available = !s.busy; + let mut entries = vec![ + Entry::Label(hub.into()), + action( + "Open Dashboard", + "dashboard", + available && matches!(s.hub, Hub::Running | Hub::Stopped), + ), + ]; + if let Some(message) = &s.message { + entries.push(Entry::Label(short(message, 180))); + } + entries.push(Entry::Separator); + match s.hub { + Hub::Running => entries.push(action( + "Stop Dashboard Hub (keep stacks running)", + "hub-stop", + available, + )), + Hub::Stopped => entries.push(action("Start Dashboard Hub", "hub-start", available)), + Hub::Foreign => entries.push(Entry::Label(format!( + "Another process uses port {}", + devstack_hub::port() + ))), + Hub::Checking => {} + } + entries.push(Entry::Separator); + entries.push(Entry::Label("Local stacks".into())); + if s.stacks.is_empty() { + entries.push(Entry::Label(if s.hub == Hub::Checking { + "Checking registered stacks…".into() + } else { + "No registered stacks — run devstack up in a repository".into() + })); + } + for stack in &s.stacks { + let id = &stack.entry.id; + let mut children = vec![Entry::Label(short(&stack.status, 120))]; + children.extend(stack.details.iter().map(|d| Entry::Label(short(d, 150)))); + children.push(Entry::Separator); + children.push(action( + "Open Dashboard", + &format!("dashboard:{id}"), + available && s.hub != Hub::Foreign && stack.entry.file.is_file(), + )); + children.push(action( + "Start Stack", + &format!("start:{id}"), + available && stack.entry.file.is_file(), + )); + children.push(action( + "Stop Main Stack & Containers", + &format!("stop:{id}"), + available && stack.daemon && stack.entry.file.is_file(), + )); + children.push(Entry::Label( + "Running lanes keep their services and containers".into(), + )); + children.push(Entry::Separator); + children.push(action( + "Open Folder", + &format!("folder:{id}"), + available && stack.entry.repo.is_dir(), + )); + entries.push(Entry::Submenu { + label: format!( + "{} — {}", + short(&stack.entry.name, 60), + short(&stack.status, 50) + ), + entries: children, + }); + } + entries.extend([ + Entry::Separator, + action("Refresh Status", "refresh", available), + action("Give Feedback…", "feedback", available), + Entry::Label(format!("devstack {}", devstack_config::VERSION)), + action("Quit Menu Bar (keep stacks running)", "quit", true), + ]); + Menu { + tooltip: format!("devstack — {hub}"), + entries, + } + } + + fn short(text: &str, max: usize) -> String { + let clean: String = text + .chars() + .map(|c| if c.is_control() { ' ' } else { c }) + .collect(); + if clean.chars().count() > max { + format!( + "{}…", + clean + .chars() + .take(max.saturating_sub(1)) + .collect::() + ) + } else { + clean + } + } + + /// The API keeps intentionally skipped containers managed (ADR-0058), + /// without exposing their startup policy. Only use the local profile when + /// the daemon reports that its configuration still matches that file. + fn profile_skips(view: &Value, file: Option<&Path>) -> Option> { + let Some(profile) = view["profile"].as_str() else { + return Some(BTreeSet::new()); + }; + if view["config_changed"] == true { + return None; + } + let config = devstack_config::load(file?).ok()?; + config + .with_profile(profile) + .ok()? + .profile + .map(|active| active.skip) + } + + /// Include Compose alongside native services, without calling a daemon + /// healthy merely because it answers. Missing infrastructure stays unknown. + fn stack_status(view: &Value, file: Option<&Path>) -> (String, Vec) { + let services: Vec<&Value> = view["services"].as_array().into_iter().flatten().collect(); + let infra: Vec<&Value> = view["infra"].as_array().into_iter().flatten().collect(); + let skips = profile_skips(view, file); + let mut left_out = 0; + let containers: Vec<&Value> = infra + .iter() + .flat_map(|g| { + g["containers"] + .as_array() + .into_iter() + .flatten() + .map(move |c| (g, c)) + }) + .filter(|(_, c)| c["managed"] != false) + .filter_map(|(g, c)| { + let stopped_normally = matches!(c["state"].as_str(), Some("stopped" | "created")) + || (c["state"] == "exited" + && c["exit_code"] + .as_i64() + .is_some_and(|code| matches!(code, 0 | 130 | 137 | 143))); + let intentionally_stopped = stopped_normally + && skips.as_ref().is_some_and(|skipped| { + skipped.contains(&( + g["group"].as_str().unwrap_or("").to_string(), + c["service"].as_str().unwrap_or("").to_string(), + )) + }); + if intentionally_stopped { + left_out += 1; + None + } else { + Some(c) + } + }) + .collect(); + let native_running = services + .iter() + .filter(|s| matches!(s["status"]["state"].as_str(), Some("running" | "healthy"))) + .count(); + let containers_running = containers + .iter() + .filter(|c| c["state"] == "running") + .count(); + let issue = infra + .iter() + .find_map(|g| g["error"].as_str()) + .map(str::to_string) + .or_else(|| { + services + .iter() + .find_map(|s| match s["status"]["state"].as_str() { + Some("failed" | "unhealthy") => Some(format!( + "{}: {}", + s["name"].as_str().unwrap_or("service"), + s["status"]["reason"].as_str().unwrap_or("needs attention") + )), + Some("exited" | "completed") + if s["status"]["exit_code"].as_i64().is_some_and(|c| c != 0) => + { + Some(format!( + "{}: exited with {}", + s["name"].as_str().unwrap_or("service"), + s["status"]["exit_code"] + )) + } + _ => None, + }) + }) + .or_else(|| { + services + .iter() + .find_map(|s| match s["candidate"]["state"].as_str() { + Some("failed" | "held") => Some(format!( + "{}: candidate {} — {}", + s["name"].as_str().unwrap_or("service"), + s["candidate"]["state"].as_str().unwrap_or(""), + s["candidate"]["reason"] + .as_str() + .unwrap_or("open Dashboard for details") + )), + _ => None, + }) + }) + .or_else(|| { + services.iter().find_map(|s| { + (s["rebuild"]["state"] == "failed").then(|| { + let error = s["rebuild"]["errors"] + .as_array() + .and_then(|lines| { + lines + .iter() + .filter_map(Value::as_str) + .find(|line| !line.trim().is_empty()) + }) + .unwrap_or("open Dashboard for details"); + format!( + "{}: rebuild failed — {error}", + s["name"].as_str().unwrap_or("service") + ) + }) + }) + }) + .or_else(|| { + containers + .iter() + .find(|c| { + c["health"] == "unhealthy" + || c["state"] == "dead" + || (c["state"] == "exited" + && c["exit_code"] + .as_i64() + .is_some_and(|n| !matches!(n, 0 | 130 | 137 | 143))) + }) + .map(|c| { + format!( + "{}: needs attention", + c["service"].as_str().unwrap_or("container") + ) + }) + }); + let starting = services + .iter() + .any(|s| matches!(s["status"]["state"].as_str(), Some("building" | "starting"))) + || containers.iter().any(|c| { + c["health"] == "starting" + || matches!(c["state"].as_str(), Some("created" | "restarting")) + }); + let running = native_running + containers_running; + let total = services.len() + containers.len(); + let completed = services + .iter() + .filter(|s| s["status"]["state"] == "completed" && s["status"]["exit_code"] == 0) + .count(); + let expected_pending = services.iter().any(|s| { + s["autostart"] != false + && !matches!(s["status"]["state"].as_str(), Some("running" | "healthy")) + && !(s["status"]["state"] == "completed" && s["status"]["exit_code"] == 0) + }); + let status = if issue.is_some() { + "Needs attention" + } else if starting { + "Starting" + } else if skips.is_none() && containers_running != containers.len() { + "Status incomplete" + } else if total == 0 { + "Daemon running" + } else if running > 0 && !expected_pending && containers_running == containers.len() { + "Running" + } else if running > 0 { + "Partly running" + } else if completed > 0 && !expected_pending && containers.is_empty() { + "Jobs completed" + } else { + "Services stopped" + }; + let mut details = vec![ + format!( + "Native services: {native_running}/{} running", + services.len() + ), + format!( + "Compose containers: {containers_running}/{} running", + containers.len() + ), + ]; + if completed > 0 { + details.push(format!("Jobs completed successfully: {completed}")); + } + if left_out > 0 { + details.push(format!("Profile leaves out {left_out} stopped containers")); + } + if skips.is_none() { + details.push( + "Profile container expectations unavailable; open Dashboard for details".into(), + ); + } + if let Some(issue) = issue { + details.push(issue); + } + (status.into(), details) + } + + fn collect_stack(entry: registry::Entry, stop: &AtomicBool) -> Stack { + let mut stack = Stack { + entry, + daemon: false, + status: "Daemon stopped".into(), + details: vec!["Containers are not checked while the daemon is stopped".into()], + }; + let Some(parent) = stack.entry.file.parent() else { + return stack; + }; + let Some(info) = devstack_daemon::read_info(&parent.join(".devstack")) else { + return stack; + }; + if !devstack_proc::pid_alive(info.pid) { + return stack; + } + stack.daemon = true; + stack.status = "Checking status".into(); + stack.details.clear(); + if info.stopping { + stack.status = "Stopping".into(); + return stack; + } + if stop.load(Ordering::Acquire) { + return stack; + } + let result = (|| -> Result { + let token = devstack_daemon::token::load().context("user token is missing")?; + let agent = ureq::Agent::config_builder() + .timeout_global(Some(REQUEST_TIMEOUT)) + .http_status_as_error(false) + .build() + .new_agent(); + let mut response = agent + .get(&format!("http://127.0.0.1:{}/v1/stack", info.port)) + .header("Authorization", &format!("Bearer {token}")) + .call()?; + if response.status() != 200 { + bail!("daemon returned HTTP {}", response.status()); + } + Ok(serde_json::from_str( + &response.body_mut().read_to_string()?, + )?) + })(); + match result { + Ok(view) => { + (stack.status, stack.details) = stack_status(&view, Some(&stack.entry.file)) + } + Err(e) => { + stack.status = "Status unavailable".into(); + stack.details.push(short(&format!("{e:#}"), 150)); + } + } + stack + } + + fn refresh(s: &mut Snapshot, stop: &AtomicBool) { + if stop.load(Ordering::Acquire) { + return; + } + s.hub = match devstack_hub::who_answers(devstack_hub::port()) { + devstack_hub::Listener::Ours => Hub::Running, + devstack_hub::Listener::Nothing => Hub::Stopped, + devstack_hub::Listener::Foreign => Hub::Foreign, + }; + let mut stacks = Vec::new(); + for entry in registry::list() { + if stop.load(Ordering::Acquire) { + return; + } + stacks.push(collect_stack(entry, stop)); + } + s.stacks = stacks; + } + + #[derive(Debug, PartialEq, Eq)] + struct Invocation { + /// `None` means this executable; folders and feedback use macOS's `open`. + program: Option, + args: Vec, + directory: Option, + progress: String, + } + + fn invocation(id: &str, s: &Snapshot) -> Option { + let args = |words: &[&str]| words.iter().map(OsString::from).collect(); + let simple = |words: &[&str], progress: &str| Invocation { + program: None, + args: args(words), + directory: None, + progress: progress.into(), + }; + match id { + "feedback" => { + return Some(Invocation { + program: Some("/usr/bin/open".into()), + args: args(&[ + "--", + "https://github.com/nuetzliches/devstack/issues/new/choose", + ]), + directory: None, + progress: "Opening GitHub feedback…".into(), + }); + } + // `/` is a directory, so `ui` opens the hub without inheriting a + // stack from the menu client's launch directory. + "dashboard" if s.hub != Hub::Foreign => { + return Some(simple(&["--file", "/", "ui"], "Opening Dashboard…")); + } + "hub-start" if s.hub == Hub::Stopped => { + return Some(simple(&["hub", "start"], "Starting Dashboard Hub…")); + } + "hub-stop" if s.hub == Hub::Running => { + return Some(simple(&["hub", "stop"], "Stopping Dashboard Hub…")); + } + _ => {} + } + let (kind, id) = id.split_once(':')?; + let stack = s.stacks.iter().find(|stack| stack.entry.id == id)?; + let entry = &stack.entry; + let mut command = Invocation { + program: None, + args: vec!["--file".into(), entry.file.as_os_str().into()], + directory: Some(entry.repo.clone()), + progress: String::new(), + }; + match kind { + "dashboard" if entry.file.is_file() && s.hub != Hub::Foreign => { + command.args.push("ui".into()); + command.progress = format!("Opening {} Dashboard…", entry.name); + } + "start" if entry.file.is_file() => { + command.args.push("up".into()); + command.progress = format!("Starting {}…", entry.name); + } + "stop" if stack.daemon && entry.file.is_file() => { + command.args.extend(args(&["down", "--infra"])); + command.progress = format!("Stopping {} main stack and containers…", entry.name); + } + "folder" if entry.repo.is_dir() => { + command.program = Some("/usr/bin/open".into()); + command.args = vec!["--".into(), entry.repo.as_os_str().into()]; + command.progress = format!("Opening {} folder…", entry.name); + } + _ => return None, + } + Some(command) + } + + struct OutputLog { + file: File, + path: PathBuf, + } + + impl OutputLog { + fn new() -> Result { + let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_nanos(); + let path = std::env::temp_dir() + .join(format!("devstack-menubar-{}-{now}.log", std::process::id())); + let mut options = OpenOptions::new(); + options.read(true).write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + Ok(Self { + file: options.open(&path)?, + path, + }) + } + + fn tail(&mut self) -> String { + let _ = self + .file + .seek(SeekFrom::End(-4096)) + .or_else(|_| self.file.seek(SeekFrom::Start(0))); + let mut bytes = Vec::new(); + let _ = self.file.read_to_end(&mut bytes); + String::from_utf8_lossy(&bytes).trim().to_string() + } + } + + impl Drop for OutputLog { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.path); + } + } + + fn execute(call: &Invocation, stop: &AtomicBool) -> Result<()> { + if stop.load(Ordering::Acquire) { + return Ok(()); + } + let mut log = OutputLog::new()?; + let program = call.program.clone().map(Ok).unwrap_or_else(|| { + std::env::current_exe().map(|exe| devstack_desktop::stable_exe(&exe)) + })?; + let mut command = Command::new(program); + command + .args(&call.args) + .stdin(Stdio::null()) + .stdout(log.file.try_clone()?) + .stderr(log.file.try_clone()?); + if let Some(dir) = &call.directory { + command.current_dir(dir); + } + if stop.load(Ordering::Acquire) { + return Ok(()); + } + let mut child = command.spawn().context("could not start command")?; + let started = Instant::now(); + loop { + if stop.load(Ordering::Acquire) { + // Only the client command belongs to this menu process. The + // existing daemon and hub keep their own lifetime. + let _ = child.kill(); + let _ = child.wait(); + return Ok(()); + } + match child.try_wait()? { + Some(status) if status.success() => return Ok(()), + Some(status) => { + let output = log.tail(); + bail!( + "command failed ({status}){}", + if output.is_empty() { + String::new() + } else { + format!(": {output}") + } + ); + } + None if started.elapsed() >= Duration::from_secs(1800) => { + let _ = child.kill(); + let _ = child.wait(); + bail!("command timed out; inspect the Dashboard for its current state"); + } + None => std::thread::sleep(Duration::from_millis(80)), + } + } + } + + fn worker(actions: Receiver, updates: Sender, stop: Arc) { + let mut s = Snapshot::default(); + loop { + refresh(&mut s, &stop); + if stop.load(Ordering::Acquire) || updates.send(menu(&s)).is_err() { + return; + } + let id = match actions.recv_timeout(REFRESH) { + Ok(id) if id == "quit" => return, + Ok(id) => id, + Err(mpsc::RecvTimeoutError::Timeout) => continue, + Err(mpsc::RecvTimeoutError::Disconnected) => return, + }; + if id == "refresh" { + continue; + } + if stop.load(Ordering::Acquire) { + return; + } + let Some(call) = invocation(&id, &s) else { + continue; + }; + s.busy = true; + s.message = Some(call.progress.clone()); + if updates.send(menu(&s)).is_err() { + return; + } + let result = execute(&call, &stop); + if stop.load(Ordering::Acquire) { + return; + } + s.busy = false; + s.message = Some(match result { + Ok(()) => "Command completed — status refreshes automatically".into(), + Err(e) => { + eprintln!("menu bar: {e:#}"); + let detail = format!("{e:#}"); + format!( + "⚠ {}", + short(detail.lines().next_back().unwrap_or(&detail), 170) + ) + } + }); + // A click queued just before a busy snapshot must not repeat an + // up/down after that command finishes. Quit still takes priority. + for queued in actions.try_iter() { + if queued == "quit" { + return; + } + } + } + } + + #[cfg(target_os = "macos")] + fn single_instance() -> Result { + let dir = devstack_daemon::token::token_path() + .parent() + .context("token directory")? + .to_path_buf(); + std::fs::create_dir_all(&dir)?; + let file = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(dir.join("menubar.lock"))?; + // The descriptor holds the lock until this process exits. No PID file + // can become stale or refer to a recycled process. + match file.try_lock() { + Ok(()) => Ok(file), + Err(std::fs::TryLockError::WouldBlock) => { + bail!("a devstack menu bar client is already running for this user") + } + Err(e) => bail!("could not lock the menu bar client: {e}"), + } + } + + #[cfg(target_os = "macos")] + pub(super) fn run() -> Result<()> { + let _instance = single_instance()?; + let (actions_tx, actions_rx) = mpsc::channel(); + let (updates_tx, updates_rx) = mpsc::channel(); + let stop = Arc::new(AtomicBool::new(false)); + let worker_stop = stop.clone(); + let shutdown = actions_tx.clone(); + let worker = std::thread::Builder::new() + .name("devstack-menu".into()) + .spawn(move || worker(actions_rx, updates_tx, worker_stop))?; + let result = + devstack_desktop::menubar::run(menu(&Snapshot::default()), updates_rx, actions_tx); + stop.store(true, Ordering::Release); + let _ = shutdown.send("quit".into()); + worker + .join() + .map_err(|_| anyhow!("menu bar worker panicked"))?; + result.map_err(|e| anyhow!(e)) + } + + #[cfg(test)] + mod tests { + use super::*; + use serde_json::json; + + fn stack_status(view: &Value) -> (String, Vec) { + super::stack_status(view, None) + } + + fn find<'a>(entries: &'a [Entry], id: &str) -> Option<&'a Entry> { + entries.iter().find_map(|entry| match entry { + Entry::Action { id: found, .. } if found == id => Some(entry), + Entry::Submenu { entries, .. } => find(entries, id), + _ => None, + }) + } + + fn enabled(menu: &Menu, id: &str) -> bool { + matches!( + find(&menu.entries, id), + Some(Entry::Action { enabled: true, .. }) + ) + } + + fn fixture() -> (tempfile::TempDir, Snapshot) { + let temp = tempfile::tempdir().unwrap(); + let file = temp.path().join("a file; $(never execute).toml"); + std::fs::write(&file, "").unwrap(); + let stack = Stack { + entry: registry::Entry { + id: "ab12".into(), + name: "Example stack".into(), + file, + repo: temp.path().to_path_buf(), + }, + daemon: true, + status: "Running".into(), + details: vec![], + }; + ( + temp, + Snapshot { + hub: Hub::Running, + stacks: vec![stack], + message: None, + busy: false, + }, + ) + } + + #[test] + fn a_foreign_hub_cannot_be_started_stopped_or_sent_dashboard_credentials() { + let (_temp, mut s) = fixture(); + s.hub = Hub::Foreign; + let menu = menu(&s); + assert!(!enabled(&menu, "dashboard")); + assert!(!enabled(&menu, "dashboard:ab12")); + assert!(find(&menu.entries, "hub-start").is_none()); + assert!(find(&menu.entries, "hub-stop").is_none()); + assert!(invocation("dashboard", &s).is_none()); + assert!(invocation("hub-stop", &s).is_none()); + } + + #[test] + fn busy_menu_disables_actions_but_quit_still_works() { + let (_temp, mut s) = fixture(); + s.busy = true; + let menu = menu(&s); + for id in [ + "dashboard", + "hub-stop", + "start:ab12", + "stop:ab12", + "folder:ab12", + "refresh", + ] { + assert!(!enabled(&menu, id), "{id}"); + } + assert!(enabled(&menu, "quit")); + } + + #[test] + fn offline_registered_stacks_can_start_and_keep_their_folder() { + let (_temp, mut s) = fixture(); + s.hub = Hub::Stopped; + s.stacks[0].daemon = false; + let menu = menu(&s); + assert!(enabled(&menu, "hub-start")); + assert!(enabled(&menu, "dashboard")); + assert!(enabled(&menu, "start:ab12")); + assert!(enabled(&menu, "folder:ab12")); + assert!(!enabled(&menu, "stop:ab12")); + } + + #[test] + fn lifecycle_and_folder_paths_are_separate_arguments_and_lanes_are_preserved() { + let (_temp, s) = fixture(); + let call = invocation("stop:ab12", &s).unwrap(); + assert_eq!( + call.args, + vec![ + OsString::from("--file"), + s.stacks[0].entry.file.as_os_str().into(), + "down".into(), + "--infra".into() + ] + ); + assert_eq!(call.program, None); + let folder = invocation("folder:ab12", &s).unwrap(); + assert_eq!( + folder.args, + vec![ + OsString::from("--"), + s.stacks[0].entry.repo.as_os_str().into() + ] + ); + assert_eq!(folder.program, Some("/usr/bin/open".into())); + assert!(invocation("start:unknown", &s).is_none()); + } + + #[test] + fn feedback_opens_only_the_official_issue_chooser_without_submitting_data() { + let (_temp, mut s) = fixture(); + s.hub = Hub::Foreign; + assert!(enabled(&menu(&s), "feedback")); + let call = invocation("feedback", &s).unwrap(); + assert_eq!(call.program, Some("/usr/bin/open".into())); + assert_eq!( + call.args, + vec![ + OsString::from("--"), + OsString::from("https://github.com/nuetzliches/devstack/issues/new/choose") + ] + ); + assert_eq!(call.directory, None); + assert!(invocation("feedback:https://example.invalid", &s).is_none()); + } + + #[test] + fn compose_is_counted_and_an_unhealthy_container_is_not_reported_running() { + let (state, details) = stack_status(&json!({"services": [], "infra": [{"containers": [ + {"service": "db", "state": "running", "health": "unhealthy", "managed": true} + ]}]})); + assert_eq!(state, "Needs attention"); + assert!( + details + .iter() + .any(|d| d == "Compose containers: 1/1 running") + ); + let (state, _) = stack_status(&json!({"services": [], "infra": [{"containers": [ + {"state": "running", "health": "healthy", "managed": true} + ]}]})); + assert_eq!(state, "Running"); + } + + #[test] + fn daemon_liveness_and_completed_jobs_do_not_claim_stack_health() { + assert_eq!( + stack_status(&json!({"services": [], "infra": []})).0, + "Daemon running" + ); + assert_eq!( + stack_status( + &json!({"services": [{"status": {"state": "starting"}}], "infra": []}) + ) + .0, + "Starting" + ); + assert_eq!(stack_status(&json!({"services": [{"name": "api", "status": {"state": "failed", "reason": "build failed"}}], "infra": []})).0, "Needs attention"); + assert_eq!(stack_status(&json!({"services": [], "infra": [{"error": "engine unavailable", "containers": []}]})).0, "Needs attention"); + } + + #[test] + fn successful_jobs_and_stopped_optional_tools_do_not_make_a_running_stack_partial() { + let (state, details) = stack_status(&json!({"services": [ + {"name": "api", "autostart": true, "status": {"state": "running"}}, + {"name": "prepare", "autostart": true, "status": {"state": "completed", "exit_code": 0}}, + {"name": "tool", "autostart": false, "status": {"state": "stopped"}} + ], "infra": []})); + assert_eq!(state, "Running"); + assert!(details.contains(&"Jobs completed successfully: 1".to_string())); + } + + fn profile_fixture() -> (tempfile::TempDir, PathBuf, Value) { + let temp = tempfile::tempdir().unwrap(); + let file = temp.path().join("devstack.toml"); + std::fs::write( + &file, + r#" +version = 1 +[stack] +name = "example" +[services.api] +run = "example-api" +[services.worker] +run = "example-worker" +[compose.app] +project = "example-app" +files = ["compose.yml"] +services = ["db", "cache"] +[compose.search] +project = "example-search" +files = ["compose.yml"] +services = ["engine"] +[profiles.lite] +skip = ["compose.app.cache", "compose.search", "worker"] +"#, + ) + .unwrap(); + let view = json!({ + "profile": "lite", "config_changed": false, + "services": [ + {"name": "api", "autostart": true, "status": {"state": "running"}}, + {"name": "worker", "autostart": false, "status": {"state": "stopped"}} + ], + "infra": [ + {"group": "app", "containers": [ + {"service": "db", "state": "running", "health": "healthy", "managed": true}, + {"service": "cache", "state": "exited", "health": "", "exit_code": 0, "managed": true} + ]}, + {"group": "search", "containers": [ + {"service": "engine", "state": "exited", "health": "", "exit_code": 0, "managed": true} + ]} + ] + }); + (temp, file, view) + } + + #[test] + fn a_profile_can_leave_out_a_container_a_group_and_a_native_service() { + let (_temp, file, view) = profile_fixture(); + let (status, details) = super::stack_status(&view, Some(&file)); + assert_eq!(status, "Running"); + assert!(details.contains(&"Compose containers: 1/1 running".to_string())); + assert!(details.contains(&"Profile leaves out 2 stopped containers".to_string())); + } + + #[test] + fn a_skipped_container_started_on_demand_is_still_counted_and_checked() { + let (_temp, file, mut view) = profile_fixture(); + let cache = &mut view["infra"][0]["containers"][1]; + cache["state"] = json!("running"); + cache["health"] = json!("healthy"); + let (status, details) = super::stack_status(&view, Some(&file)); + assert_eq!(status, "Running"); + assert!(details.contains(&"Compose containers: 2/2 running".to_string())); + view["infra"][0]["containers"][1]["health"] = json!("unhealthy"); + assert_eq!(super::stack_status(&view, Some(&file)).0, "Needs attention"); + view["infra"][0]["containers"][1]["state"] = json!("dead"); + assert_eq!(super::stack_status(&view, Some(&file)).0, "Needs attention"); + view["infra"][0]["containers"][1]["health"] = json!(""); + view["infra"][0]["containers"][1]["state"] = json!("exited"); + view["infra"][0]["containers"][1]["exit_code"] = json!(1); + assert_eq!(super::stack_status(&view, Some(&file)).0, "Needs attention"); + view["infra"][0]["containers"][1]["exit_code"] = Value::Null; + assert_eq!(super::stack_status(&view, Some(&file)).0, "Partly running"); + for code in [0, 130, 137, 143] { + view["infra"][0]["containers"][1]["exit_code"] = json!(code); + assert_eq!(super::stack_status(&view, Some(&file)).0, "Running"); + } + } + + #[test] + fn changed_or_unavailable_profile_config_does_not_hide_stopped_containers() { + let (_temp, file, mut view) = profile_fixture(); + view["config_changed"] = json!(true); + let (status, details) = super::stack_status(&view, Some(&file)); + assert_eq!(status, "Status incomplete"); + assert!(details.contains(&"Compose containers: 1/3 running".to_string())); + assert!( + details + .iter() + .any(|detail| detail.starts_with("Profile container expectations unavailable")) + ); + view["config_changed"] = json!(false); + std::fs::remove_file(&file).unwrap(); + assert_eq!( + super::stack_status(&view, Some(&file)).0, + "Status incomplete" + ); + } + + #[test] + fn a_failed_or_held_candidate_needs_attention_while_the_main_service_still_runs() { + for state in ["failed", "held"] { + let (status, _) = stack_status(&json!({"services": [ + {"name": "api", "status": {"state": "healthy"}, "candidate": {"state": state, "reason": "inspect update"}} + ], "infra": []})); + assert_eq!(status, "Needs attention"); + } + } + + #[test] + fn a_failed_live_rebuild_needs_attention_even_when_its_dev_server_is_healthy() { + for errors in [ + json!(["", "[ERROR] TS2304: Cannot find name 'missing'."]), + json!([]), + ] { + let (status, details) = stack_status(&json!({"services": [{ + "name": "web", "kind": "devserver", "autostart": true, + "status": {"state": "healthy"}, + "rebuild": {"state": "failed", "since": 1234, "ms": 120, "tool": "angular", "errors": errors} + }], "infra": []})); + assert_eq!(status, "Needs attention"); + assert!( + details + .iter() + .any(|detail| detail.starts_with("web: rebuild failed — ")) + ); + assert!(details.iter().any(|detail| detail.contains("TS2304") + || detail.contains("open Dashboard for details"))); + } + } + + #[test] + fn an_offline_collector_and_a_cancelled_worker_do_no_network_or_child_work() { + let (_temp, s) = fixture(); + let stop = Arc::new(AtomicBool::new(true)); + let stack = collect_stack(s.stacks[0].entry.clone(), &stop); + assert_eq!(stack.status, "Daemon stopped"); + let (_actions, receiver) = mpsc::channel(); + let (sender, updates) = mpsc::channel(); + worker(receiver, sender, stop); + assert!(updates.try_recv().is_err()); + } + + #[test] + fn cancellation_does_not_create_a_child_or_modify_a_stack() { + let cancelled = AtomicBool::new(true); + execute( + &Invocation { + program: Some("/this/does/not/exist".into()), + args: vec![], + directory: None, + progress: String::new(), + }, + &cancelled, + ) + .unwrap(); + } + + #[test] + fn labels_cannot_inject_menu_lines_and_are_unicode_safe() { + assert_eq!(short("two\nlines\t", 20), "two lines "); + assert_eq!(short("🔧🔧🔧", 2), "🔧…"); + } + } +} diff --git a/docs/adr/0060-macos-has-an-optional-menu-bar-client.md b/docs/adr/0060-macos-has-an-optional-menu-bar-client.md new file mode 100644 index 00000000..2071add8 --- /dev/null +++ b/docs/adr/0060-macos-has-an-optional-menu-bar-client.md @@ -0,0 +1,63 @@ +# ADR-0060: macOS has an optional menu bar client of the existing control surface + +- **Status:** Proposed (2026-10-23) +- **Date:** 2026-10-23 +- **Deciders:** project owner (pending review) +- **Related:** [ADR-0007](0007-one-http-api-is-the-control-surface.md), [ADR-0018](0018-dashboard-is-a-browser-page.md), [ADR-0021](0021-a-hub-serves-the-dashboard.md), [ADR-0045](0045-the-hub-notifies-the-desktop.md), [ADR-0054](0054-macos-is-a-developer-platform-in-preview.md) + +## Context + +The macOS preview has a dashboard hub but no persistent entry in the menu +bar. Opening a terminal to reach that dashboard or start a registered stack +interrupts work in another application. AppKit needs the process's main +thread, while the hub already has a server runtime and serves every stack. + +## Decision + +1. Add an opt-in `devstack menubar` command on macOS. It is a native AppKit + status item, without a window, web view, app bundle or extra executable. + Other platforms report that this command is macOS-only. Existing hub + startup, installers and login integration remain unchanged. +2. The menu shows the hub's availability and registered local stacks. It + opens the paired dashboard, starts or stops the hub, starts or stops an + individual stack and its Compose infrastructure, opens a stack's folder, + refreshes status, opens GitHub's feedback issue chooser, and exits the + menu client. Exiting leaves hub and stacks + running; there is no ambiguous global "quit everything" action. +3. This is another client, not another supervisor. It reads the existing + registry and authenticated API, and invokes the existing CLI lifecycle + commands with argument arrays. It implements no process killing, Docker + ownership, browser pairing or stack lifecycle logic of its own. +4. Network requests and child commands run off the AppKit main thread. The + main thread owns only the status item and menus; channels carry snapshots + and user actions. Menu actions show progress and failures. Status refreshes + periodically; a closed menu client performs no further background work. +5. AppKit bindings are dependencies for macOS only. The Windows binary and + static Linux binary acquire no new GUI runtime dependency. Unit tests of + menu decisions run without a desktop; a real Mac checks the native menu. + +The status item uses a transparent template version of the existing +dashboard logo. GitHub feedback opens a fixed page without attaching logs +or submitting a report. + +This proposes refining ADR-0018's unbuilt per-daemon tray into one optional +menu client for the user's hub. Notifications remain the hub's concern as +decided by ADR-0045. + +## Alternatives considered + +- A tray per daemon: one icon per repository and none when its daemon stops. +- AppKit inside the hub: entangles the server's lifetime with a GUI run loop + and changes existing headless and login workflows. +- A separate Swift application: a second build, packaging and update path + for actions the existing Rust binary can provide. +- A cross-platform tray crate: brings Linux desktop runtime dependencies for + a macOS preview feature and puts a wider platform decision into this change. + +## Enforced by + +- `crates/devstack-desktop/src/menubar/`: portable menu model and macOS + AppKit adapter. +- `crates/devstack/src/menubar.rs`: status collection and command dispatch. +- `crates/devstack/src/main.rs`, `dispatch/`: opt-in CLI entry point. +- `docs/macos.md`: usage, lifecycle and real-Mac verification checklist. diff --git a/docs/adr/README.md b/docs/adr/README.md index 684d06d8..6d5f8570 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -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-macos-has-an-optional-menu-bar-client.md) | macOS has an optional menu bar client of the existing control surface | Proposed | diff --git a/docs/images/macos-menu-bar.png b/docs/images/macos-menu-bar.png new file mode 100644 index 00000000..0e30fdbc Binary files /dev/null and b/docs/images/macos-menu-bar.png differ diff --git a/docs/macos.md b/docs/macos.md index 4acbcbf0..87e8f78f 100644 --- a/docs/macos.md +++ b/docs/macos.md @@ -25,6 +25,7 @@ with a browser is blocked until `xattr -d com.apple.quarantine devstack`. | | | |---|---| | CLI, daemon, hub and dashboard; lanes on the Mac | yes | +| An optional native menu bar | `devstack menubar` (see below); explicit start, no extra login integration | | 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 | @@ -33,6 +34,61 @@ with a browser is blocked until `xattr -d com.apple.quarantine devstack`. | Desktop notifications, the `devstack://` link | not yet: both need a signed app bundle | | A Mac as a pool node | not yet | +## Menu bar + +```sh +devstack menubar +``` + +Keep the command running, or launch it in the background from your shell. +It adds a native status item without a Dock window. It does not require a +stack file in the current folder: it lists stacks already registered by +`devstack up`, including stopped ones, for this user's state directory. + +The menu opens and pairs the dashboard, shows the hub's status, starts or +stops the dashboard hub, and provides a submenu for each registered stack: +open its dashboard, start it, stop it together with its Compose containers, +or open its folder in Finder. Status refreshes periodically and can also be +refreshed manually. Work is done away from the native UI thread, with +progress and errors shown in the menu. + +**Give Feedback…** opens this project's GitHub issue chooser in the default +browser. It sends no logs or report contents automatically and remains +available while the dashboard hub is stopped. + +**Quit Menu Bar leaves the hub and stacks running.** Stop Dashboard Hub +also leaves stacks running. Stopping a stack uses `down --infra`, without +`--all`: active worktree lanes keep their existing lifecycle semantics. +Use the dashboard for individual services, lanes, logs and more detailed +operations. This command installs no LaunchAgent and changes no login +settings. On Windows and Linux it reports that it is macOS-only. + +The menu respects `DEVSTACK_HUB_PORT` and `XDG_STATE_HOME`, like the CLI. +The existing `DEVSTACK_NO_HUB_INTEGRATION` setting still controls whether +other lifecycle commands register login integration. + +The status item uses devstack's three-stroke-and-dot logo as a transparent +template image, so macOS renders it for the current menu bar appearance. + +![Native macOS menu with example stacks](images/macos-menu-bar.png) + +### Verify on a real Mac + +- Start a small stack, then run `devstack menubar` from another directory. + There is one icon, its native menu opens, and the stack's status matches + the dashboard. Starting the command again should report it already runs. +- Open Dashboard: the browser is paired automatically. Stop the hub from + the menu: the stack still answers and refresh leaves the hub stopped. + Start the hub again and open the stack's dashboard. +- Stop a stack from its submenu: its HTTP ports close. Start it again: its + health check passes. While an action runs the menu remains responsive. +- A failed action or an unreachable daemon shows an error rather than a + healthy or stopped state. A missing stack folder cannot be started. +- Quit Menu Bar while a stack runs: only the icon disappears; the stack + still answers, and the hub still serves its dashboard. +- Capture screenshots using a generic demo stack and a separate state + directory, so private stack names and paths do not enter a public report. + ## Checklist for testers What CI cannot show. Each step names what to look for; anything else is a bug.