Skip to content

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

Rust

Build and run new projects through their toolchains (#1002)

BFlat17e420047943
diff --git a/crates/ai/src/rebuild/check.rs b/crates/ai/src/rebuild/check.rs
index 6046a1b4..084d8491 100644
--- a/crates/ai/src/rebuild/check.rs
+++ b/crates/ai/src/rebuild/check.rs
@@ -22,11 +22,8 @@ fn run_in(app: &Path, prog: &Path, args: &[String], minutes: u64, stop: &CancelT
/// Run one of a toolchain's commands in `app`.
fn run_tool(app: &Path, tool: &stacks::Toolchain, command: &[String], minutes: u64, stop: &CancelToken) -> Result<(bool, String), String> {
- let Some((program, args)) = command.split_first() else { return Err(format!("{} has no such command.", tool.name)) };
- let here = |p: &&String| cfg!(windows) == [".bat", ".cmd", ".exe"].iter().any(|e| p.ends_with(e));
- let local = tool.local_programs.iter().filter(here).map(|p| app.join(p)).find(|p| p.is_file());
- let system = tool.windows_program.as_ref().filter(|_| cfg!(windows)).unwrap_or(program);
- run_in(app, local.as_deref().unwrap_or(Path::new(system)), args, minutes, stop)
+ let Some((program, args)) = tool.command(app, command) else { return Err(format!("{} has no such command.", tool.name)) };
+ run_in(app, &program, &args, minutes, stop)
}
/// What a Unity without a licence prints, and what to tell the person.
@@ -162,7 +159,18 @@ pub(super) fn build_check(app: &Path, place: &str, stack: &str, editor: Option<&
}
_ if app.join("Cargo.toml").is_file() => run(Path::new("cargo"), &["build".into(), "--quiet".into()], 2 * 60),
_ if app.join("package.json").is_file() => run(Path::new(if cfg!(windows) { "npm.cmd" } else { "npm" }), &["run".into(), "build".into()], 2 * 60),
- (None, _) if static_site(app) => return (true, "Nothing to build: a static site.".into()),
+ (None, _) => {
+ return stacks::toolchain_in(app).map_or_else(
+ || {
+ if static_site(app) {
+ (true, "Nothing to build: a static site.".into())
+ } else {
+ (false, missing(app, place, format!("No project to build found in {place} yet.")))
+ }
+ },
+ |tool| own_build(app, tool, stop),
+ );
+ }
_ => return (false, missing(app, place, format!("No project to build found in {place} yet."))),
};
match result {
@@ -179,7 +187,7 @@ fn engine_for(stack: &str, app: &Path) -> Option<game::Builder> {
if static_site(app) {
return None;
}
- let own_project = app.join("Cargo.toml").is_file() || app.join("package.json").is_file();
+ let own_project = stacks::toolchain_in(app).is_some();
game::Builder::from_stack(stack).filter(|b| !own_project || engine_project(*b, app))
}
diff --git a/crates/ai/src/rebuild/kinds/app.rs b/crates/ai/src/rebuild/kinds/app.rs
index a7c1fde5..f5302db6 100644
--- a/crates/ai/src/rebuild/kinds/app.rs
+++ b/crates/ai/src/rebuild/kinds/app.rs
@@ -44,6 +44,8 @@ impl TargetKind for AppKind {
"a desktop app with the same core features"
}
+ /// Describe the checks for a new app: screenshots or recorded console runs, plus Deep-mode
+ /// requirements when studying a program. Existing projects keep their own build/test contract.
fn brief_sections(&self, cx: &BriefCx) -> Vec<String> {
let mut s = Vec::new();
if cx.ws.manifest.own_project() {
@@ -55,7 +57,7 @@ impl TargetKind for AppKind {
}
// A console program is compared by its runs, not pictured.
if runs::captured(cx.ws).is_empty() {
- s.push(screenshot::SCREENSHOT_CONTRACT.to_string());
+ s.push(screenshot::contract());
} else {
s.push(RUNS_BRIEF.to_string());
}
diff --git a/crates/ai/src/rebuild/kinds/game.rs b/crates/ai/src/rebuild/kinds/game.rs
index feefc4d4..7304c4df 100644
--- a/crates/ai/src/rebuild/kinds/game.rs
+++ b/crates/ai/src/rebuild/kinds/game.rs
@@ -115,10 +115,12 @@ impl TargetKind for GameKind {
"a playable game that plays like the original: the same rules, controls, numbers and feel"
}
+ /// Assemble the game's study, screenshot, self-test and optional generated-asset instructions.
+ /// Existing projects keep their own checks; website targets omit native-code study requirements.
fn brief_sections(&self, cx: &BriefCx) -> Vec<String> {
let target = &cx.ws.manifest.target;
if matches!(target, TargetRef::Website { .. }) {
- return vec![screenshot::SCREENSHOT_CONTRACT.to_string(), self_test::SELF_TEST_CONTRACT.to_string()];
+ return vec![screenshot::contract(), self_test::SELF_TEST_CONTRACT.to_string()];
}
// Paid, so only when the person turned it on for this project and a key is set up.
let generated = cx.assets && cx.ws.manifest.generate_assets;
@@ -129,7 +131,7 @@ impl TargetKind for GameKind {
if generated {
s.push(assets_note(cx.ws, cx.image_model));
}
- s.push(screenshot::SCREENSHOT_CONTRACT.to_string());
+ s.push(screenshot::contract());
s.push(self_test::SELF_TEST_CONTRACT.to_string());
s
}
diff --git a/crates/ai/src/rebuild/kinds/screenshot.rs b/crates/ai/src/rebuild/kinds/screenshot.rs
index b407d2d2..0c9befba 100644
--- a/crates/ai/src/rebuild/kinds/screenshot.rs
+++ b/crates/ai/src/rebuild/kinds/screenshot.rs
@@ -15,6 +15,19 @@ use craft_anything_platform::process::Process;
/// What every app and game brief asks for, so the check can see the result.
pub const SCREENSHOT_CONTRACT: &str = "Give the program a `--screenshot <file.png>` option: start normally, draw about 120 frames, save the window's picture as a PNG to that file and exit. Craft Anything runs it that way after each build to check the result, and a build without the option, or with a blank picture, doesn't pass. Try it yourself: run it with a file inside app/ (for example app/shots/now.png) and look at the picture.";
+/// Include the shared catalogue's supported entrypoints so the builder knows how checks start it.
+pub fn contract() -> String {
+ let entries = craft_anything_engine::toolchains::catalogue()
+ .iter()
+ .filter(|t| !t.launch.is_empty())
+ .map(|t| format!("{}: {}", t.name, t.launch.iter().map(|r| r.file.as_str()).collect::<Vec<_>>().join(" or ")))
+ .collect::<Vec<_>>()
+ .join("; ");
+ format!(
+ "{SCREENSHOT_CONTRACT} If not packaging an executable, keep a supported entrypoint directly in app/ ({entries}); wildcard entrypoints must match exactly one file."
+ )
+}
+
/// How long the program may take to start, draw and save its picture (or play its self-test).
const RUN_LIMIT: Duration = Duration::from_secs(90);
/// The size both pictures are brought to before comparing.
@@ -95,6 +108,37 @@ impl Check for ScreenshotCheck {
}
}
+/// Absolute capture parameters and the paths used to read back its artifacts.
+struct RuntimeCapture {
+ params: Value,
+ shot: PathBuf,
+ tree: PathBuf,
+}
+
+/// Normalize workspace-relative paths against this process's current directory. A selected local
+/// executable already includes the app path; only bare runner names are searched on PATH.
+fn capture_request(
+ app: &Path,
+ program: &Path,
+ args: &[String],
+ dir: &Path,
+ include_tree: bool,
+ find_program: impl FnOnce(&str) -> Option<PathBuf>,
+) -> Option<RuntimeCapture> {
+ let working_directory = std::path::absolute(app).ok()?;
+ let selected = if program.is_absolute() || program.components().count() > 1 { program.to_path_buf() } else { find_program(program.to_str()?)? };
+ // PATH may itself contain relative entries, so normalize the lookup's result too. Do not
+ // canonicalize a virtualenv symlink into the system Python: the selected interpreter matters.
+ let program = std::path::absolute(selected).ok()?;
+ let shot = std::path::absolute(dir.join("window.png")).ok()?;
+ let tree = std::path::absolute(dir.join("ui-tree.json")).ok()?;
+ let mut params = json!({"program": program, "args": args, "working_directory": working_directory, "wait_secs": 15, "output": &shot});
+ if include_tree {
+ params["ui_tree"] = json!(&tree);
+ }
+ Some(RuntimeCapture { params, shot, tree })
+}
+
/// Start the build normally and picture it the way Study pictured the original, when it did
/// (`capture/window.png`, and `capture/ui-tree.json` when its controls were read): how alike the
/// windows look and the controls are, and a claim for each of the original's interactive
@@ -105,11 +149,11 @@ fn running_note(cx: &CheckCx, program: &Path, args: &[String], dir: &Path) -> (S
if !original.is_file() {
return (String::new(), Vec::new());
}
- let (shot, tree) = (dir.join("window.png"), dir.join("ui-tree.json"));
- let mut params = json!({"program": program, "args": args, "wait_secs": 15, "output": &shot});
- if original_tree.is_file() {
- params["ui_tree"] = json!(&tree);
- }
+ let Some(RuntimeCapture { params, shot, tree }) =
+ capture_request(&cx.ws.app_dir(), program, args, dir, original_tree.is_file(), craft_anything_platform::which::which)
+ else {
+ return (" Started normally, its window couldn't be pictured because its project paths or interpreter couldn't be resolved.".into(), Vec::new());
+ };
if let Err(e) = cx.call("native_window_capture", params) {
return (format!(" Started normally, its window couldn't be pictured: {}", e.message), Vec::new());
}
@@ -340,6 +384,51 @@ mod tests {
use super::*;
use craft_anything_engine::tools::web_common::encode_png;
+ /// `path` with its own separators, as a resolved path has them.
+ fn native(path: PathBuf) -> PathBuf {
+ path.components().collect()
+ }
+
+ /// Relative placements produce the absolute paths required by native_window_capture,
+ /// without looking up a project-local interpreter or resolving away its virtualenv path.
+ #[test]
+ fn runtime_capture_normalizes_relative_project_paths() {
+ let cwd = std::env::current_dir().unwrap();
+ let app = Path::new("projects with spaces/sample.cany/app");
+ let interpreter = app.join(".venv/bin/python");
+ let dir = Path::new("projects with spaces/sample.cany/checks/round-1");
+ let args = vec!["main.py".to_string()];
+ let request = capture_request(app, &interpreter, &args, dir, true, |_| panic!("a selected filesystem path must not use PATH lookup")).unwrap();
+ assert_eq!(request.params["working_directory"], json!(native(cwd.join(app))));
+ assert_eq!(request.params["program"], json!(native(cwd.join(interpreter))));
+ assert_eq!(request.params["output"], json!(native(cwd.join(dir).join("window.png"))));
+ assert_eq!(request.params["ui_tree"], json!(native(cwd.join(dir).join("ui-tree.json"))));
+ assert_eq!(request.params["args"], json!(args));
+ assert_eq!(request.shot, cwd.join(dir).join("window.png"));
+ assert_eq!(request.tree, cwd.join(dir).join("ui-tree.json"));
+ }
+
+ /// Bare runners keep PATH lookup, including relative PATH results; missing runners stop
+ /// capture cleanly, and absolute executables are left at their selected location.
+ #[test]
+ fn runtime_capture_preserves_runner_lookup_and_optional_tree() {
+ let cwd = std::env::current_dir().unwrap();
+ let app = cwd.join("project/app");
+ let dir = cwd.join("project/checks/round-1");
+ let request = capture_request(&app, Path::new("python3"), &[], &dir, false, |name| {
+ assert_eq!(name, "python3");
+ Some(PathBuf::from("relative tools/python3"))
+ })
+ .unwrap();
+ assert_eq!(request.params["program"], json!(native(cwd.join("relative tools/python3"))));
+ assert_eq!(request.params["working_directory"], json!(native(app.clone())));
+ assert!(request.params.get("ui_tree").is_none());
+ assert!(capture_request(&app, Path::new("missing-runner"), &[], &dir, false, |_| None).is_none());
+ let program = native(app.join(".venv/bin/python"));
+ let request = capture_request(&app, &program, &[], &dir, false, |_| panic!("an absolute executable must not use PATH lookup")).unwrap();
+ assert_eq!(request.params["program"], json!(program));
+ }
+
fn img(w: u32, h: u32, f: &dyn Fn(u32, u32) -> [u8; 3]) -> Image {
let mut rgba = Vec::new();
for y in 0..h {
diff --git a/crates/ai/src/rebuild/stacks.rs b/crates/ai/src/rebuild/stacks.rs
index 05ffa788..2153ab2e 100644
--- a/crates/ai/src/rebuild/stacks.rs
+++ b/crates/ai/src/rebuild/stacks.rs
@@ -37,33 +37,7 @@ pub struct Stack {
pub site: bool,
}
-/// How a project builds and tests itself, whatever it's written in.
-#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Deserialize)]
-pub struct Toolchain {
- pub name: String,
- /// The files that name it, matched like [`Stack::found_by`].
- pub found_by: Vec<String>,
- /// The program that builds it and its arguments, run in the project's folder.
- #[serde(default)]
- pub build: Vec<String>,
- /// The same for its tests.
- #[serde(default)]
- pub test: Vec<String>,
- /// What its output says when no tests ran, which isn't a failure.
- #[serde(default)]
- pub no_tests: Vec<String>,
- /// The package.json script that is its tests. Whether there are any is then read from that
- /// file, as what a script prints can be about one it runs, and `no_tests` are whole scripts
- /// that are only placeholders.
- #[serde(default)]
- pub test_script: Option<String>,
- /// The project's own copies of the program, used first when one's there (`.venv/bin/python`).
- #[serde(default)]
- pub local_programs: Vec<String>,
- /// The program's name on Windows, where it differs (`python`).
- #[serde(default)]
- pub windows_program: Option<String>,
-}
+pub use craft_anything_engine::toolchains::{Toolchain, found_in as toolchain_in};
/// The stack that leaves the choice to the builder (a website's default); [`used_in`] then
/// records the one it used.
@@ -89,8 +63,6 @@ struct Table {
stack: Vec<Stack>,
#[serde(default)]
library: Vec<Library>,
- #[serde(default)]
- toolchain: Vec<Toolchain>,
}
/// The built-in table. A table that doesn't parse (a broken edit) leaves it empty, so every
@@ -148,11 +120,6 @@ pub fn found_in(dir: &std::path::Path) -> Option<&'static Stack> {
by_file(true).or_else(by_deps).or_else(|| by_file(false))
}
-/// How the project in `dir` builds and tests itself: the first toolchain a file there names.
-pub fn toolchain_in(dir: &std::path::Path) -> Option<&'static Toolchain> {
- table().toolchain.iter().find(|t| t.found_by.iter().any(|f| has_file(dir, f)))
-}
-
fn has_file(dir: &std::path::Path, name: &str) -> bool {
match name.strip_prefix('*') {
Some(ending) => std::fs::read_dir(dir).into_iter().flatten().flatten().any(|e| e.file_name().to_string_lossy().ends_with(ending)),
@@ -227,6 +194,7 @@ mod tests {
assert_eq!(found(&[("notes.md", "")]), None);
}
+ /// Verify file-based toolchain detection and that every shared row has build/test commands.
#[test]
fn a_folder_says_how_it_builds_and_tests_itself() {
let tool = |file: &str| {
@@ -244,7 +212,7 @@ mod tests {
assert_eq!(tool("build.gradle.kts"), Some("Gradle"));
assert_eq!(tool("Makefile"), Some("Make"));
assert_eq!(tool("notes.md"), None);
- for t in &table().toolchain {
+ for t in craft_anything_engine::toolchains::catalogue() {
assert!(!t.found_by.is_empty() && !t.build.is_empty() && !t.test.is_empty(), "{}", t.name);
}
}
diff --git a/crates/ai/src/rebuild/stacks.toml b/crates/ai/src/rebuild/stacks.toml
index 68c67040..bf94568b 100644
--- a/crates/ai/src/rebuild/stacks.toml
+++ b/crates/ai/src/rebuild/stacks.toml
@@ -21,17 +21,6 @@
# A `[[library]]` is a component or styling library asked for on top of a stack ("shadcn",
# "tailwind"): its `steps` are added to the stack's for the `stacks` it works with.
#
-# A `[[toolchain]]` says how a project builds and tests itself, by the file that names the tool
-# (the first in this order wins), so a person's own project can be checked in any language.
-# `build` and `test` are a program and its arguments, run in the project's folder; `no_tests` is
-# what its output says when no tests ran, which isn't a failure (with `test_script`, the
-# package.json script that is its tests, whole scripts that are only placeholders: whether there
-# are any is read from the file, as a script that runs others can print the same);
-# `local_programs` are the
-# project's own copies of the program, used first when one's there (`.bat`, `.cmd` and `.exe`
-# ones on Windows, the others elsewhere); `windows_program` is its name on Windows, where it
-# differs.
-
[[stack]]
name = "Builder's choice"
found_by = ["package.json", "Cargo.toml", "go.mod", "pom.xml", "build.gradle", "build.gradle.kts", "*.sln", "*.csproj", "Gemfile", "composer.json", "CMakeLists.txt", "Makefile"]
@@ -115,60 +104,3 @@ name = "Tailwind CSS"
asked_by = [" tailwind ", " tailwindcss "]
stacks = ["Next.js + TypeScript", "React + TypeScript (Vite)", "Electron", "Builder's choice"]
steps = "Style with Tailwind CSS (v4, through @tailwindcss/postcss for Next.js or @tailwindcss/vite for Vite), with the original's colours, fonts, text sizes, spacing and breakpoints from capture.json as theme tokens in an @theme block."
-
-[[toolchain]]
-name = "Rust"
-found_by = ["Cargo.toml"]
-build = ["cargo", "build", "--quiet"]
-test = ["cargo", "test", "--quiet"]
-
-[[toolchain]]
-name = "Node.js"
-found_by = ["package.json"]
-build = ["npm", "run", "build", "--if-present"]
-test = ["npm", "test"]
-test_script = "test"
-no_tests = ['echo "Error: no test specified" && exit 1']
-windows_program = "npm.cmd"
-
-[[toolchain]]
-name = "Python"
-found_by = ["pyproject.toml", "requirements.txt", "setup.py"]
-build = ["python3", "-m", "compileall", "-q", "-x", '[\\/](\.?venv|node_modules|\.git)[\\/]', "."]
-test = ["python3", "-m", "pytest", "-q", "-p", "no:cacheprovider"]
-no_tests = ["no tests ran", "No module named pytest"]
-local_programs = [".venv/bin/python", "venv/bin/python", ".venv/Scripts/python.exe", "venv/Scripts/python.exe"]
-windows_program = "python"
-
-[[toolchain]]
-name = "Go"
-found_by = ["go.mod"]
-build = ["go", "build", "./..."]
-test = ["go", "test", "./..."]
-
-[[toolchain]]
-name = ".NET"
-found_by = ["*.sln", "*.csproj"]
-build = ["dotnet", "build", "--nologo", "-v", "q"]
-test = ["dotnet", "test", "--nologo", "-v", "q"]
-
-[[toolchain]]
-name = "Maven"
-found_by = ["pom.xml"]
-build = ["mvn", "-q", "-B", "compile"]
-test = ["mvn", "-q", "-B", "test"]
-local_programs = ["mvnw", "mvnw.cmd"]
-
-[[toolchain]]
-name = "Gradle"
-found_by = ["build.gradle", "build.gradle.kts"]
-build = ["gradle", "-q", "assemble"]
-test = ["gradle", "-q", "test"]
-local_programs = ["gradlew", "gradlew.bat"]
-
-[[toolchain]]
-name = "Make"
-found_by = ["Makefile"]
-build = ["make"]
-test = ["make", "test"]
-no_tests = ["make: *** No rule to make target `test'.", "make: *** No rule to make target 'test'.", "make: don't know how to make test."]
diff --git a/crates/ai/src/rebuild/tests.rs b/crates/ai/src/rebuild/tests.rs
index 22521a81..f1451d54 100644
--- a/crates/ai/src/rebuild/tests.rs
+++ b/crates/ai/src/rebuild/tests.rs
@@ -1726,12 +1726,12 @@ mod picking_up_a_build {
b.hub.engine.session().settings.ai = config.to_table().unwrap();
let agent = b._dir.path().join("agent.sh");
let script = std::fs::read_to_string(&agent).unwrap();
- let script = script.replacen("#!/bin/sh\n", "#!/bin/sh\nif [ \"$2\" = '--help' ]; then printf '%s\\n' '--format'; exit 0; fi\n", 1);
+ let script = script.replacen("#!/bin/sh\n", "#!/bin/sh\nif [ \"$2\" = '--help' ]; then printf '%s\\n' '--format --standalone'; exit 0; fi\n", 1);
let error = json!({"type":"error","error":{"name":"APIError","data":{"message":"fixture sign in needed","statusCode":401,"isRetryable":false}}});
std::fs::write(&agent, script.replace("echo Done.", &format!("printf '%s\\n' '{error}'\nexit 1"))).unwrap();
let (ok, feed) = try_it(&b, &ws);
assert!(!ok);
- assert_eq!(prompts_given(&b), 1, "the unavailable scan does not block or repeat the builder");
+ assert_eq!(prompts_given(&b), 1, "the unavailable scan does not block or repeat the builder: {feed:?}");
assert!(feed.iter().any(|i| matches!(i, feed::FeedItem::Error { message, .. } if message.contains("fixture sign in needed"))), "{feed:?}");
let saved = Workspace::open(&ws.root).unwrap();
assert!(!saved.manifest.awaiting_check, "a failed turn has not finished its build");
@@ -2131,6 +2131,91 @@ fn check_worker(ws: &Workspace, deep: bool) -> Worker {
}
}
+/// A new Python project reaches the same build/screenshot path as a packaged app. The local
+/// interpreter is a stand-in: no installed Python, packages, window, network or user settings.
+#[cfg(unix)]
+#[test]
+fn new_python_projects_build_and_save_screenshots_through_their_toolchain() {
+ use craft_anything_engine::tools::web_common::{Image, encode_png};
+ use std::os::unix::fs::PermissionsExt;
+ let dir = tempfile::tempdir().unwrap();
+ let ws = Workspace::create(dir.path(), "Python sample", "Make an app in Python", TargetRef::None).unwrap();
+ let app = ws.app_dir();
+ std::fs::create_dir_all(app.join(".venv/bin")).unwrap();
+ std::fs::write(app.join("main.py"), "# Owned interpreter fixture\n").unwrap();
+ std::fs::write(app.join("pyproject.toml"), "[project]\nname = 'sample'\nversion = '0.1.0'\n").unwrap();
+ // An HTML asset beside Python code must not bypass the Python build as a static site.
+ std::fs::write(app.join("index.html"), "<h1>asset</h1>").unwrap();
+ let program = app.join(".venv/bin/python");
+ std::fs::write(
+ &program,
+ "#!/bin/sh\n\
+ if [ \"$1\" = '-m' ]; then\n\
+ printf '%s\\n' \"$@\" > build-args.txt\n\
+ if [ -f fail-build ]; then echo 'error: fixture compilation failed'; exit 1; fi\n\
+ exit 0\n\
+ fi\n\
+ [ \"$1\" = 'main.py' ] || exit 8\n\
+ [ \"$2\" = '--screenshot' ] || exit 8\n\
+ [ ! -f fail-shot ] || exit 9\n\
+ cp fixture.png \"$3\"\n",
+ )
+ .unwrap();
+ std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o700)).unwrap();
+ let rgba = (0..64 * 36).flat_map(|i| if i % 2 == 0 { [255, 0, 0, 255] } else { [0, 0, 255, 255] }).collect();
+ std::fs::write(app.join("fixture.png"), encode_png(&Image { width: 64, height: 36, rgba }).unwrap()).unwrap();
+ let worker = check_worker(&ws, false);
+ let checks = worker.run_checks(&ws, &AppKind, 1).unwrap();
+ assert_eq!(checks.iter().map(|c| (c.check.as_str(), c.passed)).collect::<Vec<_>>(), [("build", true), ("app-screenshot", true)], "{checks:?}");
+ let args = std::fs::read_to_string(app.join("build-args.txt")).unwrap();
+ assert!(args.starts_with("-m\ncompileall\n-q\n") && args.ends_with(".\n"), "{args}");
+ assert_eq!(args.lines().nth(3), Some("-f"), "{args}");
+ assert_eq!(launch(&app, None).unwrap(), (program, vec!["main.py".into()]), "Play uses the same interpreter/entrypoint");
+ let shot = ws.checks_dir().join("round-1/screenshot.png");
+ assert!(shot.is_file());
+
+ std::fs::write(app.join("fail-shot"), "").unwrap();
+ let checks = worker.run_checks(&ws, &AppKind, 1).unwrap();
+ assert!(checks[0].passed && !checks[1].passed && checks[1].note.contains("code 9"), "{checks:?}");
+ assert!(!shot.exists(), "the old screenshot cannot make a failed run pass");
+ std::fs::write(app.join("fail-build"), "").unwrap();
+ let checks = worker.run_checks(&ws, &AppKind, 2).unwrap();
+ assert_eq!(checks.len(), 1);
+ assert!(!checks[0].passed && checks[0].note.contains("fixture compilation failed"), "{checks:?}");
+}
+
+/// Opt-in smoke test with a real local Python; all files and bytecode stay in the temp project.
+/// The fixture writes a known nonblank PNG without opening a GUI or importing external packages.
+#[cfg(unix)]
+#[test]
+#[ignore = "requires Python 3 on PATH; runs an owned headless fixture"]
+fn real_python_new_project_build_and_screenshot() {
+ use craft_anything_engine::tools::web_common::{Image, encode_png};
+ let dir = tempfile::tempdir().unwrap();
+ let ws = Workspace::create(dir.path(), "Python smoke", "An app in Python", TargetRef::None).unwrap();
+ let app = ws.app_dir();
+ std::fs::create_dir_all(app.join(".venv/bin")).unwrap();
+ let python = craft_anything_platform::which("python3").expect("install Python 3 to run this ignored test");
+ std::os::unix::fs::symlink(python, app.join(".venv/bin/python")).unwrap();
+ let rgba = (0..64 * 36).flat_map(|i| if i % 2 == 0 { [255, 0, 0, 255] } else { [0, 0, 255, 255] }).collect();
+ let png = encode_png(&Image { width: 64, height: 36, rgba }).unwrap();
+ let source = format!("import pathlib, sys\nif sys.argv[1] == '--screenshot':\n pathlib.Path(sys.argv[2]).write_bytes(bytes({png:?}))\n");
+ std::fs::write(app.join("main.py"), source).unwrap();
+ // compileall's cache check uses whole-second mtimes. Keep both revisions at the same
+ // timestamp so a stale bytecode cache cannot make a syntax error look like a good build.
+ let same_time = std::time::UNIX_EPOCH + Duration::from_secs(1_700_000_000);
+ std::fs::File::open(app.join("main.py")).unwrap().set_modified(same_time).unwrap();
+ std::fs::write(app.join(".venv/ignored.py"), "def broken(\n").unwrap();
+ let worker = check_worker(&ws, false);
+ let checks = worker.run_checks(&ws, &AppKind, 1).unwrap();
+ assert_eq!(checks.iter().map(|c| (c.check.as_str(), c.passed)).collect::<Vec<_>>(), [("build", true), ("app-screenshot", true)], "{checks:?}");
+ std::fs::write(app.join("main.py"), "def broken(\n").unwrap();
+ std::fs::File::open(app.join("main.py")).unwrap().set_modified(same_time).unwrap();
+ let checks = worker.run_checks(&ws, &AppKind, 2).unwrap();
+ assert_eq!(checks.len(), 1, "{checks:?}");
+ assert!(!checks[0].passed && checks[0].note.contains("SyntaxError"), "{checks:?}");
+}
+
/// A kind with its checks after the first `.1`, so a test needn't build or start anything.
struct LaterChecks(&'static dyn TargetKind, usize);
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index ec639225..29bf1548 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -30,6 +30,7 @@ pub mod target;
pub mod testing;
pub mod tool;
pub mod tool_list;
+pub mod toolchains;
pub mod tools;
pub mod versioned;
pub mod wasm_plugins;
diff --git a/crates/engine/src/outputs.rs b/crates/engine/src/outputs.rs
index eef80771..43ac7d7e 100644
--- a/crates/engine/src/outputs.rs
+++ b/crates/engine/src/outputs.rs
@@ -5,7 +5,7 @@ use std::path::{Path, PathBuf};
/// Where a built site lives in `app`: a build folder with index.html, else a plain static site.
/// An Electron app's bundled page is its window, not a site.
pub fn site_dir(app: &Path) -> Option<PathBuf> {
- if uses_electron(app) {
+ if uses_electron(app) || crate::toolchains::found_in(app).and_then(|t| t.launch(app)).is_some() {
return None;
}
for d in ["dist", "build", "out"] {
@@ -138,6 +138,7 @@ fn cargo_programs(app: &Path) -> Vec<String> {
/// What "Play" starts for a finished game or app: (program, arguments), run from app/. A Godot
/// project opens in the Godot it was built with, an Electron app in the Electron it installed.
+/// Other toolchains may declare an interpreted/runner launch when no packaged program exists.
pub fn launch(app: &Path, godot: Option<&Path>) -> Option<(PathBuf, Vec<String>)> {
if app.join("project.godot").is_file() {
return godot.map(|g| (g.to_path_buf(), vec!["--path".to_string(), app.display().to_string()]));
@@ -145,7 +146,7 @@ pub fn launch(app: &Path, godot: Option<&Path>) -> Option<(PathBuf, Vec<String>)
if uses_electron(app) {
return electron_program(app).map(|e| (e, vec![app.display().to_string()]));
}
- built_program(app).or_else(|| packaged_program(&app.join("Build"))).map(|p| (p, Vec::new()))
+ built_program(app).or_else(|| packaged_program(&app.join("Build"))).map(|p| (p, Vec::new())).or_else(|| crate::toolchains::found_in(app)?.launch(app))
}
/// The packages `app`'s package.json depends on (dev dependencies too); none without a readable one.
diff --git a/crates/engine/src/toolchains.rs b/crates/engine/src/toolchains.rs
new file mode 100644
index 00000000..59373465
--- /dev/null
+++ b/crates/engine/src/toolchains.rs
@@ -0,0 +1,224 @@
+//! Shared project toolchains for build checks, Play and screenshot/self-test runs.
+
+use std::path::{Path, PathBuf};
+use std::sync::OnceLock;
+
+/// How a project builds and tests itself, whatever it's written in.
+#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Deserialize)]
+pub struct Toolchain {
+ pub name: String,
+ /// Files that name it: exact relative paths or a root filename suffix such as `*.csproj`.
+ pub found_by: Vec<String>,
+ /// The program that builds it and its arguments, run in the project's folder.
+ #[serde(default)]
+ pub build: Vec<String>,
+ /// The same for its tests.
+ #[serde(default)]
+ pub test: Vec<String>,
+ /// What its output says when no tests ran, which isn't a failure.
+ #[serde(default)]
+ pub no_tests: Vec<String>,
+ /// The package.json script that is its tests. Whether there are any is then read from that
+ /// file, as what a script prints can be about one it runs, and `no_tests` are whole scripts
+ /// that are only placeholders.
+ #[serde(default)]
+ pub test_script: Option<String>,
+ /// The project's own copies of the program, used first when one's there (`.venv/bin/python`).
+ #[serde(default)]
+ pub local_programs: Vec<String>,
+ /// The program's name on Windows, where it differs (`python`).
+ #[serde(default)]
+ pub windows_program: Option<String>,
+ /// Optional ways to start the app, in preference order. No recipe means no inferred launch.
+ #[serde(default)]
+ pub launch: Vec<LaunchRecipe>,
+ /// Detect a script-only project from its launch entrypoint, after checking all manifest markers.
+ #[serde(default)]
+ pub standalone_entrypoints: bool,
+}
+
+/// A declared entrypoint and argv template. A wildcard file must identify exactly one file.
+#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
+pub struct LaunchRecipe {
+ pub file: String,
+ /// `{file}` expands to the matched relative filename in a single argument, without a shell.
+ pub command: Vec<String>,
+}
+
+#[derive(Default, serde::Deserialize)]
+struct Table {
+ toolchain: Vec<Toolchain>,
+}
+
+/// Built-in toolchains in detection order. A malformed catalogue is covered by a regression test.
+pub fn catalogue() -> &'static [Toolchain] {
+ static TABLE: OnceLock<Table> = OnceLock::new();
+ &TABLE.get_or_init(|| toml::from_str(include_str!("toolchains.toml")).unwrap_or_default()).toolchain
+}
+
+/// The first toolchain whose marker files exist in this folder.
+pub fn found_in(dir: &Path) -> Option<&'static Toolchain> {
+ catalogue()
+ .iter()
+ .find(|t| t.found_by.iter().any(|pattern| !matching_files(dir, pattern).is_empty()))
+ .or_else(|| catalogue().iter().find(|t| t.standalone_entrypoints && t.launch(dir).is_some()))
+}
+
+/// Bounded root-file matching, also used for launch entrypoints. Exact paths need no directory scan.
+fn matching_files(dir: &Path, pattern: &str) -> Vec<PathBuf> {
+ match pattern.strip_prefix('*') {
+ Some(suffix) => {
+ let mut files = Vec::new();
+ let Ok(entries) = std::fs::read_dir(dir) else { return files };
+ for (i, entry) in entries.enumerate() {
+ // An incomplete scan cannot establish an unambiguous launch entrypoint.
+ if i >= 256 {
+ return Vec::new();
+ }
+ let Ok(entry) = entry else { return Vec::new() };
+ let p = entry.path();
+ if p.is_file() && p.file_name().is_some_and(|n| n.to_string_lossy().ends_with(suffix)) {
+ files.push(p);
+ }
+ }
+ files.sort();
+ files
+ }
+ None => dir.join(pattern).is_file().then(|| dir.join(pattern)).into_iter().collect(),
+ }
+}
+
+impl Toolchain {
+ /// Resolve a command, preferring the project's own interpreter/build wrapper on this OS.
+ pub fn command(&self, app: &Path, command: &[String]) -> Option<(PathBuf, Vec<String>)> {
+ self.command_for(app, command, cfg!(windows))
+ }
+
+ /// Resolve for an explicit OS so platform names and local wrappers can be tested anywhere.
+ fn command_for(&self, app: &Path, command: &[String], windows: bool) -> Option<(PathBuf, Vec<String>)> {
+ let (program, args) = command.split_first()?;
+ let here = |p: &&String| windows == [".bat", ".cmd", ".exe"].iter().any(|e| p.ends_with(e));
+ // Callers run in `app`, so a project-relative executable must first be made absolute.
+ // Keep virtualenv symlinks intact: canonicalizing can select the system interpreter.
+ let local = self.local_programs.iter().filter(here).map(|p| app.join(p)).find(|p| p.is_file()).map(std::path::absolute).transpose().ok()?;
+ let system = self.windows_program.as_ref().filter(|_| windows).unwrap_or(program);
+ Some((local.unwrap_or_else(|| PathBuf::from(system)), args.to_vec()))
+ }
+
+ /// Infer a launch only from a recipe's unambiguous entrypoint. Never guess among projects.
+ pub fn launch(&self, app: &Path) -> Option<(PathBuf, Vec<String>)> {
+ for recipe in &self.launch {
+ let files = matching_files(app, &recipe.file);
+ if files.len() != 1 {
+ continue;
+ }
+ let file = files.first()?.strip_prefix(app).ok()?.to_str()?;
+ let command: Vec<String> = recipe.command.iter().map(|arg| arg.replace("{file}", file)).collect();
+ return self.command(app, &command);
+ }
+ None
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Every catalogue row still has its original build/test commands and valid launch recipes.
+ #[test]
+ fn the_shared_catalogue_is_complete() {
+ let parsed: Table = toml::from_str(include_str!("toolchains.toml")).unwrap();
+ assert_eq!(parsed.toolchain.len(), 8);
+ for tool in catalogue() {
+ assert!(!tool.found_by.is_empty() && !tool.build.is_empty() && !tool.test.is_empty(), "{tool:?}");
+ for recipe in &tool.launch {
+ assert!(!recipe.file.is_empty() && !recipe.command.is_empty(), "{recipe:?}");
+ }
+ }
+ }
+
+ /// Shared launch detection preserves argument boundaries and refuses ambiguous projects.
+ #[test]
+ fn project_launches_come_from_entrypoints() {
+ let launch = crate::outputs::launch;
+ for (marker, file, program, args) in [
+ ("requirements.txt", "main.py", if cfg!(windows) { "python" } else { "python3" }, vec!["main.py"]),
+ ("pyproject.toml", "app.py", if cfg!(windows) { "python" } else { "python3" }, vec!["app.py"]),
+ ("pyproject.toml", "__main__.py", if cfg!(windows) { "python" } else { "python3" }, vec!["."]),
+ ("go.mod", "main.go", "go", vec!["run", "."]),
+ ("App & Sample.csproj", "App & Sample.csproj", "dotnet", vec!["run", "--no-build", "--project", "App & Sample.csproj", "--"]),
+ ] {
+ let dir = tempfile::tempdir().unwrap();
+ std::fs::write(dir.path().join(marker), "").unwrap();
+ std::fs::write(dir.path().join(file), "").unwrap();
+ std::fs::write(dir.path().join("index.html"), "<h1>embedded page</h1>").unwrap();
+ assert!(crate::outputs::site_dir(dir.path()).is_none(), "an app's HTML asset must not turn Play into a website preview");
+ assert_eq!(launch(dir.path(), None), Some((PathBuf::from(program), args.into_iter().map(String::from).collect())), "{marker}");
+ }
+ let dir = tempfile::tempdir().unwrap();
+ std::fs::write(dir.path().join("go.mod"), "module sample").unwrap();
+ assert!(launch(dir.path(), None).is_none(), "a library has no conventional entrypoint");
+ std::fs::remove_file(dir.path().join("go.mod")).unwrap();
+ for name in ["First.csproj", "Second.csproj"] {
+ std::fs::write(dir.path().join(name), "").unwrap();
+ }
+ assert!(launch(dir.path(), None).is_none(), "never choose arbitrarily between projects");
+ std::fs::remove_file(dir.path().join("Second.csproj")).unwrap();
+ for i in 0..256 {
+ std::fs::write(dir.path().join(format!("note-{i}")), "").unwrap();
+ }
+ assert!(launch(dir.path(), None).is_none(), "an incomplete scan cannot prove uniqueness");
+ }
+
+ /// A helper script must not override a project's explicit Go, Rust or Node.js manifest.
+ #[test]
+ fn manifest_markers_take_precedence_over_standalone_scripts() {
+ for (marker, name) in [("go.mod", "Go"), ("Cargo.toml", "Rust"), ("package.json", "Node.js")] {
+ let dir = tempfile::tempdir().unwrap();
+ std::fs::write(dir.path().join("main.py"), "").unwrap();
+ assert_eq!(found_in(dir.path()).unwrap().name, "Python");
+ std::fs::write(dir.path().join(marker), "").unwrap();
+ assert_eq!(found_in(dir.path()).unwrap().name, name);
+ }
+ }
+
+ /// Python build and run use the same project-local interpreter; Windows uses its own names.
+ #[test]
+ fn project_interpreters_and_platform_programs_are_shared() {
+ let dir = tempfile::tempdir().unwrap();
+ std::fs::write(dir.path().join("main.py"), "").unwrap();
+ let tool = found_in(dir.path()).unwrap();
+ for (windows, relative) in [(false, ".venv/bin/python"), (true, ".venv/Scripts/python.exe")] {
+ let path = dir.path().join(relative);
+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();
+ std::fs::write(&path, "fixture").unwrap();
+ let command = vec!["python3".to_string(), "main.py".to_string()];
+ assert_eq!(tool.command_for(dir.path(), &command, windows), Some((path.clone(), vec!["main.py".into()])));
+ assert_eq!(tool.command_for(dir.path(), &tool.build, windows).unwrap().0, path);
+ }
+ assert_eq!(tool.launch(dir.path()).unwrap().0, dir.path().join(if cfg!(windows) { ".venv/Scripts/python.exe" } else { ".venv/bin/python" }));
+ }
+
+ /// A local runner remains resolvable after the caller changes to a relative project folder.
+ #[test]
+ fn relative_projects_resolve_local_programs_absolutely() {
+ let cwd = std::env::current_dir().unwrap();
+ let dir = tempfile::tempdir_in(&cwd).unwrap();
+ let app = dir.path().strip_prefix(&cwd).unwrap();
+ std::fs::write(app.join("main.py"), "").unwrap();
+ let tool = found_in(app).unwrap();
+ let command = vec!["python3".into(), "main.py".into(), "argument with spaces".into()];
+ for (windows, relative, system) in [(false, ".venv/bin/python", "python3"), (true, ".venv/Scripts/python.exe", "python")] {
+ assert_eq!(tool.command_for(app, &command, windows), Some((PathBuf::from(system), command[1..].to_vec())));
+ let path = app.join(relative);
+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();
+ std::fs::write(&path, "fixture").unwrap();
+ let expected = std::path::absolute(&path).unwrap();
+ assert_eq!(tool.command_for(app, &command, windows), Some((expected.clone(), command[1..].to_vec())));
+ assert_eq!(tool.command_for(app, &tool.build, windows).unwrap().0, expected);
+ if windows == cfg!(windows) {
+ assert_eq!(crate::outputs::launch(app, None), Some((expected, vec!["main.py".into()])));
+ }
+ }
+ }
+}
diff --git a/crates/engine/src/toolchains.toml b/crates/engine/src/toolchains.toml
new file mode 100644
index 00000000..cf5bef84
--- /dev/null
+++ b/crates/engine/src/toolchains.toml
@@ -0,0 +1,68 @@
+# Project build/test commands and optional launch recipes, in detection order.
+# Launch recipes match a root file and pass argv directly, never through a shell.
+# {file} is replaced with the matched file; wildcard launch matches must be unique.
+
+[[toolchain]]
+name = "Rust"
+found_by = ["Cargo.toml"]
+build = ["cargo", "build", "--quiet"]
+test = ["cargo", "test", "--quiet"]
+
+[[toolchain]]
+name = "Node.js"
+found_by = ["package.json"]
+build = ["npm", "run", "build", "--if-present"]
+test = ["npm", "test"]
+test_script = "test"
+no_tests = ['echo "Error: no test specified" && exit 1']
+windows_program = "npm.cmd"
+
+[[toolchain]]
+name = "Python"
+found_by = ["pyproject.toml", "requirements.txt", "setup.py"]
+standalone_entrypoints = true
+build = ["python3", "-m", "compileall", "-q", "-f", "-x", '[\\/](\.?venv|node_modules|\.git)[\\/]', "."]
+test = ["python3", "-m", "pytest", "-q", "-p", "no:cacheprovider"]
+no_tests = ["no tests ran", "No module named pytest"]
+local_programs = [".venv/bin/python", "venv/bin/python", ".venv/Scripts/python.exe", "venv/Scripts/python.exe"]
+windows_program = "python"
+launch = [
+ { file = "main.py", command = ["python3", "{file}"] },
+ { file = "app.py", command = ["python3", "{file}"] },
+ { file = "__main__.py", command = ["python3", "."] },
+]
+
+[[toolchain]]
+name = "Go"
+found_by = ["go.mod"]
+build = ["go", "build", "./..."]
+test = ["go", "test", "./..."]
+launch = [{ file = "main.go", command = ["go", "run", "."] }]
+
+[[toolchain]]
+name = ".NET"
+found_by = ["*.sln", "*.csproj"]
+build = ["dotnet", "build", "--nologo", "-v", "q"]
+test = ["dotnet", "test", "--nologo", "-v", "q"]
+launch = [{ file = "*.csproj", command = ["dotnet", "run", "--no-build", "--project", "{file}", "--"] }]
+
+[[toolchain]]
+name = "Maven"
+found_by = ["pom.xml"]
+build = ["mvn", "-q", "-B", "compile"]
+test = ["mvn", "-q", "-B", "test"]
+local_programs = ["mvnw", "mvnw.cmd"]
+
+[[toolchain]]
+name = "Gradle"
+found_by = ["build.gradle", "build.gradle.kts"]
+build = ["gradle", "-q", "assemble"]
+test = ["gradle", "-q", "test"]
+local_programs = ["gradlew", "gradlew.bat"]
+
+[[toolchain]]
+name = "Make"
+found_by = ["Makefile"]
+build = ["make"]
+test = ["make", "test"]
+no_tests = ["make: *** No rule to make target `test'.", "make: *** No rule to make target 'test'.", "make: don't know how to make test."]
diff --git a/crates/engine/src/tools/window_tools.rs b/crates/engine/src/tools/window_tools.rs
index aa1eec14..5075e047 100644
--- a/crates/engine/src/tools/window_tools.rs
+++ b/crates/engine/src/tools/window_tools.rs
@@ -12,6 +12,8 @@ use serde_json::{Value, json};
use std::path::PathBuf;
use std::time::{Duration, Instant};
+mod process_tree;
+
/// Largest picture kept inline in the evidence (bigger ones are only written to `output`).
const MAX_INLINE: usize = 8 * 1024 * 1024;
/// Most UI elements saved to `ui_tree`.
@@ -39,6 +41,9 @@ pub struct CaptureParams {
/// Arguments for it.
#[serde(default)]
pub args: Vec<String>,
+ /// Working folder for the program (an absolute directory). Defaults to its executable's folder.
+ #[serde(default)]
+ pub working_directory: Option<PathBuf>,
/// Seconds to let it start and draw before the picture (default 8, at most 120).
#[serde(default)]
pub wait_secs: Option<u64>,
@@ -51,6 +56,8 @@ pub struct CaptureParams {
pub ui_tree: Option<PathBuf>,
}
+/// Validate paths before starting a program, run it in the requested folder, then return window
+/// evidence and optional PNG/UI-tree artifacts. Unsupported hosts never start the program.
fn native_window_capture(ctx: &mut Ctx<'_>, params: Value) -> Result<ToolOutput, ToolError> {
let p: CaptureParams = parse_params(params)?;
if !p.program.is_absolute() || !p.program.is_file() {
@@ -61,12 +68,15 @@ fn native_window_capture(ctx: &mut Ctx<'_>, params: Value) -> Result<ToolOutput,
if p.ui_tree.as_ref().is_some_and(|t| !t.is_absolute()) {
return Err(ToolError::invalid("ui_tree must be an absolute path"));
}
+ if p.working_directory.as_ref().is_some_and(|d| !d.is_absolute() || !d.is_dir()) {
+ return Err(ToolError::invalid("working_directory must be an existing absolute directory"));
+ }
// Refused before the program starts where no picture can be taken.
if !craft_anything_platform::window::SUPPORTED {
return Err(craft_anything_platform::window::unsupported());
}
let wait = Duration::from_secs(p.wait_secs.unwrap_or(8).clamp(1, 120));
- let dir = p.program.parent().map(PathBuf::from).unwrap_or_default();
+ let dir = p.working_directory.unwrap_or_else(|| p.program.parent().map(PathBuf::from).unwrap_or_default());
let cancel = ctx.cancel.clone();
ctx.report(None, format!("Starting {} for {} s…", p.program.display(), wait.as_secs()));
let mut running = Process::new(&p.program)
@@ -89,15 +99,29 @@ fn native_window_capture(ctx: &mut Ctx<'_>, params: Value) -> Result<ToolOutput,
std::thread::sleep(Duration::from_millis(200));
}
let name = p.program.file_stem().map(|s| s.to_string_lossy().into_owned());
- let shot = craft_anything_platform::window::capture_window(running.pid(), name.as_deref());
+ let shot = process_tree::capture(
+ running.pid(),
+ || process_tree::snapshot(&ctx.cancel),
+ |pid| {
+ if ctx.cancel.is_cancelled() {
+ return Err(ToolError::cancelled());
+ }
+ craft_anything_platform::window::capture_window(pid, None)
+ },
+ )
+ // A launcher hands over to a program that isn't its child: last, its name finds the window.
+ .or_else(|e| match e.code {
+ ErrorCode::NotFound => craft_anything_platform::window::capture_window(running.pid(), name.as_deref()).map(|shot| (running.pid(), shot)),
+ _ => Err(e),
+ });
// Read while it still runs; a tree that can't be read is only left out.
- let tree = p.ui_tree.as_ref().map(|_| super::apple_runtime::ui_tree(ctx, running.pid(), UI_TREE_NODES));
+ let tree = shot.as_ref().ok().and_then(|(pid, _)| p.ui_tree.as_ref().map(|_| super::apple_runtime::ui_tree(ctx, *pid, UI_TREE_NODES)));
// Always closed again, picture or not, and confirmed before we return (a caller such as the
// CLI may exit right after, before a background kill would happen).
if !running.kill_and_wait(Duration::from_secs(10)) {
log::warn!("{} may still be running", p.program.display());
}
- let shot = shot?;
+ let (_, shot) = shot?;
let png = encode_png(&Image { width: shot.width, height: shot.height, rgba: shot.rgba })?;
if let Some(out) = &p.output {
if !out.is_absolute() {
@@ -128,7 +152,7 @@ fn native_window_capture(ctx: &mut Ctx<'_>, params: Value) -> Result<ToolOutput,
}
let mut b =
EvidenceBuilder::new("native_window_capture", Subject { kind: "program".into(), sha256: None, name: name.clone() }, super::artifact_tools::env(ctx))
- .params(json!({"program": p.program.display().to_string(), "args": p.args, "wait_secs": wait.as_secs()}))
+ .params(json!({"program": p.program.display().to_string(), "args": p.args, "working_directory": dir, "wait_secs": wait.as_secs()}))
.result(result)
.summary(format!("Pictured \"{}\" ({}×{}) after {} s.", shot.title, shot.width, shot.height, started.elapsed().as_secs()))
.confidence(Confidence::Observed)
@@ -145,6 +169,7 @@ mod tests {
use super::*;
use crate::{CallOptions, Caller, Consent, Engine};
+ /// Reject missing consent, invalid paths and unsupported hosts before launching any program.
#[test]
fn it_needs_consent_and_a_real_program() {
let e = Engine::new(crate::testing::session());
@@ -158,6 +183,17 @@ mod tests {
e.call("native_window_capture", relative, CallOptions::new(Caller::Mcp).with_consent(Consent::Granted)).unwrap_err().message.contains("ui_tree"),
"checked before anything starts"
);
+ let dir = tempfile::tempdir().unwrap();
+ for invalid in [PathBuf::from("relative"), dir.path().join("missing")] {
+ let params = json!({"program": exe, "working_directory": invalid});
+ assert!(
+ e.call("native_window_capture", params, CallOptions::new(Caller::Mcp).with_consent(Consent::Granted))
+ .unwrap_err()
+ .message
+ .contains("working_directory"),
+ "checked before anything starts"
+ );
+ }
// Where windows can't be pictured, nothing is started.
if !craft_anything_platform::window::SUPPORTED {
let err = e.call("native_window_capture", json!({"program": exe}), CallOptions::new(Caller::Mcp).with_consent(Consent::Granted)).unwrap_err();
diff --git a/crates/engine/src/tools/window_tools/process_tree.rs b/crates/engine/src/tools/window_tools/process_tree.rs
new file mode 100644
index 00000000..4bb3f122
--- /dev/null
+++ b/crates/engine/src/tools/window_tools/process_tree.rs
@@ -0,0 +1,152 @@
+//! A runner such as `go run` or `dotnet run` may own no window. Only inspect its descendants;
+//! a process with the same name elsewhere on the desktop is not part of this capture.
+
+use craft_anything_evidence::{ErrorCode, ToolError};
+use craft_anything_platform::process::Process;
+use std::collections::{BTreeMap, BTreeSet, VecDeque};
+use std::time::Duration;
+
+const MAX_PROCESSES: usize = 32_768;
+
+/// Read only numeric process relationships, with bounded output and a deadline.
+pub(super) fn snapshot(cancel: &crate::tool::CancelToken) -> Result<String, ToolError> {
+ #[cfg(windows)]
+ let command = {
+ let windir = std::env::var_os("SystemRoot").map(std::path::PathBuf::from).unwrap_or_else(|| std::path::PathBuf::from(r"C:\Windows"));
+ Process::new(windir.join(r"System32\WindowsPowerShell\v1.0\powershell.exe")).args([
+ "-NoProfile",
+ "-NonInteractive",
+ "-Command",
+ "$ErrorActionPreference = 'Stop'; Get-CimInstance Win32_Process | ForEach-Object { '{0} {1}' -f $_.ProcessId, $_.ParentProcessId }",
+ ])
+ };
+ #[cfg(not(windows))]
+ let command = Process::new("/bin/ps").args(["-A", "-o", "pid=,ppid="]);
+ let cancel = cancel.clone();
+ let out = command
+ .timeout(Duration::from_secs(10))
+ .idle_timeout(Duration::from_secs(10))
+ .stdout_cap(1024 * 1024)
+ .cancel_when(move || cancel.is_cancelled())
+ .run_checked()?;
+ if out.stdout_truncated {
+ return Err(ToolError::new(ErrorCode::ProgramFailed, "The process list was too large to identify the application's window safely."));
+ }
+ Ok(out.stdout_text())
+}
+
+/// Breadth-first descendants, regardless of snapshot order. Bound malformed/cyclic input too.
+fn descendants(root: u32, text: &str) -> Vec<u32> {
+ let mut children = BTreeMap::<u32, Vec<u32>>::new();
+ for line in text.lines().take(MAX_PROCESSES) {
+ let mut words = line.split_whitespace();
+ if let (Some(pid), Some(parent), None) = (words.next(), words.next(), words.next())
+ && let (Ok(pid), Ok(parent)) = (pid.parse::<u32>(), parent.parse::<u32>())
+ && pid != 0
+ {
+ children.entry(parent).or_default().push(pid);
+ }
+ }
+ let mut seen = BTreeSet::from([root]);
+ let mut pending = VecDeque::from([root]);
+ let mut result = Vec::new();
+ while let Some(parent) = pending.pop_front() {
+ for pid in children.remove(&parent).unwrap_or_default() {
+ if seen.insert(pid) {
+ result.push(pid);
+ pending.push_back(pid);
+ }
+ }
+ }
+ result
+}
+
+/// Return the window owner's PID alongside its picture so accessibility uses that same process.
+pub(super) fn capture<T>(
+ root: u32,
+ snapshot: impl FnOnce() -> Result<String, ToolError>,
+ mut picture: impl FnMut(u32) -> Result<T, ToolError>,
+) -> Result<(u32, T), ToolError> {
+ let missing = match picture(root) {
+ Ok(shot) => return Ok((root, shot)),
+ Err(e) if e.code == ErrorCode::NotFound => e,
+ Err(e) => return Err(e),
+ };
+ let candidates = descendants(root, &snapshot()?);
+ if candidates.len() > 64 {
+ return Err(ToolError::new(ErrorCode::ProgramFailed, "The program started too many processes to identify its window safely."));
+ }
+ for pid in candidates {
+ match picture(pid) {
+ Ok(shot) => return Ok((pid, shot)),
+ Err(e) if e.code == ErrorCode::NotFound => {}
+ Err(e) => return Err(e),
+ }
+ }
+ Err(missing)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn missing() -> ToolError {
+ ToolError::new(ErrorCode::NotFound, "No window")
+ }
+
+ #[test]
+ fn runner_capture_returns_application_pid_and_ignores_unrelated_windows() {
+ let mut looked_up = Vec::new();
+ let (tree_pid, shot) = capture(
+ 10,
+ || Ok("30 20\n99 1\n20 10\n".into()),
+ |pid| {
+ looked_up.push(pid);
+ if pid == 30 || pid == 99 { Ok("application picture") } else { Err(missing()) }
+ },
+ )
+ .unwrap();
+ assert_eq!(looked_up, [10, 20, 30]);
+ assert_eq!(tree_pid, 30, "UI tree must use the actual window owner");
+ assert_eq!(shot, "application picture");
+ assert!(capture::<()>(10, || Ok("99 1\n".into()), |_| Err(missing())).is_err());
+ }
+
+ #[test]
+ fn direct_window_needs_no_process_list_and_capture_errors_are_preserved() {
+ assert_eq!(capture(10, || panic!("unneeded process list"), |_| Ok("direct")).unwrap(), (10, "direct"));
+ let error = capture::<()>(10, || panic!("capture permission failure"), |_| Err(ToolError::new(ErrorCode::ProgramFailed, "denied"))).unwrap_err();
+ assert_eq!(error.message, "denied");
+ assert!(capture::<()>(10, || Err(ToolError::cancelled()), |_| Err(missing())).is_err());
+ }
+
+ #[test]
+ fn process_relationships_are_bounded_and_cycle_safe() {
+ assert_eq!(descendants(10, "20 10\n30 20\n10 30\n20 10\n0 10\nbad\n40 10 extra\n"), [20, 30]);
+ let text = format!("{}20 10\n", "bad\n".repeat(MAX_PROCESSES));
+ assert!(descendants(10, &text).is_empty());
+ let text = (20..85).map(|pid| format!("{pid} 10\n")).collect::<String>();
+ let mut attempts = 0;
+ let error = capture::<()>(
+ 10,
+ || Ok(text),
+ |_| {
+ attempts += 1;
+ Err(missing())
+ },
+ )
+ .unwrap_err();
+ assert_eq!(error.code, ErrorCode::ProgramFailed);
+ assert_eq!(attempts, 1, "oversized process families must not trigger repeated window scans");
+ }
+
+ /// Exercise the OS snapshot without opening any windows or requiring a language toolchain.
+ #[cfg(unix)]
+ #[test]
+ fn snapshot_finds_an_owned_child_on_this_host() {
+ let mut child = Process::new("/bin/sleep").arg("20").timeout(Duration::from_secs(30)).spawn().unwrap();
+ let family = snapshot(&crate::CancelToken::default()).map(|text| descendants(std::process::id(), &text));
+ assert!(child.kill_and_wait(Duration::from_secs(5)));
+ assert!(family.unwrap().contains(&child.pid()));
+ }
+}
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 5ca6ab26..c75126ac 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -746,7 +746,7 @@ Owner: open · Status: in progress
used to ask for Unity even in a Godot project, and an app got the kind's default
— claimed: xerenon, branch bugfix/r2.7-stack-from-files; PR #755
- [x] A person's own project (edited in place, nothing to recreate) is judged by what it does for
- itself: its own build, then its own tests, through `[[toolchain]]` in `stacks.toml` (Rust,
+ itself: its own build, then its own tests, through `[[toolchain]]` in `engine/src/toolchains.toml` (Rust,
Node.js, Python, Go, .NET, Maven, Gradle, Make). Nothing is added to it for our sake: no
`--screenshot`, `--self-test` or mechanics sheet. A site stack with nothing to recreate is a
website, whatever the request says
@@ -758,8 +758,18 @@ Owner: open · Status: in progress
- [ ] A person's own tests that already failed before their request fail the check too, so the
builder is sent to fix them. If that proves a nuisance, run them once before the first turn
and hold it only to what it broke
-- [ ] A new project in Python, Go or the like still fails the build check ("No project to build
- found") and has no program for the screenshot check: `[[toolchain]]` could build it too
+- [x] New projects build through the shared `[[toolchain]]` catalogue. Python root entrypoints,
+ Go's root `main.go`, and one root `.csproj` also launch for screenshots, self-tests and Play;
+ existing packaged programs, Rust, Electron and game-engine paths keep priority — PR #950
+ — claimed: Codex, branch bugfix/r2.7-new-project-toolchains
+- [x] Runtime window capture follows runner descendants (including `go run`) and reads controls
+ from the same process that supplied the picture, without falling back to unrelated names — PR #950
+- [x] Shared toolchain commands make project-local executables absolute before changing the
+ working directory, preserving virtualenv paths for relative project placements — PR #950
+- [ ] Extend launch recipes beyond conventional root entrypoints: Python package scripts, Go
+ `cmd/` layouts, and Java build outputs; build checks already use their toolchain commands
+- [ ] Audit relative project placements in build, option-run and Play paths too: runtime window
+ capture now normalizes its request paths, but earlier runner paths can still be relative
- [x] "player" alone doesn't make a request a game: a video or music player is an app (#953)
— claimed: justinjohn0306, branch bugfix/953-player-not-a-game
- [ ] Game words can't tell these apart from games: "a low level disk tool", "an MPEG 2 player",
diff --git a/docs/STATUS.md b/docs/STATUS.md
index e48688b4..350498f3 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -8,6 +8,8 @@ workspace clippy, layers, fmt and the secret scan of all history were clean. Chi
| Area | State | Verified by |
|---|---|---|
+| Runner-owned app windows | Runtime capture tries the launched process and its descendants; the captured window owner's PID is also used for the UI tree. Unrelated processes with matching names are excluded. Process discovery has a deadline, output cap and candidate limit | Hermetic regressions cover runner/child/grandchild ownership, unrelated windows, direct launches, cycles, malformed rows, caps and errors. A macOS process snapshot finds an owned child without opening a window. Windows and real Go GUI capture have not been run |
+| New-project toolchains | New Python, Go, .NET, Maven, Gradle and Make projects use the same build catalogue as existing projects (`engine/src/toolchains.toml`). Shared launch recipes let screenshots, self-tests and Play start Python `main.py`, `app.py` or `__main__.py`, Go with a root `main.go`, and one root `.csproj`. Python uses a project-local virtual environment when present, resolves its executable to an absolute path even for relative project folders, and forces fresh syntax compilation; .NET passes app options after `--`. Manifest markers take priority over standalone Python files. Runtime window-capture requests normalize relative project and runner paths to absolute paths. Existing packaged programs, Rust, Electron and Godot keep launch priority. Multiple `.csproj` matches or a capped scan do not choose a project. Other layouts still need a packaged program or another launch recipe | Catalogue and launch regressions cover argv boundaries, ambiguous entrypoints, scan limits and Windows/local interpreter selection, including relative project folders and unchanged argument boundaries. Capture-request tests cover relative placements and PATH results, local interpreters and optional UI-tree output without opening a window. An owned interpreter stand-in runs the full new-project build/screenshot path, rejects failed builds, and verifies a failed screenshot cannot reuse an old PNG. An opt-in real Python 3.15.2 fixture on macOS passes build/screenshot checks, ignores invalid virtualenv code, and rejects a syntax error even when its mtime matches the cached version. Without `compileall -f` that same syntax-error probe incorrectly exits zero. Real Go/.NET/Maven/Gradle runs, Windows and GUI apps have not been verified for this change |
| macOS optional UI tree | `runtime_ui_read` with `accessibility: false` skips the tree and its permission check, returns empty nodes without truncation, and records the flag and skipped read in its evidence (#307). Walkthroughs still require Accessibility. Screenshot capture remains open (#248) | Engine regression on macOS compiles and runs the real Swift helper with zero and one node limits, without reading another app's UI. No granted-permission tree read or walkthrough was run for this change |
| DNS question boundaries | A question is retained only when its name, type and class are complete. A missing class byte marks the DNS message incomplete; preceding complete questions remain available, and incomplete questions do not enter the query inventory | Four packet regressions cover both truncation lengths, multiple questions, complete class values and the capture summary. No live capture was used |
| Reject impossible IPv4 header and total lengths | IPv4 decoding rejects impossible header lengths and reports incomplete base headers or options. | Synthetic byte fixtures in `pcap_ipv4_lengths` integration regressions. Cover 10–19 captured header bytes, total lengths below IHL, missing options, complete options, truncated transport headers with readable ports, and a cut UDP payload with both ports and its captured length preserved. |
diff --git a/docs/extending.md b/docs/extending.md
index be52cd1f..f2a705a0 100644
--- a/docs/extending.md
+++ b/docs/extending.md
@@ -11,7 +11,7 @@ place to add yours. Follow `AGENTS.md` (never crash, layers, external programs t
| A kind of thing to make | `crates/ai/src/rebuild/kinds/` | Implement `TargetKind` (detection score, default stack, brief sections, checks, refine message, the app's words) and `KindRegistry::register` it. |
| A way to judge a build | `crates/ai/src/rebuild/kinds/` | Implement `Check` (`run(&mut CheckCx) -> CheckResult`; `applies` to skip it in some runs, or wrap it in `DeepOnly`); return it from your kind's `checks`. Decide on `passed`/`similarity`, never on text. |
| A stack | `crates/ai/src/rebuild/stacks.toml` | One `[[stack]]` entry: name, the builder's steps, the phrases that ask for it, its engine, the package.json or Cargo.toml dependencies that show a build uses it, the files that show a person's own folder is built with it. A component or styling library is a `[[library]]` entry (name, phrases, the stacks it works with, steps). |
-| A way to build and test someone's own project | `crates/ai/src/rebuild/stacks.toml` | One `[[toolchain]]` entry: name, the files that name it, its build and test commands, what it prints when no tests ran. Earlier entries win. |
+| A way to build, test or launch a project | `crates/engine/src/toolchains.toml` | One `[[toolchain]]` entry: name, marker files, build/test commands, no-tests messages and optional `launch` recipes. Earlier markers win; `standalone_entrypoints` detects script-only projects only after every manifest has been checked. Each launch recipe has a root `file` and argv `command`; `{file}` substitutes the matching relative filename without a shell. A wildcard entrypoint must match exactly one file within the bounded scan. `local_programs` and `windows_program` apply to build, test and launch. Packaged programs, Electron and Godot keep priority. AI's `stacks::Toolchain` and `toolchain_in` re-export this shared catalogue. |
| A coding agent | `crates/ai/src/cli_agents/adapters.rs` | Implement `AgentAdapter` (args, required flags, stream parsing, resume, sign-in check) and register it in `AgentAdapters`. Use `has_model_catalog`, `model_catalog`, `validate_model` and the shared `AgentModel`/`ModelContext` picker and tools for model/thinking selection; set `model_catalog_depends_on_selection` when metadata depends on the selected model. ACP agents also get a row in `cli_agents::acp::ACP_AGENTS`; if their ACP mode takes the backend's model, a row in `ACP_MODEL_FLAGS` too. Override ACP startup options, process setup or `requires_acp` when needed; verify actual tool exposure, not only startup. |
| An asset provider | `crates/engines/src/assets/` | Implement `AssetProvider` (`key_env` names its environment variable); add its models and prices to `assets.toml`. Its key is its own: `assets_key_set` with `provider`, kept as `assets:<id>`. |
| An external engine | `crates/engines/src/table.rs` | One `ExternalEngine` entry (exes, known paths, what it's for, install pins with SHA-256 checked against the publisher), plus a `tool_paths!` id in `settings.rs` if people can point at their own install. |
diff --git a/docs/pitfalls.md b/docs/pitfalls.md
index 19fc3200..85e3f036 100644
--- a/docs/pitfalls.md
+++ b/docs/pitfalls.md
@@ -71,6 +71,11 @@ names (`git merge-base --is-ancestor <fix> <release tag>`), and check the messag
## Tests
+**Python compilation reused stale bytecode after a fast edit.** The new-project toolchain probe
+changed valid Python to a syntax error within the same mtime second. `compileall` skipped it and
+exited zero; the screenshot run then failed instead. Use `compileall -f` for a build check, and
+hold the valid and broken fixture revisions at the same timestamp in the real-Python regression.
+
**A test started a real download on a contributor's machine.** A test called `engines_install` for
Unity; a later change made that download the vendor installer and open it on Windows. It also
created folders in the real config directory (`Session::default()` uses it).
@@ -150,6 +155,16 @@ call it and make them `wait` for the result, not `run_steps(n)`.
## Building and running
+**A runner's PID isn't the window owner's.** `go run` starts a compiled child, so picturing the
+runner missed the app (or a name fallback found another app). Search only the launched process
+and its descendants, and read the UI tree from the same PID that supplied the picture.
+
+**Runtime capture passed relative paths to a tool that needs absolute ones.** With a relative
+project placement, the selected virtualenv interpreter and artifact paths stayed relative;
+PATH lookup can return a relative path too. Resolve workspace paths against the process's
+current directory, look up only bare program names, and make the result absolute without
+dereferencing the virtualenv symlink. Test the generated capture request without opening a GUI.
+
**A model catalogue queried in the wrong project.** OpenCode V2's raw `api get /api/model` does
not reliably select the invoking CLI's directory. Use the `model.list` operation with an explicit
`location[directory]` parameter, and test that the returned Location matches it. Over SSH,
@@ -805,3 +820,9 @@ with a multi-megabyte line, not a short one.
body, so its second copy was rejected before it could be discarded as a duplicate. Apply aggregate
budgets only to distinct bodies actually retained. When a budget removes a body, preserve unavailable
cached 304 responses and deduplicate identical omitted samples.
+
+**Two worktrees shared build artifacts during conflict checks.** Concurrent Cargo checks of
+different branches reused the same package output path and one saw the other branch's engine.
+Give every worktree its own `CARGO_TARGET_DIR`, even when one agent manages both. Cleaning
+the shared engine cache then removed 11.6 GiB of compiled artifacts: avoid shared-cache
+cleanup as a recovery shortcut; use an isolated target directory for further verification.