diff --git a/LLM.md b/LLM.md index 57eef329..af0bc0e3 100644 --- a/LLM.md +++ b/LLM.md @@ -619,6 +619,40 @@ browser works with or without one running. The Hanzo extension registers as checkout builds with `TAURI_CONFIG='{"bundle":{"externalBin":[],"resources":[]}}'` when the sidecars are not downloaded. +## Local runs: Dev in a folder, no terminal + +Dev's New starts on **This computer** (`desktopLocal()` in `@hanzo/app` `lib/local-fs.ts`, handed to +`@hanzo/build` as `Host.local`). A run is the `dev` agent in one folder (`dev exec -C `), no +repository, nothing sent to the platform. The window supplies four commands +(`src-tauri/src/commands/local_workspace.rs`), each its own `allow-` entry in `capabilities/main.json`: + +- `local_workspace_open_dialog` — the OS folder dialog. +- `local_workspace_discover` — the project folders found where people keep them (`~/Documents`, `Projects`, + `work`, `code`, ...: at most two folders down, never inside another project, never hidden or generated; + names and times only, no file is read), newest first, at most 50. The logic is the `hanzo-projects` crate + (`src-tauri/projects`); `desktopLocal()` asks once when Dev opens and merges the answer after the + folders Hanzo opened, so Auto has folders to pick from on a first run. On macOS the first look into + Documents and Desktop shows the system's own permission prompt. +- `local_workspace_run_dev` — runs the agent with `--color never --skip-git-repo-check -s workspace-write + -C -o -- ` and answers `{session_id, output, process, success}`: `output` is the + agent's final message (`-o`, else stdout), `process` its log (stderr). `-s workspace-write` is passed + because `dev exec` otherwise runs read-only and cannot edit. The window shows `output` in words and + `process` only in Developer mode (`@hanzo/build` `plainAnswer`, `RanHere`). +- **The agent is fetched when the computer has none**, so a person never meets `npm install`. Lookup + (`hanzo-dev-agent` crate, `src-tauri/dev-agent`): `HANZO_DEV_BIN`, `~/.local/bin/dev`, + `~/.cargo/bin/dev`, `PATH`, then the app's own copy in the app data dir + (`/dev//dev`). None found: download `hanzoai/dev`'s pinned release (`VERSION` in + `dev-agent/src/lib.rs`, the one place it is written; `dev-.tar.gz`, Windows + `dev-x86_64-pc-windows-msvc.exe.zip`, ~120 MB), check it against the `.sha256` beside it, unpack the one + binary, let older versions go. The window hears `local-dev-setup` `{percent}` (0-100) while it + downloads and says "Setting up Hanzo Dev on this computer…". One download at a time; a failure is a + plain sentence the window shows as it is (no connection, a download that did not check out). Move the + pin by changing `VERSION` and running `cargo test --manifest-path src-tauri/dev-agent/Cargo.toml`. + +Auto (the Folder pill) is `@hanzo/build` `route(folders, ask)`: the folder whose name the ask says, then the +folders it sits in, else the folder used last; same words, same folder, a tie goes to the more recent. The +pill reads `Auto · ` as the ask is typed, and a folder the person chose is never moved by the words. + ## Machines (Docker Desktop replacement) Desktop UI for Linux VMs (vfkit) and the docker / k3s stack served by the diff --git a/apps/hanzo-desktop/src-tauri/Cargo.lock b/apps/hanzo-desktop/src-tauri/Cargo.lock index 2131be4a..d7290a3d 100644 --- a/apps/hanzo-desktop/src-tauri/Cargo.lock +++ b/apps/hanzo-desktop/src-tauri/Cargo.lock @@ -2711,6 +2711,7 @@ checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" dependencies = [ "crc32fast", "miniz_oxide", + "zlib-rs", ] [[package]] @@ -3640,11 +3641,13 @@ dependencies = [ "fix-path-env", "futures-util", "hanzo", + "hanzo-dev-agent", "hanzo-engine", "hanzo-engine-bin", "hanzo-log-redact", "hanzo-mining", "hanzo-node-secret", + "hanzo-projects", "hanzo-server-core", "hex", "http-body-util", @@ -3694,6 +3697,17 @@ dependencies = [ "zapd", ] +[[package]] +name = "hanzo-dev-agent" +version = "0.1.0" +dependencies = [ + "flate2", + "hex", + "sha2 0.10.9", + "tar", + "zip 4.6.1", +] + [[package]] name = "hanzo-engine" version = "1.7.108" @@ -4003,6 +4017,10 @@ dependencies = [ "thiserror 2.0.18", ] +[[package]] +name = "hanzo-projects" +version = "0.1.0" + [[package]] name = "hanzo-quant" version = "1.7.108" @@ -12115,8 +12133,10 @@ checksum = "caa8cd6af31c3b31c6631b8f483848b91589021b28fffe50adada48d4f4d2ed1" dependencies = [ "arbitrary", "crc32fast", + "flate2", "indexmap 2.14.0", "memchr", + "zopfli", ] [[package]] @@ -12131,12 +12151,30 @@ dependencies = [ "typed-path", ] +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + [[package]] name = "zmij" version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" +[[package]] +name = "zopfli" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] + [[package]] name = "zune-core" version = "0.5.1" diff --git a/apps/hanzo-desktop/src-tauri/Cargo.toml b/apps/hanzo-desktop/src-tauri/Cargo.toml index 1f74b4e2..39e73fa5 100644 --- a/apps/hanzo-desktop/src-tauri/Cargo.toml +++ b/apps/hanzo-desktop/src-tauri/Cargo.toml @@ -49,6 +49,10 @@ hanzo-log-redact = { path = "log-redact" } hanzo-node-secret = { path = "node-secret" } # Finds a local hanzo-server, or says there is none (cloud#760). See engine-bin/src/lib.rs. hanzo-engine-bin = { path = "engine-bin" } +# Finds Hanzo Dev, or names the release the app fetches so a local run needs no terminal. See dev-agent/src/lib.rs. +hanzo-dev-agent = { path = "dev-agent" } +# The project folders Auto can pick from. See projects/src/lib.rs. +hanzo-projects = { path = "projects" } anyhow = "1.0.89" uuid = { version = "1.10.0", features = ["v4"] } kill_tree = { version = "0.2", features = ["tokio"] } diff --git a/apps/hanzo-desktop/src-tauri/capabilities/main.json b/apps/hanzo-desktop/src-tauri/capabilities/main.json index 9ffbd4f0..c20d09a7 100644 --- a/apps/hanzo-desktop/src-tauri/capabilities/main.json +++ b/apps/hanzo-desktop/src-tauri/capabilities/main.json @@ -172,6 +172,7 @@ "allow-local-workspace-create-dir", "allow-local-workspace-delete", "allow-local-workspace-run-dev", + "allow-local-workspace-discover", "allow-browser", "allow-browsers", "allow-check-claude-installed", diff --git a/apps/hanzo-desktop/src-tauri/dev-agent/Cargo.lock b/apps/hanzo-desktop/src-tauri/dev-agent/Cargo.lock new file mode 100644 index 00000000..5d0f2abe --- /dev/null +++ b/apps/hanzo-desktop/src-tauri/dev-agent/Cargo.lock @@ -0,0 +1,396 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" +dependencies = [ + "derive_arbitrary", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "derive_arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "filetime" +version = "0.2.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1255e7a9f1902190d4c10a75f2f7f495d3d3ce13e9ba26e6c48683a0f4dbed7" +dependencies = [ + "cfg-if", + "libc", +] + +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "hanzo-dev-agent" +version = "0.1.0" +dependencies = [ + "flate2", + "hex", + "sha2", + "tar", + "tempfile", + "zip", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", + "xattr", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "xattr" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "963d6fab92d5504b971dc8bd90ca743c2575e590bc8071ea5bc571598667ae08" +dependencies = [ + "libc", + "rustix", +] + +[[package]] +name = "zip" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa8cd6af31c3b31c6631b8f483848b91589021b28fffe50adada48d4f4d2ed1" +dependencies = [ + "arbitrary", + "crc32fast", + "flate2", + "indexmap", + "memchr", + "zopfli", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zopfli" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] diff --git a/apps/hanzo-desktop/src-tauri/dev-agent/Cargo.toml b/apps/hanzo-desktop/src-tauri/dev-agent/Cargo.toml new file mode 100644 index 00000000..58efc84e --- /dev/null +++ b/apps/hanzo-desktop/src-tauri/dev-agent/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "hanzo-dev-agent" +version = "0.1.0" +edition = "2021" +publish = false +description = "Finds Hanzo Dev on this computer, or names the release to fetch, checks it and unpacks it" +license = "Apache-2.0" + +[dependencies] +flate2 = "1.1" +hex = "0.4" +sha2 = "0.10" +tar = "0.4" +zip = { version = "4.6", default-features = false, features = ["deflate"] } + +[dev-dependencies] +tempfile = "3" diff --git a/apps/hanzo-desktop/src-tauri/dev-agent/src/lib.rs b/apps/hanzo-desktop/src-tauri/dev-agent/src/lib.rs new file mode 100644 index 00000000..c41ac88c --- /dev/null +++ b/apps/hanzo-desktop/src-tauri/dev-agent/src/lib.rs @@ -0,0 +1,427 @@ +//! Hanzo Dev on this computer: the coding agent a run in a folder works with. +//! +//! A local run is `dev exec` in the person's folder. Most people have no `dev` +//! and no terminal to install one in, so the desktop finds it ([`resolve`]) or +//! fetches the pinned release once ([`VERSION`], [`asset`]), checks it against +//! the checksum published beside it ([`verify`]) and unpacks the one binary it +//! holds ([`unpack`]). Everything here is a pure function of its arguments +//! (paths, names, bytes); the download itself, its progress and the run are the +//! app's (`src/commands/local_workspace.rs`). + +use std::ffi::OsStr; +use std::fs::{self, File}; +use std::io::{self, Read, Write}; +use std::path::{Path, PathBuf}; + +use sha2::{Digest, Sha256}; + +/// The release fetched when the computer has no `dev`. The one place the version is written. +pub const VERSION: &str = "0.7.23"; + +/// Environment variable naming the agent explicitly. +pub const OVERRIDE_VAR: &str = "HANZO_DEV_BIN"; + +const RELEASES: &str = "https://github.com/hanzoai/dev/releases/download"; + +/// The agent's file name on this platform. +pub const fn file_name() -> &'static str { + if cfg!(windows) { + "dev.exe" + } else { + "dev" + } +} + +/// How a release file packs the binary. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + TarGz, + Zip, +} + +/// One file of the release: its name there, and how it is packed. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Asset { + pub name: &'static str, + pub kind: Kind, +} + +impl Asset { + /// Where the file is published. + pub fn url(&self) -> String { + format!("{RELEASES}/v{VERSION}/{}", self.name) + } + + /// Where its checksum is published: `.sha256`, beside it. + pub fn digest_url(&self) -> String { + format!("{}.sha256", self.url()) + } +} + +/// The release file for an operating system and CPU (Rust's `std::env::consts` +/// names), or `None` where Hanzo Dev publishes none. +pub fn asset(os: &str, arch: &str) -> Option { + let (name, kind) = match (os, arch) { + ("macos", "aarch64") => ("dev-aarch64-apple-darwin.tar.gz", Kind::TarGz), + ("macos", "x86_64") => ("dev-x86_64-apple-darwin.tar.gz", Kind::TarGz), + ("linux", "x86_64") => ("dev-x86_64-unknown-linux-musl.tar.gz", Kind::TarGz), + ("linux", "aarch64") => ("dev-aarch64-unknown-linux-musl.tar.gz", Kind::TarGz), + ("windows", "x86_64") => ("dev-x86_64-pc-windows-msvc.exe.zip", Kind::Zip), + _ => return None, + }; + Some(Asset { name, kind }) +} + +/// The release file for this computer. +pub fn here() -> Option { + asset(std::env::consts::OS, std::env::consts::ARCH) +} + +/// Where the app keeps its own copy under `data_dir`: one folder per version, so a +/// newer pin is fetched beside the old one and the old one can be let go. +pub fn own(data_dir: &Path) -> PathBuf { + data_dir.join("dev").join(VERSION).join(file_name()) +} + +/// The agent to run, or `None` when the computer has none and the release must be fetched. +/// +/// In this order: [`OVERRIDE_VAR`] when set and not empty (the person's explicit choice, returned as +/// written so a bad value surfaces as a real error), `dev` in `~/.local/bin`, in `~/.cargo/bin`, on +/// `PATH`, then the app's own copy (`own_copy`). The values are parameters, not read here, so the +/// lookup is testable. +pub fn resolve( + override_bin: Option<&OsStr>, + home: Option<&Path>, + own_copy: &Path, + path_var: Option<&OsStr>, +) -> Option { + if let Some(bin) = override_bin.filter(|v| !v.is_empty()) { + return Some(PathBuf::from(bin)); + } + let homes = home + .into_iter() + .flat_map(|h| [h.join(".local/bin"), h.join(".cargo/bin")]); + let paths = path_var + .into_iter() + .flat_map(std::env::split_paths) + .filter(|dir| !dir.as_os_str().is_empty()); + homes + .chain(paths) + .map(|dir| dir.join(file_name())) + .chain(std::iter::once(own_copy.to_path_buf())) + .find(|candidate| is_executable_file(candidate)) +} + +/// A regular file the current user could execute (on Unix, any execute bit). +fn is_executable_file(path: &Path) -> bool { + let Ok(meta) = fs::metadata(path) else { + return false; + }; + if !meta.is_file() { + return false; + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + meta.permissions().mode() & 0o111 != 0 + } + #[cfg(not(unix))] + { + true + } +} + +/// The digest in a published `.sha256` file (` `), lowercase, or `None` when the file is not one. +pub fn expected(sha256_file: &str) -> Option { + let word = sha256_file.split_whitespace().next()?; + (word.len() == 64 && word.bytes().all(|b| b.is_ascii_hexdigit())).then(|| word.to_ascii_lowercase()) +} + +/// The SHA-256 of a file, as lowercase hex. +pub fn sha256_file(path: &Path) -> io::Result { + let mut file = File::open(path)?; + let mut hasher = Sha256::new(); + let mut buf = vec![0u8; 1 << 20]; + loop { + let n = file.read(&mut buf)?; + if n == 0 { + break; + } + hasher.update(&buf[..n]); + } + Ok(hex::encode(hasher.finalize())) +} + +/// Whether the file at `path` is the one `expected_hex` names. +pub fn verify(path: &Path, expected_hex: &str) -> io::Result { + Ok(sha256_file(path)?.eq_ignore_ascii_case(expected_hex)) +} + +/// Writes the one binary a release file holds to `dest`, and makes it executable. The archive's own +/// names and paths are never used, so nothing in it can write anywhere but `dest`. +pub fn unpack(archive: &Path, kind: Kind, dest: &Path) -> io::Result<()> { + if let Some(dir) = dest.parent() { + fs::create_dir_all(dir)?; + } + let part = dest.with_extension("part"); + let written = match kind { + Kind::TarGz => first_in_tar(archive, &part), + Kind::Zip => first_in_zip(archive, &part), + }; + if let Err(e) = written { + let _ = fs::remove_file(&part); + return Err(e); + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&part, fs::Permissions::from_mode(0o755))?; + } + fs::rename(&part, dest) +} + +fn nothing() -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, "the download holds no program") +} + +fn first_in_tar(archive: &Path, out: &Path) -> io::Result<()> { + let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(File::open(archive)?)); + for entry in tar.entries()? { + let mut entry = entry?; + if entry.header().entry_type().is_file() { + io::copy(&mut entry, &mut File::create(out)?)?; + return Ok(()); + } + } + Err(nothing()) +} + +fn first_in_zip(archive: &Path, out: &Path) -> io::Result<()> { + let mut zip = zip::ZipArchive::new(File::open(archive)?).map_err(io::Error::other)?; + for i in 0..zip.len() { + let mut file = zip.by_index(i).map_err(io::Error::other)?; + if file.is_file() { + let mut dest = File::create(out)?; + io::copy(&mut file, &mut dest)?; + dest.flush()?; + return Ok(()); + } + } + Err(nothing()) +} + +/// What a finished `dev exec` gives back: the answer, and how it got there. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Outcome { + /// The agent's final message: what a person reads. + pub output: String, + /// What it did on the way: its log (stderr), and what it printed when that is not the answer. + pub process: String, +} + +/// Splits a run into its answer and its process. `last` is what `--output-last-message` wrote, and is the +/// answer when it holds one; otherwise the answer is what the agent printed (stdout), which is that same +/// message when the file could not be written. The process is the agent's log, and holds stdout only when +/// stdout is not what was shown as the answer. +pub fn outcome(last: Option<&str>, stdout: &str, stderr: &str) -> Outcome { + let last = last.map(str::trim).filter(|s| !s.is_empty()); + let printed = stdout.trim(); + let output = last.unwrap_or(printed).to_string(); + let mut process = stderr.trim().to_string(); + if !printed.is_empty() && printed != output { + if !process.is_empty() { + process.push('\n'); + } + process.push_str(printed); + } + Outcome { output, process } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::ffi::OsString; + + fn executable(path: &Path) { + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, b"#!/bin/sh\n").unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(path, fs::Permissions::from_mode(0o755)).unwrap(); + } + } + + #[test] + fn names_the_release_file_for_every_computer_it_publishes_for() { + let a = asset("macos", "aarch64").unwrap(); + assert_eq!(a.name, "dev-aarch64-apple-darwin.tar.gz"); + assert_eq!(a.kind, Kind::TarGz); + assert_eq!(asset("macos", "x86_64").unwrap().name, "dev-x86_64-apple-darwin.tar.gz"); + assert_eq!(asset("linux", "x86_64").unwrap().name, "dev-x86_64-unknown-linux-musl.tar.gz"); + assert_eq!(asset("linux", "aarch64").unwrap().name, "dev-aarch64-unknown-linux-musl.tar.gz"); + let w = asset("windows", "x86_64").unwrap(); + assert_eq!(w.name, "dev-x86_64-pc-windows-msvc.exe.zip"); + assert_eq!(w.kind, Kind::Zip); + assert_eq!(asset("windows", "aarch64"), None); + assert_eq!(asset("freebsd", "x86_64"), None); + } + + #[test] + fn the_release_and_its_checksum_sit_beside_each_other() { + let a = asset("linux", "x86_64").unwrap(); + assert_eq!( + a.url(), + format!("https://github.com/hanzoai/dev/releases/download/v{VERSION}/dev-x86_64-unknown-linux-musl.tar.gz") + ); + assert_eq!(a.digest_url(), format!("{}.sha256", a.url())); + } + + #[test] + fn reads_a_published_checksum() { + let hex = "07a7d7fb02a406d6aafd96eac7c3a9f37250210378241b896401ec1fdaa8a83b"; + assert_eq!(expected(&format!("{hex} dev-x86_64-unknown-linux-musl.tar.gz\n")).as_deref(), Some(hex)); + assert_eq!(expected(&hex.to_uppercase()).as_deref(), Some(hex)); + assert_eq!(expected("Not Found"), None); + assert_eq!(expected("abc123 file"), None); + assert_eq!(expected(""), None); + } + + #[test] + fn a_file_matches_its_digest_and_nothing_else() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("f"); + fs::write(&file, b"hello").unwrap(); + let hello = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"; + assert_eq!(sha256_file(&file).unwrap(), hello); + assert!(verify(&file, hello).unwrap()); + assert!(verify(&file, &hello.to_uppercase()).unwrap()); + assert!(!verify(&file, &"0".repeat(64)).unwrap()); + assert!(verify(&dir.path().join("missing"), hello).is_err()); + } + + #[test] + fn an_explicit_choice_is_returned_as_written() { + let own_copy = Path::new("/nowhere/dev"); + let chosen = OsString::from("/opt/dev"); + assert_eq!(resolve(Some(chosen.as_os_str()), None, own_copy, None), Some(PathBuf::from("/opt/dev"))); + let empty = OsString::new(); + assert_eq!(resolve(Some(empty.as_os_str()), None, own_copy, None), None); + } + + #[test] + fn finds_dev_in_the_homes_bins_then_on_the_path_then_the_apps_own_copy() { + let dir = tempfile::tempdir().unwrap(); + let home = dir.path().join("home"); + let on_path = dir.path().join("bin"); + let own_copy = dir.path().join("data").join("dev").join(VERSION).join(file_name()); + let path_var = std::env::join_paths([&on_path]).unwrap(); + assert_eq!(resolve(None, Some(&home), &own_copy, Some(&path_var)), None); + + executable(&own_copy); + assert_eq!(resolve(None, Some(&home), &own_copy, Some(&path_var)), Some(own_copy.clone())); + + executable(&on_path.join(file_name())); + assert_eq!(resolve(None, Some(&home), &own_copy, Some(&path_var)), Some(on_path.join(file_name()))); + + executable(&home.join(".cargo/bin").join(file_name())); + assert_eq!(resolve(None, Some(&home), &own_copy, Some(&path_var)), Some(home.join(".cargo/bin").join(file_name()))); + + executable(&home.join(".local/bin").join(file_name())); + assert_eq!(resolve(None, Some(&home), &own_copy, Some(&path_var)), Some(home.join(".local/bin").join(file_name()))); + } + + #[cfg(unix)] + #[test] + fn a_file_that_cannot_run_is_not_found() { + let dir = tempfile::tempdir().unwrap(); + let home = dir.path(); + let plain = home.join(".local/bin").join(file_name()); + fs::create_dir_all(plain.parent().unwrap()).unwrap(); + fs::write(&plain, b"x").unwrap(); + assert_eq!(resolve(None, Some(home), &dir.path().join("none"), None), None); + } + + fn tar_gz(path: &Path, members: &[(&str, &[u8])]) { + let file = File::create(path).unwrap(); + let mut builder = tar::Builder::new(flate2::write::GzEncoder::new(file, flate2::Compression::fast())); + for (name, body) in members { + let mut header = tar::Header::new_gnu(); + header.set_size(body.len() as u64); + header.set_mode(0o644); + header.set_cksum(); + builder.append_data(&mut header, name, *body).unwrap(); + } + builder.into_inner().unwrap().finish().unwrap(); + } + + #[test] + fn unpacks_the_one_binary_whatever_it_is_called_and_makes_it_run() { + let dir = tempfile::tempdir().unwrap(); + let archive = dir.path().join("dev.tar.gz"); + tar_gz(&archive, &[("elsewhere/inside/dev-x86_64-unknown-linux-musl", b"binary".as_slice())]); + let dest = dir.path().join("data/dev/1/dev"); + unpack(&archive, Kind::TarGz, &dest).unwrap(); + assert_eq!(fs::read(&dest).unwrap(), b"binary"); + assert!(!dir.path().join("elsewhere").exists()); + assert!(!dest.with_extension("part").exists()); + assert!(is_executable_file(&dest)); + } + + #[test] + fn unpacks_a_zip() { + let dir = tempfile::tempdir().unwrap(); + let archive = dir.path().join("dev.zip"); + { + let mut zip = zip::ZipWriter::new(File::create(&archive).unwrap()); + zip.start_file("dev-x86_64-pc-windows-msvc.exe", zip::write::SimpleFileOptions::default()).unwrap(); + zip.write_all(b"exe").unwrap(); + zip.finish().unwrap(); + } + let dest = dir.path().join("dev.exe"); + unpack(&archive, Kind::Zip, &dest).unwrap(); + assert_eq!(fs::read(&dest).unwrap(), b"exe"); + } + + #[test] + fn an_archive_with_no_file_in_it_or_that_is_not_one_leaves_nothing_behind() { + let dir = tempfile::tempdir().unwrap(); + let empty = dir.path().join("empty.tar.gz"); + tar_gz(&empty, &[]); + let dest = dir.path().join("out/dev"); + assert_eq!(unpack(&empty, Kind::TarGz, &dest).unwrap_err().kind(), io::ErrorKind::InvalidData); + assert!(!dest.exists() && !dest.with_extension("part").exists()); + let junk = dir.path().join("junk"); + fs::write(&junk, b"not an archive").unwrap(); + assert!(unpack(&junk, Kind::TarGz, &dest).is_err()); + assert!(unpack(&junk, Kind::Zip, &dest).is_err()); + assert!(!dest.exists() && !dest.with_extension("part").exists()); + } + + #[test] + fn the_answer_is_the_last_message_and_the_process_is_the_log() { + let o = outcome(Some("I added the page.\n"), "I added the page.\n", "workdir: /x\nexec ls\n"); + assert_eq!(o.output, "I added the page."); + assert_eq!(o.process, "workdir: /x\nexec ls"); + } + + #[test] + fn without_the_file_the_answer_is_what_was_printed() { + let o = outcome(None, "Done.\n", "log\n"); + assert_eq!(o, Outcome { output: "Done.".into(), process: "log".into() }); + let blank = outcome(Some(" \n"), "Done.", ""); + assert_eq!(blank, Outcome { output: "Done.".into(), process: String::new() }); + } + + #[test] + fn what_was_printed_beside_a_different_answer_stays_in_the_process() { + let o = outcome(Some("Final."), "Progress text", "log"); + assert_eq!(o.output, "Final."); + assert_eq!(o.process, "log\nProgress text"); + } + + #[test] + fn a_run_that_said_nothing_has_no_answer() { + assert_eq!(outcome(None, "", "boom"), Outcome { output: String::new(), process: "boom".into() }); + } +} diff --git a/apps/hanzo-desktop/src-tauri/projects/Cargo.lock b/apps/hanzo-desktop/src-tauri/projects/Cargo.lock new file mode 100644 index 00000000..e3740292 --- /dev/null +++ b/apps/hanzo-desktop/src-tauri/projects/Cargo.lock @@ -0,0 +1,114 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "hanzo-projects" +version = "0.1.0" +dependencies = [ + "tempfile", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] diff --git a/apps/hanzo-desktop/src-tauri/projects/Cargo.toml b/apps/hanzo-desktop/src-tauri/projects/Cargo.toml new file mode 100644 index 00000000..4e969080 --- /dev/null +++ b/apps/hanzo-desktop/src-tauri/projects/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "hanzo-projects" +version = "0.1.0" +edition = "2021" +publish = false +description = "Finds the project folders on this computer a run could work in, most recently touched first" +license = "Apache-2.0" + +[dependencies] + +[dev-dependencies] +tempfile = "3" diff --git a/apps/hanzo-desktop/src-tauri/projects/src/lib.rs b/apps/hanzo-desktop/src-tauri/projects/src/lib.rs new file mode 100644 index 00000000..8ecbaae9 --- /dev/null +++ b/apps/hanzo-desktop/src-tauri/projects/src/lib.rs @@ -0,0 +1,230 @@ +//! The project folders on this computer, found where people keep them. +//! +//! A run on this computer works in a folder, and the person should not have to browse for it: Auto +//! picks the one the ask is about (build's `local.ts`), from the folders Hanzo opened and the ones +//! found here. A folder is a project when it holds something projects hold (a git checkout, a +//! package manifest, a page), and it is looked for in the usual places under the home folder, at most +//! two folders down (`~/work/app`, `~/work/org/app`), never inside another project and never in a +//! hidden or generated folder. Only names and times are read; no file's contents are. + +use std::fs; +use std::path::{Path, PathBuf}; +use std::time::UNIX_EPOCH; + +/// The places under the home folder projects usually live in. +pub const PLACES: &[&str] = &[ + "Documents", "Projects", "Developer", "code", "Code", "src", "work", "dev", "repos", "GitHub", "github", "Sites", "Desktop", +]; + +/// What a project folder holds: a git checkout, a manifest of a language's tooling, or a page. +pub const MARKERS: &[&str] = &[ + ".git", + "package.json", + "Cargo.toml", + "go.mod", + "pyproject.toml", + "requirements.txt", + "Gemfile", + "composer.json", + "pom.xml", + "build.gradle", + "deno.json", + "mix.exs", + "CMakeLists.txt", + "index.html", +]; + +/// Folders that hold what is built or installed, never a person's project. +const GENERATED: &[&str] = &["node_modules", "target", "dist", "build", "vendor", "venv", "__pycache__", "out"]; + +/// How many folders are looked at in all, so a home folder with thousands of checkouts answers promptly. +const BUDGET: usize = 4000; + +/// How many projects are answered. +pub const LIMIT: usize = 50; + +/// A project folder, as the desktop hands it to the app. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Project { + pub name: String, + pub path: PathBuf, + /// When it was last touched (ms since the epoch): the newest of the folder and what marks it a project. + pub modified: u64, +} + +fn millis(path: &Path) -> u64 { + fs::metadata(path) + .and_then(|m| m.modified()) + .ok() + .and_then(|t| t.duration_since(UNIX_EPOCH).ok()) + .map(|d| d.as_millis() as u64) + .unwrap_or(0) +} + +fn visible(name: &str) -> bool { + !name.starts_with('.') && !GENERATED.contains(&name) +} + +/// The project at `dir`, or `None` when it holds none of the [`MARKERS`]. +fn project(dir: &Path) -> Option { + let mut found = false; + let mut modified = millis(dir); + for marker in MARKERS { + let path = dir.join(marker); + if path.exists() { + found = true; + modified = modified.max(millis(&path)); + } + } + let name = dir.file_name()?.to_string_lossy().into_owned(); + found.then(|| Project { name, path: dir.to_path_buf(), modified }) +} + +fn subfolders(dir: &Path) -> Vec { + let Ok(read) = fs::read_dir(dir) else { + return Vec::new(); + }; + let mut out: Vec = read + .flatten() + .filter(|e| visible(&e.file_name().to_string_lossy())) + .map(|e| e.path()) + .filter(|p| p.is_dir()) + .collect(); + out.sort(); + out +} + +/// The projects in `places` (folders under `home`), at most two folders down, newest first. `limit` caps the answer. +pub fn discover_in(home: &Path, places: &[&str], limit: usize) -> Vec { + let mut seen = 0usize; + let mut found: Vec = Vec::new(); + 'places: for place in places { + let root = home.join(place); + for child in subfolders(&root) { + seen += 1; + if seen > BUDGET { + break 'places; + } + if let Some(p) = project(&child) { + found.push(p); + continue; + } + for grandchild in subfolders(&child) { + seen += 1; + if seen > BUDGET { + break 'places; + } + if let Some(p) = project(&grandchild) { + found.push(p); + } + } + } + } + found.sort_by(|a, b| b.modified.cmp(&a.modified).then_with(|| a.path.cmp(&b.path))); + found.dedup_by(|a, b| a.path == b.path); + found.truncate(limit); + found +} + +/// The projects under `home`, in the usual places ([`PLACES`]), newest first, at most [`LIMIT`]. +pub fn discover(home: &Path) -> Vec { + discover_in(home, PLACES, LIMIT) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::{Duration, SystemTime}; + + fn now() -> u64 { + SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as u64 + } + + fn touch(path: &Path, age: u64) { + let file = fs::OpenOptions::new().write(true).open(path).unwrap(); + file.set_modified(SystemTime::now() - Duration::from_secs(age)).unwrap(); + } + + fn mark(dir: &Path, marker: &str, age: u64) { + fs::create_dir_all(dir).unwrap(); + let path = dir.join(marker); + fs::write(&path, b"{}").unwrap(); + touch(&path, age); + let folder = fs::File::open(dir).unwrap(); + folder.set_modified(SystemTime::now() - Duration::from_secs(age)).unwrap(); + } + + fn names(found: &[Project]) -> Vec<&str> { + found.iter().map(|p| p.name.as_str()).collect() + } + + #[test] + fn finds_projects_one_and_two_folders_down_newest_first() { + let home = tempfile::tempdir().unwrap(); + mark(&home.path().join("work/shop"), "package.json", 300); + mark(&home.path().join("work/hanzo/desktop"), "Cargo.toml", 100); + mark(&home.path().join("Documents/blog"), "index.html", 200); + let found = discover(home.path()); + assert_eq!(names(&found), ["desktop", "blog", "shop"]); + assert_eq!(found[0].path, home.path().join("work/hanzo/desktop")); + assert!(found[0].modified > found[1].modified); + } + + #[test] + fn a_git_checkout_counts_and_a_folder_of_notes_does_not() { + let home = tempfile::tempdir().unwrap(); + fs::create_dir_all(home.path().join("code/api/.git")).unwrap(); + fs::create_dir_all(home.path().join("code/notes")).unwrap(); + fs::write(home.path().join("code/notes/todo.txt"), b"x").unwrap(); + assert_eq!(names(&discover(home.path())), ["api"]); + } + + #[test] + fn never_looks_inside_a_project_nor_deeper_than_two_folders() { + let home = tempfile::tempdir().unwrap(); + mark(&home.path().join("work/mono"), "package.json", 10); + mark(&home.path().join("work/mono/packages/inner"), "package.json", 5); + mark(&home.path().join("work/a/b/too-deep"), "package.json", 5); + assert_eq!(names(&discover(home.path())), ["mono"]); + } + + #[test] + fn skips_hidden_and_generated_folders_and_places_that_are_not_there() { + let home = tempfile::tempdir().unwrap(); + mark(&home.path().join("work/.cache/hidden"), "package.json", 5); + mark(&home.path().join("work/vendor"), "package.json", 5); + mark(&home.path().join("work/ok/node_modules"), "package.json", 5); + mark(&home.path().join("Library/Caches/x"), "package.json", 5); + mark(&home.path().join("work/real"), "package.json", 5); + assert_eq!(names(&discover(home.path())), ["real"]); + assert!(discover(&home.path().join("missing")).is_empty()); + } + + #[test] + fn answers_at_most_the_limit_keeping_the_newest() { + let home = tempfile::tempdir().unwrap(); + for i in 0..8u64 { + mark(&home.path().join(format!("work/p{i}")), "package.json", 100 + i * 10); + } + let found = discover_in(home.path(), PLACES, 3); + assert_eq!(names(&found), ["p0", "p1", "p2"]); + } + + #[test] + fn a_folder_in_two_places_is_listed_once() { + let home = tempfile::tempdir().unwrap(); + mark(&home.path().join("work/shop"), "package.json", 5); + let found = discover_in(home.path(), &["work", "work"], LIMIT); + assert_eq!(names(&found), ["shop"]); + } + + #[test] + fn a_projects_time_is_the_newest_of_it_and_its_marker() { + let home = tempfile::tempdir().unwrap(); + let dir = home.path().join("work/shop"); + mark(&dir, "package.json", 1000); + touch(&dir.join("package.json"), 10); + let found = discover(home.path()); + assert!(now() - found[0].modified < 60_000); + } +} diff --git a/apps/hanzo-desktop/src-tauri/src/commands/local_workspace.rs b/apps/hanzo-desktop/src-tauri/src/commands/local_workspace.rs index 477184f2..d6bd3aab 100644 --- a/apps/hanzo-desktop/src-tauri/src/commands/local_workspace.rs +++ b/apps/hanzo-desktop/src-tauri/src/commands/local_workspace.rs @@ -1,7 +1,11 @@ use std::fs; +use std::io::Write; use std::path::{Path, PathBuf}; -use std::process::Command; +use std::process::{Command, Stdio}; +use futures_util::StreamExt; +use once_cell::sync::Lazy; use serde::{Deserialize, Serialize}; +use tauri::{Emitter, Manager}; use tauri_plugin_dialog::DialogExt; #[derive(Debug, Serialize, Deserialize)] @@ -19,13 +23,31 @@ pub struct LocalWorkspaceInfo { pub path: String, } +/// What a run in a folder answers with: the agent's final message (`output`), what it did on the way +/// (`process`, its log), and whether it finished. The app shows the answer, and the process only to +/// someone who turned Developer mode on. #[derive(Debug, Serialize, Deserialize)] pub struct DevRunResult { pub session_id: String, pub output: String, + pub process: String, pub success: bool, } +/// A project folder found on this computer, for Auto to pick from. `modified` is ms since the epoch. +#[derive(Debug, Serialize, Deserialize)] +pub struct LocalFolder { + pub name: String, + pub path: String, + pub modified: u64, +} + +/// The event the window hears while Hanzo Dev is fetched: `{ "percent": 0..100 }`. +const SETUP_EVENT: &str = "local-dev-setup"; + +/// One fetch at a time: a second run that needs the agent waits for the first run's download. +static SETUP: Lazy> = Lazy::new(|| tokio::sync::Mutex::new(())); + #[tauri::command] pub async fn local_workspace_open_dialog(app: tauri::AppHandle) -> Result, String> { let (tx, rx) = tokio::sync::oneshot::channel(); @@ -210,46 +232,205 @@ pub async fn local_workspace_delete(path: String) -> Result<(), String> { } } -#[tauri::command] -pub async fn local_workspace_run_dev(workspace_path: String, prompt: String) -> Result { - let dev_bin = std::env::var("HANZO_DEV_BIN") - .map(PathBuf::from) - .unwrap_or_else(|_| { - let user_home = dirs::home_dir().unwrap_or_default(); - let local_bin = user_home.join(".local/bin/dev"); - if local_bin.exists() { - local_bin - } else { - let cargo_bin = user_home.join(".cargo/bin/dev"); - if cargo_bin.exists() { - cargo_bin - } else { - PathBuf::from("dev") - } +/// Where the app keeps what it fetched. +fn data_dir(app: &tauri::AppHandle) -> Result { + app.path().app_data_dir().map_err(|e| e.to_string()) +} + +fn say_setup(app: &tauri::AppHandle, percent: u8) { + let _ = app.emit(SETUP_EVENT, serde_json::json!({ "percent": percent })); +} + +/// The agent a run uses: the computer's own `dev` when it has one, else the copy the app fetched. +fn found_dev(own_copy: &Path) -> Option { + hanzo_dev_agent::resolve( + std::env::var_os(hanzo_dev_agent::OVERRIDE_VAR).as_deref(), + dirs::home_dir().as_deref(), + own_copy, + std::env::var_os("PATH").as_deref(), + ) +} + +/// The agent to run, fetching Hanzo Dev first when the computer has none: no terminal, no install step +/// for the person to find. The window hears `local-dev-setup` while it downloads. +async fn dev_bin(app: &tauri::AppHandle) -> Result { + let data = data_dir(app)?; + let own_copy = hanzo_dev_agent::own(&data); + if let Some(bin) = found_dev(&own_copy) { + return Ok(bin); + } + let _one_at_a_time = SETUP.lock().await; + if let Some(bin) = found_dev(&own_copy) { + return Ok(bin); + } + if let Err(e) = fetch_dev(app, &own_copy).await { + log::warn!("Hanzo Dev setup failed: {e}"); + return Err(e.plain()); + } + Ok(own_copy) +} + +/// Why Hanzo Dev could not be set up. `plain` is what the person reads; `Display` is the log's. +#[derive(Debug)] +enum SetupError { + Unsupported, + Network(String), + Mismatch, + Unpack(String), +} + +impl SetupError { + fn plain(&self) -> String { + match self { + SetupError::Unsupported => "Hanzo Dev is not available for this kind of computer yet.".to_string(), + SetupError::Network(_) => "Hanzo Dev could not be downloaded. Check your internet connection and try again.".to_string(), + SetupError::Mismatch => "The download of Hanzo Dev did not check out, so it was not used. Try again.".to_string(), + SetupError::Unpack(_) => "Hanzo Dev could not be set up on this computer. Try again.".to_string(), + } + } +} + +impl std::fmt::Display for SetupError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + SetupError::Unsupported => write!(f, "no release for this computer"), + SetupError::Network(why) => write!(f, "download failed: {why}"), + SetupError::Mismatch => write!(f, "checksum mismatch"), + SetupError::Unpack(why) => write!(f, "unpack failed: {why}"), + } + } +} + +/// Downloads the pinned release, checks it against the checksum published beside it, and unpacks the +/// one program it holds to `dest`. The download is 0-90%, checking and unpacking the rest. +async fn fetch_dev(app: &tauri::AppHandle, dest: &Path) -> Result<(), SetupError> { + let asset = hanzo_dev_agent::here().ok_or(SetupError::Unsupported)?; + let net = |e: reqwest::Error| SetupError::Network(e.to_string()); + let io = |e: std::io::Error| SetupError::Unpack(e.to_string()); + let client = reqwest::Client::new(); + say_setup(app, 0); + + let digest = client.get(asset.digest_url()).send().await.and_then(|r| r.error_for_status()).map_err(net)?.text().await.map_err(net)?; + let expected = hanzo_dev_agent::expected(&digest).ok_or_else(|| SetupError::Network("no checksum published".to_string()))?; + + let dir = dest.parent().ok_or_else(|| SetupError::Unpack("no folder".to_string()))?; + fs::create_dir_all(dir).map_err(io)?; + let archive = dir.join(asset.name); + let result = download_and_unpack(app, &client, &asset, &expected, &archive, dest).await; + let _ = fs::remove_file(&archive); + result?; + + // Older pins are let go once the pinned one is in place. + if let Some(all) = dir.parent() { + for old in fs::read_dir(all).into_iter().flatten().flatten() { + if old.path() != dir { + let _ = fs::remove_dir_all(old.path()); } - }); + } + } + say_setup(app, 100); + Ok(()) +} - let output = Command::new(&dev_bin) - .arg("exec") - .arg("--skip-git-repo-check") - .arg("-C") - .arg(&workspace_path) - .arg(&prompt) - .output() - .map_err(|e| format!("Failed to invoke dev at {:?}: {}", dev_bin, e))?; +async fn download_and_unpack( + app: &tauri::AppHandle, + client: &reqwest::Client, + asset: &hanzo_dev_agent::Asset, + expected: &str, + archive: &Path, + dest: &Path, +) -> Result<(), SetupError> { + let net = |e: reqwest::Error| SetupError::Network(e.to_string()); + let res = client.get(asset.url()).send().await.and_then(|r| r.error_for_status()).map_err(net)?; + let total = res.content_length().unwrap_or(0); + let mut file = fs::File::create(archive).map_err(|e| SetupError::Unpack(e.to_string()))?; + let mut stream = res.bytes_stream(); + let (mut got, mut shown) = (0u64, 0u8); + while let Some(chunk) = stream.next().await { + let chunk = chunk.map_err(net)?; + file.write_all(&chunk).map_err(|e| SetupError::Unpack(e.to_string()))?; + got += chunk.len() as u64; + if total > 0 { + let percent = ((got * 90) / total).min(90) as u8; + if percent != shown { + shown = percent; + say_setup(app, percent); + } + } + } + file.flush().map_err(|e| SetupError::Unpack(e.to_string()))?; + drop(file); - let stdout = String::from_utf8_lossy(&output.stdout).to_string(); - let stderr = String::from_utf8_lossy(&output.stderr).to_string(); - let combined = if stderr.is_empty() { - stdout - } else { - format!("{}\n{}", stdout, stderr) - }; + let (archive, dest, expected, kind) = (archive.to_path_buf(), dest.to_path_buf(), expected.to_string(), asset.kind); + tokio::task::spawn_blocking(move || { + if !hanzo_dev_agent::verify(&archive, &expected).map_err(|e| SetupError::Unpack(e.to_string()))? { + return Err(SetupError::Mismatch); + } + hanzo_dev_agent::unpack(&archive, kind, &dest).map_err(|e| SetupError::Unpack(e.to_string())) + }) + .await + .map_err(|e| SetupError::Unpack(e.to_string()))? +} - let session_id = format!("local_{}", uuid::Uuid::new_v4()); +#[tauri::command] +pub async fn local_workspace_run_dev(app: tauri::AppHandle, workspace_path: String, prompt: String) -> Result { + if !Path::new(&workspace_path).is_dir() { + return Err(format!("The folder {workspace_path} is not on this computer any more. Choose another folder.")); + } + let dev = dev_bin(&app).await?; + let last = std::env::temp_dir().join(format!("hanzo-dev-{}.txt", uuid::Uuid::new_v4())); + let (bin, folder, said, last_message) = (dev, workspace_path, prompt, last.clone()); + let output = tokio::task::spawn_blocking(move || { + let mut run = Command::new(bin); + // The agent works in the folder and nowhere else (workspace-write), with no colour codes in what it + // prints, and its final message in a file of its own. `--` keeps a prompt that starts with a dash + // from being read as an option. + run.args(["exec", "--color", "never", "--skip-git-repo-check", "-s", "workspace-write", "-C"]) + .arg(&folder) + .arg("-o") + .arg(&last_message) + .arg("--") + .arg(&said) + .stdin(Stdio::null()); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + run.creation_flags(0x0800_0000); + } + run.output() + }) + .await + .map_err(|e| e.to_string())? + .map_err(|e| format!("Hanzo Dev could not start on this computer: {e}"))?; + + let final_message = fs::read_to_string(&last).ok(); + let _ = fs::remove_file(&last); + let outcome = hanzo_dev_agent::outcome( + final_message.as_deref(), + &String::from_utf8_lossy(&output.stdout), + &String::from_utf8_lossy(&output.stderr), + ); Ok(DevRunResult { - session_id, - output: combined, + session_id: format!("local_{}", uuid::Uuid::new_v4()), + output: outcome.output, + process: outcome.process, success: output.status.success(), }) } + +/// The project folders found where people keep them (Documents, Projects, work, code, ...), newest first. +/// Auto picks from these and from the folders Hanzo opened. +#[tauri::command] +pub async fn local_workspace_discover() -> Result, String> { + let Some(home) = dirs::home_dir() else { + return Ok(Vec::new()); + }; + tokio::task::spawn_blocking(move || { + hanzo_projects::discover(&home) + .into_iter() + .map(|p| LocalFolder { name: p.name, path: p.path.to_string_lossy().into_owned(), modified: p.modified }) + .collect() + }) + .await + .map_err(|e| e.to_string()) +} diff --git a/apps/hanzo-desktop/src-tauri/src/main.rs b/apps/hanzo-desktop/src-tauri/src/main.rs index dfc6561e..94486ca4 100644 --- a/apps/hanzo-desktop/src-tauri/src/main.rs +++ b/apps/hanzo-desktop/src-tauri/src/main.rs @@ -53,7 +53,7 @@ use crate::commands::local_workspace::{ local_workspace_open_dialog, local_workspace_open_file_dialog, local_workspace_clone_repo, local_workspace_import_file, local_workspace_list, local_workspace_read_file, local_workspace_write_file, local_workspace_create_file, local_workspace_create_dir, - local_workspace_delete, local_workspace_run_dev, + local_workspace_delete, local_workspace_discover, local_workspace_run_dev, }; use crate::mining::MiningManager; use crate::model_tools::{ @@ -284,6 +284,7 @@ fn main() { local_workspace_create_dir, local_workspace_delete, local_workspace_run_dev, + local_workspace_discover, #[cfg(feature = "machine")] machine::commands::machine_health, #[cfg(feature = "machine")] diff --git a/hanzo.yml b/hanzo.yml index 83477486..869b61ed 100644 --- a/hanzo.yml +++ b/hanzo.yml @@ -57,6 +57,18 @@ test: run: | set -e cargo test --locked --manifest-path apps/hanzo-desktop/src-tauri/engine-bin/Cargo.toml + # Hanzo Dev on this computer: where the app finds it, the release it fetches + # when there is none, the checksum it checks, the binary it unpacks, and how a + # run's answer is told from its log. Pure Rust, no Tauri or system libraries. + - name: dev-agent + run: | + set -e + cargo test --locked --manifest-path apps/hanzo-desktop/src-tauri/dev-agent/Cargo.toml + # The project folders Auto can pick from (Documents, work, code, ...). Pure Rust. + - name: projects + run: | + set -e + cargo test --locked --manifest-path apps/hanzo-desktop/src-tauri/projects/Cargo.toml # No secret-bearing value may be printed or logged from the Tauri crate: # whole-call (multiline) scan plus Debug-format of credential-like values. # The self-test proves the scanner still catches the shapes it must.