Craft Anything: understand how any software works, and craft your own.
Rust
Delete private browser profiles when the browser closes (#822)
Agapenorf3efc1eb6156
diff --git a/crates/engine/src/tools/web_common.rs b/crates/engine/src/tools/web_common.rsindex 0b6aaf99..7606fb2d 100644--- a/crates/engine/src/tools/web_common.rs+++ b/crates/engine/src/tools/web_common.rs@@ -49,12 +49,23 @@ pub struct Browser {/// The `User-Agent` from `/json/version` (empty when unknown); names the runtime.pub user_agent: String,pub launched: bool,- // Held only so the owned browser process (and its temp profile) are killed/kept alive for the- // lifetime of this handle and cleaned up on drop; never read directly.+ // The process is dropped before the profile so its supervisor is asked to stop it first.#[allow(dead_code)]_proc: Option<RunningProcess>,#[allow(dead_code)]- _profile: Option<std::path::PathBuf>,+ _profile: Option<BrowserProfile>,+}++struct BrowserProfile(std::path::PathBuf);++impl Drop for BrowserProfile {+ fn drop(&mut self) {+ if let Err(e) = std::fs::remove_dir_all(&self.0)+ && e.kind() != std::io::ErrorKind::NotFound+ {+ log::warn!("couldn't remove the private browser profile {}: {e}", self.0.display());+ }+ }}/// What is answering on a CDP endpoint: `electron`, `edge`, `chrome`, or `unknown`, from the@@ -136,9 +147,9 @@ 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 profile = super::artifact_tools::fresh_dir_in(&profile_base(&exe, dirs::home_dir()), "craft-browser")?;+ 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.display()),+ format!("--user-data-dir={}", profile.0.display()),"--remote-debugging-port=0".into(),"--remote-allow-origins=*".into(),"--no-first-run".into(),@@ -170,7 +181,7 @@ impl Browser {.hands_off().spawn()?;let name = exe.file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "the browser".into());- let endpoint = Self::await_devtools(&profile, dl, &mut proc, &tail, &name)?;+ let endpoint = Self::await_devtools(&profile.0, dl, &mut proc, &tail, &name)?;let version = cdp::json_version(&endpoint, dl)?;Ok(Browser {product: version.get("Browser").and_then(Value::as_str).unwrap_or("unknown").to_string(),@@ -191,9 +202,9 @@ impl Browser {return Err(ToolError::new(ErrorCode::NotFound, format!("{} is not a file", exe.display())).with_remediation("Give the absolute path of the app's executable."));}- let profile = super::artifact_tools::fresh_temp_dir("craft-electron")?;+ let profile = BrowserProfile(super::artifact_tools::fresh_temp_dir("craft-electron")?);let mut args: Vec<String> = vec![- format!("--user-data-dir={}", profile.display()),+ format!("--user-data-dir={}", profile.0.display()),"--remote-debugging-port=0".into(),"--remote-allow-origins=*".into(),"--no-first-run".into(),@@ -212,7 +223,7 @@ impl Browser {.hands_off().spawn()?;let name = exe.file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "the app".into());- let endpoint = Self::await_devtools(&profile, dl, &mut proc, &tail, &name)?;+ let endpoint = Self::await_devtools(&profile.0, dl, &mut proc, &tail, &name)?;let version = cdp::json_version(&endpoint, dl)?;Ok(Browser {product: version.get("Browser").and_then(Value::as_str).unwrap_or("Electron app").to_string(),@@ -1051,6 +1062,25 @@ pub fn png_artifact(bytes: &[u8]) -> Result<Value, ToolError> {#[cfg(test)]mod tests {+ #[test]+ fn a_launched_browser_deletes_its_profile_on_drop() {+ let root = tempfile::tempdir().unwrap();+ let profile = root.path().join("private-profile");+ std::fs::create_dir(&profile).unwrap();+ std::fs::write(profile.join("Preferences"), b"private browser state").unwrap();+ let browser = super::Browser {+ endpoint: super::cdp::parse_endpoint("http://127.0.0.1:9222").unwrap(),+ product: "Test Browser".into(),+ version: String::new(),+ user_agent: String::new(),+ launched: true,+ _proc: None,+ _profile: Some(super::BrowserProfile(profile.clone())),+ };+ drop(browser);+ assert!(!profile.exists(), "the private browser profile survived its owner");+ }+/// #747: a Flatpak or Snap browser keeps its profile where its sandbox can reach it and we can/// read its port; any other browser uses the temp folder.#[test]diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex 1cb1eea0..de6dc5c3 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -705,6 +705,9 @@ Gaps found while using the app for real projects.ended 30 s later. Not run on a Mac- [ ] Find why a site capture lost its browser ("the WebSocket is closed", 419 ms into`web_site_capture` for a second page, seen once; the same capture passed 41 s earlier)+- [x] Delete a private browser's temporary profile when it closes or fails to start (#810) — PR #822+- [ ] Stop private browsers that outlive the app after an abrupt exit, and investigate the Brave+ Helper crash (#810); both still need macOS reproduction- [ ] Claude Code's Ultracode switch (a setting, not an effort level; the effort environmentvariable we use can't turn it on)- [x] A model the list doesn't offer (`opusplan`, `[1m]` variants, one another harness serves) candiff --git a/docs/STATUS.md b/docs/STATUS.mdindex e8e88377..37c5b5b1 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -28,7 +28,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 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 run on example.com; unit tests |+| 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 || 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`. 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 |