SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Put solidcraft-cli on PATH from the AppImage and the macOS app (#6347)
bherbrucka150822d9b53
diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.ymlindex dcd50b8fe6..a468e76ab5 100644--- a/.github/workflows/packaging-lint.yml+++ b/.github/workflows/packaging-lint.yml@@ -39,6 +39,8 @@ jobs:run: python3 packaging/tests/nightly_test.py- name: Windows executable icon validation regressionrun: python3 packaging/tests/windows_icon_test.py+ - name: AppImage CLI wrapper regression+ run: python3 packaging/tests/apprun_test.py- name: Flatpak desktop smoke validation regressionrun: python3 packaging/tests/flatpak_test.py- name: PowerShelldiff --git a/apps/solidcraft/src/main.rs b/apps/solidcraft/src/main.rsindex 2137672c0e..f9164f6834 100644--- a/apps/solidcraft/src/main.rs+++ b/apps/solidcraft/src/main.rs@@ -111,6 +111,9 @@ impl eframe::App for App {ctx.send_viewport_cmd(egui::ViewportCommand::Focus);}solidcraft_engine::crash::phase(solidcraft_engine::crash::RUNNING);+ // A DMG install has no installer step: put solidcraft-cli on PATH, quietly.+ #[cfg(target_os = "macos")]+ std::thread::spawn(solidcraft_ui_egui::cli_link::install_on_launch);if let Some(dir) = self.starting.take() {startup::started(&dir);}diff --git a/apps/solidcraft/src/native_menu.rs b/apps/solidcraft/src/native_menu.rsindex 02e9d55716..4df20439a0 100644--- a/apps/solidcraft/src/native_menu.rs+++ b/apps/solidcraft/src/native_menu.rs@@ -105,6 +105,7 @@ impl NativeMenu {("messages", "Messages\u{2026}"),("report", "Report an Issue\u{2026}"),("crashes", "Crash Reports\u{2026}"),+ ("install_cli", "Install solidcraft-cli command"),] {let item = MenuItem::new(app.tr_label(label), true, None);help.append(&item)?;diff --git a/crates/ui-egui/src/cli_link.rs b/crates/ui-egui/src/cli_link.rsnew file mode 100644index 0000000000..286d941686--- /dev/null+++ b/crates/ui-egui/src/cli_link.rs@@ -0,0 +1,197 @@+//! `solidcraft-cli` on PATH for a macOS app bundle (a DMG install has no installer step): a+//! symlink in `/opt/homebrew/bin` or `/usr/local/bin` to the CLI inside the bundle, made quietly at+//! launch when one of them is writable, or from Help > Install solidcraft-cli command, which asks+//! for an administrator password when it must. A file that is not our symlink is never replaced.++use std::path::{Path, PathBuf};++/// What a link's place holds now.+#[derive(Debug, PartialEq)]+pub enum Slot {+ Empty,+ /// A symbolic link, to this path.+ Link(PathBuf),+ /// A file, a folder, or anything else: the user's.+ Other,+}++#[derive(Debug, PartialEq)]+pub enum Plan {+ /// The link is already right.+ Keep,+ /// Make it, or replace a stale link of ours.+ Write,+ /// Leave it: something else is there.+ Skip,+}++/// Whether `target` is a CLI inside some SolidCraft app bundle (an older or moved bundle's link+/// is ours to refresh).+fn ours(target: &Path) -> bool {+ let s = target.to_string_lossy();+ s.ends_with(".app/Contents/MacOS/solidcraft-cli")+}++/// What to do about the link slot for the CLI at `cli`.+pub fn plan(slot: &Slot, cli: &Path) -> Plan {+ match slot {+ Slot::Empty => Plan::Write,+ Slot::Link(t) if t == cli => Plan::Keep,+ Slot::Link(t) if ours(t) => Plan::Write,+ _ => Plan::Skip,+ }+}++/// The folders a link goes in, best first.+pub const DIRS: &[&str] = &["/opt/homebrew/bin", "/usr/local/bin"];++fn slot(link: &Path) -> Slot {+ match std::fs::symlink_metadata(link) {+ Err(_) => Slot::Empty,+ Ok(m) if m.file_type().is_symlink() => std::fs::read_link(link).map_or(Slot::Other, Slot::Link),+ Ok(_) => Slot::Other,+ }+}++/// The CLI beside the running app, when the app runs from a bundle.+fn bundled_cli() -> Option<PathBuf> {+ let cli = std::env::current_exe().ok()?.parent()?.join("solidcraft-cli");+ (cli.is_file() && ours(&cli)).then_some(cli)+}++fn on_path_elsewhere(path_var: &std::ffi::OsStr, dirs: &[&str]) -> bool {+ std::env::split_paths(path_var).any(|d| !dirs.iter().any(|x| Path::new(x) == d) && d.join("solidcraft-cli").exists())+}++/// Make the link in `dirs` (the first that takes it). Returns the link made or kept.+#[cfg(unix)]+fn link_in(dirs: &[&str], cli: &Path) -> Option<PathBuf> {+ for dir in dirs {+ let link = Path::new(dir).join("solidcraft-cli");+ match plan(&slot(&link), cli) {+ Plan::Keep => return Some(link),+ Plan::Skip => continue,+ Plan::Write => {+ if !Path::new(dir).is_dir() {+ continue;+ }+ let _ = std::fs::remove_file(&link);+ if std::os::unix::fs::symlink(cli, &link).is_ok() {+ return Some(link);+ }+ }+ }+ }+ None+}++#[cfg(not(unix))]+fn link_in(_dirs: &[&str], _cli: &Path) -> Option<PathBuf> {+ None+}++/// At launch: best effort, silent. Does nothing off macOS, outside a bundle, or when+/// `solidcraft-cli` is already on PATH from somewhere else.+pub fn install_on_launch() {+ if !cfg!(target_os = "macos") {+ return;+ }+ let Some(cli) = bundled_cli() else { return };+ if std::env::var_os("PATH").is_some_and(|p| on_path_elsewhere(&p, DIRS)) {+ return;+ }+ link_in(DIRS, &cli);+}++/// Help > Install solidcraft-cli command: the same, then with an administrator prompt into+/// `/usr/local/bin` when no folder is writable. A message for the status line, and whether it failed.+pub fn install_from_menu() -> (String, bool) {+ if !cfg!(target_os = "macos") {+ return ("This is for the macOS app; the other packages put solidcraft-cli on PATH themselves.".into(), true);+ }+ let Some(cli) = bundled_cli() else {+ return ("solidcraft-cli was not found inside this app.".into(), true);+ };+ if let Some(l) = link_in(DIRS, &cli) {+ return (format!("solidcraft-cli is available as {}", l.display()), false);+ }+ let Some(script) = admin_script(&cli) else {+ return ("The app's path has characters the installer cannot quote; move SolidCraft to /Applications.".into(), true);+ };+ match std::process::Command::new("osascript").args(["-e", &script]).output() {+ Ok(o) if o.status.success() => ("solidcraft-cli is available as /usr/local/bin/solidcraft-cli".into(), false),+ Ok(o) => (format!("Not installed: {}", String::from_utf8_lossy(&o.stderr).trim()), true),+ Err(e) => (format!("Not installed: {e}"), true),+ }+}++/// The AppleScript that links `cli` into `/usr/local/bin` as an administrator. None when the path+/// holds a character that would need escaping (a quote or backslash), or an existing file is there.+pub fn admin_script(cli: &Path) -> Option<String> {+ let c = cli.to_str()?;+ if c.contains(['\'', '"', '\\', '\n']) {+ return None;+ }+ // `[ -e ] && ! [ -L ]`: never replace a file that is not a link.+ Some(format!(+ "do shell script \"mkdir -p /usr/local/bin && if [ -e /usr/local/bin/solidcraft-cli ] && [ ! -L /usr/local/bin/solidcraft-cli ]; then echo 'a file named solidcraft-cli is already in /usr/local/bin' >&2; exit 1; fi && ln -sfn '{c}' /usr/local/bin/solidcraft-cli\" with administrator privileges"+ ))+}++#[cfg(test)]+mod tests {+ use super::*;++ const CLI: &str = "/Applications/SolidCraft.app/Contents/MacOS/solidcraft-cli";++ #[test]+ fn plans() {+ let cli = Path::new(CLI);+ assert_eq!(plan(&Slot::Empty, cli), Plan::Write);+ assert_eq!(plan(&Slot::Link(cli.into()), cli), Plan::Keep);+ // A link to a moved or older bundle is ours to refresh; to anything else, not.+ assert_eq!(plan(&Slot::Link("/Users/me/Old.app/Contents/MacOS/solidcraft-cli".into()), cli), Plan::Write);+ assert_eq!(plan(&Slot::Link("/opt/other/solidcraft-cli".into()), cli), Plan::Skip);+ assert_eq!(plan(&Slot::Other, cli), Plan::Skip);+ }++ #[test]+ fn links_only_where_it_may() {+ let d = std::env::temp_dir().join(format!("solidcraft-cli-link-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&d);+ let (a, b) = (d.join("a"), d.join("b"));+ std::fs::create_dir_all(&a).unwrap();+ std::fs::create_dir_all(&b).unwrap();+ let cli = Path::new(CLI);+ let dirs = [a.to_str().unwrap(), b.to_str().unwrap()];+ // A file of the user's blocks its folder; the next one gets the link.+ std::fs::write(a.join("solidcraft-cli"), "mine").unwrap();+ assert_eq!(link_in(&dirs, cli), Some(b.join("solidcraft-cli")));+ assert_eq!(std::fs::read_to_string(a.join("solidcraft-cli")).unwrap(), "mine");+ assert_eq!(std::fs::read_link(b.join("solidcraft-cli")).unwrap(), cli);+ // A stale link of ours is refreshed.+ std::fs::remove_file(b.join("solidcraft-cli")).unwrap();+ std::os::unix::fs::symlink("/x/Old.app/Contents/MacOS/solidcraft-cli", b.join("solidcraft-cli")).unwrap();+ assert_eq!(link_in(&dirs[1..], cli), Some(b.join("solidcraft-cli")));+ assert_eq!(std::fs::read_link(b.join("solidcraft-cli")).unwrap(), cli);+ let _ = std::fs::remove_dir_all(&d);+ }++ #[test]+ fn path_check_ignores_our_own_folders() {+ let d = std::env::temp_dir().join(format!("solidcraft-cli-path-{}", std::process::id()));+ std::fs::create_dir_all(&d).unwrap();+ std::fs::write(d.join("solidcraft-cli"), "").unwrap();+ let path = std::env::join_paths([d.as_path()]).unwrap();+ assert!(on_path_elsewhere(&path, &["/opt/homebrew/bin"]));+ assert!(!on_path_elsewhere(&path, &[d.to_str().unwrap()]));+ let _ = std::fs::remove_dir_all(&d);+ }++ #[test]+ fn admin_script_refuses_paths_that_need_escaping() {+ assert!(admin_script(Path::new(CLI)).unwrap().contains("with administrator privileges"));+ assert!(admin_script(Path::new("/Apps/It's.app/Contents/MacOS/solidcraft-cli")).is_none());+ assert!(admin_script(Path::new("/Apps/a\"b.app/Contents/MacOS/solidcraft-cli")).is_none());+ }+}diff --git a/crates/ui-egui/src/help.rs b/crates/ui-egui/src/help.rsindex 3e832fb021..2b687eb95e 100644--- a/crates/ui-egui/src/help.rs+++ b/crates/ui-egui/src/help.rs@@ -38,7 +38,7 @@ pub fn diagnostics(app: &SolveApp) -> String {)}-/// Run a Help menu item: `docs`, `about`, `shortcuts`, `messages`, `report`, `crashes`.+/// Run a Help menu item: `docs`, `about`, `shortcuts`, `messages`, `report`, `crashes`, `install_cli` (macOS).pub fn run(app: &mut SolveApp, ctx: &egui::Context, item: &str) {app.help.menu = false;match item {@@ -49,6 +49,10 @@ pub fn run(app: &mut SolveApp, ctx: &egui::Context, item: &str) {app.keymap.read_only = true;}"crashes" => crate::crash_ui::open(app),+ "install_cli" => {+ let (msg, error) = crate::cli_link::install_from_menu();+ app.set_status(msg, error);+ }"messages" => app.messages.open = true,"report" => {let dialog = app.dialog.clone();@@ -77,7 +81,11 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context, anchor: egui::Pos2) {("messages", "Messages…", "list"),("report", "Report an Issue…", "bug_report"),("crashes", "Crash Reports…", "status_error"),- ] {+ ("install_cli", "Install solidcraft-cli command", "settings"),+ ]+ .into_iter()+ .filter(|(id, ..)| *id != "install_cli" || cfg!(target_os = "macos"))+ {if crate::context_menu::list_row(ui, &crate::context_menu::Item::action(id, label, icon)).is_some() {pick = Some(id);}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 17f51060dd..06471e11d9 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -17,6 +17,7 @@ pub mod browser;pub mod browser_canvas;pub mod browser_prompts;pub mod canvas;+pub mod cli_link;#[cfg(test)]mod colour_tokens_tests;#[cfg(test)]diff --git a/docs/mcp.md b/docs/mcp.mdindex fd0c764718..3796fc6c1a 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -133,7 +133,7 @@ not read-only, `destructiveHint` and `openWorldHint` are true.### Client configuration-On Windows the installer adds its folder to the system `PATH`, so `solidcraft-cli` works by name in clients opened after the install (restart the client).+`solidcraft-cli` is on `PATH` after every package install: the Windows installer adds its folder, the deb, rpm and FreeBSD packages install it in `/usr/bin`, the Homebrew cask links it, the AppImage writes a small `solidcraft-cli` launcher into `~/.local/bin` on its first run, and the macOS app links it into `/opt/homebrew/bin` or `/usr/local/bin` when it starts (Help > Install solidcraft-cli command does it with an administrator prompt when those are not writable). Two packages keep it out of `PATH` by design: Snap exposes it as `solidcraft.cli`, and Flatpak runs it as `flatpak run --command=solidcraft-cli ai.storyteller.solidcraft`; use those as the client's `command` (with `mcp` as the arguments).Claude Code (project `.mcp.json`, or `claude mcp add solidcraft -- solidcraft-cli mcp`; a setupadded under the previous name keeps working, see the [compatibility notes](https://github.com/bherbruck/solidcraft/blob/main/docs/compatibility.md#mcp)):diff --git a/packaging/linux/AppRun b/packaging/linux/AppRunindex acd8f67f85..345091d5af 100755--- a/packaging/linux/AppRun+++ b/packaging/linux/AppRun@@ -14,14 +14,39 @@# installed either when appimaged (go-appimage) already made an entry for this AppImage, or when# a launcher that manages AppImages (Gear Lever, AppImageLauncher) started it: it sets# DESKTOPINTEGRATION and owns the menu entry.+#+# The same step puts `solidcraft-cli` on PATH: a small wrapper script in ~/.local/bin that starts this+# AppImage in command-line mode (SOLIDCRAFT_APPIMAGE_CLI=1 makes AppRun run the bundled+# solidcraft-cli), so MCP clients and shells find it by name. It is rewritten when the AppImage+# moves, and a file there that this script did not write is never touched. The same opt-outs apply.set -uAPPDIR="$(dirname "$(readlink -f "$0")")"DESK_ID=ai.storyteller.solidcraft+CLI_MARKER="# solidcraft-cli wrapper written by the SolidCraft AppImage"# Compatibility shim (docs/compatibility.md): the desktop id of releases before 0.8.OLD_DESK_ID=ai.storyteller.solvecraft+# The wrapper in ~/.local/bin: $1 is the AppImage's path, $2 the home folder.+install_cli() {+ bin="${XDG_BIN_HOME:-$2/.local/bin}"+ wrapper="$bin/solidcraft-cli"+ # Anything there that is not our wrapper (a file, a link, a directory) is the user's.+ if [ -e "$wrapper" ] || [ -L "$wrapper" ]; then+ [ -f "$wrapper" ] && [ ! -L "$wrapper" ] && grep -qF "$CLI_MARKER" "$wrapper" 2>/dev/null || return 0+ fi+ mkdir -p "$bin" 2>/dev/null || return 0+ tmp="$bin/.solidcraft-cli.tmp.$$"+ printf '#!/bin/sh\n%s\nSOLIDCRAFT_APPIMAGE_CLI=1 exec "%s" "$@"\n' "$CLI_MARKER" "$1" >"$tmp" 2>/dev/null || { rm -f "$tmp"; return 0; }+ chmod 755 "$tmp" 2>/dev/null+ if cmp -s "$tmp" "$wrapper" 2>/dev/null; then+ rm -f "$tmp"+ else+ mv -f "$tmp" "$wrapper" 2>/dev/null || rm -f "$tmp"+ fi+}+integrate() {case "${SOLIDCRAFT_NO_DESKTOP_INTEGRATION:-${SOLVECRAFT_NO_DESKTOP_INTEGRATION:-}}" in1 | true | yes) return 0 ;;@@ -41,6 +66,7 @@ integrate() {[ -n "$home" ] || return 0data="${XDG_DATA_HOME:-$home/.local/share}"[ -e "$data/solidcraft/no-desktop-integration" ] && return 0+ install_cli "$appimage" "$home"src_desktop="$APPDIR/usr/share/applications/$DESK_ID.desktop"[ -f "$src_desktop" ] || return 0@@ -111,5 +137,11 @@ integrate() {done}+# Started through the wrapper `integrate` installs: the command-line tool, with no integration.+if [ "${SOLIDCRAFT_APPIMAGE_CLI:-}" = 1 ]; then+ unset SOLIDCRAFT_APPIMAGE_CLI+ exec "$APPDIR/usr/bin/solidcraft-cli" "$@"+fi+integrateexec "$APPDIR/usr/bin/solidcraft" "$@"diff --git a/packaging/tests/apprun_test.py b/packaging/tests/apprun_test.pynew file mode 100644index 0000000000..a59a3e5421--- /dev/null+++ b/packaging/tests/apprun_test.py@@ -0,0 +1,70 @@+"""AppRun puts a `solidcraft-cli` wrapper on PATH (~/.local/bin) and the wrapper runs the bundled CLI."""+import os+import shutil+import subprocess+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parents[2]+++class AppRunCli(unittest.TestCase):+ def setUp(self):+ self.tmp = Path(tempfile.mkdtemp())+ self.addCleanup(shutil.rmtree, self.tmp, True)+ self.appdir = self.tmp / "app" / "AppDir"+ (self.appdir / "usr/bin").mkdir(parents=True)+ (self.appdir / "usr/share/applications").mkdir(parents=True)+ shutil.copy(ROOT / "packaging/linux/AppRun", self.appdir / "AppRun")+ (self.appdir / "usr/share/applications/ai.storyteller.solidcraft.desktop").write_text("[Desktop Entry]\nExec=solidcraft\n")+ for name in ("solidcraft", "solidcraft-cli"):+ p = self.appdir / "usr/bin" / name+ p.write_text(f"#!/bin/sh\necho {name} \"$@\"\n")+ p.chmod(0o755)+ # The AppImage file: running it runs AppRun, as the runtime does.+ self.image = self.tmp / "My App" / "SolidCraft.AppImage"+ self.image.parent.mkdir()+ self.image.write_text(f'#!/bin/sh\nexec "{self.appdir}/AppRun" "$@"\n')+ self.image.chmod(0o755)+ self.home = self.tmp / "home"+ self.home.mkdir()+ self.env = {"PATH": os.environ["PATH"], "HOME": str(self.home), "APPIMAGE": str(self.image)}+ self.wrapper = self.home / ".local/bin/solidcraft-cli"++ def run_apprun(self, *args, **extra):+ env = {**self.env, **extra}+ return subprocess.run([str(self.appdir / "AppRun"), *args], env=env, capture_output=True, text=True, check=True).stdout.strip()++ def test_wrapper_runs_the_bundled_cli(self):+ self.assertEqual(self.run_apprun("a"), "solidcraft a")+ self.assertTrue(self.wrapper.is_file())+ out = subprocess.run([str(self.wrapper), "mcp", "setup"], env=self.env, capture_output=True, text=True, check=True).stdout.strip()+ self.assertEqual(out, "solidcraft-cli mcp setup")++ def test_wrapper_follows_a_moved_appimage(self):+ self.run_apprun()+ moved = self.tmp / "moved.AppImage"+ shutil.move(self.image, moved)+ self.env["APPIMAGE"] = str(moved)+ self.run_apprun()+ self.assertIn(str(moved), self.wrapper.read_text())++ def test_a_file_that_is_not_ours_is_left_alone(self):+ self.wrapper.parent.mkdir(parents=True)+ self.wrapper.write_text("#!/bin/sh\necho mine\n")+ self.run_apprun()+ self.assertEqual(self.wrapper.read_text(), "#!/bin/sh\necho mine\n")+ other = self.home / ".local/bin/solidcraft-cli"+ other.unlink()+ other.symlink_to("/bin/true")+ self.run_apprun()+ self.assertTrue(other.is_symlink())++ def test_opt_out_installs_nothing(self):+ self.run_apprun(SOLIDCRAFT_NO_DESKTOP_INTEGRATION="1")+ self.assertFalse(self.wrapper.exists())+++if __name__ == "__main__":+ unittest.main()