All your machines, one app. For you and your AI agents: agent sessions, desktops, files, logs and GitHub across your Macs, Linux and Windows machines, with an MCP server.
Command palette and quick switcher, theme picker, destroy fixes
Adib Hannaddb73197e2bf
diff --git a/README.md b/README.mdindex 802075d..d20dfb7 100644--- a/README.md+++ b/README.md@@ -80,7 +80,7 @@ muxen statusThe macOS themes also switch to the system fonts (SF Pro, and SF Mono when it's installed). The choice is saved in `config.toml` (`[ui]`).-Keyboard: ⌘1…⌘9 go to your machines · ⌃1…⌃4 overview, jobs, workspaces, GitHub (Alt on Linux and Windows) · ⌘J activity · ⌘R check machines · ⇧⌘R sync GitHub · ⌘N add machine · ⌘T new session · ⌘F or `/` search the fleet · ⌘B sidebar · ⌘[ / ⌘] back / forward · ⌘, settings. Hold ⌘ to see them in the app, and change them in Settings › Keyboard. On Linux and Windows, use Ctrl instead of ⌘.+Keyboard: ⌘P goes to any machine, session or desktop by name, and ⇧⌘P (or ⌘P then `>`) runs any command, including **Theme: Choose…**, which previews each theme as you move through the list · ⌘1…⌘9 go to your machines · ⌃1…⌃4 overview, jobs, workspaces, GitHub (Alt on Linux and Windows) · ⌘J activity · ⌘R check machines · ⇧⌘R sync GitHub · ⌘N add machine · ⌘T new session · ⌘F or `/` search the fleet · ⌘B sidebar · ⌘[ / ⌘] back / forward · ⌘, settings. Hold ⌘ to see them in the app, and change them in Settings › Keyboard. On Linux and Windows, use Ctrl instead of ⌘.## Your settings: `config.toml`diff --git a/src/config.rs b/src/config.rsindex e33eecf..bfc45c3 100644--- a/src/config.rs+++ b/src/config.rs@@ -28,6 +28,9 @@ pub struct Paths {pub state: PathBuf,/// Agent workspaces, shared by every Muxen process (see fleet::workspaces).pub workspaces: PathBuf,+ /// Cloud machines destroyed lately (see DestroyedCloud). Its own file, so+ /// the processes that write state.json don't save over each other's.+ pub cloud_history: PathBuf,}impl Paths {@@ -47,6 +50,7 @@ impl Paths {config,state: dir.join("state.json"),workspaces: dir.join("workspaces.json"),+ cloud_history: dir.join("cloud-history.json"),dir,}}@@ -311,6 +315,21 @@ pub struct CloudRef {pub created_at: String,}+/// Cloud machines destroyed lately, from cloud-history.json.+pub fn read_cloud_history(path: &Path) -> Vec<DestroyedCloud> {+ std::fs::read_to_string(path).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default()+}++/// Adds one (replacing an earlier entry for the same droplet) and forgets+/// those destroyed more than about a year ago.+pub fn add_cloud_history(path: &Path, entry: DestroyedCloud) -> Result<()> {+ let mut all = read_cloud_history(path);+ let keep_from = entry.destroyed_at - chrono::Duration::days(400);+ all.retain(|e| e.destroyed_at > keep_from && e.cloud.id != entry.cloud.id);+ all.push(entry);+ write_atomic(path, serde_json::to_string_pretty(&all)?.as_bytes())+}+/// A cloud machine Muxen destroyed, kept so this month's costs still count it.#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]@@ -628,8 +647,6 @@ pub struct PersistedState {/// Cloud machines' power ("active", "off", ...) as the provider last/// reported it, by machine id.pub droplets: HashMap<String, String>,- /// Cloud machines destroyed lately (for this month's costs).- pub cloud_history: Vec<DestroyedCloud>,pub check_started_at: Option<DateTime<Utc>>,pub check_finished_at: Option<DateTime<Utc>>,}@@ -657,6 +674,27 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<()> {#[cfg(test)]mod tests {+ #[test]+ fn cloud_history_keeps_one_entry_per_droplet() {+ let dir = std::env::temp_dir().join(format!("muxen-cloud-history-{}", std::process::id()));+ let path = dir.join("cloud-history.json");+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ let entry = |id: u64, at: &str| DestroyedCloud {+ name: format!("dev-{id}"),+ cloud: CloudRef { provider: "digitalocean".into(), id, region: "nyc3".into(), size: "s-1vcpu-1gb".into(), price_hourly: 0.00893, created_at: "2026-10-09T18:53:17Z".into() },+ destroyed_at: DateTime::parse_from_rfc3339(at).unwrap().with_timezone(&Utc),+ };+ assert!(read_cloud_history(&path).is_empty());+ add_cloud_history(&path, entry(1, "2025-01-01T00:00:00Z")).unwrap();+ add_cloud_history(&path, entry(2, "2026-10-09T21:22:19Z")).unwrap();+ add_cloud_history(&path, entry(2, "2026-10-09T21:22:20Z")).unwrap();+ // Over a year old is gone; the same droplet twice is one entry.+ let all = read_cloud_history(&path);+ assert_eq!(all.iter().map(|e| e.cloud.id).collect::<Vec<_>>(), vec![2]);+ let _ = std::fs::remove_dir_all(&dir);+ }+#[test]fn old_files_become_one_config_toml() {let dir = std::env::temp_dir().join(format!("muxin-migrate-{}", std::process::id()));diff --git a/src/fleet/engine.rs b/src/fleet/engine.rsindex b3c3683..8872176 100644--- a/src/fleet/engine.rs+++ b/src/fleet/engine.rs@@ -75,8 +75,6 @@ struct State {tailscale: Option<super::model::TailscaleStatus>,/// Cloud machines' power as the provider last reported it ("active", "off", ...).droplets: HashMap<String, String>,- /// Cloud machines destroyed lately (see config::DestroyedCloud).- cloud_history: Vec<crate::config::DestroyedCloud>,/// Stop flags of the operations that can be cancelled.cancels: HashMap<u64, Arc<std::sync::atomic::AtomicBool>>,}@@ -148,7 +146,6 @@ impl Engine {tailnet: persisted.tailnet,tailscale: None,droplets: persisted.droplets,- cloud_history: persisted.cloud_history,cancels: HashMap::new(),};let (tx, _) = watch::channel(Arc::new(Snapshot::default()));@@ -506,16 +503,16 @@ impl Engine {/// Remembers a destroyed cloud machine for this month's costs (and the/// next one's, for a while), and forgets its power state.pub(crate) fn record_destroyed(&self, machine_id: &str, entry: crate::config::DestroyedCloud) {+ if let Err(e) = crate::config::add_cloud_history(&self.paths().cloud_history, entry) {+ tracing::warn!("couldn't write {}: {e}", self.paths().cloud_history.display());+ }let mut st = self.state.lock().unwrap();st.droplets.remove(machine_id);- let keep_from = entry.destroyed_at - chrono::Duration::days(400);- st.cloud_history.retain(|e| e.destroyed_at > keep_from && e.cloud.id != entry.cloud.id);- st.cloud_history.push(entry);self.save_state(&mut st);}pub(crate) fn cloud_history(&self) -> Vec<crate::config::DestroyedCloud> {- self.state.lock().unwrap().cloud_history.clone()+ crate::config::read_cloud_history(&self.paths().cloud_history)}/// True while another operation is changing this machine.@@ -971,11 +968,13 @@ impl Engine {/// Writes state.json (checks and what Tailscale knows).fn save_state(&self, st: &mut State) {+ // Power states of machines no longer in the fleet (destroyed ones) go.+ let ids: HashSet<String> = st.inventory.machines.iter().map(|m| m.id.clone()).collect();+ st.droplets.retain(|id, _| ids.contains(id));let persisted = PersistedState {probes: st.probes.clone(),tailnet: st.tailnet.clone(),droplets: st.droplets.clone(),- cloud_history: st.cloud_history.clone(),check_started_at: st.check_started_at,check_finished_at: st.check_finished_at,};diff --git a/src/ops/cloud.rs b/src/ops/cloud.rsindex 8cbd627..ca6ded4 100644--- a/src/ops/cloud.rs+++ b/src/ops/cloud.rs@@ -272,7 +272,8 @@ impl Engine {// Its cost this month still counts.me.record_destroyed(&spec.id, crate::config::DestroyedCloud { name: spec.name.clone(), cloud: cloud.clone(), destroyed_at: Utc::now() });me.op_log(op, format!("▸ Removing {} from config.toml", spec.name));- me.remove_machine(&spec.id)?;+ // Not remove_machine: this operation is the one keeping the machine busy.+ me.forget_machine(&spec.id)?;// Its address may be reused by someone else's droplet.if let Some(ip) = spec.host.rsplit('@').next() {let _ = tokio::process::Command::new("ssh-keygen").args(["-R", ip]).output().await;@@ -388,7 +389,8 @@ impl Engine {since_created: usage::cost_since(c.price_hourly, created, None, now),});}- let hourly_now = machines.iter().map(|l| l.price_hourly).sum::<f64>();+ // fold, not sum: an empty f64 sum is -0.0 ("$-0.00").+ let hourly_now = machines.iter().fold(0., |t, l| t + l.price_hourly);for h in self.cloud_history() {let created = DateTime::parse_from_rfc3339(&h.cloud.created_at).map(|t| t.with_timezone(&Utc)).unwrap_or(h.destroyed_at);let this_month = usage::cost_in_month(h.cloud.price_hourly, created, Some(h.destroyed_at), month, now);@@ -410,7 +412,7 @@ impl Engine {since_created: usage::cost_since(h.cloud.price_hourly, created, Some(h.destroyed_at), now),});}- let this_month = machines.iter().map(|l| l.this_month).sum::<f64>();+ let this_month = machines.iter().fold(0., |t, l| t + l.this_month);let (mut account, mut account_error, mut account_needs_sign_in) = (None, None, false);if self.demo_world().is_none() {diff --git a/src/ops/mod.rs b/src/ops/mod.rsindex ed23f22..b8bfd24 100644--- a/src/ops/mod.rs+++ b/src/ops/mod.rs@@ -340,6 +340,12 @@ impl Engine {if self.machine_busy(machine_id) {return Err("An operation is still running on this machine. Wait for it to finish.".into());}+ self.forget_machine(machine_id)+ }++ /// Drops a machine from config.toml, for an operation that is itself+ /// what's changing it (destroying a cloud machine).+ pub(crate) fn forget_machine(self: &Arc<Self>, machine_id: &str) -> Result<(), String> {let edit = |text: &str| inventory_edit::remove_machine(text, machine_id);match self.demo_world() {Some(w) => w.edit_inventory(edit)?,diff --git a/src/ui/input.rs b/src/ui/input.rsindex 444629e..ffb9482 100644--- a/src/ui/input.rs+++ b/src/ui/input.rs@@ -62,6 +62,8 @@ pub struct TextInput {mono: bool,/// Shows "•" for each character and won't copy (tokens, keys).secret: bool,+ /// No frame of its own (it sits in one, like the palette's).+ bare: bool,}impl EventEmitter<InputEvent> for TextInput {}@@ -80,6 +82,7 @@ impl TextInput {is_selecting: false,mono: false,secret: false,+ bare: false,}}@@ -93,6 +96,11 @@ impl TextInput {self}+ pub fn bare(mut self) -> Self {+ self.bare = true;+ self+ }+/// Where a text offset is on screen: the same, unless each character is/// shown as one "•" (3 bytes).fn to_display(&self, offset: usize) -> usize {@@ -569,12 +577,11 @@ impl Render for TextInput {.h(px(28.)).px(px(8.)).rounded(px(6.))- .border_1()- .border_color(if focused { theme.border_focused } else { theme.border_variant })- .bg(theme.canvas)+ .when(!self.bare, |d| d.border_1().border_color(if focused { theme.border_focused } else { theme.border_variant }).bg(theme.canvas))+ .when(self.bare, |d| d.px(px(0.))).text_color(theme.text).font_family(if self.mono { mono_font() } else { ui_font() })- .text_size(px(13.))+ .text_size(px(if self.bare { 14. } else { 13. })).line_height(px(18.)).overflow_hidden().child(TextElement { input: cx.entity() })diff --git a/src/ui/mod.rs b/src/ui/mod.rsindex d4e037a..19c4766 100644--- a/src/ui/mod.rs+++ b/src/ui/mod.rs@@ -13,6 +13,7 @@ mod input;mod kit;mod menu;mod overview;+mod palette;mod desktop;mod sessions;mod settings;@@ -71,6 +72,9 @@ pub fn run(engine: Arc<Engine>, initial_view: Option<String>) {titlebar: Some(titlebar),window_min_size: Some(size(px(960.), px(600.))),app_id: Some("muxen".into()),+ // A test window (on the laptop's screen) doesn't take the keyboard+ // from whatever the user is typing in.+ focus: !wants_builtin,..Default::default()},|window, cx| {@@ -96,7 +100,9 @@ pub fn run(engine: Arc<Engine>, initial_view: Option<String>) {}}).detach();- cx.activate(true);+ if !wants_builtin {+ cx.activate(true);+ }});}diff --git a/src/ui/palette.rs b/src/ui/palette.rsnew file mode 100644index 0000000..44506b2--- /dev/null+++ b/src/ui/palette.rs@@ -0,0 +1,601 @@+//! ⌘P: go to a machine, a session or a desktop. ⇧⌘P (or ">" first): run a+//! command. One search box for both, like an editor's; both shortcuts can be+//! changed in Settings › Keyboard.++use gpui::{AnyElement, App, Context, Entity, Focusable, FontWeight, KeyBinding, ScrollHandle, SharedString, Subscription, Window, actions, div, prelude::*, px};++use super::format;+use super::input::{InputEvent, TextInput};+use super::kit::{self, icon};+use super::root::{Root, Route};+use super::settings::SettingsTab;+use super::theme::{self, Mode, Theme, mono_font};++actions!(palette, [PaletteUp, PaletteDown]);++const CONTEXT: &str = "Palette";+const WIDTH: f32 = 640.;+/// A row's inset from the panel, and its own padding: the search icon and the+/// hints line up with the rows' icons.+const ROW_INSET: f32 = 10.;+const ROW_PAD: f32 = 14.;+const EDGE: f32 = ROW_INSET + ROW_PAD;+/// How far a machine's sessions and desktop sit in under it.+const INDENT: f32 = 28.;+/// What's left for an item's words: the width less insets, glyph, gaps and the right-hand label.+const TEXT_WIDTH: f32 = WIDTH - 2. * EDGE - 22. - 2. * 12. - 120.;++pub fn bind_keys(cx: &mut App) {+ cx.bind_keys([+ KeyBinding::new("up", PaletteUp, Some(CONTEXT)),+ KeyBinding::new("down", PaletteDown, Some(CONTEXT)),+ KeyBinding::new("ctrl-p", PaletteUp, Some(CONTEXT)),+ KeyBinding::new("ctrl-n", PaletteDown, Some(CONTEXT)),+ ]);+}++pub struct Palette {+ input: Entity<TextInput>,+ /// A row picked with the arrows, and the text it was picked for. Until+ /// then, or once the text changes, the selection is the best match.+ picked: Option<(String, usize)>,+ scroll: ScrollHandle,+ /// Picking a theme: the preferences to go back to, and the theme that was showing.+ themes: Option<(theme::Appearance, String)>,+ /// The text the list was last made for (changes that leave it alone don't reset the selection).+ query: String,+ _changes: Subscription,+}++#[derive(Clone, Copy, PartialEq)]+enum Command {+ AddMachine,+ NewCloudMachine,+ NewSession,+ NewWorkspace,+ CopyFiles,+ CheckMachines,+ SyncGitHub,+ ToggleSidebar,+ Back,+ Forward,+ Settings(SettingsTab),+ Theme(Mode),+ ChooseTheme,+}++#[derive(Clone)]+enum Run {+ Go(Route),+ Do(Command),+ /// A theme, by id.+ Theme(&'static str),+}++enum Glyph {+ Icon(&'static str),+ /// An agent CLI's id ("claude", "shell", ...).+ Agent(String),+ Machine(&'static str, (u32, u32)),+ /// A theme's background and accent.+ Swatch(u32, u32),+}++struct Item {+ title: String,+ detail: String,+ /// The right-hand side: "Machine", "Session", "Desktop", or a command's keys.+ side: String,+ side_is_keys: bool,+ glyph: Glyph,+ run: Run,+ /// Under its machine (a session or desktop), like the sidebar's tree.+ indent: bool,+ /// The machine it's under, or is (places only).+ group: Option<String>,+ /// More words a search can match that the row doesn't show (its machine's name).+ also: String,+ /// How well it matched the search; None when it's only there as its group's heading.+ score: Option<i32>,+}++impl Item {+ fn new(title: impl Into<String>, detail: impl Into<String>, side: impl Into<String>, glyph: Glyph, run: Run) -> Item {+ Item { title: title.into(), detail: detail.into(), side: side.into(), side_is_keys: false, glyph, run, indent: false, group: None, also: String::new(), score: None }+ }+}++/// How well `query` matches `text`: every word of it, in order within the+/// word, case-insensitive; None when it doesn't. Higher is better: whole+/// substrings beat scattered letters, and starts of words count extra.+pub fn score(query: &str, text: &str) -> Option<i32> {+ let text = text.to_lowercase();+ let mut total = 0;+ for word in query.to_lowercase().split_whitespace() {+ total += word_score(word, &text)?;+ }+ Some(total)+}++fn word_score(word: &str, text: &str) -> Option<i32> {+ if let Some(pos) = text.find(word) {+ let at_word = pos == 0 || !text[..pos].chars().next_back().is_some_and(char::is_alphanumeric);+ return Some(1000 - pos.min(200) as i32 + if pos == 0 { 300 } else if at_word { 150 } else { 0 });+ }+ // Letters in order, anywhere.+ let chars: Vec<char> = text.chars().collect();+ let (mut i, mut s, mut last) = (0, 0, None::<usize>);+ for c in word.chars() {+ let found = (i..chars.len()).find(|&j| chars[j] == c)?;+ s += 10;+ if last == Some(found.wrapping_sub(1)) {+ s += 15;+ }+ if found == 0 || !chars[found - 1].is_alphanumeric() {+ s += 20;+ }+ last = Some(found);+ i = found + 1;+ }+ Some(s)+}++impl Root {+ /// Opens the palette: commands (`commands`) or places. The same shortcut+ /// again closes it.+ pub(super) fn open_palette(&mut self, commands: bool, window: &mut Window, cx: &mut Context<Self>) {+ if self.modal.is_some() {+ return;+ }+ if let Some(p) = &self.palette {+ let showing_commands = p.input.read(cx).text().starts_with('>');+ if showing_commands == commands {+ self.close_palette(window, cx);+ return;+ }+ }+ let input = cx.new(|cx| TextInput::new(cx, "Go to a machine, session or desktop (> for commands)").bare().with_text(if commands { ">" } else { "" }));+ let changes = cx.subscribe_in(&input, window, |this, _, e: &InputEvent, window, cx| match e {+ InputEvent::Changed => {+ let Some(p) = &this.palette else { return };+ let text = p.input.read(cx).text().to_string();+ if text == p.query {+ return;+ }+ let best = this.best_palette_item(cx);+ let Some(p) = &mut this.palette else { return };+ p.query = text;+ p.scroll.scroll_to_item(best);+ this.preview_theme(window, cx);+ cx.notify()+ }+ InputEvent::Submit => this.run_palette_item(None, window, cx),+ InputEvent::Cancel => this.close_palette(window, cx),+ });+ window.focus(&input.focus_handle(cx));+ self.context_menu = None;+ let query = input.read(cx).text().to_string();+ self.palette = Some(Palette { input, picked: None, scroll: ScrollHandle::new(), themes: None, query, _changes: changes });+ cx.notify();+ }++ /// The palette with `text` typed (test views).+ pub(super) fn open_palette_with(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {+ self.open_palette(text.starts_with('>'), window, cx);+ if let Some(p) = &self.palette {+ p.input.update(cx, |i, cx| i.set_text(text.to_string(), cx));+ }+ }++ /// Closes it; a theme being previewed goes back to the one before.+ pub(super) fn close_palette(&mut self, window: &mut Window, cx: &mut Context<Self>) {+ if let Some(p) = self.palette.take() {+ if let Some((before, _)) = p.themes {+ theme::preview_appearance(window, cx, before);+ }+ window.focus(&self.focus);+ cx.notify();+ }+ }++ /// The selected row: the one picked for this text, else the best match.+ fn palette_selection(&self, cx: &App) -> usize {+ let Some(p) = &self.palette else { return 0 };+ match &p.picked {+ Some((text, ix)) if text.as_str() == p.input.read(cx).text() => *ix,+ _ => self.best_palette_item(cx),+ }+ }++ fn move_palette(&mut self, by: isize, window: &mut Window, cx: &mut Context<Self>) {+ let count = self.palette_items(cx).len();+ let from = self.palette_selection(cx);+ if let Some(p) = &mut self.palette {+ if count > 0 {+ let to = (from as isize + by).rem_euclid(count as isize) as usize;+ p.picked = Some((p.input.read(cx).text().to_string(), to));+ p.scroll.scroll_to_item(to);+ }+ }+ self.preview_theme(window, cx);+ cx.notify();+ }++ /// Lists the themes, starting at the one showing; moving through them shows each.+ pub(super) fn choose_theme(&mut self, cx: &mut Context<Self>) {+ let showing = theme::ActiveTheme::theme(&**cx).id.to_string();+ let before = cx.global::<theme::Appearance>().clone();+ let Some(p) = &mut self.palette else { return };+ p.themes = Some((before, showing.clone()));+ p.query = String::new();+ p.input.update(cx, |i, cx| {+ i.set_placeholder("Pick a theme (↑↓ to try one)", cx);+ i.set_text("", cx);+ });+ let at = super::themes::PALETTES.iter().position(|t| t.id == showing).unwrap_or(0);+ if let Some(p) = &mut self.palette {+ p.picked = Some((String::new(), at));+ p.scroll.scroll_to_item(at);+ }+ cx.notify();+ }++ /// Shows the selected theme, without keeping it (Enter keeps it).+ fn preview_theme(&mut self, window: &mut Window, cx: &mut Context<Self>) {+ let Some(p) = &self.palette else { return };+ let Some((before, _)) = p.themes.clone() else { return };+ if let Some(Run::Theme(id)) = self.palette_items(cx).into_iter().nth(self.palette_selection(cx)).map(|i| i.run) {+ let mut a = before;+ theme::choose_theme(&mut a, id, window.appearance());+ theme::preview_appearance(window, cx, a);+ }+ }++ /// Runs the item at `index`, or the selected one.+ fn run_palette_item(&mut self, index: Option<usize>, window: &mut Window, cx: &mut Context<Self>) {+ if self.palette.is_none() {+ return;+ }+ let ix = index.unwrap_or_else(|| self.palette_selection(cx));+ let Some(run) = self.palette_items(cx).into_iter().nth(ix).map(|i| i.run) else { return };+ match run {+ Run::Do(Command::ChooseTheme) => return self.choose_theme(cx),+ Run::Theme(id) => {+ // Keep it: nothing to go back to.+ if let Some(p) = &mut self.palette {+ p.themes = None;+ }+ self.close_palette(window, cx);+ theme::update_appearance(window, cx, |a, system| theme::choose_theme(a, id, system));+ return;+ }+ _ => {}+ }+ self.close_palette(window, cx);+ match run {+ Run::Go(route) => self.navigate(route, window, cx),+ Run::Do(c) => match c {+ Command::AddMachine => self.show_add_machine(window, cx),+ Command::NewCloudMachine => self.show_cloud_dialog(window, cx),+ Command::NewSession => self.show_new_session(None, window, cx),+ Command::NewWorkspace => self.show_new_workspace(None, window, cx),+ Command::CopyFiles => self.show_copy_files(None, None, window, cx),+ Command::CheckMachines => self.engine.trigger_check(None),+ Command::SyncGitHub => self.engine.trigger_sync(),+ Command::ToggleSidebar => self.toggle_sidebar(cx),+ Command::Back => window.dispatch_action(Box::new(super::root::GoBack), cx),+ Command::Forward => window.dispatch_action(Box::new(super::root::GoForward), cx),+ Command::Settings(tab) => self.open_settings_tab(tab, window, cx),+ Command::Theme(mode) => theme::update_appearance(window, cx, |a, _| a.mode = mode),+ Command::ChooseTheme => {}+ },+ Run::Theme(_) => {}+ }+ }++ /// What the palette lists for its query, best first.+ fn palette_items(&self, cx: &App) -> Vec<Item> {+ let Some(p) = &self.palette else { return Vec::new() };+ let text = p.input.read(cx).text().to_string();+ let (items, query) = match text.strip_prefix('>') {+ _ if p.themes.is_some() => (self.theme_items(), text.trim().to_string()),+ Some(q) => (self.command_items(cx), q.trim().to_string()),+ None => (self.place_items(cx), text.trim().to_string()),+ };+ if query.is_empty() {+ return items;+ }+ // The title counts most; the rest (machine, folder, kind) can still match.+ let matches = |i: &Item| {+ score(&query, &i.title)+ .map(|s| s + 500)+ .or_else(|| score(&query, &format!("{} {} {} {}", i.title, i.detail, i.also, if i.side_is_keys { "" } else { &i.side })))+ };+ let scores: Vec<Option<i32>> = items.iter().map(matches).collect();+ if items.iter().any(|i| i.group.is_some()) {+ // Places keep their tree: a machine stays, as the heading, when+ // something under it matches.+ let groups: std::collections::HashSet<String> = items.iter().zip(&scores).filter(|(_, s)| s.is_some()).filter_map(|(i, _)| i.group.clone()).collect();+ return items+ .into_iter()+ .zip(scores)+ .filter_map(|(mut i, s)| {+ let heading = !i.indent && i.group.as_ref().is_some_and(|g| groups.contains(g));+ (s.is_some() || heading).then(|| {+ i.score = s;+ i+ })+ })+ .collect();+ }+ let mut scored: Vec<Item> = items+ .into_iter()+ .zip(scores)+ .filter_map(|(mut i, s)| {+ i.score = Some(s?);+ Some(i)+ })+ .collect();+ scored.sort_by(|a, b| b.score.cmp(&a.score));+ scored+ }++ /// The row to start on: the best match (the first, when nothing's typed).+ fn best_palette_item(&self, cx: &App) -> usize {+ let items = self.palette_items(cx);+ items.iter().enumerate().filter_map(|(ix, i)| Some((i.score?, std::cmp::Reverse(ix)))).max().map(|(_, std::cmp::Reverse(ix))| ix).unwrap_or(0)+ }++ /// Each machine (in the sidebar's order), with its sessions and its+ /// desktop under it.+ fn place_items(&self, cx: &App) -> Vec<Item> {+ let s = &self.snapshot;+ let favorites = cx.global::<theme::Appearance>().favorite_machines.clone();+ let machines = Root::machine_order(s, &favorites);+ let session = |x: &crate::fleet::sessions::SessionInfo, machine: &str| {+ let folder = x.cwd.rsplit('/').find(|p| !p.is_empty()).unwrap_or(&x.cwd).to_string();+ let who = if x.agent_name.is_empty() { "Session".to_string() } else { x.agent_name.clone() };+ let mut item = Item::new(+ x.title.clone(),+ [who, folder].into_iter().filter(|p| !p.is_empty()).collect::<Vec<_>>().join(" · "),+ if x.status == "exited" { "Session · ended" } else { "Session" },+ Glyph::Agent(x.agent.clone()),+ Run::Go(Route::Session(x.id.clone())),+ );+ item.also = machine.to_string();+ item+ };+ let mut out = Vec::new();+ for m in &machines {+ let mut head = Item::new(m.name.clone(), format::machine_subtitle(m).0, "Machine", Glyph::Machine(format::machine_icon(m), format::machine_tile(m)), Run::Go(Route::Machine(m.id.clone())));+ head.group = Some(m.id.clone());+ out.push(head);+ for x in s.sessions.iter().filter(|x| x.machine_id == m.id) {+ let mut item = session(x, &m.name);+ item.indent = true;+ item.group = Some(m.id.clone());+ out.push(item);+ }+ if format::has_desktop(m) && !m.local && m.status == "online" {+ let mut item = Item::new("Desktop", "See and use its screen", "Desktop", Glyph::Icon("monitor"), Run::Go(Route::Desktop(m.id.clone())));+ item.indent = true;+ item.group = Some(m.id.clone());+ item.also = m.name.clone();+ out.push(item);+ }+ }+ // Sessions on machines that aren't in the fleet anymore.+ for x in s.sessions.iter().filter(|x| !s.machines.iter().any(|m| m.id == x.machine_id)) {+ out.push(session(x, &x.machine_id));+ }+ out+ }++ fn theme_items(&self) -> Vec<Item> {+ let showing = self.palette.as_ref().and_then(|p| p.themes.as_ref()).map(|(_, id)| id.as_str()).unwrap_or_default();+ super::themes::PALETTES+ .iter()+ .map(|t| {+ let side = format!("{}{}", if t.dark { "Dark" } else { "Light" }, if t.id == showing { " · current" } else { "" });+ Item::new(t.name, "", side, Glyph::Swatch(t.canvas, t.accent), Run::Theme(t.id))+ })+ .collect()+ }++ fn command_items(&self, cx: &App) -> Vec<Item> {+ use super::shortcuts::label_for;+ let keys = |id: &str| label_for(cx, id);+ let item = |title: &str, glyph: &'static str, shortcut: Option<&str>, run: Run| {+ let mut i = Item::new(title, "", shortcut.map(keys).unwrap_or_default(), Glyph::Icon(glyph), run);+ i.side_is_keys = true;+ i+ };+ vec![+ item("Add machine…", "plus", Some("add-machine"), Run::Do(Command::AddMachine)),+ item("New cloud machine…", "cloud", None, Run::Do(Command::NewCloudMachine)),+ item("New session…", "square-terminal", Some("new-session"), Run::Do(Command::NewSession)),+ item("New workspace…", "layers", None, Run::Do(Command::NewWorkspace)),+ item("Copy files between machines…", "folder", None, Run::Do(Command::CopyFiles)),+ item("Go to Overview", "gauge", Some("overview"), Run::Go(Route::Overview)),+ item("Go to Jobs", "workflow", Some("jobs"), Run::Go(Route::Jobs)),+ item("Go to Workspaces", "layers", Some("workspaces"), Run::Go(Route::Workspaces)),+ item("Go to GitHub", "agent-github", Some("github"), Run::Go(Route::Github)),+ item("Go to Activity", "activity", Some("activity"), Run::Go(Route::Activity)),+ item("Check all machines", "refresh-cw", Some("check"), Run::Do(Command::CheckMachines)),+ item("Sync GitHub", "refresh-cw", Some("sync"), Run::Do(Command::SyncGitHub)),+ item("Hide or show the sidebar", "panel-left", Some("sidebar"), Run::Do(Command::ToggleSidebar)),+ item("Back", "arrow-left", Some("back"), Run::Do(Command::Back)),+ item("Forward", "arrow-right", Some("forward"), Run::Do(Command::Forward)),+ item("Settings", "settings", Some("settings"), Run::Do(Command::Settings(SettingsTab::General))),+ item("Settings: Appearance", "palette", None, Run::Do(Command::Settings(SettingsTab::Appearance))),+ item("Settings: Terminal", "terminal", None, Run::Do(Command::Settings(SettingsTab::Terminal))),+ item("Settings: GitHub", "agent-github", None, Run::Do(Command::Settings(SettingsTab::GitHub))),+ item("Settings: Cloud", "cloud", None, Run::Do(Command::Settings(SettingsTab::Cloud))),+ item("Settings: Keyboard shortcuts", "keyboard", None, Run::Do(Command::Settings(SettingsTab::Keyboard))),+ item("Cloud usage and cost", "cloud", None, Run::Do(Command::Settings(SettingsTab::Cloud))),+ item("Install the muxen command", "terminal", None, Run::Do(Command::Settings(SettingsTab::General))),+ item("Theme: Choose…", "palette", None, Run::Do(Command::ChooseTheme)),+ item("Theme: Light mode", "palette", None, Run::Do(Command::Theme(Mode::Light))),+ item("Theme: Dark mode", "palette", None, Run::Do(Command::Theme(Mode::Dark))),+ item("Theme: Match the system", "palette", None, Run::Do(Command::Theme(Mode::System))),+ item("About Muxen", "info", None, Run::Go(Route::About)),+ ]+ }++ pub(super) fn render_palette(&self, theme: &Theme, cx: &mut Context<Self>) -> Option<AnyElement> {+ let p = self.palette.as_ref()?;+ let items = self.palette_items(cx);+ let picking = p.themes.is_some();+ let commands = !picking && p.input.read(cx).text().starts_with('>');+ let selected = self.palette_selection(cx).min(items.len().saturating_sub(1));+ let rows: Vec<AnyElement> = items+ .into_iter()+ .enumerate()+ .map(|(i, item)| {+ let glyph: AnyElement = match item.glyph {+ Glyph::Icon(name) => kit::color_tile(name, 22.).into_any_element(),+ Glyph::Agent(agent) => {+ let (name, (from, to)) = kit::agent_look(&agent);+ kit::tile(name, from, to, 22.).into_any_element()+ }+ Glyph::Machine(name, (from, to)) => kit::tile(name, from, to, 22.).into_any_element(),+ Glyph::Swatch(bg, accent) => div()+ .size(px(22.))+ .rounded(px(6.))+ .border_1()+ .border_color(theme.border)+ .bg(gpui::rgb(bg))+ .flex()+ .items_center()+ .justify_center()+ .child(div().size(px(8.)).rounded_full().bg(gpui::rgb(accent)))+ .into_any_element(),+ };+ let text_w = TEXT_WIDTH - if item.indent { INDENT } else { 0. };+ let side: AnyElement = if item.side_is_keys {+ if item.side.is_empty() { div().into_any_element() } else { kit::kbd(theme, item.side).into_any_element() }+ } else {+ div().text_size(px(11.5)).text_color(theme.text_placeholder).child(item.side).into_any_element()+ };+ div()+ .id(("palette-item", i))+ .flex()+ .items_center()+ .gap(px(12.))+ .h(px(if item.detail.is_empty() { 36. } else { 48. }))+ .mx(px(ROW_INSET))+ .px(px(ROW_PAD))+ .when(item.indent, |d| d.pl(px(ROW_PAD + INDENT)))+ .rounded(px(8.))+ .cursor_pointer()+ .when(i == selected, |d| d.bg(theme.element_selected))+ .when(i != selected, |d| d.hover(|st| st.bg(theme.ghost_hover)))+ .child(div().w(px(22.)).flex_none().flex().justify_center().child(glyph))+ .child(+ div()+ .flex()+ .flex_col()+ .flex_1()+ .min_w(px(0.))+ .child(div().w(px(text_w)).truncate().text_size(px(13.)).text_color(theme.text).child(item.title))+ .when(!item.detail.is_empty(), |d| d.child(div().w(px(text_w)).truncate().text_size(px(11.5)).text_color(theme.text_muted).child(item.detail))),+ )+ .child(div().w(px(120.)).flex_none().flex().justify_end().child(side))+ .on_click(cx.listener(move |this, _, window, cx| this.run_palette_item(Some(i), window, cx)))+ .into_any_element()+ })+ .collect();+ let empty = rows.is_empty();+ let hint = if picking {+ "↑↓ try ↵ keep esc put back"+ } else if commands {+ "↑↓ move ↵ run esc close"+ } else {+ "↑↓ move ↵ open > commands esc close"+ };+ let panel = div()+ .id("palette")+ .key_context(CONTEXT)+ .on_action(cx.listener(|this, _: &PaletteUp, window, cx| this.move_palette(-1, window, cx)))+ .on_action(cx.listener(|this, _: &PaletteDown, window, cx| this.move_palette(1, window, cx)))+ .occlude()+ .on_click(|_, _, cx| cx.stop_propagation())+ .w(px(WIDTH))+ .flex()+ .flex_col()+ .rounded(px(12.))+ .bg(theme.elevated)+ .border_1()+ .border_color(theme.border)+ .shadow_lg()+ .font_weight(FontWeight::NORMAL)+ .child(+ div()+ .flex()+ .items_center()+ .gap(px(12.))+ .px(px(EDGE + 4.))+ .h(px(50.))+ .border_b_1()+ .border_color(theme.border_variant)+ .child(icon(if picking { "palette" } else if commands { "zap" } else { "search" }, 15., theme.text_muted))+ .child(div().flex_1().min_w(px(0.)).text_size(px(14.)).child(p.input.clone())),+ )+ .child(+ div()+ .id("palette-items")+ .max_h(px(420.))+ .overflow_y_scroll()+ .track_scroll(&p.scroll)+ .py(px(8.))+ .when(empty, |d| d.child(div().px(px(EDGE)).py(px(10.)).text_size(px(12.5)).text_color(theme.text_muted).child(if picking { "No theme like that." } else if commands { "No command like that." } else { "Nothing like that. Type > for commands." })))+ .children(rows),+ )+ .child(+ div()+ .flex()+ .items_center()+ .px(px(EDGE))+ .h(px(32.))+ .border_t_1()+ .border_color(theme.border_variant)+ .font_family(mono_font())+ .text_size(px(11.))+ .text_color(theme.text_placeholder)+ .child(SharedString::from(hint)),+ );+ Some(+ div()+ .id("palette-layer")+ .absolute()+ .inset_0()+ .flex()+ .justify_center()+ // At the top, as tall as what it lists.+ .items_start()+ .pt(px(72.))+ .occlude()+ .on_click(cx.listener(|this, _, window, cx| this.close_palette(window, cx)))+ .child(panel)+ .into_any_element(),+ )+ }+}++#[cfg(test)]+mod tests {+ use super::score;++ #[test]+ fn finds_words_and_letters_in_order() {+ assert!(score("bee", "Beelink").is_some());+ assert!(score("blk", "Beelink").is_some());+ assert!(score("xyz", "Beelink").is_none());+ // Every word must match.+ assert!(score("claude bee", "Claude Code · Beelink · api").is_some());+ assert!(score("claude mac", "Claude Code · Beelink · api").is_none());+ // A whole word at the start beats one inside; both beat scattered letters.+ assert!(score("set", "Settings") > score("set", "Reset machines"));+ assert!(score("dark", "Theme: Dark") > score("drk", "Theme: Dark"));+ }+}diff --git a/src/ui/root.rs b/src/ui/root.rsindex 5cbc34a..fbb6816 100644--- a/src/ui/root.rs+++ b/src/ui/root.rs@@ -51,6 +51,8 @@ actions!(ToggleSidebar,AddMachine,NewSession,+ QuickOpen,+ CommandPalette,ShowAbout,SignInGitHub,GrantGitHubAccess,@@ -72,6 +74,7 @@ const PULSE_EVERY: Duration = Duration::from_secs(5);pub fn bind_keys(cx: &mut App) {let custom = super::shortcuts::bindings(cx);cx.bind_keys(custom);+ super::palette::bind_keys(cx);cx.bind_keys([KeyBinding::new("secondary-q", Quit, None),KeyBinding::new("escape", Dismiss, Some(WORKSPACE)),@@ -104,6 +107,9 @@ pub fn menus() -> Vec<Menu> {Menu {name: "View".into(),items: vec![+ MenuItem::action("Go to…", QuickOpen),+ MenuItem::action("Command Palette…", CommandPalette),+ MenuItem::separator(),MenuItem::action("Overview", ShowOverview),MenuItem::action("Jobs", ShowJobs),MenuItem::action("Workspaces", ShowWorkspaces),@@ -237,6 +243,8 @@ pub struct Root {pub(super) offline_details: std::collections::HashSet<String>,/// The open right-click menu.pub(super) context_menu: Option<super::menu::ContextMenu>,+ /// ⌘P / ⇧⌘P, while it's open.+ pub(super) palette: Option<super::palette::Palette>,/// Focus the root on the next render (the focused terminal went away).refocus: bool,/// The newest session notice already announced (None until the first snapshot).@@ -367,6 +375,7 @@ impl Root {last_notice: None,refocus: false,context_menu: None,+ palette: None,window_active: false,ws_ui: WorkspaceUi::default(),clipboard_seen: (super::pasteboard_state().map(|s| s.0).unwrap_or(0), String::new()),@@ -397,6 +406,13 @@ impl Root {self.refocus = true;}}+ // Favorites of machines that are gone (removed, destroyed) go too. Not+ // while the list is empty: that's before config.toml has been read.+ let favorites = &cx.global::<super::theme::Appearance>().favorite_machines;+ if !snapshot.machines.is_empty() && favorites.iter().any(|f| !snapshot.machines.iter().any(|m| &m.id == f)) {+ let ids: Vec<String> = snapshot.machines.iter().map(|m| m.id.clone()).collect();+ super::theme::remember(cx, |a| a.favorite_machines.retain(|f| ids.contains(f)));+ }self.snapshot = snapshot;cx.notify();}@@ -591,6 +607,12 @@ impl Root {"menu" => self.open_menu(super::menu::MenuTarget::Machine(arg.into()), gpui::point(px(260.), px(160.)), cx),"runner-menu" => self.open_menu(super::menu::MenuTarget::Runner(arg.into()), gpui::point(px(200.), px(560.)), cx),"favorite" => self.set_favorite_machine(arg, true, cx),+ // The palette with this text typed: "palette:" (places), "palette:>set" (commands).+ "palette" => self.open_palette_with(arg, window, cx),+ "themes" => {+ self.open_palette(true, window, cx);+ self.choose_theme(cx);+ }"cloud" => self.show_cloud_dialog(window, cx),// An icon style ("icons:tiles"), for screenshots."icons" => super::theme::update_appearance(window, cx, |a, _| a.icon_style = arg.into()),@@ -1205,6 +1227,10 @@ impl Root {}fn dismiss(&mut self, _: &Dismiss, window: &mut Window, cx: &mut Context<Self>) {+ if self.palette.is_some() {+ self.close_palette(window, cx);+ return;+ }if self.context_menu.take().is_some() {cx.notify();return;@@ -1905,7 +1931,7 @@ impl Root {// Toolbar and overlays/// Hides or shows the sidebar, and remembers it.- fn toggle_sidebar(&mut self, cx: &mut Context<Self>) {+ pub(super) fn toggle_sidebar(&mut self, cx: &mut Context<Self>) {self.sidebar_hidden = !self.sidebar_hidden;let hidden = self.sidebar_hidden;super::theme::remember(cx, |a| a.sidebar_hidden = hidden);@@ -2196,6 +2222,7 @@ impl Render for Root {});let notice = self.render_notice(&theme);let menu = self.render_menu(&theme, cx);+ let palette = self.render_palette(&theme, cx);div().id("workspace")@@ -2224,6 +2251,8 @@ impl Render for Root {.on_action(cx.listener(Self::toggle_activity)).on_action(cx.listener(Self::add_machine)).on_action(cx.listener(Self::new_session))+ .on_action(cx.listener(|this, _: &QuickOpen, window, cx| this.open_palette(false, window, cx)))+ .on_action(cx.listener(|this, _: &CommandPalette, window, cx| this.open_palette(true, window, cx))).on_action(cx.listener(|this, _: &ShowAbout, window, cx| this.navigate(Route::About, window, cx))).on_action(cx.listener(|this, _: &SignInGitHub, window, cx| {// GitHub CLI's browser sign-in, in a terminal on this computer.@@ -2260,6 +2289,7 @@ impl Render for Root {.on_action(cx.listener(|this, _: &ToggleSidebar, _, cx| this.toggle_sidebar(cx))).children(notice).children(menu)+ .children(palette).when_some(modal, |d, modal| {d.child(div()diff --git a/src/ui/settings.rs b/src/ui/settings.rsindex b8d513e..d2cfe56 100644--- a/src/ui/settings.rs+++ b/src/ui/settings.rs@@ -715,23 +715,8 @@ impl SettingsPage {let swatches: Vec<AnyElement> = PALETTES.iter().filter(|p| p.dark == dark).map(|p| {let id = p.id;swatch(theme, p, p.id == chosen, theme.id == p.id).on_click(cx.listener(move |_, _, window, cx| {- theme_mod::update_appearance(window, cx, |a, system| {- let system_dark = matches!(system, gpui::WindowAppearance::Dark | gpui::WindowAppearance::VibrantDark);- if dark {- a.dark = id.into();- } else {- a.light = id.into();- }- // Picking a theme you can't currently see switches to it.- let showing_dark = match a.mode {- Mode::Dark => true,- Mode::Light => false,- Mode::System => system_dark,- };- if showing_dark != dark {- a.mode = if dark { Mode::Dark } else { Mode::Light };- }- })+ // Picking a theme you can't currently see switches to it.+ theme_mod::update_appearance(window, cx, |a, system| theme_mod::choose_theme(a, id, system))})).into_any_element()}).collect();swatch_rows(swatches)diff --git a/src/ui/shortcuts.rs b/src/ui/shortcuts.rsindex 9ec2b55..b52a8c6 100644--- a/src/ui/shortcuts.rs+++ b/src/ui/shortcuts.rs@@ -5,9 +5,9 @@use gpui::{App, KeyBinding, Keystroke};use super::root::{- AddMachine, CheckNow, FocusFilter, GoBack, GoForward, GoToMachine1, GoToMachine2, GoToMachine3, GoToMachine4, GoToMachine5, GoToMachine6,+ AddMachine, CheckNow, CommandPalette, FocusFilter, GoBack, GoForward, GoToMachine1, GoToMachine2, GoToMachine3, GoToMachine4, GoToMachine5, GoToMachine6,GoToMachine7, GoToMachine8, GoToMachine9, NewSession, OpenSettings, ShowGithub, ShowJobs, ShowOverview, ShowWorkspaces, SyncGitHub,- ToggleActivity, ToggleSidebar,+ QuickOpen, ToggleActivity, ToggleSidebar,};use super::theme::Appearance;@@ -34,6 +34,8 @@ const fn page(mac: &'static str, other: &'static str) -> &'static str {/// In the order Settings lists them.pub const ALL: &[Shortcut] = &[+ shortcut!("quick-open", "Go to a machine, session or desktop", "secondary-p", QuickOpen),+ shortcut!("commands", "Command palette", "secondary-shift-p", CommandPalette),shortcut!("overview", "Overview", page("ctrl-1", "alt-1"), ShowOverview),shortcut!("jobs", "Jobs", page("ctrl-2", "alt-2"), ShowJobs),shortcut!("workspaces", "Workspaces", page("ctrl-3", "alt-3"), ShowWorkspaces),diff --git a/src/ui/theme.rs b/src/ui/theme.rsindex 6fdd7a8..7c076ae 100644--- a/src/ui/theme.rs+++ b/src/ui/theme.rs@@ -261,6 +261,32 @@ pub fn save_sidebar_width(cx: &mut App, width: f32) {}/// Changes the appearance preference, saves it, and re-themes the window.+/// Makes `id` the theme for its kind (light or dark), switching to that kind+/// when it isn't the one showing.+pub fn choose_theme(a: &mut Appearance, id: &str, system: WindowAppearance) {+ let Some(dark) = super::themes::find(id).map(|p| p.dark) else { return };+ if dark {+ a.dark = id.into();+ } else {+ a.light = id.into();+ }+ let showing_dark = match a.mode {+ Mode::Dark => true,+ Mode::Light => false,+ Mode::System => matches!(system, WindowAppearance::Dark | WindowAppearance::VibrantDark),+ };+ if showing_dark != dark {+ a.mode = if dark { Mode::Dark } else { Mode::Light };+ }+}++/// Shows these preferences without saving them (a preview).+pub fn preview_appearance(window: &mut Window, cx: &mut App, appearance: Appearance) {+ cx.set_global(appearance);+ apply(window, cx);+ window.refresh();+}+pub fn update_appearance(window: &mut Window, cx: &mut App, f: impl FnOnce(&mut Appearance, WindowAppearance)) {let system = window.appearance();let mut appearance = cx.global::<Appearance>().clone();