diff --git a/crates/pipdock-core/src/envs/mod.rs b/crates/pipdock-core/src/envs/mod.rs index 3f28449..447d124 100644 --- a/crates/pipdock-core/src/envs/mod.rs +++ b/crates/pipdock-core/src/envs/mod.rs @@ -211,8 +211,116 @@ pub struct Candidate { /// Sources are queried independently and merged by canonical identity, so a Chocolatey shim and /// the installation it points at collapse into one entry (SP-6). The **first** source to report a /// path wins, and sources are ordered so the more authoritative one is asked first. +/// +/// Discovery alone: interpreters a person added are not here. Code Health's choice of a Python to +/// build its tools venv with reads this, and should choose among installations, not among whatever +/// the user pointed the Environments screen at. pub async fn scan() -> Vec { - scan_reporting(&|_| {}).await + scan_reporting(&[], &|_| {}).await +} + +/// Discovery plus the interpreters a person added (*Browse…*, `pipdock env add`), for the two +/// listings — the Environments screen and `pipdock env list`. +pub async fn scan_with(manual: &[PathBuf]) -> Vec { + scan_reporting(manual, &|_| {}).await +} + +/// Refuse an interpreter path a person supplied before anything runs it (SECURITY §2). +/// +/// Discovery finds interpreters where Python installs them. A path from *Browse…*, `pipdock env +/// add`, `env use` or `--env` can name anything, and the probe **runs** the file — so this is the +/// enforcement point, not the picker, which only suggests: +/// +/// - it must exist and be a file, or there is nothing to probe; +/// - its name must be `python.exe`, `python3.exe` or `python3.12.exe` (`python`, `python3`, … off +/// Windows), so that adding an interpreter is not a way to start any program with PipDock's +/// arguments. `pythonw.exe` is refused too: it has no console, the probe's output would be empty, +/// and the failure would read as a broken environment instead of the wrong file; +/// - it must not be one of PipDock's own environments — Code Health's tools venv or the Security +/// tab's audit venv — which PipDock builds and replaces itself, and which a user's update would +/// quietly break. The check is on canonical paths, or `..` would walk past it. +/// +/// Returns the canonical path without Windows' verbatim prefix, which is what is stored and shown. +/// +/// # Errors +/// `PD-ENV-001` for each refusal, the message saying which. A missing file reads exactly as the +/// probe's own "no interpreter at …", so a caller that validates first changes no output. +pub fn validate_interpreter(path: &Path, app_data: &Path) -> Result { + let refuse = |why: String| PdError::new(Code::EnvInterpreterMissing, why); + if !path.is_file() { + return Err(refuse(format!("no interpreter at {}", path.display()))); + } + if !is_python_name(path) { + return Err(refuse(format!( + "{} is not a Python interpreter PipDock will run: the file has to be python.exe \ + (or python3.exe, python3.12.exe)", + path.display() + ))); + } + let canonical = path + .canonicalize() + .map(crate::health::project::plain) + .map_err(|e| refuse(format!("cannot read {}: {e}", path.display())))?; + for own in [ + crate::health::tools_dir(app_data), + crate::health::audit_dir(app_data), + ] { + if let Ok(own) = own.canonicalize().map(crate::health::project::plain) + && canonical.starts_with(&own) + { + return Err(refuse(format!( + "{} is one of PipDock's own environments, which it manages itself", + path.display() + ))); + } + } + Ok(canonical) +} + +/// `python`, `python3` or `python3.12`, with `.exe` on Windows; any case. +fn is_python_name(path: &Path) -> bool { + let Some(name) = path.file_name().and_then(|n| n.to_str()) else { + return false; + }; + let name = name.to_ascii_lowercase(); + let stem = if cfg!(windows) { + match name.strip_suffix(".exe") { + Some(stem) => stem, + None => return false, + } + } else { + name.as_str() + }; + let Some(version) = stem.strip_prefix("python") else { + return false; + }; + version.is_empty() + || (version.split('.').count() <= 2 + && version + .split('.') + .all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit()))) +} + +/// An interpreter path, or the interpreter inside an environment directory (CLI-SPEC §2). +/// +/// `\Scripts\python.exe` on Windows, `/bin/python` elsewhere; anything else comes back +/// unchanged, for [`validate_interpreter`] to refuse with the path the person gave. +#[must_use] +pub fn interpreter_in(path: &Path) -> PathBuf { + if path.is_file() { + return path.to_path_buf(); + } + let exe: PathBuf = if cfg!(windows) { + ["Scripts", "python.exe"].iter().collect() + } else { + ["bin", "python"].iter().collect() + }; + let candidate = path.join(&exe); + if candidate.is_file() { + candidate + } else { + path.to_path_buf() + } } /// Where a discovery sweep currently is. @@ -260,11 +368,21 @@ pub enum ScanPhase { /// How many sources a sweep reads, for the `total` a caller renders against. const SCAN_SOURCES: usize = 5; -/// Discover environments, reporting progress as each source is read. +/// Discover environments, reporting progress as each source is read, and append the interpreters a +/// person added. +/// +/// `manual` comes last, so an interpreter discovery also finds keeps the discovered source — the +/// chip says where Python put it, which is the more useful fact. Unlike every discovered path, a +/// manual one is kept **when its file is gone**: dropping it would make an entry the user added +/// vanish without a word, and with no row there would be nothing to remove it from. Its probe then +/// fails with `PD-ENV-001`, whose remedy is exactly that removal. /// /// The callback is synchronous and must not block: it is called between sources, on the task /// driving the scan. -pub async fn scan_reporting(report: &(dyn Fn(ScanProgress) + Sync)) -> Vec { +pub async fn scan_reporting( + manual: &[PathBuf], + report: &(dyn Fn(ScanProgress) + Sync), +) -> Vec { let step = |phase: ScanPhase, done: usize| ScanProgress { phase, done, @@ -299,8 +417,23 @@ pub async fn scan_reporting(report: &(dyn Fn(ScanProgress) + Sync)) -> Vec, manual: &[PathBuf]) -> Vec { + let mut seen: std::collections::HashSet = found.keys().cloned().collect(); + let mut out: Vec = found.into_values().collect(); + for path in manual { + if seen.insert(canonical_interpreter(path)) { + out.push(Candidate { + path: path.clone(), + source: EnvSource::Manual, + }); + } + } + out } /// PEP 514 registry entries: `HKCU`, and both views of `HKLM`. @@ -465,6 +598,176 @@ mod tests { } } + fn scratch(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("pd-envs-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("create scratch dir"); + dir + } + + /// An empty file at `dir/rel`, which is all [`validate_interpreter`] looks at — it never runs it. + fn touch(dir: &Path, rel: &str) -> PathBuf { + let path = dir.join(rel); + std::fs::create_dir_all(path.parent().expect("a parent")).expect("parents"); + std::fs::write(&path, "").expect("write"); + path + } + + fn exe(stem: &str) -> String { + if cfg!(windows) { + format!("{stem}.exe") + } else { + stem.to_owned() + } + } + + #[test] + fn only_a_file_named_like_python_is_accepted() { + for name in ["python", "PYTHON", "python3", "python3.12", "Python3.14"] { + assert!(is_python_name(Path::new(&exe(name))), "{name}"); + } + // pythonw has no console; the rest are other programs, or versions that are not versions. + for name in [ + "pythonw", + "notepad", + "py", + "python3.12.1", + "python3.", + "python.3", + "python3x", + "mypython", + ] { + assert!(!is_python_name(Path::new(&exe(name))), "{name}"); + } + if cfg!(windows) { + assert!( + !is_python_name(Path::new("python.bat")), + "a script is not an exe" + ); + assert!( + !is_python_name(Path::new("python")), + "Windows needs the .exe" + ); + } + } + + #[test] + fn a_missing_interpreter_reads_exactly_as_the_probe_says_it() { + // The CLI's error-envelope goldens pin this sentence for `--env C:/definitely/not/here`. + let err = validate_interpreter(Path::new("C:/definitely/not/here"), &scratch("missing")) + .expect_err("nothing there"); + assert_eq!(err.code, Code::EnvInterpreterMissing); + assert_eq!(err.message, "no interpreter at C:/definitely/not/here"); + } + + #[test] + fn another_program_is_refused_before_anything_runs_it() { + let dir = scratch("other"); + let notepad = touch(&dir, &exe("notepad")); + let err = validate_interpreter(¬epad, &dir.join("data")).expect_err("not python"); + assert_eq!(err.code, Code::EnvInterpreterMissing); + assert!( + err.message.contains("is not a Python interpreter"), + "{}", + err.message + ); + } + + #[test] + fn a_python_is_accepted_and_comes_back_canonical_and_plain() { + let dir = scratch("ok"); + let python = touch(&dir, &format!("proj/.venv/Scripts/{}", exe("python"))); + let got = validate_interpreter(&python, &dir.join("data")).expect("a python"); + assert!( + !got.display().to_string().starts_with(r"\\?\"), + "no verbatim prefix: {}", + got.display() + ); + assert_eq!( + got, + crate::health::project::plain(python.canonicalize().expect("canonical")) + ); + } + + #[test] + fn pipdocks_own_environments_are_refused_even_through_dot_dot() { + let dir = scratch("own"); + let app_data = dir.join("data"); + for own in ["tools", "audit"] { + let python = touch(&app_data, &format!("{own}/.venv/Scripts/{}", exe("python"))); + let err = validate_interpreter(&python, &app_data).expect_err("PipDock's own"); + assert!(err.message.contains("PipDock's own"), "{}", err.message); + + // Reached the long way round: canonicalized before the comparison, or `..` walks past. + let sideways = app_data + .join("elsewhere") + .join("..") + .join(own) + .join(".venv") + .join("Scripts") + .join(exe("python")); + std::fs::create_dir_all(app_data.join("elsewhere")).expect("dir"); + let err = validate_interpreter(&sideways, &app_data).expect_err("still PipDock's own"); + assert!(err.message.contains("PipDock's own"), "{}", err.message); + } + // A sibling whose name merely starts with "tools" is someone else's. + let neighbour = touch(&app_data, &format!("tools-mine/{}", exe("python"))); + validate_interpreter(&neighbour, &app_data).expect("not inside tools"); + } + + #[test] + fn an_environment_directory_resolves_to_its_interpreter() { + let dir = scratch("dir"); + let inside = if cfg!(windows) { + format!("venv/Scripts/{}", exe("python")) + } else { + "venv/bin/python".to_owned() + }; + let python = touch(&dir, &inside); + assert_eq!(interpreter_in(&dir.join("venv")), python); + assert_eq!(interpreter_in(&python), python, "a file is itself"); + let nothing = dir.join("nothing-here"); + assert_eq!( + interpreter_in(¬hing), + nothing, + "left for the validator to refuse" + ); + } + + #[test] + fn manual_entries_come_last_and_never_shadow_discovery() { + let discovered = PathBuf::from(r"C:\Python314\python.exe"); + let mut found = BTreeMap::new(); + found.insert( + canonical_interpreter(&discovered), + Candidate { + path: discovered.clone(), + source: EnvSource::Registry, + }, + ); + let manual = [ + PathBuf::from(r"D:\work\proj\myenv\Scripts\python.exe"), + // The same interpreter the registry reported, in other casing: discovery keeps it. + PathBuf::from(r"c:\python314\python.exe"), + // Added twice, listed once. + PathBuf::from(r"D:\work\proj\myenv\Scripts\python.exe"), + // Gone from disk: still listed, so it can be removed. + PathBuf::from(r"E:\gone\python.exe"), + ]; + let merged = merge_manual(found, &manual); + let sources: Vec<_> = merged.iter().map(|c| (c.path.clone(), c.source)).collect(); + let mut expected = vec![(discovered, EnvSource::Registry)]; + if !cfg!(windows) { + // Off Windows the casing differs, so the second is its own interpreter. + expected.push((manual[0].clone(), EnvSource::Manual)); + expected.push((manual[1].clone(), EnvSource::Manual)); + } else { + expected.push((manual[0].clone(), EnvSource::Manual)); + } + expected.push((manual[3].clone(), EnvSource::Manual)); + assert_eq!(sources, expected); + } + #[test] fn env_hash_is_stable_and_case_insensitive_on_windows() { // SP-6: the Chocolatey shim and the direct install differ only in casing. Two hashes for diff --git a/crates/pipdock-core/src/store/mod.rs b/crates/pipdock-core/src/store/mod.rs index c383ca1..ec0dd15 100644 --- a/crates/pipdock-core/src/store/mod.rs +++ b/crates/pipdock-core/src/store/mod.rs @@ -20,7 +20,7 @@ use crate::errors::{Code, PdError, Result}; pub const DB_FILE: &str = "index.db"; /// Schema version this build expects. Bump when adding a migration. -pub const SCHEMA_VERSION: i64 = 4; +pub const SCHEMA_VERSION: i64 = 5; /// An open store. #[derive(Debug)] @@ -192,6 +192,16 @@ impl Store { version TEXT NOT NULL, requires_python TEXT, PRIMARY KEY (normalized, version) + ); + + -- v5. Interpreters a person added - Browse... in the GUI, `pipdock env add` in the + -- CLI - for discovery to list beside its own (PRD P0-1). Not the `envs` table: + -- that is the CLI's recents and its starred default, and adding an interpreter to + -- the list is not choosing it. Same env_hash as everywhere, case-folded (SP-6). + CREATE TABLE IF NOT EXISTS manual_envs ( + env_hash TEXT PRIMARY KEY, + interpreter TEXT NOT NULL, + added_at TEXT NOT NULL );", ) .map_err(sql)?; @@ -203,6 +213,17 @@ impl Store { } } +/// An interpreter a person added with *Browse…* or `pipdock env add`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ManualEnv { + /// Identity, case-folded (SP-6). + pub env_hash: String, + /// The canonical interpreter path, as stored. + pub interpreter: String, + /// RFC 3339, which orders the list. + pub added_at: String, +} + /// A remembered environment (ARCHITECTURE §6, PRD P0-1 "recents persisted"). #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct RecentEnv { @@ -285,6 +306,67 @@ impl Store { Ok(self.recent_envs()?.into_iter().find(|e| e.is_default)) } + /// Put an interpreter a person added on the list (PRD P0-1's manual browse). + /// + /// Adding one that is already there keeps its place and its date — the list is in the order + /// things were added, and adding again is not a new addition — but takes the path as given + /// this time, which is the canonical one [`crate::envs::validate_interpreter`] returned. + /// + /// # Errors + /// `PD-INT-001` when the write fails. + pub fn add_manual_env(&self, env_hash: &str, interpreter: &str, now: &str) -> Result<()> { + self.conn + .execute( + "INSERT INTO manual_envs (env_hash, interpreter, added_at) VALUES (?1, ?2, ?3) + ON CONFLICT (env_hash) DO UPDATE SET interpreter = excluded.interpreter", + rusqlite::params![env_hash, interpreter, now], + ) + .map_err(|e| PdError::new(Code::IntUnexpected, format!("manual env store: {e}")))?; + Ok(()) + } + + /// The interpreters a person added, oldest first. + /// + /// # Errors + /// `PD-INT-001` when the read fails. + pub fn manual_envs(&self) -> Result> { + let err = |e: rusqlite::Error| { + PdError::new(Code::IntUnexpected, format!("manual env store: {e}")) + }; + let mut stmt = self + .conn + .prepare( + "SELECT env_hash, interpreter, added_at FROM manual_envs + ORDER BY added_at, rowid", + ) + .map_err(err)?; + let rows = stmt + .query_map([], |r| { + Ok(ManualEnv { + env_hash: r.get(0)?, + interpreter: r.get(1)?, + added_at: r.get(2)?, + }) + }) + .map_err(err)?; + rows.collect::, _>>() + .map_err(err) + } + + /// Take an interpreter off the list. Only the entry goes: nothing on disk is touched, and the + /// pins, snapshots and Health folder keyed to the same `env_hash` stay, ready for the day it + /// is added — or discovered — again. + /// + /// # Errors + /// `PD-INT-001` when the write fails. `Ok(false)` when it was not on the list. + pub fn remove_manual_env(&self, env_hash: &str) -> Result { + let removed = self + .conn + .execute("DELETE FROM manual_envs WHERE env_hash = ?1", [env_hash]) + .map_err(|e| PdError::new(Code::IntUnexpected, format!("manual env store: {e}")))?; + Ok(removed > 0) + } + /// The project folder Code Health last ran in for this environment (CODE-HEALTH-SPEC §3). /// /// Per environment, because deptry compares declared dependencies against what is *installed* @@ -351,7 +433,14 @@ mod tests { .filter_map(std::result::Result::ok) .collect(); - for expected in ["envs", "health_projects", "meta_cache", "names", "pins"] { + for expected in [ + "envs", + "health_projects", + "manual_envs", + "meta_cache", + "names", + "pins", + ] { assert!( tables.contains(&expected.to_owned()), "missing {expected}: {tables:?}" @@ -458,4 +547,87 @@ mod tests { ) .expect("the v4 table exists"); } + + #[test] + fn a_v4_store_gains_the_manual_list_and_keeps_its_data() { + let store = Store::in_memory().expect("open"); + store + .remember_env("h1", r"C:\a\python.exe", "2026-11-01T00:00:00Z", true) + .expect("a CLI default from 1.5.0"); + store + .conn() + .execute_batch("DROP TABLE manual_envs; PRAGMA user_version = 4;") + .expect("rewind to v4"); + store.migrate().expect("migrate"); + assert!(store.manual_envs().expect("the v5 table exists").is_empty()); + assert_eq!( + store.default_env().expect("read").map(|e| e.env_hash), + Some("h1".to_owned()), + "the migration does not touch what was there" + ); + } + + #[test] + fn the_manual_list_keeps_its_order_and_takes_no_duplicates() { + let store = Store::in_memory().expect("open"); + store + .add_manual_env("b", r"D:\b\python.exe", "2026-11-02T00:00:00Z") + .expect("add"); + store + .add_manual_env("a", r"D:\a\python.exe", "2026-11-03T00:00:00Z") + .expect("add"); + // Added again, later and spelled differently: one entry, first place, the new spelling. + store + .add_manual_env("b", r"D:\B\python.exe", "2026-11-04T00:00:00Z") + .expect("add again"); + + let listed = store.manual_envs().expect("read"); + assert_eq!( + listed + .iter() + .map(|m| ( + m.env_hash.as_str(), + m.interpreter.as_str(), + m.added_at.as_str() + )) + .collect::>(), + [ + ("b", r"D:\B\python.exe", "2026-11-02T00:00:00Z"), + ("a", r"D:\a\python.exe", "2026-11-03T00:00:00Z"), + ] + ); + } + + #[test] + fn removing_from_the_manual_list_touches_nothing_else() { + let store = Store::in_memory().expect("open"); + store + .add_manual_env("h", r"D:\p\python.exe", "2026-11-02T00:00:00Z") + .expect("add"); + store + .remember_env("h", r"D:\p\python.exe", "2026-11-02T00:00:00Z", true) + .expect("also the CLI default"); + store + .set_health_project("h", r"D:\p", "2026-11-02T00:00:00Z") + .expect("and Health's folder"); + + assert!( + store.remove_manual_env("h").expect("remove"), + "it was there" + ); + assert!( + !store.remove_manual_env("h").expect("again"), + "and is not now" + ); + assert!(store.manual_envs().expect("read").is_empty()); + assert!( + store.default_env().expect("read").is_some(), + "the CLI default is another list" + ); + assert_eq!( + store.health_project("h").expect("read").as_deref(), + Some(r"D:\p"), + "keyed data outlives the entry" + ); + } } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 0bc133c..4773aaa 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -140,7 +140,8 @@ From `requires_dist` the core builds the **reverse-dependency graph** used by: h ## 6. Storage (`%LOCALAPPDATA%\PipDock\data\`) ```text -index.db # SQLite, schema v4: names, meta_cache, envs (recents, default), +index.db # SQLite, schema v5: names, meta_cache, envs (the CLI's recents, default), + # manual_envs (interpreters added with Browse… or `env add`, v5), # pins(env_hash, pkg, mode, version, reason), health_projects, # kv (settings, consent, index refresh stamp), release_meta snapshots//.freeze.txt + .meta.json # id: 20261016T145809-423560600Z @@ -169,8 +170,9 @@ This table is the surface. A command that is not listed here does not exist; add |---|---|---| | `app_info` | `AppInfo` | PipDock's version, and the hash of the legal documents this build ships against. | | `env_scan` | `EnvRow[]` | Discover environments, streaming `scan-progress`. A probe failure is reported on its own row, never fatal to the scan. Carries `pipVersion` and `healthProject`, both read before the probe loop so the store guard is never held across a probe. Probes run four at a time (they ran in series until 1.4.0), each under its own 60 s watchdog, so one hung interpreter costs its own row; rows keep discovery order. | -| `env_add_manual` | `EnvRow` | Persist an interpreter chosen through *Browse…*. **Not implemented** — the one entry left in `NOT_YET` (`src-tauri/src/lib.rs`), owed by M3. | -| `env_probe` | `EnvRow` | Probe one interpreter without persisting it. Takes an optional `source`: absent means *Browse…*, and a **refresh must pass the row's own**, or the row comes back relabelled `manual`. Fills every field `env_scan` does, because `upgradePip` replaces the row wholesale. | +| `env_add_manual` | `EnvRow` | Add an interpreter chosen through *Add interpreter…* (*Browse…*, PRD P0-1) to the list `env_scan` appends to discovery, and return its row (1.6.0; the last entry `NOT_YET` held). `envs::validate_interpreter` first — an existing file named like Python, not one of PipDock's own venvs — then the probe, then the store, so a refused or broken interpreter is never listed. The row carries the canonical path that is stored. | +| `env_remove_manual` | `boolean` | Take an added interpreter off that list, by `envHash`; `false` when it was not on it. Touches nothing on disk, and leaves the pins, snapshots and Health folder keyed to it. | +| `env_probe` | `EnvRow` | Probe one interpreter without persisting it. Takes an optional `source`: absent means manual, and a **refresh must pass the row's own**, or the row comes back relabelled `manual`. A `manual` path is validated as `env_add_manual` validates one. Fills every field `env_scan` does, because `upgradePip` replaces the row wholesale. | | `env_export` | `string` | Write the environment's `Engine::freeze` document to a user-chosen path and return it (PRD P1-3). Byte for byte, with no formatter: a freeze *is* a requirements file, and a constraints file is the same body under a different name. Rust-side for `health_save_report`'s reason — `dialog:allow-save` asks for a path and grants no `fs`. | | `requirements_read` | `ParsedRequirements` | Read a `requirements.txt` into install specs **and whatever it could not use**. The skipped lines are the point: an include or an editable install means the file asks for something PipDock will not do, and the user has to see that before a preview claims to represent their file. | | `pkg_list` | `Dist[]` | Installed distributions, read from `probe.py` rather than the engine — see §4 and DATA-FLOW §7. | diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index c4fc90d..d98bafa 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -169,8 +169,19 @@ pub async fn env_scan( app: tauri::AppHandle, state: tauri::State<'_, AppState>, ) -> Wire> { + // The interpreters added through *Browse…*, read and the guard dropped before discovery + // spawns anything. A failed read costs those rows this once, not the screen. + let manual: Vec = { + let store = state.store.lock().await; + store + .manual_envs() + .unwrap_or_default() + .into_iter() + .map(|m| std::path::PathBuf::from(m.interpreter)) + .collect() + }; let emitter = app.clone(); - let candidates = envs::scan_reporting(&move |progress: ScanProgress| { + let candidates = envs::scan_reporting(&manual, &move |progress: ScanProgress| { // A UI that stopped listening is not a reason to abandon the scan. let _ = emitter.emit("scan-progress", &progress); }) @@ -240,6 +251,10 @@ pub async fn env_scan( /// now a parameter: `None` is the *Browse…* path, which really is manual; a refresh passes the /// source the row already had. /// +/// A path the webview names as `manual` is checked by [`envs::validate_interpreter`] before the +/// probe runs it, as `env_add_manual` checks one: discovery found the others where Python puts +/// interpreters, and only a manual path can name anything at all. +/// /// # Errors /// `PD-ENV-001` when there is no usable interpreter there, `PD-ENV-003` when the probe output /// cannot be read. @@ -252,6 +267,9 @@ pub async fn env_probe( let path = std::path::PathBuf::from(&interpreter); let env_hash = envs::env_hash(&path); let source = source.unwrap_or(EnvSource::Manual); + if source == EnvSource::Manual { + validated(&state.app_data, path.clone()).await?; + } let folder = { let store = state.store.lock().await; store.health_project(&env_hash).ok().flatten() @@ -272,6 +290,75 @@ pub async fn env_probe( }) } +/// Add an interpreter the person picked with *Browse…* to the list, and return its row (PRD P0-1). +/// +/// Validated, probed, then stored — in that order, so the list never gains an entry that was +/// refused or broken on arrival. The row carries the canonical path, which is what is stored and +/// what the next `env_scan` returns, so the screen does not change under the user's eyes. Adding +/// one already listed — by discovery or by an earlier *Browse…* — is not an error: the row comes +/// back, and the frontend merges it by `envHash`. +/// +/// # Errors +/// `PD-ENV-001` when the file is missing, is not named like a Python interpreter, or is one of +/// PipDock's own environments; `PD-ENV-003` when the probe fails; `PD-INT-001` when the store +/// cannot be written. +#[tauri::command] +pub async fn env_add_manual( + state: tauri::State<'_, AppState>, + interpreter: String, +) -> Wire { + let path = validated(&state.app_data, std::path::PathBuf::from(interpreter)).await?; + let env_hash = envs::env_hash(&path); + let folder = { + let store = state.store.lock().await; + store.health_project(&env_hash).ok().flatten() + }; + let probed = envs::probe(&path, EnvSource::Manual).await?; + let shown = path.display().to_string(); + { + let store = state.store.lock().await; + store.add_manual_env(&env_hash, &shown, &jiff::Timestamp::now().to_string())?; + } + Ok(EnvRow { + interpreter: shown, + source: EnvSource::Manual, + env_hash, + packages: Some(probed.dists.len()), + pip_version: pip_version_of(&probed.dists), + health_project: folder, + env: Some(probed.env), + error: None, + }) +} + +/// Take an interpreter off the list *Browse…* put it on. Nothing on disk is touched, and its pins, +/// snapshots and Health folder stay keyed to it for the day it is added again. +/// +/// # Errors +/// `PD-INT-001` when the store cannot be written. `false` when it was not on the list. +#[tauri::command] +pub async fn env_remove_manual(state: tauri::State<'_, AppState>, env_hash: String) -> Wire { + let store = state.store.lock().await; + Ok(store.remove_manual_env(&env_hash)?) +} + +/// [`envs::validate_interpreter`], off the async workers: it reads the file system, which +/// `rust:S7493` keeps out of an `async fn`. +async fn validated( + app_data: &std::path::Path, + path: std::path::PathBuf, +) -> pipdock_core::Result { + let app_data = app_data.to_path_buf(); + tokio::task::spawn_blocking(move || envs::validate_interpreter(&path, &app_data)) + .await + .map_err(|e| { + PdError::new( + pipdock_core::errors::Code::IntUnexpected, + format!("interpreter check stopped: {e}"), + ) + })? +} + /// Everything installed in one environment — the Installed table (UI-SPEC §4). /// /// Goes through `envs::probe`, **not** `Engine::list_installed`. The probe carries diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index fa8dc8c..234f879 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -18,7 +18,7 @@ pub mod window; /// runtime, and typechecked the whole time. This list is what makes the gap explicit instead of /// invisible: a name here is a promise with a date on it, and the test below fails the moment /// `COMMANDS` and reality disagree in either direction. -pub const NOT_YET: &[(&str, &str)] = &[("env_add_manual", "M3 — Browse… has no surface yet")]; +pub const NOT_YET: &[(&str, &str)] = &[]; /// Start the app's own log: `data\logs\pipdock..log`, at `PIPDOCK_LOG` or INFO. /// @@ -140,6 +140,8 @@ pub fn run() { commands::app_info, commands::env_scan, commands::env_probe, + commands::env_add_manual, + commands::env_remove_manual, commands::pkg_list, commands::pkg_outdated, commands::pin_list, @@ -233,7 +235,7 @@ mod tests { "core:event:allow-unlisten", // Decline on the legal gate. "core:window:allow-close", - // Code Health's folder, Import requirements; Save report, Export. + // Code Health's folder, Import requirements, Add interpreter…; Save report, Export. "dialog:allow-open", "dialog:allow-save", // Scoped; see the next test.