Skip to content

armgit / muxin

Public Imported from GitHub
0

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.

Cloud usage and cost, the muxen command in your PATH

Adib Hannac286e05cf8f7
diff --git a/AGENTS.md b/AGENTS.md
index 07c4b9c..148923d 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -121,11 +121,12 @@ Muxen can create DigitalOcean droplets in the user's account and make them fleet
- `cloud_options` shows the sign-in, regions, sizes with hourly and monthly prices, and the defaults.
- `cloud_create(name, region?, size?)` creates one, sets it up (the user's account and SSH key; Docker, git, gh; Node with Claude Code and Codex; Tailscale, as the user's settings say) and adds it to the fleet. **It costs money every hour it exists:** tell the user the size and price and get their OK first.
-- `cloud_power(machine_id, "on"|"off")`: a powered-off droplet is still billed.
+- `cloud_power(machine_id, "on"|"off")`: a powered-off droplet is still billed. Only `cloud_destroy` stops the charges.
+- `cloud_usage` says what they cost: each one's hourly rate, monthly cap, this month and since created (destroyed ones this month too), the totals, and the account's DigitalOcean bill when the sign-in may read it.
- `cloud_destroy(machine_id)` deletes the droplet and everything on it. Confirm first and make sure work there is pushed.
- A cloud machine's `cloud` field (in `get_machine`) has its region, size, price, cost so far and how long it has been idle.
-The CLI equivalents are `muxen cloud options|create|power|destroy|login|logout`.
+The CLI equivalents are `muxen cloud options|create|usage|power|destroy|login|logout`.
## Files
diff --git a/README.md b/README.md
index 9b440a8..802075d 100644
--- a/README.md
+++ b/README.md
@@ -45,6 +45,8 @@ cargo build --release --no-default-features
There's nothing else to set up. Fonts and icons are compiled into the binary.
+To run `muxen` from a terminal, use **Settings › General › Command line › Install**, or `muxen shell-command install`. On macOS it links `/usr/local/bin/muxen` to the app (macOS asks for your password when that folder needs it), on Linux `~/.local/bin/muxen`, and on Windows it adds Muxen's folder to your user PATH. `muxen shell-command remove` takes it out again.
+
To get a real app with the Muxen icon:
- **macOS:** `./scripts/bundle-macos.sh` builds `dist/Muxen.app` (ad-hoc signed). Drag it to Applications. Agents can still use the binary inside it: `Muxen.app/Contents/MacOS/muxen mcp`.
@@ -380,12 +382,13 @@ muxen cp adibs-macbook-pro:~/Projects/site beelink:~/www --no-wait
Need a machine you don't have? Muxen can make one in your DigitalOcean account. Connect in **Settings › Cloud** with an API token (kept in the macOS Keychain), the browser sign-in, or `doctl`'s login. Then pick **New cloud machine…** in the Add machine dialog: a name, a region (the nearest is preselected) and a size with its price. Muxen creates the droplet with your user and SSH key, installs what you chose (Docker, git and the GitHub CLI; Node with Claude Code and Codex; Tailscale), and adds it to your fleet. Then it's like any other machine: terminals, agent sessions, files, workspaces.
-Its page shows what it costs, with **Power off** (DigitalOcean still bills a droplet that's off) and **Destroy**. Settings › Cloud also says what happens when one sits idle: nothing, a reminder, power off, or destroy, after the hours you choose.
+DigitalOcean bills a droplet by the second while it exists, **powered on or off**, up to its monthly price; only destroying it stops the charges. Each cloud machine's page shows its rate, what it has cost this month and since it was created, and what this month comes to if you keep it, with **Power on/off** and **Destroy**. **Settings › Cloud › Usage and cost** adds them up: what you're paying per hour now, this month so far (machines destroyed this month included), the month's total if nothing changes, and your whole DigitalOcean bill this month (when Muxen may read it: sign in again in the browser, or use a token with `billing:read`). Settings › Cloud also says what happens when one sits idle: nothing, a reminder, power off, or destroy, after the hours you choose.
```sh
muxen cloud login --token dop_v1_...
muxen cloud options
muxen cloud create dev-1 --size s-2vcpu-4gb
+muxen cloud usage # what they cost
muxen cloud destroy dev-1
```
diff --git a/src/api.rs b/src/api.rs
index 0e41848..9764220 100644
--- a/src/api.rs
+++ b/src/api.rs
@@ -422,6 +422,10 @@ pub struct CloudOut {
pub created_at: Option<DateTime<Utc>>,
/// USD since it was created.
pub cost_so_far: f64,
+ /// USD this month (UTC).
+ pub this_month: f64,
+ /// The most it costs in a month, in USD.
+ pub price_monthly: f64,
pub idle_since: Option<DateTime<Utc>>,
/// "on", "off" (still billed) or "starting", as last seen; null until known.
pub power: Option<String>,
@@ -664,7 +668,9 @@ pub fn machine_summary(m: &Machine) -> MachineSummary {
size: c.size.clone(),
price_hourly: c.price_hourly,
created_at: c.created_at,
- cost_so_far: (c.cost_so_far * 100.).round() / 100.,
+ cost_so_far: c.cost_so_far,
+ this_month: c.this_month,
+ price_monthly: c.price_monthly,
idle_since: c.idle_since,
power: c.power.clone(),
}),
@@ -1245,6 +1251,13 @@ pub async fn cloud_options(engine: &Arc<Engine>) -> crate::cloud::CloudOptions {
engine.cloud_options().await
}
+/// What the cloud machines cost: each one, this month, by the month's end,
+/// and the DigitalOcean account's bill when the sign-in may read it.
+pub async fn cloud_usage(engine: &Arc<Engine>) -> crate::cloud::usage::CloudUsage {
+ freshen(engine).await;
+ engine.cloud_usage().await
+}
+
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CloudCreateRequest {
diff --git a/src/cli.rs b/src/cli.rs
index b06544d..379964a 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -205,6 +205,39 @@ pub fn jobs(j: &JobsResponse) -> String {
out
}
+pub fn cloud_usage(u: &crate::cloud::usage::CloudUsage) -> String {
+ let mut out = String::new();
+ let _ = writeln!(out, "Now ${:.3}/h · this month ${:.2} · by the month's end ${:.2} if kept", u.hourly_now, u.this_month, u.month_if_kept);
+ match (&u.account, &u.account_error) {
+ (Some(b), _) => {
+ let _ = writeln!(out, "DigitalOcean bill this month: ${:.2} (balance ${:.2})", b.month_to_date_usage, b.month_to_date_balance);
+ }
+ (None, Some(e)) => {
+ let _ = writeln!(out, "DigitalOcean bill: {e}");
+ }
+ _ => {}
+ }
+ if !u.machines.is_empty() {
+ let _ = writeln!(out, "\n{:<20} {:<10} {:<6} {:<16} {:>9} {:>7} {:>11} {:>10}", "MACHINE", "POWER", "REGION", "SIZE", "RATE", "CAP", "THIS MONTH", "SINCE NEW");
+ for m in &u.machines {
+ let _ = writeln!(
+ out,
+ "{:<20} {:<10} {:<6} {:<16} {:>9} {:>7} {:>11} {:>10}",
+ m.name,
+ m.power.as_deref().unwrap_or("?"),
+ m.region,
+ m.size,
+ format!("${:.3}/h", m.price_hourly),
+ format!("${:.0}/mo", m.price_monthly),
+ format!("${:.2}", m.this_month),
+ format!("${:.2}", m.since_created)
+ );
+ }
+ }
+ let _ = writeln!(out, "\n{}", u.billing);
+ out
+}
+
pub fn cloud_options(o: &crate::cloud::CloudOptions) -> String {
let mut out = String::new();
let method = match o.method.as_str() {
diff --git a/src/cloud/auth.rs b/src/cloud/auth.rs
index d357b9c..718c98f 100644
--- a/src/cloud/auth.rs
+++ b/src/cloud/auth.rs
@@ -28,7 +28,7 @@ const CLIENT_ID: &str = "df4228c4a87c9e8d950e0a519d5f41796c0131356c188e5dcabe2e1
const CALLBACK_PATH: &str = "/digitalocean";
/// What Muxen asks to do in the account, and nothing more.
-const SCOPES: &str = "account:read regions:read sizes:read ssh_key:read ssh_key:create droplet:create droplet:read droplet:update droplet:delete actions:read";
+const SCOPES: &str = "account:read regions:read sizes:read ssh_key:read ssh_key:create droplet:create droplet:read droplet:update droplet:delete actions:read billing:read";
fn client_id() -> Option<&'static str> {
Some(option_env!("MUXEN_DO_CLIENT_ID").unwrap_or(CLIENT_ID)).filter(|id| !id.is_empty())
@@ -45,6 +45,15 @@ struct OAuthTokens {
refresh_token: String,
/// Unix seconds.
expires_at: i64,
+ /// What DigitalOcean granted, space-separated ("" from before Muxen kept it).
+ #[serde(default)]
+ scope: String,
+}
+
+/// The permissions the browser sign-in was granted, when Muxen knows them.
+pub fn granted_scopes(dir: &std::path::Path) -> Option<String> {
+ let tokens: OAuthTokens = serde_json::from_str(&secrets::get(dir, OAUTH)?).ok()?;
+ Some(tokens.scope).filter(|s| !s.is_empty())
}
/// A token for the API, by the chosen method.
@@ -185,6 +194,8 @@ async fn exchange(params: &[(&str, &str)]) -> Result<OAuthTokens, String> {
refresh_token: String,
#[serde(default)]
expires_in: i64,
+ #[serde(default)]
+ scope: String,
}
let http = reqwest::Client::builder().timeout(Duration::from_secs(30)).build().map_err(|e| e.to_string())?;
let url = reqwest::Url::parse_with_params("https://cloud.digitalocean.com/v1/oauth/token", params).map_err(|e| e.to_string())?;
@@ -193,7 +204,7 @@ async fn exchange(params: &[(&str, &str)]) -> Result<OAuthTokens, String> {
return Err(format!("DigitalOcean didn't accept the sign-in ({}). Sign in again.", resp.status()));
}
let a: Answer = resp.json().await.map_err(|e| format!("Unexpected answer from DigitalOcean: {e}"))?;
- Ok(OAuthTokens { access_token: a.access_token, refresh_token: a.refresh_token, expires_at: chrono::Utc::now().timestamp() + a.expires_in.max(60) })
+ Ok(OAuthTokens { access_token: a.access_token, refresh_token: a.refresh_token, expires_at: chrono::Utc::now().timestamp() + a.expires_in.max(60), scope: a.scope })
}
/// The browser sign-in: opens DigitalOcean's consent page (`open`), waits up
diff --git a/src/cloud/digitalocean.rs b/src/cloud/digitalocean.rs
index c55ee83..ed88f04 100644
--- a/src/cloud/digitalocean.rs
+++ b/src/cloud/digitalocean.rs
@@ -58,6 +58,18 @@ pub struct Droplet {
pub created_at: String,
}
+/// The account's bill so far this month, as DigitalOcean reports it (USD).
+#[derive(Debug, Clone, Serialize)]
+pub struct Balance {
+ /// Usage this month, before credits and payments.
+ pub month_to_date_usage: f64,
+ /// What's owed for this month so far (usage less credits).
+ pub month_to_date_balance: f64,
+ /// Balance carried on the account (negative is credit).
+ pub account_balance: f64,
+ pub generated_at: Option<String>,
+}
+
#[derive(Debug, Clone)]
pub struct SshKey {
pub id: u64,
@@ -112,6 +124,19 @@ impl Client {
})
}
+ /// Needs the billing:read permission.
+ pub async fn balance(&self) -> Result<Balance, String> {
+ let v = self.call(Method::GET, "/customers/my/balance", None).await?;
+ // Amounts come as strings ("11.21").
+ let amount = |k: &str| v[k].as_str().and_then(|s| s.parse().ok()).or_else(|| v[k].as_f64()).unwrap_or(0.);
+ Ok(Balance {
+ month_to_date_usage: amount("month_to_date_usage"),
+ month_to_date_balance: amount("month_to_date_balance"),
+ account_balance: amount("account_balance"),
+ generated_at: v["generated_at"].as_str().map(str::to_string),
+ })
+ }
+
pub async fn regions(&self) -> Result<Vec<Region>, String> {
let v = self.call(Method::GET, "/regions?per_page=200", None).await?;
Ok(v["regions"]
diff --git a/src/cloud/mod.rs b/src/cloud/mod.rs
index cfab157..acbcf4e 100644
--- a/src/cloud/mod.rs
+++ b/src/cloud/mod.rs
@@ -5,6 +5,7 @@ pub mod auth;
pub mod digitalocean;
pub mod secrets;
pub mod setup;
+pub mod usage;
use serde::{Deserialize, Serialize};
@@ -81,6 +82,40 @@ pub fn city_of_slug(regions: &[Region], slug: &str) -> Option<String> {
Some(r.name.trim_end_matches(|c: char| c.is_ascii_digit() || c == ' ').trim().to_string())
}
+/// A region's city from its slug alone ("nyc3" → "New York"), for when the
+/// region list isn't at hand.
+pub fn region_city(slug: &str) -> Option<&'static str> {
+ let prefix = slug.trim_end_matches(|c: char| c.is_ascii_digit());
+ Some(match prefix {
+ "nyc" => "New York",
+ "sfo" => "San Francisco",
+ "tor" => "Toronto",
+ "atl" => "Atlanta",
+ "ric" => "Richmond",
+ "mkc" => "Kansas City",
+ "mem" => "Memphis",
+ "lon" => "London",
+ "ams" => "Amsterdam",
+ "fra" => "Frankfurt",
+ "blr" => "Bangalore",
+ "sgp" => "Singapore",
+ "syd" => "Sydney",
+ _ => return None,
+ })
+}
+
+/// A size slug in words: "s-2vcpu-4gb" → "2 vCPU · 4 GB" (the slug itself
+/// when it doesn't say).
+pub fn size_label(slug: &str) -> String {
+ let parts: Vec<&str> = slug.split('-').collect();
+ let cpu = parts.iter().find_map(|p| p.strip_suffix("vcpu"));
+ let mem = parts.iter().find_map(|p| p.strip_suffix("gb").filter(|n| n.chars().all(|c| c.is_ascii_digit())));
+ match (cpu, mem) {
+ (Some(c), Some(m)) => format!("{c} vCPU · {m} GB"),
+ _ => slug.to_string(),
+ }
+}
+
/// The region nearest this computer, by its UTC offset, among `available`.
pub fn nearest_region(offset_hours: i32, available: &[String]) -> Option<String> {
let preferences: &[&str] = match offset_hours {
@@ -100,6 +135,16 @@ pub fn nearest_region(offset_hours: i32, available: &[String]) -> Option<String>
mod tests {
use super::*;
+ #[test]
+ fn regions_and_sizes_in_words() {
+ assert_eq!(region_city("nyc3"), Some("New York"));
+ assert_eq!(region_city("mkc1"), Some("Kansas City"));
+ assert_eq!(region_city("zzz1"), None);
+ assert_eq!(size_label("s-1vcpu-1gb"), "1 vCPU · 1 GB");
+ assert_eq!(size_label("s-2vcpu-4gb-amd"), "2 vCPU · 4 GB");
+ assert_eq!(size_label("gpu-h100x1-80gb"), "gpu-h100x1-80gb");
+ }
+
#[test]
fn one_choice_per_city() {
let r = |slug: &str, name: &str| Region { slug: slug.into(), name: name.into(), sizes: Vec::new() };
diff --git a/src/cloud/usage.rs b/src/cloud/usage.rs
new file mode 100644
index 0000000..44fe8ee
--- /dev/null
+++ b/src/cloud/usage.rs
@@ -0,0 +1,142 @@
+//! What cloud machines cost. DigitalOcean bills a droplet by the second (at
+//! least $0.01) from creation until it's destroyed, powered off too, up to
+//! 672 hours a month on standard plans: never more than its monthly price.
+
+use chrono::{DateTime, Datelike, Months, TimeZone, Utc};
+use serde::Serialize;
+
+use super::digitalocean::Balance;
+
+/// What the cloud machines cost: now, this month, and by the month's end.
+#[derive(Debug, Clone, Serialize)]
+pub struct CloudUsage {
+ pub currency: &'static str,
+ /// "2026-10"
+ pub month: String,
+ /// What the ones that exist cost per hour together, on or off.
+ pub hourly_now: f64,
+ /// This month so far, destroyed ones included.
+ pub this_month: f64,
+ /// This month if the ones that exist are kept until it ends.
+ pub month_if_kept: f64,
+ pub machines: Vec<UsageLine>,
+ /// The whole DigitalOcean account's bill this month, when Muxen may read it.
+ pub account: Option<Balance>,
+ /// Why `account` is missing.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub account_error: Option<String>,
+ /// Signing in again (in the browser) would let Muxen read the bill.
+ pub account_needs_sign_in: bool,
+ pub billing: &'static str,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct UsageLine {
+ /// None once destroyed.
+ pub machine_id: Option<String>,
+ pub name: String,
+ pub region: String,
+ pub size: String,
+ /// "on" | "off" | "starting" | "destroyed" | null (not known yet)
+ pub power: Option<String>,
+ pub price_hourly: f64,
+ /// The most it costs in a month.
+ pub price_monthly: f64,
+ pub created_at: Option<DateTime<Utc>>,
+ pub destroyed_at: Option<DateTime<Utc>>,
+ pub this_month: f64,
+ pub since_created: f64,
+}
+
+/// Hours a month DigitalOcean bills at most.
+pub const MONTHLY_CAP_HOURS: f64 = 672.;
+
+/// How DigitalOcean bills, in one sentence for people.
+pub const BILLING: &str = "DigitalOcean bills a droplet by the second while it exists, powered on or off, up to its monthly price. Destroying it stops the charges.";
+
+/// The most a droplet costs in a month.
+pub fn monthly_price(hourly: f64) -> f64 {
+ round2(hourly * MONTHLY_CAP_HOURS)
+}
+
+/// The first moment of `t`'s month (UTC, as DigitalOcean bills).
+pub fn month_start(t: DateTime<Utc>) -> DateTime<Utc> {
+ Utc.with_ymd_and_hms(t.year(), t.month(), 1, 0, 0, 0).single().unwrap_or(t)
+}
+
+fn next_month(t: DateTime<Utc>) -> DateTime<Utc> {
+ month_start(t).checked_add_months(Months::new(1)).unwrap_or(t)
+}
+
+/// What it cost in the month that starts at `month`, existing from `created`
+/// until `ended` (or still, at `now`).
+pub fn cost_in_month(hourly: f64, created: DateTime<Utc>, ended: Option<DateTime<Utc>>, month: DateTime<Utc>, now: DateTime<Utc>) -> f64 {
+ let start = created.max(month);
+ let end = ended.unwrap_or(now).min(now).min(next_month(month));
+ if end <= start || hourly <= 0. {
+ return 0.;
+ }
+ let hours = (end - start).num_seconds() as f64 / 3600.;
+ round2((hours.min(MONTHLY_CAP_HOURS) * hourly).max(0.01))
+}
+
+/// What it has cost since it was created, month by month.
+pub fn cost_since(hourly: f64, created: DateTime<Utc>, ended: Option<DateTime<Utc>>, now: DateTime<Utc>) -> f64 {
+ let last = ended.unwrap_or(now).min(now);
+ let mut month = month_start(created);
+ let mut total = 0.;
+ while month <= last {
+ total += cost_in_month(hourly, created, ended, month, now);
+ month = next_month(month);
+ }
+ round2(total)
+}
+
+/// What it will have cost this month if it keeps existing until the month ends.
+pub fn month_if_kept(hourly: f64, created: DateTime<Utc>, now: DateTime<Utc>) -> f64 {
+ let end = next_month(now);
+ cost_in_month(hourly, created, Some(end), month_start(now), end)
+}
+
+pub fn round2(v: f64) -> f64 {
+ (v * 100.).round() / 100.
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn t(s: &str) -> DateTime<Utc> {
+ DateTime::parse_from_rfc3339(s).unwrap().with_timezone(&Utc)
+ }
+
+ #[test]
+ fn bills_by_the_second_up_to_the_monthly_price() {
+ let hourly = 0.00893;
+ assert_eq!(monthly_price(hourly), 6.0);
+ let created = t("2026-10-09T18:53:00Z");
+ let month = month_start(created);
+ // Two hours in: two hours' worth, but at least a cent.
+ assert_eq!(cost_in_month(hourly, created, None, month, t("2026-10-09T20:53:00Z")), 0.02);
+ assert_eq!(cost_in_month(hourly, created, None, month, t("2026-10-09T18:54:00Z")), 0.01);
+ // A whole month never costs more than the monthly price.
+ assert_eq!(cost_in_month(hourly, t("2026-09-01T00:00:00Z"), None, month_start(t("2026-09-15T00:00:00Z")), t("2026-10-05T00:00:00Z")), 6.0);
+ // Destroyed after a day.
+ assert_eq!(cost_in_month(hourly, created, Some(t("2026-10-10T18:53:00Z")), month, t("2026-10-20T00:00:00Z")), 0.21);
+ // Not in a month it didn't exist in.
+ assert_eq!(cost_in_month(hourly, created, None, month_start(t("2026-09-15T00:00:00Z")), t("2026-10-20T00:00:00Z")), 0.0);
+ }
+
+ #[test]
+ fn adds_up_months_and_projects_this_one() {
+ let hourly = 0.03571; // $24/mo
+ let created = t("2026-09-20T00:00:00Z");
+ let now = t("2026-10-02T00:00:00Z");
+ // September: 11 days = 264h; October so far: 1 day.
+ assert_eq!(cost_since(hourly, created, None, now), round2(round2(264. * hourly) + round2(24. * hourly)));
+ // Kept all of October: capped at the monthly price.
+ assert_eq!(month_if_kept(hourly, created, now), monthly_price(hourly));
+ // Created late in the month: only what's left of it.
+ assert_eq!(month_if_kept(hourly, t("2026-10-30T00:00:00Z"), t("2026-10-30T00:00:00Z")), round2(48. * hourly));
+ }
+}
diff --git a/src/config.rs b/src/config.rs
index f0e07d6..e33eecf 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -311,6 +311,15 @@ pub struct CloudRef {
pub created_at: String,
}
+/// A cloud machine Muxen destroyed, kept so this month's costs still count it.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct DestroyedCloud {
+ pub name: String,
+ pub cloud: CloudRef,
+ pub destroyed_at: DateTime<Utc>,
+}
+
fn yes() -> bool {
true
}
@@ -619,6 +628,8 @@ 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>>,
}
diff --git a/src/fleet/build.rs b/src/fleet/build.rs
index 76fbf1a..b115e2c 100644
--- a/src/fleet/build.rs
+++ b/src/fleet/build.rs
@@ -167,8 +167,9 @@ pub fn build(input: &Inputs) -> Snapshot {
unreachable,
tailnet: device.cloned(),
cloud: spec.cloud.as_ref().map(|c| {
+ use crate::cloud::usage;
let created_at = DateTime::parse_from_rfc3339(&c.created_at).ok().map(|t| t.with_timezone(&Utc));
- let hours = created_at.map(|t| (input.now - t).num_minutes().max(0) as f64 / 60.).unwrap_or(0.);
+ let created = created_at.unwrap_or(input.now);
crate::fleet::model::CloudInfo {
provider: c.provider.clone(),
id: c.id,
@@ -176,7 +177,9 @@ pub fn build(input: &Inputs) -> Snapshot {
size: c.size.clone(),
price_hourly: c.price_hourly,
created_at,
- cost_so_far: (hours.ceil() * c.price_hourly * 100.).round() / 100.,
+ cost_so_far: usage::cost_since(c.price_hourly, created, None, input.now),
+ this_month: usage::cost_in_month(c.price_hourly, created, None, usage::month_start(input.now), input.now),
+ price_monthly: usage::monthly_price(c.price_hourly),
idle_since: crate::ops::cloud::idle_since(&spec.id),
power: if status == "online" {
Some("on".into())
diff --git a/src/fleet/engine.rs b/src/fleet/engine.rs
index 3fcda98..b3c3683 100644
--- a/src/fleet/engine.rs
+++ b/src/fleet/engine.rs
@@ -75,6 +75,8 @@ 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>>,
}
@@ -146,6 +148,7 @@ 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()));
@@ -500,6 +503,21 @@ 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) {
+ 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()
+ }
+
/// True while another operation is changing this machine.
pub(crate) fn machine_busy(&self, machine_id: &str) -> bool {
let st = self.state.lock().unwrap();
@@ -957,6 +975,7 @@ impl Engine {
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/fleet/model.rs b/src/fleet/model.rs
index a8b2b08..a1013b8 100644
--- a/src/fleet/model.rs
+++ b/src/fleet/model.rs
@@ -228,6 +228,10 @@ pub struct CloudInfo {
pub created_at: Option<DateTime<Utc>>,
/// What it has cost since it was created, in USD.
pub cost_so_far: f64,
+ /// What it has cost this month (UTC), in USD.
+ pub this_month: f64,
+ /// The most it costs in a month (DigitalOcean caps it), in USD.
+ pub price_monthly: f64,
/// Idle (no busy session, job or CPU) since then, as this app has seen it.
pub idle_since: Option<DateTime<Utc>>,
/// "on", "off" or "starting", as last seen; None until known.
diff --git a/src/main.rs b/src/main.rs
index eec503d..ad56e2b 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -8,6 +8,7 @@ mod github;
mod mcp;
mod ops;
mod probe;
+mod shell_command;
#[cfg(feature = "gui")]
mod ui;
mod util;
@@ -104,6 +105,26 @@ enum Command {
Init(InitArgs),
/// Print where Muxen keeps its files
Paths(CommonArgs),
+ /// Put `muxen` in your PATH (macOS: /usr/local/bin, Linux: ~/.local/bin,
+ /// Windows: this folder in your user PATH), or take it out
+ ShellCommand(ShellCommandArgs),
+}
+
+#[derive(Args)]
+struct ShellCommandArgs {
+ /// status (the default), install or remove
+ #[arg(value_enum, default_value = "status")]
+ action: ShellCommandAction,
+ /// Print machine-readable JSON
+ #[arg(long)]
+ json: bool,
+}
+
+#[derive(Clone, Copy, clap::ValueEnum)]
+enum ShellCommandAction {
+ Status,
+ Install,
+ Remove,
}
#[derive(Args, Clone)]
@@ -360,6 +381,8 @@ struct GhRepoArgs {
enum CloudCommand {
/// The account, regions, sizes and defaults for a new machine
Options(AgentArgs),
+ /// What the cloud machines cost: now, this month, by the month's end, and the account's bill
+ Usage(AgentArgs),
/// Create a droplet, set it up, and add it to the fleet (it costs money while it exists)
Create(CloudCreateArgs),
/// Delete a cloud machine's droplet and remove it from the fleet
@@ -1090,6 +1113,40 @@ fn main() -> ExitCode {
println!("state {}", display_path(&p.state));
0
}
+ Some(Command::ShellCommand(args)) => {
+ let result = match args.action {
+ ShellCommandAction::Status => Ok(shell_command::status()),
+ ShellCommandAction::Install => shell_command::install(),
+ ShellCommandAction::Remove => shell_command::remove(),
+ };
+ match (result, args.json) {
+ (Ok(s), true) => {
+ println!("{}", serde_json::to_string_pretty(&s).unwrap_or_default());
+ 0
+ }
+ (Ok(s), false) => {
+ let line = match s.state {
+ "installed" => format!("muxen is installed: {}", s.path),
+ "missing" => format!("Not installed (it would go in {}). Run `muxen shell-command install`.", s.path),
+ "other" => format!("{} is something else{}", s.path, s.target.as_deref().map(|t| format!(" (-> {t})")).unwrap_or_default()),
+ _ => "Not available here.".to_string(),
+ };
+ println!("{line}");
+ if let Some(note) = s.note {
+ println!("{note}");
+ }
+ 0
+ }
+ (Err(e), true) => {
+ println!("{}", serde_json::json!({ "error": { "code": "operation_failed", "message": e } }));
+ 1
+ }
+ (Err(e), false) => {
+ eprintln!("error: {e}");
+ 1
+ }
+ }
+ }
};
ExitCode::from(code)
}
@@ -1399,6 +1456,7 @@ fn github(cmd: GithubCommand, runtime: &tokio::runtime::Runtime) -> u8 {
fn cloud(cmd: CloudCommand, runtime: &tokio::runtime::Runtime) -> u8 {
match cmd {
CloudCommand::Options(a) => run(runtime, &a, async move |e| Ok::<_, api::ApiError>(api::cloud_options(&e).await), cli::cloud_options),
+ CloudCommand::Usage(a) => run(runtime, &a, async move |e| Ok::<_, api::ApiError>(api::cloud_usage(&e).await), cli::cloud_usage),
CloudCommand::Create(a) => {
let req = api::CloudCreateRequest {
name: a.name,
diff --git a/src/mcp.rs b/src/mcp.rs
index 4abb85c..3130b93 100644
--- a/src/mcp.rs
+++ b/src/mcp.rs
@@ -293,6 +293,7 @@ async fn dispatch(engine: &Arc<Engine>, session: &Session, name: &str, a: Value)
"runner_action" => ok(api::runner_action(engine, args(a)?, Surface::Mcp, |_| {}).await?),
"cancel_run" => ok(api::cancel_run(engine, args(a)?, Surface::Mcp, |_| {}).await?),
"cloud_options" => ok(api::cloud_options(engine).await),
+ "cloud_usage" => ok(api::cloud_usage(engine).await),
"cloud_create" => ok(api::cloud_create(engine, args(a)?, Surface::Mcp, |_| {}).await?),
"cloud_destroy" => ok(api::cloud_destroy(engine, args(a)?, Surface::Mcp, |_| {}).await?),
"cloud_power" => ok(api::cloud_power(engine, args(a)?, Surface::Mcp, |_| {}).await?),
@@ -451,6 +452,12 @@ pub fn tools() -> Vec<Value> {
"inputSchema": schema(json!({}), &[]),
"annotations": annotations("Cloud options", true, false, true, true),
}),
+ json!({
+ "name": "cloud_usage",
+ "description": "What the user's cloud machines cost: each droplet's hourly rate, monthly cap, cost this month and since it was created (destroyed ones this month too), the totals now / this month / by the month's end, and the DigitalOcean account's month-to-date bill when the sign-in may read it. Droplets are billed while they exist, powered off too; only destroying one stops the charges. Read-only.",
+ "inputSchema": schema(json!({}), &[]),
+ "annotations": annotations("Cloud usage", true, false, true, true),
+ }),
json!({
"name": "cloud_create",
"description": "Create a DigitalOcean droplet in the user's account, set it up (their user and SSH key, git, and the extras chosen: Docker, GitHub CLI, languages like Go, Rust, Python or PHP, agent CLIs, Tailscale), and add it to the fleet. It COSTS MONEY every hour it exists: tell the user the size and price (cloud_options) and get their OK first. Takes a few minutes.",
@@ -867,7 +874,7 @@ mod tests {
#[test]
fn tool_schemas_are_well_formed() {
let tools = tools();
- assert_eq!(tools.len(), 55);
+ assert_eq!(tools.len(), 56);
let mut names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();
names.sort();
names.dedup();
diff --git a/src/ops/cloud.rs b/src/ops/cloud.rs
index 42dff53..8cbd627 100644
--- a/src/ops/cloud.rs
+++ b/src/ops/cloud.rs
@@ -12,7 +12,7 @@ use chrono::{DateTime, Utc};
use super::inventory_edit;
use super::NewMachine;
use crate::cloud::digitalocean::{Client, same_key};
-use crate::cloud::{CloudCreate, CloudOptions, TAILSCALE_KEY, auth, nearest_region, secrets, setup};
+use crate::cloud::{CloudCreate, CloudOptions, TAILSCALE_KEY, auth, nearest_region, secrets, setup, usage};
use crate::config::{CloudRef, MachineSpec};
use crate::fleet::Engine;
@@ -259,6 +259,9 @@ impl Engine {
pub fn cloud_destroy(self: &Arc<Self>, machine_id: &str) -> Result<u64, String> {
let (spec, _) = self.machine(machine_id).ok_or("That machine isn't in the fleet anymore.")?;
let cloud = spec.cloud.clone().ok_or_else(|| format!("{} isn't a cloud machine Muxen created.", spec.name))?;
+ if self.machine_busy(&spec.id) {
+ return Err("An operation is still running on this machine. Wait for it to finish.".into());
+ }
let op = self.begin_op("cloud-destroy", format!("Destroy {}", spec.name), Some(spec.id.clone()), None);
let me = self.clone();
self.runtime().spawn(async move {
@@ -266,6 +269,8 @@ impl Engine {
let client = me.do_client().await?;
me.op_log(op, format!("▸ Deleting droplet {} from DigitalOcean", cloud.id));
client.delete_droplet(cloud.id).await?;
+ // 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)?;
// Its address may be reused by someone else's droplet.
@@ -357,6 +362,94 @@ impl Engine {
Ok(())
}
+ /// What the cloud machines cost: each one (destroyed ones this month
+ /// too), the totals, and the account's bill when the sign-in may read it.
+ pub async fn cloud_usage(self: &Arc<Self>) -> usage::CloudUsage {
+ let now = Utc::now();
+ let month = usage::month_start(now);
+ let snap = self.current();
+ let mut machines = Vec::new();
+ let mut if_kept = 0.;
+ for m in &snap.machines {
+ let Some(c) = &m.cloud else { continue };
+ let created = c.created_at.unwrap_or(now);
+ if_kept += usage::month_if_kept(c.price_hourly, created, now);
+ machines.push(usage::UsageLine {
+ machine_id: Some(m.id.clone()),
+ name: m.name.clone(),
+ region: c.region.clone(),
+ size: c.size.clone(),
+ power: c.power.clone(),
+ price_hourly: c.price_hourly,
+ price_monthly: usage::monthly_price(c.price_hourly),
+ created_at: c.created_at,
+ destroyed_at: None,
+ this_month: usage::cost_in_month(c.price_hourly, created, None, month, now),
+ since_created: usage::cost_since(c.price_hourly, created, None, now),
+ });
+ }
+ let hourly_now = machines.iter().map(|l| l.price_hourly).sum::<f64>();
+ 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);
+ if this_month <= 0. {
+ continue;
+ }
+ if_kept += this_month;
+ machines.push(usage::UsageLine {
+ machine_id: None,
+ name: h.name.clone(),
+ region: h.cloud.region.clone(),
+ size: h.cloud.size.clone(),
+ power: Some("destroyed".into()),
+ price_hourly: h.cloud.price_hourly,
+ price_monthly: usage::monthly_price(h.cloud.price_hourly),
+ created_at: Some(created),
+ destroyed_at: Some(h.destroyed_at),
+ this_month,
+ 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 (mut account, mut account_error, mut account_needs_sign_in) = (None, None, false);
+ if self.demo_world().is_none() {
+ let method = self.settings().cloud.digitalocean_auth;
+ match self.do_client().await {
+ Ok(client) => match client.balance().await {
+ Ok(b) => account = Some(b),
+ // Not allowed to read the bill: say what would allow it, and what DigitalOcean said.
+ Err(e) if e.contains("refused") => {
+ let said = e.trim_start_matches("DigitalOcean refused: ").trim_end_matches(" (the token may be read-only)").to_string();
+ let granted = (method == "oauth").then(|| auth::granted_scopes(&self.paths().dir)).flatten();
+ account_needs_sign_in = method == "oauth" && granted.as_deref().is_none_or(|g| !g.split_whitespace().any(|s| s == "billing:read"));
+ account_error = Some(match method.as_str() {
+ // It says "not authorized" even with billing:read granted, at least for a new account.
+ "oauth" if !account_needs_sign_in => "DigitalOcean isn't sharing the bill yet; a new account may not have one.".to_string(),
+ "oauth" => format!("Sign in again so Muxen can read your DigitalOcean bill. ({said})"),
+ "doctl" => format!("doctl's token can't read billing; it needs billing:read. ({said})"),
+ _ => format!("This API token can't read billing; it needs billing:read. ({said})"),
+ });
+ }
+ Err(e) => account_error = Some(e),
+ },
+ Err(_) => account_error = Some("Not signed in to DigitalOcean.".into()),
+ }
+ }
+ usage::CloudUsage {
+ currency: "USD",
+ month: now.format("%Y-%m").to_string(),
+ hourly_now: (hourly_now * 100_000.).round() / 100_000.,
+ this_month: usage::round2(this_month),
+ month_if_kept: usage::round2(if_kept),
+ machines,
+ account,
+ account_error,
+ account_needs_sign_in,
+ billing: usage::BILLING,
+ }
+ }
+
/// Watches cloud machines for idleness (every 10 minutes) and does what
/// Settings › Cloud says. Run by one process (the app).
#[cfg_attr(not(feature = "gui"), allow(dead_code))]
diff --git a/src/shell_command.rs b/src/shell_command.rs
new file mode 100644
index 0000000..0cd2b1f
--- /dev/null
+++ b/src/shell_command.rs
@@ -0,0 +1,314 @@
+//! The `muxen` command in the user's PATH, so terminals (and other agents,
+//! with `muxen mcp`) can run it: a link to this executable in
+//! /usr/local/bin on macOS (asking for an administrator's password when the
+//! folder isn't writable) and ~/.local/bin on Linux; on Windows, this
+//! executable's folder added to the user's PATH.
+
+use std::path::{Path, PathBuf};
+
+use serde::Serialize;
+
+#[derive(Debug, Clone, Serialize)]
+pub struct Status {
+ /// "installed" | "missing" | "other" (something else is there) | "unsupported"
+ pub state: &'static str,
+ /// Where the command lives: the link, or on Windows the folder in PATH.
+ pub path: String,
+ /// What runs: this executable, or what the link points to now.
+ pub target: Option<String>,
+ /// Something to know, in plain words ("Open a new terminal to use it.").
+ pub note: Option<String>,
+ /// "other" that install may replace: a link to another copy of Muxen.
+ pub replaceable: bool,
+}
+
+/// Whether `muxen` is in the PATH and runs this copy of Muxen.
+pub fn status() -> Status {
+ let exe = match this_exe() {
+ Ok(exe) => exe,
+ Err(e) => return Status { state: "unsupported", path: String::new(), target: None, note: Some(e), replaceable: false },
+ };
+ imp::status(&exe)
+}
+
+pub fn install() -> Result<Status, String> {
+ let exe = this_exe()?;
+ if exe.to_string_lossy().contains("/AppTranslocation/") {
+ return Err("macOS is running Muxen from a temporary copy. Move Muxen to Applications, open it from there, and try again.".into());
+ }
+ imp::install(&exe)?;
+ Ok(imp::status(&exe))
+}
+
+pub fn remove() -> Result<Status, String> {
+ let exe = this_exe()?;
+ imp::remove(&exe)?;
+ Ok(imp::status(&exe))
+}
+
+fn this_exe() -> Result<PathBuf, String> {
+ let exe = std::env::current_exe().map_err(|e| format!("Couldn't tell where Muxen is: {e}"))?;
+ Ok(std::fs::canonicalize(&exe).unwrap_or(exe))
+}
+
+/// A link of ours: it points to a Muxen executable (this one, or another
+/// copy), not to something else that happens to be called muxen.
+#[cfg(unix)]
+fn is_muxen(target: &Path) -> bool {
+ let s = target.to_string_lossy();
+ target.file_name().is_some_and(|n| n == "muxen") || s.contains("Muxen.app/")
+}
+
+#[cfg(unix)]
+mod imp {
+ use super::*;
+ use std::io::ErrorKind;
+
+ /// Where the link goes on this OS.
+ fn link_path() -> Result<PathBuf, String> {
+ if cfg!(target_os = "macos") {
+ Ok(PathBuf::from("/usr/local/bin/muxen"))
+ } else {
+ let home = std::env::var_os("HOME").ok_or("HOME isn't set.")?;
+ Ok(PathBuf::from(home).join(".local/bin/muxen"))
+ }
+ }
+
+ pub fn status(exe: &Path) -> Status {
+ match link_path() {
+ Ok(link) => status_at(&link, exe),
+ Err(e) => Status { state: "unsupported", path: String::new(), target: None, note: Some(e), replaceable: false },
+ }
+ }
+
+ pub(super) fn status_at(link: &Path, exe: &Path) -> Status {
+ let link = link.to_path_buf();
+ let path = link.display().to_string();
+ let Ok(meta) = std::fs::symlink_metadata(&link) else {
+ return Status { state: "missing", path, target: None, note: None, replaceable: false };
+ };
+ if !meta.file_type().is_symlink() {
+ return Status { state: "other", path, target: None, note: Some("A different program called muxen is there; Muxen leaves it alone.".into()), replaceable: false };
+ }
+ let target = std::fs::read_link(&link).ok();
+ let resolved = std::fs::canonicalize(&link).ok();
+ let shown = target.as_ref().map(|t| t.display().to_string());
+ let ours = target.as_deref().is_some_and(is_muxen);
+ let other = |note: &str, replaceable| Status { state: "other", path: path.clone(), target: shown.clone(), note: Some(note.into()), replaceable };
+ match resolved {
+ Some(r) if r == exe => Status { state: "installed", path: path.clone(), target: shown.clone(), note: in_path_note(&link), replaceable: false },
+ _ if !ours => other("It links to a different program called muxen; Muxen leaves it alone.", false),
+ None => other("It points to a copy of Muxen that isn't there anymore.", true),
+ Some(_) => other("It runs another copy of Muxen.", true),
+ }
+ }
+
+ /// Linux: ~/.local/bin is only in PATH when the login that started this
+ /// app found it (Ubuntu adds it at login, once it exists).
+ fn in_path_note(link: &Path) -> Option<String> {
+ if cfg!(target_os = "macos") {
+ return None;
+ }
+ let dir = link.parent()?;
+ let in_path = std::env::var_os("PATH").is_some_and(|p| std::env::split_paths(&p).any(|d| d == dir));
+ (!in_path).then(|| format!("{} isn't in your PATH yet. It usually is after you log in again; or add it in your shell's profile.", dir.display()))
+ }
+
+ pub fn install(exe: &Path) -> Result<(), String> {
+ install_at(&link_path()?, exe)
+ }
+
+ pub(super) fn install_at(link: &Path, exe: &Path) -> Result<(), String> {
+ refuse_others(link)?;
+ match link_here(link, exe) {
+ Ok(()) => Ok(()),
+ Err(e) if e.kind() == ErrorKind::PermissionDenied && cfg!(target_os = "macos") => {
+ let dir = link.parent().map(|d| d.display().to_string()).unwrap_or_default();
+ as_admin(&format!("mkdir -p {} && ln -sfn {} {}", sh(&dir), sh(&exe.display().to_string()), sh(&link.display().to_string())))
+ }
+ Err(e) => Err(format!("Couldn't create {}: {e}", link.display())),
+ }
+ }
+
+ pub fn remove(_exe: &Path) -> Result<(), String> {
+ remove_at(&link_path()?)
+ }
+
+ pub(super) fn remove_at(link: &Path) -> Result<(), String> {
+ let Ok(meta) = std::fs::symlink_metadata(link) else { return Ok(()) };
+ let ours = meta.file_type().is_symlink() && std::fs::read_link(link).is_ok_and(|t| is_muxen(&t));
+ if !ours {
+ return Err(format!("{} isn't a link to Muxen, so Muxen leaves it alone.", link.display()));
+ }
+ match std::fs::remove_file(link) {
+ Ok(()) => Ok(()),
+ Err(e) if e.kind() == ErrorKind::PermissionDenied && cfg!(target_os = "macos") => as_admin(&format!("rm -f {}", sh(&link.display().to_string()))),
+ Err(e) => Err(format!("Couldn't remove {}: {e}", link.display())),
+ }
+ }
+
+ /// Only ever replace a link to Muxen, never someone else's file.
+ fn refuse_others(link: &Path) -> Result<(), String> {
+ match std::fs::symlink_metadata(link) {
+ Ok(m) if !m.file_type().is_symlink() => Err(format!("There's already a file at {} that isn't a link to Muxen. Remove it first if you don't need it.", link.display())),
+ Ok(_) if !std::fs::read_link(link).is_ok_and(|t| is_muxen(&t)) => {
+ Err(format!("{} already links to another program. Remove it first if you don't need it.", link.display()))
+ }
+ _ => Ok(()),
+ }
+ }
+
+ fn link_here(link: &Path, exe: &Path) -> std::io::Result<()> {
+ if let Some(dir) = link.parent() {
+ std::fs::create_dir_all(dir)?;
+ }
+ if std::fs::symlink_metadata(link).is_ok() {
+ std::fs::remove_file(link)?;
+ }
+ std::os::unix::fs::symlink(exe, link)
+ }
+
+ /// Runs a shell command as an administrator; macOS asks for the password.
+ fn as_admin(command: &str) -> Result<(), String> {
+ let applescript = format!("do shell script \"{}\" with administrator privileges", command.replace('\\', "\\\\").replace('"', "\\\""));
+ let out = std::process::Command::new("osascript").arg("-e").arg(applescript).output().map_err(|e| format!("Couldn't ask for an administrator's password: {e}"))?;
+ if out.status.success() {
+ return Ok(());
+ }
+ let err = String::from_utf8_lossy(&out.stderr);
+ if err.contains("-128") || err.to_lowercase().contains("cancel") {
+ Err("Cancelled.".into())
+ } else {
+ Err(format!("It didn't work: {}", err.trim()))
+ }
+ }
+
+ /// Single-quoted for sh.
+ fn sh(s: &str) -> String {
+ format!("'{}'", s.replace('\'', "'\\''"))
+ }
+}
+
+#[cfg(windows)]
+mod imp {
+ use super::*;
+
+ // The user's PATH as stored (unexpanded, keeping its kind), changed in
+ // place; SetEnvironmentVariable on a scratch name then tells Explorer and
+ // new terminals to reload the environment.
+ const READ: &str = r#"
+$k = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment')
+$p = if ($k) { $k.GetValue('Path', '', 'DoNotExpandEnvironmentNames') } else { '' }
+[Console]::Out.Write($p)
+"#;
+
+ const WRITE: &str = r#"
+$k = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment')
+$p = $k.GetValue('Path', '', 'DoNotExpandEnvironmentNames')
+$kind = if ($p) { $k.GetValueKind('Path') } else { [Microsoft.Win32.RegistryValueKind]::ExpandString }
+$parts = @($p -split ';' | Where-Object { $_ -and ($_.TrimEnd('\') -ne $env:MUXEN_DIR.TrimEnd('\')) })
+if ($env:MUXEN_ADD -eq '1') { $parts += $env:MUXEN_DIR }
+$k.SetValue('Path', ($parts -join ';'), $kind)
+[Environment]::SetEnvironmentVariable('MUXEN_PATH_CHANGED', $null, 'User')
+"#;
+
+ fn powershell(script: &str, env: &[(&str, &str)]) -> Result<String, String> {
+ use std::os::windows::process::CommandExt;
+ const CREATE_NO_WINDOW: u32 = 0x0800_0000;
+ let mut cmd = std::process::Command::new("powershell.exe");
+ cmd.args(["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", script]).creation_flags(CREATE_NO_WINDOW);
+ for (k, v) in env {
+ cmd.env(k, v);
+ }
+ let out = cmd.output().map_err(|e| format!("Couldn't run PowerShell: {e}"))?;
+ if !out.status.success() {
+ return Err(format!("PowerShell: {}", String::from_utf8_lossy(&out.stderr).trim()));
+ }
+ Ok(String::from_utf8_lossy(&out.stdout).to_string())
+ }
+
+ fn dir_of(exe: &Path) -> Result<String, String> {
+ let dir = exe.parent().ok_or("Couldn't tell which folder Muxen is in.")?.display().to_string();
+ // canonicalize gives \\?\C:\...; PATH wants C:\...
+ Ok(dir.strip_prefix(r"\\?\").unwrap_or(&dir).to_string())
+ }
+
+ fn same(a: &str, b: &str) -> bool {
+ a.trim_end_matches('\\').eq_ignore_ascii_case(b.trim_end_matches('\\'))
+ }
+
+ pub fn status(exe: &Path) -> Status {
+ let dir = match dir_of(exe) {
+ Ok(d) => d,
+ Err(e) => return Status { state: "unsupported", path: String::new(), target: None, note: Some(e), replaceable: false },
+ };
+ let target = Some(exe.display().to_string().trim_start_matches(r"\\?\").to_string());
+ match powershell(READ, &[]) {
+ Ok(path) if path.split(';').any(|p| same(p, &dir)) => Status { state: "installed", path: dir, target, note: Some("Open a new terminal to use it.".into()), replaceable: false },
+ Ok(_) => Status { state: "missing", path: dir, target, note: None, replaceable: false },
+ Err(e) => Status { state: "unsupported", path: dir, target, note: Some(e), replaceable: false },
+ }
+ }
+
+ pub fn install(exe: &Path) -> Result<(), String> {
+ powershell(WRITE, &[("MUXEN_DIR", &dir_of(exe)?), ("MUXEN_ADD", "1")]).map(|_| ())
+ }
+
+ pub fn remove(exe: &Path) -> Result<(), String> {
+ powershell(WRITE, &[("MUXEN_DIR", &dir_of(exe)?), ("MUXEN_ADD", "0")]).map(|_| ())
+ }
+}
+
+#[cfg(test)]
+#[cfg(unix)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn knows_its_own_links() {
+ assert!(is_muxen(Path::new("/Applications/Muxen.app/Contents/MacOS/muxen")));
+ assert!(is_muxen(Path::new("/home/me/.cargo/bin/muxen")));
+ assert!(!is_muxen(Path::new("/usr/bin/python3")));
+ }
+
+ #[test]
+ fn links_replaces_and_removes_only_its_own() {
+ let tmp = std::env::temp_dir().join(format!("muxen-shell-command-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&tmp);
+ let exe = tmp.join("Muxen.app/Contents/MacOS/muxen");
+ std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
+ std::fs::write(&exe, "").unwrap();
+ let exe = std::fs::canonicalize(&exe).unwrap();
+ let link = tmp.join("bin/muxen");
+
+ assert_eq!(imp::status_at(&link, &exe).state, "missing");
+ imp::install_at(&link, &exe).unwrap();
+ assert_eq!(imp::status_at(&link, &exe).state, "installed");
+ // Again: replaces its own link.
+ imp::install_at(&link, &exe).unwrap();
+ assert_eq!(imp::status_at(&link, &exe).state, "installed");
+ // A link to another copy is "other" and gets replaced.
+ let old = tmp.join("old/muxen");
+ std::fs::create_dir_all(old.parent().unwrap()).unwrap();
+ std::fs::write(&old, "").unwrap();
+ std::fs::remove_file(&link).unwrap();
+ std::os::unix::fs::symlink(&old, &link).unwrap();
+ assert_eq!((imp::status_at(&link, &exe).state, imp::status_at(&link, &exe).replaceable), ("other", true));
+ imp::install_at(&link, &exe).unwrap();
+ assert_eq!(imp::status_at(&link, &exe).state, "installed");
+ imp::remove_at(&link).unwrap();
+ assert_eq!(imp::status_at(&link, &exe).state, "missing");
+
+ // Someone else's file, or a link to another program: left alone.
+ std::fs::write(&link, "#!/bin/sh").unwrap();
+ assert_eq!(imp::status_at(&link, &exe).state, "other");
+ assert!(imp::install_at(&link, &exe).is_err());
+ assert!(imp::remove_at(&link).is_err());
+ std::fs::remove_file(&link).unwrap();
+ std::os::unix::fs::symlink("/usr/bin/env", &link).unwrap();
+ assert_eq!((imp::status_at(&link, &exe).state, imp::status_at(&link, &exe).replaceable), ("other", false));
+ assert!(imp::install_at(&link, &exe).is_err());
+ assert!(imp::remove_at(&link).is_err());
+ let _ = std::fs::remove_dir_all(&tmp);
+ }
+}
diff --git a/src/ui/detail.rs b/src/ui/detail.rs
index cb43580..a3f6e53 100644
--- a/src/ui/detail.rs
+++ b/src/ui/detail.rs
@@ -245,50 +245,93 @@ impl Root {
"cloud-power-off" => Some(false),
_ => None,
});
- let title = match powering {
- Some(true) => "DigitalOcean · powering on…",
- Some(false) => "DigitalOcean · shutting down…",
- None if off => "DigitalOcean · powered off (still billed)",
- None => "DigitalOcean",
- };
let power_label = match powering {
Some(true) => "Powering on…",
Some(false) => "Shutting down…",
None if off => "Power on",
None => "Power off",
};
- let idle = c.idle_since.map(|t| (chrono::Utc::now() - t).num_minutes()).filter(|min| *min >= 30).map(|min| format!(" · idle {}", crate::util::short_duration(min as u64 * 60)));
- let detail = format!(
- "{} · {} · ${:.3}/h · ${:.2} so far{}",
- c.region.to_uppercase(),
- c.size,
- c.price_hourly,
- c.cost_so_far,
- idle.unwrap_or_default()
- );
+ use crate::cloud::usage;
+ let now = chrono::Utc::now();
+ let idle = c.idle_since.map(|t| (now - t).num_minutes()).filter(|min| *min >= 30).map(|min| format!(" · idle {}", crate::util::short_duration(min as u64 * 60)));
+ let state = match powering {
+ Some(true) => ("Powering on…".to_string(), theme.text_muted),
+ Some(false) => ("Shutting down…".to_string(), theme.text_muted),
+ None if off => ("Powered off · still billed".to_string(), theme.warning),
+ None => (format!("Running{}", idle.unwrap_or_default()), theme.text_placeholder),
+ };
+ let place = crate::cloud::region_city(&c.region).map(str::to_string).unwrap_or_else(|| c.region.to_uppercase());
+ let title = format!("DigitalOcean · {place} · {}", crate::cloud::size_label(&c.size));
+ let created = c.created_at.unwrap_or(now);
+ let month_end = usage::month_start(now).checked_add_months(chrono::Months::new(1)).map(|t| (t - chrono::Duration::days(1)).format("%b %-d").to_string()).unwrap_or_default();
+ let if_kept = usage::month_if_kept(c.price_hourly, created, now);
+ let age = crate::util::short_duration((now - created).num_seconds().max(0) as u64);
+ let stat = |label: &'static str, value: String, sub: String| {
+ div()
+ .flex()
+ .flex_col()
+ .flex_1()
+ .min_w(px(0.))
+ .gap(px(2.))
+ .child(div().text_size(px(11.)).text_color(theme.text_placeholder).child(label))
+ .child(div().font_family(mono_font()).text_size(px(15.)).child(value))
+ .child(div().truncate().text_size(px(11.5)).text_color(theme.text_muted).child(sub))
+ };
+ let note = if off {
+ ("triangle-alert", theme.warning, "Powering off doesn't stop the charges: DigitalOcean bills a droplet until it's destroyed.".to_string())
+ } else {
+ ("info", theme.text_placeholder, format!("Billed by the second while it exists, on or off, up to ${:.2} a month. Destroy it to stop the charges.", c.price_monthly))
+ };
let (mid, machine) = (m.id.clone(), m.clone());
card(theme)
- .flex_row()
- .items_center()
- .gap(px(12.))
- .px(px(14.))
- .py(px(12.))
- .child({
- let (from, to) = format::machine_tile(m);
- kit::tile(format::machine_icon(m), from, to, 28.)
- })
.child(
div()
.flex()
- .flex_col()
- .flex_1()
- .min_w(px(0.))
- .gap(px(2.))
- .child(div().text_size(px(13.)).child(title))
- .child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child(detail)),
+ .items_center()
+ .gap(px(12.))
+ .px(px(14.))
+ .py(px(12.))
+ .child({
+ let (from, to) = format::machine_tile(m);
+ kit::tile(format::machine_icon(m), from, to, 28.)
+ })
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .flex_1()
+ .min_w(px(0.))
+ .gap(px(2.))
+ .child(div().truncate().text_size(px(13.)).child(title))
+ .child(div().text_size(px(11.5)).text_color(state.1).child(state.0)),
+ )
+ .child(Button::new("m-cloud-power", power_label).icon("power").disabled(busy).on_click(cx.listener(move |this, _, _, cx| this.cloud_power(&mid, off, cx))))
+ .child(Button::new("m-cloud-destroy", "Destroy…").style(ButtonStyle::Danger).disabled(busy).on_click(cx.listener(move |this, _, window, cx| this.confirm_remove_machine(&machine, window, cx)))),
+ )
+ .child(
+ div()
+ .flex()
+ .gap(px(16.))
+ .px(px(14.))
+ .py(px(12.))
+ .border_t_1()
+ .border_color(theme.border_variant)
+ .child(stat("Rate", format!("${:.3}/h", c.price_hourly), format!("up to ${:.2} a month", c.price_monthly)))
+ .child(stat("This month", format!("${:.2}", c.this_month), format!("about ${if_kept:.2} by {month_end} if kept")))
+ .child(stat("Since created", format!("${:.2}", c.cost_so_far), format!("created {age} ago"))),
+ )
+ .child(
+ div()
+ .flex()
+ .items_center()
+ .gap(px(8.))
+ .px(px(14.))
+ .py(px(10.))
+ .border_t_1()
+ .border_color(theme.border_variant)
+ .child(icon(note.0, 13., note.1))
+ .child(div().flex_1().min_w(px(0.)).truncate().text_size(px(12.)).text_color(if off { theme.warning } else { theme.text_muted }).child(note.2)),
)
- .child(Button::new("m-cloud-power", power_label).icon("power").disabled(busy).on_click(cx.listener(move |this, _, _, cx| this.cloud_power(&mid, off, cx))))
- .child(Button::new("m-cloud-destroy", "Destroy…").style(ButtonStyle::Danger).disabled(busy).on_click(cx.listener(move |this, _, window, cx| this.confirm_remove_machine(&machine, window, cx))))
}
fn machine_runner_row(&self, theme: &Theme, s: &Snapshot, r: &Runner, i: usize, busy: bool, cx: &mut Context<Self>) -> AnyElement {
diff --git a/src/ui/root.rs b/src/ui/root.rs
index 19e722a..5cbc34a 100644
--- a/src/ui/root.rs
+++ b/src/ui/root.rs
@@ -1343,15 +1343,6 @@ impl Root {
}
fn brand(&self, theme: &Theme, s: &Snapshot, cx: &mut Context<Self>) -> impl IntoElement {
- // What it's looking after: "2 machines · 3 runners · 1 session".
- let count = |n: usize, one: &str| format!("{n} {one}{}", if n == 1 { "" } else { "s" });
- let mut summary = vec![count(s.machines.len(), "machine")];
- if s.counts.runners > 0 {
- summary.push(count(s.counts.runners, "runner"));
- }
- if !s.sessions.is_empty() {
- summary.push(count(s.sessions.len(), "session"));
- }
// GPUI 0.2 only ellipsizes text whose width is known before layout.
let text_w = self.sidebar_width - 74. - if s.demo { 48. } else { 0. };
div()
@@ -1370,8 +1361,7 @@ impl Root {
.flex()
.flex_col()
.min_w(px(0.))
- .child(div().w(px(text_w)).truncate().text_size(px(14.)).font_weight(FontWeight::SEMIBOLD).text_color(theme.text).child("Muxen"))
- .child(div().w(px(text_w)).truncate().text_size(px(11.5)).text_color(theme.text_placeholder).child(summary.join(" · "))),
+ .child(div().w(px(text_w)).truncate().text_size(px(14.)).font_weight(FontWeight::SEMIBOLD).text_color(theme.text).child("Muxen")),
)
.when(s.demo, |d| d.child(div().flex_1()).child(kit::pill("demo", theme.warning)))
}
diff --git a/src/ui/settings.rs b/src/ui/settings.rs
index f30edcb..b8d513e 100644
--- a/src/ui/settings.rs
+++ b/src/ui/settings.rs
@@ -6,6 +6,7 @@ use std::time::{Duration, Instant};
use gpui::{AnyElement, App, Context, Entity, Focusable, SharedString, Subscription, Task, Window, div, prelude::*, px};
mod cloud;
+mod shell;
pub(super) use cloud::regular_size;
@@ -71,6 +72,8 @@ pub struct SettingsPage {
pub scroll: gpui::ScrollHandle,
tab: SettingsTab,
cloud: cloud::CloudState,
+ /// The `muxen` command in the PATH.
+ shell: shell::ShellState,
/// A shortcut waiting for its new keys, and what catches them before
/// they run anything.
recording: Option<&'static str>,
@@ -139,6 +142,7 @@ impl SettingsPage {
scroll: gpui::ScrollHandle::new(),
tab: SettingsTab::default(),
cloud: cloud_state,
+ shell: shell::ShellState::default(),
recording: None,
catch_keys: None,
shortcut_note: None,
@@ -148,6 +152,7 @@ impl SettingsPage {
if !page.snapshot.demo {
page.load_access(cx);
}
+ page.load_shell(cx);
page
}
@@ -959,6 +964,7 @@ impl Render for SettingsPage {
let body = div().w_full().max_w(px(760.)).flex().flex_col().gap(px(28.));
let body = match self.tab {
SettingsTab::General => body
+ .child(self.shell_section(&theme, cx))
.child(self.clipboard_section(&theme))
.children(self.tailscale_section(&theme))
.child(self.checks_section(&theme, false, cx))
@@ -966,7 +972,7 @@ impl Render for SettingsPage {
SettingsTab::Appearance => body.child(self.appearance_section(&theme, cx)),
SettingsTab::Terminal => body.child(self.terminal_section(&theme, super::terminal::font_family(window), super::terminal::monospace_families(window), cx)),
SettingsTab::GitHub => body.child(self.github_section(&theme, cx)).child(self.checks_section(&theme, true, cx)),
- SettingsTab::Cloud => body.child(self.cloud_section(&theme, cx)),
+ SettingsTab::Cloud => body.child(self.cloud_usage_section(&theme, cx)).child(self.cloud_section(&theme, cx)),
SettingsTab::Keyboard => body.child(self.keyboard_section(&theme, cx)),
};
div()
diff --git a/src/ui/settings/cloud.rs b/src/ui/settings/cloud.rs
index 7e9b56f..f8cfa33 100644
--- a/src/ui/settings/cloud.rs
+++ b/src/ui/settings/cloud.rs
@@ -4,6 +4,7 @@
use gpui::{AnyElement, App, Context, Entity, SharedString, Window, div, prelude::*, px};
use super::SettingsPage;
+use crate::cloud::usage::CloudUsage;
use crate::cloud::{CloudOptions, TAILSCALE_KEY, secrets};
use crate::config::CloudSettings;
use crate::ui::github::Load;
@@ -13,6 +14,8 @@ use crate::ui::theme::{Theme, mono_font};
pub(super) struct CloudState {
options: Option<Load<CloudOptions>>,
+ /// What the cloud machines cost (see cloud::usage).
+ usage: Option<CloudUsage>,
token: Entity<TextInput>,
tailscale_key: Entity<TextInput>,
busy: bool,
@@ -36,7 +39,7 @@ impl CloudState {
}
}),
];
- (CloudState { options: None, token, tailscale_key, busy: false, message: None }, subs)
+ (CloudState { options: None, usage: None, token, tailscale_key, busy: false, message: None }, subs)
}
}
@@ -51,6 +54,10 @@ impl SettingsPage {
let engine = engine.clone();
async move { engine.cloud_options().await }
});
+ let usage = engine.runtime().spawn({
+ let engine = engine.clone();
+ async move { engine.cloud_usage().await }
+ });
let task = cx.spawn(async move |this, cx| {
if let Ok(options) = job.await {
let _ = this.update(cx, |this, cx| {
@@ -58,10 +65,147 @@ impl SettingsPage {
cx.notify()
});
}
+ if let Ok(usage) = usage.await {
+ let _ = this.update(cx, |this, cx| {
+ this.cloud.usage = Some(usage);
+ cx.notify()
+ });
+ }
});
self._tasks.push(task);
}
+ /// What the cloud machines cost: now, this month, by its end, each one,
+ /// and the account's bill when Muxen may read it.
+ pub(super) fn cloud_usage_section(&self, theme: &Theme, cx: &mut Context<Self>) -> AnyElement {
+ let body: AnyElement = match &self.cloud.usage {
+ None => div().p(px(14.)).flex().items_center().gap(px(6.)).text_size(px(12.5)).text_color(theme.text_muted).child(kit::spinner("cloud-usage", 12., theme.text_muted)).child("Adding it up…").into_any_element(),
+ Some(u) => {
+ let now = chrono::Utc::now();
+ let month_end = crate::cloud::usage::month_start(now)
+ .checked_add_months(chrono::Months::new(1))
+ .map(|t| (t - chrono::Duration::days(1)).format("%b %-d").to_string())
+ .unwrap_or_default();
+ let live = u.machines.iter().filter(|m| m.machine_id.is_some()).count();
+ let stat = |label: String, value: String, sub: String| {
+ div()
+ .flex()
+ .flex_col()
+ .flex_1()
+ .min_w(px(0.))
+ .gap(px(2.))
+ .child(div().text_size(px(11.)).text_color(theme.text_placeholder).child(label))
+ .child(div().font_family(mono_font()).text_size(px(15.)).child(value))
+ .child(div().truncate().text_size(px(11.5)).text_color(theme.text_muted).child(sub))
+ };
+ let bill = match (&u.account, &u.account_error) {
+ (Some(b), _) => stat("DigitalOcean bill".into(), format!("${:.2}", b.month_to_date_usage), "this month, whole account".into()),
+ _ => stat("DigitalOcean bill".into(), "—".into(), if u.account_needs_sign_in { "needs one more permission".into() } else { "not shared yet".into() }),
+ };
+ let rows: Vec<AnyElement> = u
+ .machines
+ .iter()
+ .map(|m| {
+ let (word, color) = match m.power.as_deref() {
+ Some("on") => ("on", theme.success),
+ Some("off") => ("off · still billed", theme.warning),
+ Some("starting") => ("starting", theme.text_muted),
+ Some("destroyed") => ("destroyed", theme.text_placeholder),
+ _ => ("—", theme.text_placeholder),
+ };
+ let place = crate::cloud::region_city(&m.region).map(str::to_string).unwrap_or_else(|| m.region.to_uppercase());
+ let gone = m.machine_id.is_none();
+ div()
+ .flex()
+ .items_center()
+ .gap(px(12.))
+ .px(px(14.))
+ .py(px(9.))
+ .border_t_1()
+ .border_color(theme.border_variant)
+ .when(gone, |d| d.opacity(0.6))
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .flex_1()
+ .min_w(px(0.))
+ .child(div().flex().items_center().gap(px(8.)).text_size(px(12.5)).child(m.name.clone()).child(div().text_size(px(11.5)).text_color(color).child(word)))
+ .child(div().truncate().text_size(px(11.5)).text_color(theme.text_placeholder).child(format!("{place} · {}", crate::cloud::size_label(&m.size)))),
+ )
+ .child(div().w(px(90.)).flex_none().font_family(mono_font()).text_size(px(12.)).text_color(theme.text_muted).child(if gone { "—".to_string() } else { format!("${:.3}/h", m.price_hourly) }))
+ .child(div().w(px(110.)).flex_none().flex().justify_end().font_family(mono_font()).text_size(px(12.5)).child(format!("${:.2}", m.this_month)))
+ .into_any_element()
+ })
+ .collect();
+ div()
+ .flex()
+ .flex_col()
+ .child(
+ div()
+ .flex()
+ .gap(px(16.))
+ .px(px(14.))
+ .py(px(12.))
+ .child(stat("Now".into(), format!("${:.3}/h", u.hourly_now), format!("{live} machine{}, on or off", if live == 1 { "" } else { "s" })))
+ .child(stat("This month".into(), format!("${:.2}", u.this_month), "so far".into()))
+ .child(stat(format!("By {month_end}"), format!("${:.2}", u.month_if_kept), "if they're kept".into()))
+ .child(bill),
+ )
+ .when(!rows.is_empty(), |d| {
+ d.child(
+ div()
+ .flex()
+ .items_center()
+ .gap(px(12.))
+ .px(px(14.))
+ .pt(px(8.))
+ .pb(px(6.))
+ .border_t_1()
+ .border_color(theme.border_variant)
+ .text_size(px(11.))
+ .text_color(theme.text_placeholder)
+ .child(div().flex_1().child("Machine"))
+ .child(div().w(px(90.)).flex_none().child("Rate"))
+ .child(div().w(px(110.)).flex_none().flex().justify_end().child("This month")),
+ )
+ .children(rows)
+ })
+ .when_some(u.account_error.clone().filter(|_| u.account.is_none()), |d, e| {
+ d.child(
+ div()
+ .flex()
+ .items_center()
+ .gap(px(8.))
+ .px(px(14.))
+ .py(px(10.))
+ .border_t_1()
+ .border_color(theme.border_variant)
+ .child(div().flex_1().min_w(px(0.)).truncate().text_size(px(12.)).text_color(theme.text_muted).child(e))
+ .child(if u.account_needs_sign_in {
+ Button::new("do-sign-in-again", "Sign in again").loading(self.cloud.busy).on_click(cx.listener(|this, _, _, cx| this.cloud_connect("oauth", cx)))
+ } else {
+ Button::new("do-billing", "Open billing").icon("external-link").on_click(|_, _, cx| cx.open_url("https://cloud.digitalocean.com/account/billing"))
+ }),
+ )
+ })
+ // A column, so the sentence wraps (wrapping text in a row mis-measures).
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .px(px(14.))
+ .py(px(10.))
+ .border_t_1()
+ .border_color(theme.border_variant)
+ .child(div().w_full().min_w(px(0.)).text_size(px(12.)).text_color(theme.text_muted).child(u.billing)),
+ )
+ .into_any_element()
+ }
+ };
+ div().flex().flex_col().gap(px(10.)).child(section_title(theme, "Usage and cost", None)).child(card(theme).child(body)).into_any_element()
+ }
+
fn cloud_connect(&mut self, method: &'static str, cx: &mut Context<Self>) {
if self.cloud.busy {
return;
diff --git a/src/ui/settings/shell.rs b/src/ui/settings/shell.rs
new file mode 100644
index 0000000..bbc2e86
--- /dev/null
+++ b/src/ui/settings/shell.rs
@@ -0,0 +1,100 @@
+//! Settings › General › Command line: the `muxen` command in the PATH (see
+//! crate::shell_command), so terminals and other agents can run Muxen.
+
+use gpui::{AnyElement, Context, div, prelude::*, px};
+
+use super::SettingsPage;
+use crate::shell_command::{self, Status};
+use crate::ui::kit::{Button, ButtonStyle, card, icon, section_title};
+use crate::ui::theme::{Theme, mono_font};
+
+#[derive(Default)]
+pub(super) struct ShellState {
+ status: Option<Status>,
+ busy: bool,
+ error: Option<String>,
+}
+
+impl SettingsPage {
+ /// Looks at the PATH (in the background: on Windows it runs PowerShell).
+ pub(super) fn load_shell(&mut self, cx: &mut Context<Self>) {
+ self.run_shell(None, cx);
+ }
+
+ /// Installs (`Some(true)`), removes (`Some(false)`) or just looks.
+ fn run_shell(&mut self, install: Option<bool>, cx: &mut Context<Self>) {
+ if self.shell.busy {
+ return;
+ }
+ self.shell.busy = true;
+ self.shell.error = None;
+ let job = self.engine.runtime().spawn_blocking(move || match install {
+ Some(true) => shell_command::install(),
+ Some(false) => shell_command::remove(),
+ None => Ok(shell_command::status()),
+ });
+ let task = cx.spawn(async move |this, cx| {
+ let result = job.await.unwrap_or_else(|e| Err(e.to_string()));
+ let _ = this.update(cx, |this, cx| {
+ this.shell.busy = false;
+ match result {
+ Ok(status) => this.shell.status = Some(status),
+ Err(e) => this.shell.error = Some(e),
+ }
+ cx.notify();
+ });
+ });
+ self._tasks.push(task);
+ cx.notify();
+ }
+
+ pub(super) fn shell_section(&self, theme: &Theme, cx: &mut Context<Self>) -> AnyElement {
+ let st = &self.shell;
+ let (glyph, color, line): (&str, _, String) = match &st.status {
+ None => ("loader-circle", theme.text_muted, "Looking…".into()),
+ Some(s) => match s.state {
+ "installed" => ("circle-check", theme.success, format!("Installed: {}", s.path)),
+ "missing" if cfg!(windows) => ("circle", theme.text_muted, "Not installed. Muxen's folder gets added to your PATH.".into()),
+ "missing" => ("circle", theme.text_muted, format!("Not installed. It goes in {}.", s.path)),
+ "other" => ("triangle-alert", theme.warning, format!("{} is already there.", s.path)),
+ _ => ("circle-x", theme.error, "Not available on this computer.".into()),
+ },
+ };
+ let note = st.status.as_ref().and_then(|s| s.note.clone()).or_else(|| {
+ // Before it asks: macOS shows its own password prompt for /usr/local/bin.
+ st.status.as_ref().filter(|s| s.state == "missing" && cfg!(target_os = "macos")).map(|_| "macOS may ask for your password to add it there.".to_string())
+ });
+ let state = st.status.as_ref().map(|s| (s.state, s.replaceable));
+ let button = match state {
+ Some(("missing", _)) => Some(Button::new("shell-install", "Install").icon("plus").style(ButtonStyle::Primary).loading(st.busy).on_click(cx.listener(|this, _, _, cx| this.run_shell(Some(true), cx)))),
+ Some(("other", true)) => Some(Button::new("shell-replace", "Use this copy").icon("refresh-cw").loading(st.busy).on_click(cx.listener(|this, _, _, cx| this.run_shell(Some(true), cx)))),
+ Some(("installed", _)) => Some(Button::new("shell-remove", "Remove").loading(st.busy).on_click(cx.listener(|this, _, _, cx| this.run_shell(Some(false), cx)))),
+ _ => None,
+ };
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(10.))
+ .child(section_title(theme, "Command line", None))
+ .child(
+ card(theme)
+ .p(px(14.))
+ .gap(px(10.))
+ .child(div().w_full().min_w(px(0.)).text_size(px(12.5)).text_color(theme.text_muted).child(
+ "Use Muxen from a terminal, and connect other agents to it with muxen mcp.",
+ ))
+ .child(
+ div()
+ .flex()
+ .items_center()
+ .gap(px(8.))
+ .child(icon(glyph, 14., color))
+ .child(div().flex_1().min_w(px(0.)).truncate().font_family(mono_font()).text_size(px(12.5)).child(line))
+ .children(button),
+ )
+ .children(note.map(|n| div().text_size(px(12.)).text_color(theme.text_placeholder).child(n)))
+ .children(st.error.clone().map(|e| div().text_size(px(12.)).text_color(theme.error).child(e))),
+ )
+ .into_any_element()
+ }
+}