Skip to content

Craft Anything: understand how any software works, and craft your own.

Rust

Find browsers under their other Linux names, and say why one isn't found (#927)

Justin Johnc858a61c8d5c
diff --git a/README.md b/README.md
index 12e02306..42c1b017 100644
--- a/README.md
+++ b/README.md
@@ -333,7 +333,7 @@ run the file; report it with the output and the release tag.
| Format | x86_64 | aarch64 (ARM64) | Notes |
|---|---|---|---|
| AppImage | `craft-anything-<ver>-linux-x86_64.AppImage` | `craft-anything-<ver>-linux-aarch64.AppImage` | Runs anywhere; updates itself with [AppImageUpdate](https://github.com/AppImageCommunity/AppImageUpdate) (`.zsync` files) |
-| Flatpak | `craft-anything-<ver>-linux-x86_64.flatpak` | `craft-anything-<ver>-linux-aarch64.flatpak` | Sandboxed; `flatpak install --user <file>` |
+| Flatpak | `craft-anything-<ver>-linux-x86_64.flatpak` | `craft-anything-<ver>-linux-aarch64.flatpak` | Sandboxed, so it can't start a browser on your computer, which studying websites needs (use another package for that); `flatpak install --user <file>` |
| Debian/Ubuntu | `craft-anything-<ver>-linux-x86_64.deb` | `craft-anything-<ver>-linux-aarch64.deb` | |
| Fedora/RHEL/openSUSE | `craft-anything-<ver>-linux-x86_64.rpm` | `craft-anything-<ver>-linux-aarch64.rpm` | |
| Tarball | `craft-anything-<ver>-linux-x86_64.tar.gz` | `craft-anything-<ver>-linux-aarch64.tar.gz` | Unpack anywhere |
diff --git a/crates/ai/src/cli_agents/adapters.rs b/crates/ai/src/cli_agents/adapters.rs
index 7f8a0108..c22e45fd 100644
--- a/crates/ai/src/cli_agents/adapters.rs
+++ b/crates/ai/src/cli_agents/adapters.rs
@@ -580,11 +580,7 @@ fn claude_config_dir() -> Option<std::path::PathBuf> {
set.or_else(flatpak_claude_dir).or_else(|| dirs::home_dir().map(|h| h.join(".claude")))
}
-/// Whether this app runs in a Flatpak sandbox (it sets `FLATPAK_ID` and makes `/.flatpak-info`).
-pub fn in_flatpak() -> bool {
- static IN: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
- *IN.get_or_init(|| std::env::var_os("FLATPAK_ID").is_some() || std::path::Path::new("/.flatpak-info").exists())
-}
+pub use craft_anything_platform::in_flatpak;
/// Where Claude Code keeps its conversations when we start it under a Flatpak and the person
/// hasn't chosen a folder: its own is `~/.claude`, which the sandbox only lets us read, so a
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index f408f9f7..ec639225 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -184,10 +184,10 @@ impl Engine {
}
Requires::Engine(id) => match session.settings.engine_path(id) {
Some(_) => Availability::ok(),
- None => Availability::no(
- format!("This needs {} installed.", craft_anything_engines::display_name(id)),
- format!("Install {} from Settings → Engines.", craft_anything_engines::display_name(id)),
- ),
+ None => {
+ let (reason, remediation) = session.settings.engine_not_found(id);
+ Availability::no(reason, remediation)
+ }
},
Requires::Os(hosts) => {
if hosts.contains(&std::env::consts::OS) {
@@ -311,6 +311,17 @@ mod tests {
assert_eq!(err.code, ErrorCode::BadInput);
}
+ /// #841: Try again repeated "install a browser" for a person who had set a path to theirs.
+ #[test]
+ fn a_tool_says_when_the_path_set_for_its_engine_is_not_there() {
+ let mut session = crate::testing::session();
+ session.settings.engines.tools.chromium = Some("/nowhere/brave".into());
+ let e = Engine::new(session);
+ let err = e.call("web_site_open", serde_json::json!({"url": "https://example.com"}), CallOptions::new(Caller::Cli)).unwrap_err();
+ assert_eq!(err.code, ErrorCode::EngineMissing);
+ assert!(err.message.contains("isn't there") && err.message.contains("brave"), "{}", err.message);
+ }
+
#[test]
fn every_engine_a_tool_needs_is_in_the_engine_table() {
let e = Engine::new(crate::testing::session());
diff --git a/crates/engine/src/settings.rs b/crates/engine/src/settings.rs
index f6b08c98..6b28981b 100644
--- a/crates/engine/src/settings.rs
+++ b/crates/engine/src/settings.rs
@@ -458,6 +458,12 @@ impl Settings {
craft_anything_engines::locate(id, &self.engines.tools, &self.engine_store_dir())
}
}
+
+ /// Why an engine wasn't found and what to do about it, as (reason, remediation).
+ pub fn engine_not_found(&self, id: &str) -> (String, String) {
+ use craft_anything_engines::ToolPathLookup;
+ craft_anything_engines::not_found_help(id, self.engines.tools.override_for(id).as_deref(), craft_anything_platform::in_flatpak())
+ }
}
#[cfg(test)]
diff --git a/crates/engine/src/tools/web_common.rs b/crates/engine/src/tools/web_common.rs
index 8c0502f9..ccb44037 100644
--- a/crates/engine/src/tools/web_common.rs
+++ b/crates/engine/src/tools/web_common.rs
@@ -96,7 +96,7 @@ pub fn runtime_of(product: &str, user_agent: &str) -> &'static str {
/// The error returned when no browser is available and none was asked to launch.
pub fn engine_missing(detail: impl std::fmt::Display) -> ToolError {
ToolError::new(ErrorCode::EngineMissing, format!("no browser is available: {detail}")).with_remediation(
- "Give a loopback CDP endpoint (start a browser with --remote-debugging-port), or install a browser from Settings → Engines so one can be launched.",
+ "Give a loopback CDP endpoint (start a browser with --remote-debugging-port), or install a Chromium-based browser so one can be launched (set its path in Settings → Engines if it isn't found).",
)
}
@@ -155,8 +155,13 @@ impl Browser {
}
pub(crate) fn launch(ctx: &Ctx<'_>, opts: &LaunchOptions, dl: &Deadline) -> Result<Browser, ToolError> {
- let exe = craft_anything_engines::locate("chromium", &ctx.session.settings.engines.tools, &ctx.session.settings.engine_store_dir())
- .ok_or_else(|| engine_missing("no Chromium-based browser was found"))?;
+ let exe =
+ craft_anything_engines::locate("chromium", &ctx.session.settings.engines.tools, &ctx.session.settings.engine_store_dir()).ok_or_else(|| {
+ // Browser tools that take an endpoint come here without `Requires::Engine`'s check.
+ let (reason, fix) = ctx.session.settings.engine_not_found("chromium");
+ ToolError::new(ErrorCode::EngineMissing, reason)
+ .with_remediation(format!("{fix} Or give a loopback CDP endpoint (start a browser with --remote-debugging-port)."))
+ })?;
let profile = BrowserProfile(super::artifact_tools::fresh_dir_in(&profile_base(&exe, dirs::home_dir()), "craft-browser")?);
let mut args: Vec<String> = vec![
format!("--user-data-dir={}", profile.0.display()),
diff --git a/crates/engines/src/lib.rs b/crates/engines/src/lib.rs
index 658e12dd..8ea168af 100644
--- a/crates/engines/src/lib.rs
+++ b/crates/engines/src/lib.rs
@@ -46,6 +46,32 @@ pub fn display_name(id: &str) -> &'static str {
engine(id).map(|e| e.name).unwrap_or("an external tool")
}
+/// What to tell the person when an engine wasn't found, as (reason, remediation): `set` is the path
+/// in Settings → Engines, which wasn't there, and `flatpak` whether this app runs in that sandbox.
+pub fn not_found_help(id: &str, set: Option<&Path>, flatpak: bool) -> (String, String) {
+ let name = display_name(id);
+ // Settings → Engines can only install what has pins; these the person installs themselves.
+ let manual = engine(id).is_some_and(|e| matches!(e.install, Install::Manual));
+ let reason = match set {
+ Some(p) => format!("This needs {name}, and the path set for it in Settings → Engines ({}) isn't there.", p.display()),
+ None => format!("This needs {name} installed."),
+ };
+ const CORRECT: &str = "Correct the path in Settings → Engines, or clear it to look in the usual places.";
+ let sandbox = (flatpak && manual).then(|| {
+ format!(
+ "This app is running as a Flatpak, and its sandbox can't see programs in your system's folders, so a path to one won't work. To use {name} from your computer, run the AppImage, .deb, .rpm or tarball version instead."
+ )
+ });
+ let remediation = match (set, sandbox) {
+ (Some(_), Some(sandbox)) => format!("{CORRECT} {sandbox}"),
+ (Some(_), None) => CORRECT.to_string(),
+ (None, Some(sandbox)) => sandbox,
+ (None, None) if manual => format!("Install {name}, then set its path in Settings → Engines if it still isn't found."),
+ (None, None) => format!("Install {name} from Settings → Engines."),
+ };
+ (reason, remediation)
+}
+
/// Find an engine: user override, then the managed store (`<store>/<id>/bin/<exe>`), then PATH,
/// then its standard install folders, then the folders where an unpacked copy is usually kept.
pub fn locate(id: &str, overrides: &dyn ToolPathLookup, store: &Path) -> Option<PathBuf> {
@@ -175,6 +201,37 @@ mod tests {
assert!(locate("ghidra", &NoOverrides, empty.path()).is_none() || installed);
}
+ /// #841: a path set for a browser was ignored without a word, and the message offered an
+ /// install that Settings can't do.
+ #[test]
+ fn a_missing_engine_is_explained_by_why_it_was_not_found() {
+ let set = Path::new("/usr/bin/brave");
+ let (reason, fix) = not_found_help("chromium", Some(set), true);
+ assert!(reason.contains(&set.display().to_string()), "{reason}");
+ // The path may only be mistyped, and one in the home folder can work, so correcting it comes first.
+ assert!(fix.starts_with("Correct the path") && fix.contains("Flatpak") && fix.contains("AppImage"), "{fix}");
+ // A Flatpak can't reach a browser with no path set either, and there's no path to correct.
+ let (_, fix) = not_found_help("chromium", None, true);
+ assert!(fix.contains("Flatpak") && !fix.contains("Correct the path"), "{fix}");
+
+ let (reason, fix) = not_found_help("chromium", Some(set), false);
+ assert!(reason.contains("isn't there") && fix.contains("Correct the path") && !fix.contains("Flatpak"), "{reason} {fix}");
+
+ let (_, fix) = not_found_help("chromium", None, false);
+ assert!(fix.starts_with("Install a Chromium-based browser,") && !fix.contains("from Settings"), "{fix}");
+
+ // What Settings can install still says so, and a sandbox doesn't stop it.
+ for flatpak in [false, true] {
+ assert_eq!(not_found_help("adb", None, flatpak).1, "Install Android platform tools (adb) from Settings → Engines.");
+ }
+ }
+
+ #[test]
+ fn browsers_are_looked_for_under_their_linux_package_names() {
+ let exes = engine("chromium").unwrap().exes;
+ assert!(["google-chrome-stable", "brave-browser", "microsoft-edge"].iter().all(|x| exes.contains(x)), "{exes:?}");
+ }
+
#[test]
fn browsers_have_well_known_locations_off_path() {
assert!(well_known("adb").is_empty());
diff --git a/crates/engines/src/table.rs b/crates/engines/src/table.rs
index e7766404..8ba30d63 100644
--- a/crates/engines/src/table.rs
+++ b/crates/engines/src/table.rs
@@ -449,7 +449,20 @@ pub const ENGINES: &[ExternalEngine] = &[
id: "chromium",
name: "a Chromium-based browser",
needed_for: "Studying websites in a live browser",
- exes: &["chromium", "chromium-browser", "google-chrome", "chrome", "msedge", "brave"],
+ // Linux packages differ: Arch's Chrome is only google-chrome-stable, Debian's Brave only brave-browser (#841).
+ exes: &[
+ "chromium",
+ "chromium-browser",
+ "google-chrome",
+ "google-chrome-stable",
+ "chrome",
+ "msedge",
+ "microsoft-edge",
+ "microsoft-edge-stable",
+ "brave",
+ "brave-browser",
+ "brave-browser-stable",
+ ],
exes_windows: &["chrome.exe", "msedge.exe", "brave.exe"],
known_paths: CHROMIUM_PATHS,
known_roots: NO_ROOTS,
diff --git a/crates/platform/src/lib.rs b/crates/platform/src/lib.rs
index c1c62135..24a5562d 100644
--- a/crates/platform/src/lib.rs
+++ b/crates/platform/src/lib.rs
@@ -21,6 +21,12 @@ pub use fs::{backup_once, write_atomic, write_atomic_private};
pub use process::{Cancel, Ended, Launch, Launched, LineSink, Output, Process, RunningProcess, StdinMode, open_path};
pub use which::{cli_file_name, self_cli_path, which, which_all};
+/// Whether this app runs in a Flatpak sandbox (it sets `FLATPAK_ID` and makes `/.flatpak-info`).
+pub fn in_flatpak() -> bool {
+ static IN: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+ *IN.get_or_init(|| std::env::var_os("FLATPAK_ID").is_some() || std::path::Path::new("/.flatpak-info").exists())
+}
+
/// Owns the helper that keeps a build awake until the guard is released. Dropping it waits up to
/// five seconds for supervised cleanup and logs a warning if that deadline passes.
#[derive(Debug)]
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index cca4db69..a7b2cd55 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -442,6 +442,12 @@ Owner: open · Status: in progress
- [x] Find Chrome, Brave, Chromium and Edge installed as Flatpaks on Linux (system and per-user
exports), and keep a Flatpak or Snap browser's private profile in the home folder its
sandbox shares, since its /tmp is its own (#747). Unit-tested; not run on a real Flatpak
+- [x] Find browsers under their other Linux names, and say why one isn't found: a set path that
+ isn't there, or a Flatpak's sandbox (#841). Unit-tested; not run on Linux or in a real Flatpak
+- [ ] **decision** Let the Flatpak start browsers on the computer. It can't see system ones today;
+ a per-user Flatpak browser in `~/.local/share/flatpak/exports/bin` is found, but its start
+ script needs `flatpak`, which the sandbox doesn't have. `flatpak-spawn --host` would need
+ `--talk-name=org.freedesktop.Flatpak`, which lets the app run anything outside its sandbox (#841)
- [ ] More pins once their hashes are checked against the publisher: Chromium (no published
checksums found yet), Rizin for Linux (the tar.xz unpacks to ~800 MB, so it needs streaming
extraction) and macOS (a .pkg)
diff --git a/docs/STATUS.md b/docs/STATUS.md
index 82784e1a..b8a4bbde 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -65,7 +65,7 @@ workspace clippy, layers, fmt and the secret scan of all history were clean. Chi
| Program facts across builds | `native_library_calls_list` (delay-load too), `native_offered_symbols_list`, `native_publisher_show` (checks the file hash and the signature, not Windows trust), `app_builds_line_up` pairs functions across two builds and says how, `native_source_folder_write` writes pseudo-C to a folder and picks up where it stopped, `android_components_list` | Unit tests. Real PE, ELF and Mach-O files; two builds of a 276 MB program; a signed Microsoft DLL; Android components from one real APK, spot-checked |
| ARM32 value flow | A32 and Thumb calls define ARM scratch registers, and word results flow through `r0` into returns in `native_value_flow_show`. Conditional A32 calls retain the earlier value when skipped and a possible returned result; calls to known non-returning targets keep only the skipped path | Synthetic instruction fixtures for leaf results and indirect calls in both modes, with AArch64 and x86-64 controls; direct and indirect A32 conditional calls within and across basic blocks, including a named `abort` target and unconditional controls. This correction was not checked on real ARM binaries or devices |
| Stand-in backends | `web_standin_build` turns a HAR into `standin.json` (secrets dropped, varying path parts templated); `web_standin_start` answers from it on loopback; `web_standin_show` lists what it had no answer for. A 304 without a usable cached body is counted at build time and skipped during replay; if its matching group has no usable answer, requests get a 404 with `cached_body_unavailable`, also shown in the request log. Writes replay what was recorded and don't change later reads. Older saved query variants keep explicit empty pairs when credential rules are reapplied; raw separators remain ignored and the 200-pair limit matches capture. App maps list GraphQL and tRPC operations; `web_walkthrough_check` checks a scripted session without a browser | Unit tests, real loopback requests, and a run with curl on a hand-written HAR. The 304 correction passes 99 analysis tests and a real-loopback regression, covering mixed samples, omitted bodies, matching boundaries and existing v1 files. [Hosted CI for #543](https://github.com/storytold/craft-anything/actions/runs/41585168291) also passed the full engine tests and workspace gates. Public capture/replay regressions cover legacy empty pairs, raw separators and the query-pair limit. No browser-made recording or real front end yet |
-| Websites as targets | `web_site_open` keeps a private browser for the session and deletes its temporary profile when the browser closes or fails to start; every browser tool inspects that page; `web_site_capture` records screenshots at each width (desktop, tablet and phone), rendered HTML, design tokens (colours in hex, spacing, content widths), the CSS breakpoints, the layout at each width (page width, heading sizes, each section's padding, gap, content column and items per row), page health (script and console errors, failed requests) and an accessibility outline, layout outline, assets with font files and requests, links and form outlines. In Clean room the capture keeps only what a visitor sees (no HTML, CSS rules, scripts, requests or errors), and opening a site reports no load errors | Live runs on example.com and a local page with Chromium on Linux, including profile cleanup after success and failed startup; unit tests. Brave on macOS was not run |
+| Websites as targets | `web_site_open` keeps a private browser for the session and deletes its temporary profile when the browser closes or fails to start; every browser tool inspects that page; `web_site_capture` records screenshots at each width (desktop, tablet and phone), rendered HTML, design tokens (colours in hex, spacing, content widths), the CSS breakpoints, the layout at each width (page width, heading sizes, each section's padding, gap, content column and items per row), page health (script and console errors, failed requests) and an accessibility outline, layout outline, assets with font files and requests, links and form outlines. In Clean room the capture keeps only what a visitor sees (no HTML, CSS rules, scripts, requests or errors), and opening a site reports no load errors. The Flatpak build can't start a browser on the computer (#841) | Live runs on example.com and a local page with Chromium on Linux, including profile cleanup after success and failed startup; unit tests. Brave on macOS was not run |
| Electron window comparisons | `app_graphs_compare` retains every unassigned window and every construction with a reused local binding. Windows are paired by module, binding and occurrence, so inserting comments does not hide preference changes. Colliding display labels receive a separate `#N` suffix without changing literal binding names or occurrence indices | Synthetic applications parsed through the ordinary analyzer exercise anonymous and reused bindings, shifted source lines, unequal counts, literal names resembling occurrence or collision suffixes, and stable labels when only one window changes. Pairing remains positional within each binding group; reordered constructions and real application releases were not checked for this correction |
| Rebuild workflow (Study → Build → Check → Refine) | `crates/ai/src/rebuild/` (kinds, checks and stacks are pluggable: docs/extending.md). Three kinds: website, app, game (a project whose stack is a game engine is always a game). The request decides how to build: a language, framework, engine or platform it names wins over the kind's default stack (Rust + egui for apps, Unity for games, the original's for websites), and the build check, the recorded stack and Play follow what was built (an Electron app opens in its own Electron; a plain static site has nothing to build and passes the build check as it is). Websites: Study also captures up to 4 other pages of the site; menus are opened on a computer and on a phone; the check serves the build on loopback and compares every page at 1440, 768 and 390 px (likeness = mean of layout and perceptual detail, SSIM, averaged over pages, leaving out the parts of the original that change by themselves, found by photographing it three times; the note adds text, page structure, the colours, font, text sizes and spacing the build misses, and per width a page that scrolls sideways, heading sizes and sections whose padding, items per row or content column differ, the errors, failed requests and accessibility gaps the build adds, and the opened menus and pop-ups). A stack or library named in the request (Next.js, shadcn/ui, Tailwind CSS…, `stacks.toml`) is what the builder uses; with none named, a website's stack is the builder's choice (told to match what the original is built with) and the stack it used is recorded from app/package.json. The builder leads: it studies, asks the tools follow-up questions, records what it can't find out as unknowns (`core_unknown_add`; the run reports the open ones), and tests its own build mid-turn with `rebuild_check` (the same checks, for every kind); a check with anything it couldn't compare, or any claim that fails (a website page that scrolls sideways, logs new errors, fails to load a file, lacks a landmark, or a menu that doesn't open; for games each self-test step, for Deep-mode sheets each original number in the code, for console apps the same exit and output as the original's runs), isn't good enough; apps and games by whether they build. Up to 6 refinement rounds, or until a website reaches 90% likeness. A turn cut off by a time limit, crash or dropped connection resumes (up to 3 times); builder turns may run 24 h. A project copied from another computer (or moved to another folder) keeps building with Claude Code: the project keeps a copy of the builder's session (`agent-session.jsonl`) after every turn and puts it back where Claude Code finds it on a computer without it, so the same conversation carries on (#451); when the session still isn't there, a new one starts from the brief, what's in app/ and the kept requests and replies (or the last summary), and questions about the build put the kept session back too, else are answered from the files and forget the missing session (#452). Live runs with Claude Code 2.1.316 on one Mac (2026-11-02), a second computer stood in for by a separate signed-in `CLAUDE_CONFIG_DIR`: a copied project's session was put back and resumed (the builder recalled its first reply from memory); a kept copy of another session was refused and the new session used the handoff; a real project synced from Windows whose session was missing started afresh and reached Ready. Not yet run between two real computers | Unit tests for prompts, stack choice, site detection, feed folding; live runs reached Build and decompiling (below) |
| Context-summary usage | Successful API context summaries contribute to the message totals consumed by build usage and receive a `model_turn` journal entry with `purpose: context_summary`. Input tokens include cached ones, as coding agents report them (Ollama 0.40 sends them apart). Cached-token pricing is retained; an unknown summary price makes the total unknown, and a failed call adds no invented usage | Scripted-model tests exercise the real `ApiConversation`, transcript resumption, exact input/output and cache-price totals, journal entries, empty summaries, local zero cost, unknown prices and failed summaries. No live provider or end-to-end rebuild was used for this correction |