diff --git a/.gitignore b/.gitignore index 8cc2fc8..1a2c3b4 100644 --- a/.gitignore +++ b/.gitignore @@ -51,6 +51,11 @@ tauri-signing-private.key* # Logs & scratch *.log +# insta's pending snapshots: review them with `cargo insta review`, never commit them. +*.snap.new +*.pending-snap +# A release's checksums, when downloaded beside the checkout to verify an installer. +/SHA256SUMS.txt /spikes/out/ # Spike tooling venvs (SP-1 needs several uv versions side by side) diff --git a/crates/pipdock-core/Cargo.toml b/crates/pipdock-core/Cargo.toml index 2cf2797..aedf8c6 100644 --- a/crates/pipdock-core/Cargo.toml +++ b/crates/pipdock-core/Cargo.toml @@ -11,6 +11,10 @@ authors.workspace = true [lints] workspace = true +[features] +# `fixtures.rs`: the L3 payloads xtask writes for the frontend's tests. +fixtures = [] + [dependencies] async-trait = "0.1.92" jiff = { version = "0.2.38", features = ["serde"] } diff --git a/crates/pipdock-core/examples/sp3_search.rs b/crates/pipdock-core/examples/sp3_search.rs index 3656d6e..a270507 100644 --- a/crates/pipdock-core/examples/sp3_search.rs +++ b/crates/pipdock-core/examples/sp3_search.rs @@ -13,7 +13,7 @@ //! //! ```text //! pipdock index refresh -//! cargo run --release --example sp3_search -- "%LOCALAPPDATA%\PipDock\index.db" +//! cargo run --release --example sp3_search -- "%LOCALAPPDATA%\PipDock\data\index.db" //! ``` // A measurement harness reports to a human on stdout; the library-level ban does not apply. diff --git a/crates/pipdock-core/src/engine/parse.rs b/crates/pipdock-core/src/engine/parse.rs index 7eaea3f..16573d4 100644 --- a/crates/pipdock-core/src/engine/parse.rs +++ b/crates/pipdock-core/src/engine/parse.rs @@ -457,7 +457,7 @@ pub fn uv_plan(stdout: &str, stderr: &str, installed: &[Dist]) -> Result Option { - let flat = flatten(&strip_uv_decoration(text)); + let flat = crate::errors::catalog::collapse_whitespace(&strip_uv_decoration(text)); let idx = flat.find("No solution found when resolving")?; let explanation = flat[idx..] .trim() @@ -493,7 +493,10 @@ fn uv_no_solution(text: &str) -> Option { /// `warning: \`urllib3==2.0.0\` is yanked (reason: "…")` fn uv_yank_warnings(text: &str) -> Vec { let mut out = Vec::new(); - for line in flatten(text).split("warning:").skip(1) { + for line in crate::errors::catalog::collapse_whitespace(text) + .split("warning:") + .skip(1) + { if !line.contains("is yanked") { continue; } @@ -651,28 +654,6 @@ fn strip_uv_decoration(text: &str) -> String { out } -/// Collapse wrapping and CRLF so multi-word phrases can be found. -/// -/// uv hard-wraps its diagnostics mid-sentence, so a literal search for a phrase that spans the -/// wrap point finds nothing. The same normalization is applied by the error classifiers, and for -/// the same reason. -fn flatten(text: &str) -> String { - let mut out = String::with_capacity(text.len()); - let mut in_space = false; - for ch in text.chars() { - if ch.is_whitespace() { - in_space = true; - } else { - if in_space && !out.is_empty() { - out.push(' '); - } - in_space = false; - out.push(ch); - } - } - out -} - fn classify_change(from: Option<&Version>, to: &Version, requested: bool) -> ChangeKind { match from { None if requested => ChangeKind::NewInstall, diff --git a/crates/pipdock-core/src/engine/pip.rs b/crates/pipdock-core/src/engine/pip.rs index c221822..743577c 100644 --- a/crates/pipdock-core/src/engine/pip.rs +++ b/crates/pipdock-core/src/engine/pip.rs @@ -1,8 +1,8 @@ //! The pip adapter: ` -m pip …`. //! -//! Command mapping is fixed by `docs/DATA-FLOW.md` §7. Implementation lands in M1; the argv -//! builders below are already exercised by tests because they are the surface SECURITY §2 cares -//! about — nothing else in this file may construct engine arguments. +//! Command mapping is fixed by `docs/DATA-FLOW.md` §7. The argv builders below are the surface +//! SECURITY §2 cares about, and are tested as such — nothing else in this file may construct +//! engine arguments. use async_trait::async_trait; diff --git a/crates/pipdock-core/src/envs/mod.rs b/crates/pipdock-core/src/envs/mod.rs index f3fa10e..3f28449 100644 --- a/crates/pipdock-core/src/envs/mod.rs +++ b/crates/pipdock-core/src/envs/mod.rs @@ -51,19 +51,8 @@ pub struct ProbeResult { /// directory and the recents list, so a change here orphans a user's data. #[must_use] pub fn env_hash(interpreter: &Path) -> String { - use std::fmt::Write as _; - - use sha2::{Digest as _, Sha256}; let canonical = canonical_interpreter(interpreter); - let digest = Sha256::digest(canonical.as_bytes()); - digest - .iter() - .fold(String::with_capacity(64), |mut acc, byte| { - // Infallible: writing to a String cannot fail, and `?` here would need a Result return - // for a function that has no other failure mode. - let _ = write!(acc, "{byte:02x}"); - acc - }) + crate::model::sha256_hex(canonical.as_bytes()) } /// Run `probe.py` against an interpreter. diff --git a/crates/pipdock-core/src/errors/catalog.rs b/crates/pipdock-core/src/errors/catalog.rs index 9ef124b..279f112 100644 --- a/crates/pipdock-core/src/errors/catalog.rs +++ b/crates/pipdock-core/src/errors/catalog.rs @@ -599,6 +599,15 @@ pub fn classify_stderr(stderr: &str) -> Code { /// Lowercase and collapse every run of whitespace to a single space, so patterns survive the /// engines' line wrapping and CRLF. fn normalize(text: &str) -> String { + collapse_whitespace(text).to_lowercase() +} + +/// Collapse every run of whitespace — wrapping, CRLF, indentation — to one space, and trim. +/// +/// uv hard-wraps its diagnostics mid-sentence, so a literal search for a phrase that spans the +/// wrap point finds nothing. The classifiers above and the plan parser both need this, and had two +/// copies of it. +pub(crate) fn collapse_whitespace(text: &str) -> String { let mut out = String::with_capacity(text.len()); let mut in_space = false; for ch in text.chars() { @@ -609,7 +618,7 @@ fn normalize(text: &str) -> String { out.push(' '); } in_space = false; - out.extend(ch.to_lowercase()); + out.push(ch); } } out diff --git a/crates/pipdock-core/src/graph/mod.rs b/crates/pipdock-core/src/graph/mod.rs index 45133fa..56dea80 100644 --- a/crates/pipdock-core/src/graph/mod.rs +++ b/crates/pipdock-core/src/graph/mod.rs @@ -306,15 +306,6 @@ impl ReverseDeps { out } - /// Every package in `all` that nothing else depends on. - #[must_use] - pub fn leaves(&self, all: &[PkgName]) -> Vec { - all.iter() - .filter(|p| self.dependents_of(p).is_empty()) - .cloned() - .collect() - } - /// Everything that must also go if `removing` is removed and nothing may be left broken. /// /// This is the *transitive* closure, which DATA-FLOW §5's "[Remove dependents too] (adds Y,Z @@ -990,12 +981,6 @@ mod tests { assert!(g.dependent_count(&pkg("urllib3")) >= PIN_SUGGEST_THRESHOLD); } - #[test] - fn leaves_are_packages_nothing_depends_on() { - let g = ReverseDeps::build(&[dist("x", "1.0", &[]), dist("y", "2.0", &["x>=1"])]); - assert_eq!(g.leaves(&[pkg("x"), pkg("y")]), [pkg("y")]); - } - #[test] fn the_guard_reports_the_documented_example() { // DATA-FLOW §5: "Removing X breaks Y (requires X>=1), Z". diff --git a/crates/pipdock-core/src/health/mod.rs b/crates/pipdock-core/src/health/mod.rs index 3119ea4..0d22313 100644 --- a/crates/pipdock-core/src/health/mod.rs +++ b/crates/pipdock-core/src/health/mod.rs @@ -209,19 +209,7 @@ pub fn pins_for(tools: &[&str]) -> Result> { /// Same construction as `envs::env_hash`, so there is one hashing idiom in the codebase. #[must_use] pub fn pins_hash(pins: &[PinnedSpec]) -> String { - use std::fmt::Write as _; - - use sha2::{Digest as _, Sha256}; - - let digest = Sha256::digest(requirements_body(pins).as_bytes()); - digest - .iter() - .fold(String::with_capacity(64), |mut acc, byte| { - // Infallible: writing to a String cannot fail, and `?` here would need a Result return - // for a function that has no other failure mode. - let _ = write!(acc, "{byte:02x}"); - acc - }) + crate::model::sha256_hex(requirements_body(pins).as_bytes()) } /// The requirements file written into the tools directory, and the bytes the hash covers. @@ -448,10 +436,9 @@ fn parse_ledger(text: &str) -> Result> { /// Refuse a ledger version that is not shaped like one. /// -/// The same character-class check `pins::validated_hold` applies, and for the same reason: these -/// strings reach argv as `name==version`, so SECURITY §2's "validated before argv" claim has to -/// hold here too. Deliberately not a full PEP 440 parse — the job is to refuse whitespace, quotes, -/// path separators and control characters, not to second-guess an epoch or a local-version segment. +/// The same `pep440::is_version` check `pins::validated_hold` applies, and for the same reason: +/// these strings reach argv as `name==version`, so SECURITY §2's "validated before argv" claim has +/// to hold here too. fn validated_version(raw: &str) -> Result { let invalid = || { PdError::new( diff --git a/crates/pipdock-core/src/health/project.rs b/crates/pipdock-core/src/health/project.rs index 8f759f5..f74f510 100644 --- a/crates/pipdock-core/src/health/project.rs +++ b/crates/pipdock-core/src/health/project.rs @@ -36,15 +36,6 @@ impl DeclaredSource { } } -/// What `project` declares its dependencies in (CODE-HEALTH-SPEC §3's detection order). -/// -/// `pyproject.toml` wins outright when present, rather than being merged with any -/// `requirements*.txt` beside it. That is deptry's own precedence, and reporting both would invite -/// the UI to explain a distinction deptry did not make. -/// -/// # Errors -/// `PD-ENV-003` when the folder cannot be read at all — a path that is not a directory, or one the -/// user cannot list. Health has nothing to run against in either case. /// Refuse a project folder Code Health must not run in. /// /// SECURITY §2 validates package names, versions and interpreter paths; the project folder is the @@ -106,6 +97,15 @@ pub fn plain(path: PathBuf) -> PathBuf { path } +/// What `project` declares its dependencies in (CODE-HEALTH-SPEC §3's detection order). +/// +/// `pyproject.toml` wins outright when present, rather than being merged with any +/// `requirements*.txt` beside it. That is deptry's own precedence, and reporting both would invite +/// the UI to explain a distinction deptry did not make. +/// +/// # Errors +/// `PD-ENV-003` when the folder cannot be read at all — a path that is not a directory, or one the +/// user cannot list. Health has nothing to run against in either case. pub fn declared_source(project: &Path) -> Result { let unreadable = |e: &dyn std::fmt::Display| { PdError::new( diff --git a/crates/pipdock-core/src/health/run.rs b/crates/pipdock-core/src/health/run.rs index cf73213..35a56ce 100644 --- a/crates/pipdock-core/src/health/run.rs +++ b/crates/pipdock-core/src/health/run.rs @@ -411,15 +411,6 @@ pub fn has_findings(report: &HealthReport) -> bool { !report.deptry.is_empty() || !report.vulture.is_empty() || !report.ruff.findings.is_empty() } -/// Ensure `total` is not smaller than what will actually be emitted. -/// -/// A sink whose total is wrong is a progress bar that stops short or overshoots, and the caller -/// cannot always know whether a tools-venv sync will be needed until it asks. -#[must_use] -pub fn sink_for(sink: &ProgressSink, first_step: usize) -> ProgressSink { - sink.at(first_step) -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/pipdock-core/src/lib.rs b/crates/pipdock-core/src/lib.rs index 99cf9ce..81c3660 100644 --- a/crates/pipdock-core/src/lib.rs +++ b/crates/pipdock-core/src/lib.rs @@ -17,9 +17,8 @@ //! //! # Status //! -//! Phase 0. Types and command surfaces are defined; behaviour lands in M1, gated on the spikes in -//! `docs/ROADMAP.md`. In particular [`engine::uv`] is gated on SP-1, which decides whether v1.0 -//! ships both engines. +//! Shipped, with both engines, since 1.0. What is built and what is owed is `docs/ROADMAP.md`; the +//! spikes whose findings bind every adapter are `spikes/README.md`. #![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))] @@ -31,6 +30,9 @@ pub mod engine; pub mod envs; pub mod errors; pub mod exec; +// The L3 fixtures are generated by xtask and checked by a test here; nothing in a release build +// reads them, so they are not compiled into one. +#[cfg(any(test, feature = "fixtures"))] pub mod fixtures; pub mod flow; pub mod graph; diff --git a/crates/pipdock-core/src/model.rs b/crates/pipdock-core/src/model.rs index deb0ee7..02f5a11 100644 --- a/crates/pipdock-core/src/model.rs +++ b/crates/pipdock-core/src/model.rs @@ -1,10 +1,25 @@ //! Core domain types shared by every module, the CLI and the GUI. //! -//! These are the types `specta`/`tauri-specta` will export to TypeScript (ARCHITECTURE §9), so -//! their serde representation is part of the public contract — see `docs/CLI-SPEC.md` §6. +//! These are the types `cargo run -p xtask -- bindings` exports to TypeScript through `schemars` +//! (ARCHITECTURE §9, as `bindings.rs` corrects it), so their serde representation is part of the +//! public contract — see `docs/CLI-SPEC.md` §6. use std::path::PathBuf; +/// SHA-256 of `data`, as lowercase hex. Three hashes folded their own digests by hand. +#[must_use] +pub(crate) fn sha256_hex(data: &[u8]) -> String { + use sha2::{Digest as _, Sha256}; + use std::fmt::Write as _; + Sha256::digest(data) + .iter() + .fold(String::with_capacity(64), |mut acc, byte| { + // Infallible: writing to a String cannot fail. + let _ = write!(acc, "{byte:02x}"); + acc + }) +} + use crate::errors::{Code, PdError, Result}; /// Which resolver PipDock is driving. diff --git a/crates/pipdock-core/src/pins/mod.rs b/crates/pipdock-core/src/pins/mod.rs index cc999bd..c069d5c 100644 --- a/crates/pipdock-core/src/pins/mod.rs +++ b/crates/pipdock-core/src/pins/mod.rs @@ -109,10 +109,10 @@ pub fn list(store: &Store, env_hash: &str) -> Result> { /// but `Version` is a transparent newtype over whatever the engine reported — so the one place a /// *user* supplies a version is the one place that claim needs enforcing. /// -/// Deliberately a character-class check and not a full PEP 440 parse. The job is to refuse -/// whitespace, quotes, path separators and control characters, not to second-guess an epoch or a -/// local-version segment that the resolver understands better than PipDock does. Rejecting a -/// legitimate version would be the worse failure: it would make a package unpinnable. +/// The PEP 440 grammar check every argv boundary shares (`pep440::is_version`), not a resolver's +/// parse: it refuses whitespace, quotes, separators and anything else no version contains, and +/// leaves epochs and local segments to the engine. Rejecting a legitimate version would be the +/// worse failure — it would make a package unpinnable. fn validated_hold(version: &Version) -> Result<&str> { let raw = version.0.as_str(); let invalid = || { diff --git a/crates/pipdock-core/src/plan/mod.rs b/crates/pipdock-core/src/plan/mod.rs index b116efd..3fbb127 100644 --- a/crates/pipdock-core/src/plan/mod.rs +++ b/crates/pipdock-core/src/plan/mod.rs @@ -540,24 +540,15 @@ pub fn verify_age(made_at: jiff::Timestamp, now: jiff::Timestamp) -> Result<()> /// is not drift. Only the set of `name==version` pairs matters. #[must_use] pub fn fingerprint(installed: &[crate::model::Dist]) -> String { - use std::fmt::Write as _; - - use sha2::{Digest as _, Sha256}; - let mut pairs: Vec = installed .iter() .map(|d| format!("{}=={}", d.name, d.version)) .collect(); pairs.sort_unstable(); - let digest = Sha256::digest(pairs.join("\n").as_bytes()); - digest - .iter() - .take(16) - .fold(String::with_capacity(32), |mut acc, b| { - let _ = write!(acc, "{b:02x}"); - acc - }) + let mut hex = crate::model::sha256_hex(pairs.join("\n").as_bytes()); + hex.truncate(32); + hex } /// Execute a confirmed plan (ARCHITECTURE §8, DATA-FLOW §3). diff --git a/crates/pipdock-core/src/snapshot/mod.rs b/crates/pipdock-core/src/snapshot/mod.rs index d2a950e..25e72fe 100644 --- a/crates/pipdock-core/src/snapshot/mod.rs +++ b/crates/pipdock-core/src/snapshot/mod.rs @@ -2,8 +2,9 @@ //! //! DATA-FLOW §9.2 is absolute: **no mutating engine call happens without a successful snapshot //! write.** A failed write aborts the plan and executes nothing (`PD-SNP-001`). That rule is not -//! left to convention: [`crate::plan::execute`] takes a [`Snapshot`], so there is no way to call -//! it without having made one. +//! left to convention: [`crate::plan::execute`] takes a [`SnapshotProof`] — a written [`Snapshot`], +//! or a waiver that names itself — so there is no way to call it without having made one or +//! saying, greppably, why not. //! //! Layout, per ARCHITECTURE §6: //! @@ -117,23 +118,6 @@ pub enum SnapshotProof<'a> { WaivedForDisposableEnvironment, } -impl SnapshotProof<'_> { - /// The snapshot id, when there is one, for the summary and the log. - #[must_use] - pub fn id(&self) -> Option<&str> { - match self { - Self::Taken(s) => Some(&s.meta.id), - Self::WaivedForDisposableEnvironment => None, - } - } - - /// True when the user has no way back from what is about to happen. - #[must_use] - pub fn is_waived(&self) -> bool { - matches!(self, Self::WaivedForDisposableEnvironment) - } -} - /// Parse a `pip freeze` / `uv pip freeze` document. /// /// Only `name==version` lines are kept. Editable installs (`-e .`), direct URLs diff --git a/crates/pipdock-core/tests/search_latency.rs b/crates/pipdock-core/tests/search_latency.rs index 0aab0d2..edae362 100644 --- a/crates/pipdock-core/tests/search_latency.rs +++ b/crates/pipdock-core/tests/search_latency.rs @@ -5,7 +5,7 @@ //! whatever the local index actually contains now, which is the number that matters — the index //! grew from 858k to 864k projects in the week between those two measurements. //! -//! `#[ignore]` by default: it needs `%LOCALAPPDATA%\PipDock\index.db` populated by a real +//! `#[ignore]` by default: it needs `%LOCALAPPDATA%\PipDock\data\index.db` populated by a real //! `pipdock index refresh`, which CI does not have and should not spend four seconds getting. Run //! it deliberately: //! diff --git a/tools/tools-requirements.txt b/tools/tools-requirements.txt index 1a3bdc5..d2f899a 100644 --- a/tools/tools-requirements.txt +++ b/tools/tools-requirements.txt @@ -1,9 +1,11 @@ # Code Health tools — CODE-HEALTH-SPEC §2. # # These are installed into PipDock's own isolated environment at -# %LOCALAPPDATA%\PipDock\tools\.venv, NEVER into the user's environment. Exact `==` pins are +# %LOCALAPPDATA%\PipDock\data\tools\.venv, NEVER into the user's environment. Exact `==` pins are # resolved at PipDock release time; there are no floating versions at runtime, so a report is -# reproducible for a given PipDock build. +# reproducible for a given PipDock build. Their dependencies are pinned too, by +# tools-constraints.txt beside this file — regenerate it whenever a pin here moves (the command is +# in its header). # # Dependabot bumps these in their own group (see .github/dependabot.yml) so a tool upgrade is # never bundled with application dependencies — a ruff minor can change findings across every diff --git a/ui/src/ipc/errors.ts b/ui/src/ipc/errors.ts index 321682b..88cf357 100644 --- a/ui/src/ipc/errors.ts +++ b/ui/src/ipc/errors.ts @@ -9,6 +9,15 @@ import type { PdError } from '@/ipc' +/** + * A rejection as a `PdError`. Anything else reaching a store's `catch` can only be a bug in the + * bridge, and PD-INT-001 means exactly that — one honest internal code beats a blank error row. + * Six stores each had a copy of this. + */ +export function asPdError(e: unknown): PdError { + return isPdError(e) ? e : { code: 'PD-INT-001', message: String(e) } +} + export function isPdError(value: unknown): value is PdError { return ( typeof value === 'object' && diff --git a/ui/src/ipc/index.ts b/ui/src/ipc/index.ts index 06f44b2..6591b07 100644 --- a/ui/src/ipc/index.ts +++ b/ui/src/ipc/index.ts @@ -497,12 +497,13 @@ export const auditSaveReport = (report: AuditReport, path: string): Promise => invoke('health_dirty') + /** * Apply ruff's safe fixes to the project the parked report was produced from. * @@ -514,17 +515,16 @@ export const auditSaveReport = (report: AuditReport, path: string): Promise => invoke('health_dirty') - export const healthFix = (files: number, acknowledgedDirty: boolean): Promise => invoke('health_fix', { files, acknowledgedDirty }) +/** + * Write the report beside `path`, as Markdown and JSON. Returns the two paths written. + * + * The webview has no filesystem permission at all: `dialog:allow-save` only lets it *ask* for a + * path, and Rust does the writing. A general write permission here would be a write-anywhere + * primitive in a tool that already runs subprocesses. + */ export const healthSaveReport = (report: HealthReport, path: string): Promise => invoke('health_save_report', { report, path }) diff --git a/ui/src/locales/en/common.json b/ui/src/locales/en/common.json index 78d1459..9444109 100644 --- a/ui/src/locales/en/common.json +++ b/ui/src/locales/en/common.json @@ -17,21 +17,16 @@ "status": { "idle": "idle", "scanning": "scanning", - "resolving": "resolving", - "executing": "executing", "log": "log", "noEnvironment": "no environment selected", - "ready": "ready", "packages_one": "{{count}} package", "packages_other": "{{count}} packages", "warningsDetail": "Problems currently shown on screen." }, "actions": { - "confirm": "Confirm", "cancel": "Cancel", "back": "Back", "rescan": "Rescan", - "browse": "Browse…", "selectAll": "Select all", "details": "Details", "copyLog": "Copy full log", @@ -40,14 +35,11 @@ "decline": "Decline and exit", "open": "Open", "use": "Use", - "retry": "Retry", - "openLogs": "Open logs folder", "openFailed": "Could not open that link in your browser." }, "env": { "partialListing": "Packages installed for your user account are not shown here.", "partialListingDetail": "PipDock reads this environment in isolated mode, which skips {{path}}. Virtual environments are unaffected.", - "requiresPython": "Needs Python {{required}} — this environment is {{found}}.", "pipUpgrade": "Upgrade pip", "pipUpgrading": "Upgrading…", "pipUpgradeTitle": "Upgrade pip in this environment?", @@ -74,7 +66,6 @@ }, "managed": "MANAGED", "managedDetail": "Externally managed (PEP 668). Create a virtual environment instead; the override lives in Settings and is discouraged.", - "unusable": "This interpreter could not be read.", "selected": "Selected" }, "packages": { @@ -102,7 +93,6 @@ "updateSelected": "Update selected", "clearSelection": "Clear" }, - "updateSelectedSoon": "Previewing and applying updates arrives in a later version.", "selected_one": "{{count}} selected", "selected_other": "{{count}} selected", "pinnedExcluded_one": "{{count}} pinned excluded", @@ -332,7 +322,6 @@ }, "deptryNote": "deptry compares imports against PipDock's own tools environment, not this one — DEP001 and DEP003 can be swapped for packages it happens to hold.", "reviewInUninstall": "Review in Uninstall…", - "notInstalled": "not installed here", "vultureHint": "Confidence below 100% can be a false positive — review before deleting.", "vultureWhitelist": "vulture's whitelist", "fixableBadge": "fixable", @@ -430,12 +419,10 @@ "engine": "Engine", "engineDetail": "Which resolver PipDock drives. Both are supported; uv is faster, pip is always present.", "locale": "Language", - "localeSystem": "Follow the system", "pinThreshold": "Suggest pinning at", "pinThresholdDetail": "How many other packages must depend on something before the Pins screen suggests pinning it. Zero turns the suggestions off.", "override": "Allow externally managed environments", "overrideDetail": "PEP 668 marks some Pythons as managed by the operating system. Installing into one can break system tools, and there is no undo beyond a snapshot. Leave this off unless you know why you need it.", - "saved": "Saved", "logs": "Logs", "logsDetail": "PipDock keeps its own log for 14 days in this folder. Nothing in it is sent anywhere; copy it into a bug report if you want someone to read it.", "logsCopy": "Copy recent log", @@ -443,7 +430,8 @@ "logsEmpty": "Nothing has been logged yet.", "overrideConfirmTitle": "Allow changes to externally managed Pythons?", "overrideConfirmBody": "PipDock will pass --break-system-packages to pip or uv for every environment marked EXTERNALLY-MANAGED. Installing into such a Python can break tools your operating system relies on, and rolling back to a snapshot may not repair them. A virtual environment is almost always the better answer.", - "overrideConfirm": "Allow" + "overrideConfirm": "Allow", + "engineMissing": "not found" }, "legal": { "title": "Before you start", diff --git a/ui/src/locales/vi/common.json b/ui/src/locales/vi/common.json index 1423d12..6b62e75 100644 --- a/ui/src/locales/vi/common.json +++ b/ui/src/locales/vi/common.json @@ -17,20 +17,15 @@ "status": { "idle": "rảnh", "scanning": "đang quét", - "resolving": "đang phân giải", - "executing": "đang chạy", "log": "nhật ký", "noEnvironment": "chưa chọn môi trường", - "ready": "sẵn sàng", "packages_other": "{{count}} gói", "warningsDetail": "Số vấn đề đang hiển thị trên màn hình." }, "actions": { - "confirm": "Xác nhận", "cancel": "Hủy", "back": "Quay lại", "rescan": "Quét lại", - "browse": "Duyệt…", "selectAll": "Chọn tất cả", "details": "Chi tiết", "copyLog": "Sao chép toàn bộ nhật ký", @@ -39,14 +34,11 @@ "decline": "Từ chối và thoát", "open": "Mở", "use": "Dùng", - "retry": "Thử lại", - "openLogs": "Mở thư mục nhật ký", "openFailed": "Không mở được liên kết đó trong trình duyệt của bạn." }, "env": { "partialListing": "Các gói cài riêng cho tài khoản của bạn không hiển thị ở đây.", "partialListingDetail": "PipDock đọc môi trường này ở chế độ cách ly nên bỏ qua {{path}}. Môi trường ảo không bị ảnh hưởng.", - "requiresPython": "Cần Python {{required}} — môi trường này là {{found}}.", "pipUpgrade": "Nâng cấp pip", "pipUpgrading": "Đang nâng cấp…", "pipUpgradeTitle": "Nâng cấp pip trong môi trường này?", @@ -73,7 +65,6 @@ }, "managed": "HỆ THỐNG", "managedDetail": "Môi trường do hệ điều hành quản lý (PEP 668). Hãy tạo một môi trường ảo; tuỳ chọn ghi đè nằm trong Cài đặt và không được khuyến khích.", - "unusable": "Không đọc được trình thông dịch này.", "selected": "Đang chọn" }, "packages": { @@ -101,7 +92,6 @@ "updateSelected": "Cập nhật các gói đã chọn", "clearSelection": "Bỏ chọn" }, - "updateSelectedSoon": "Xem trước và áp dụng cập nhật sẽ có ở phiên bản sau.", "selected_other": "Đã chọn {{count}}", "pinnedExcluded_other": "{{count}} gói đã ghim bị loại trừ", "checkingUpdates": "Đang kiểm tra cập nhật…", @@ -302,7 +292,6 @@ }, "deptryNote": "deptry đối chiếu các import với môi trường công cụ riêng của PipDock, không phải môi trường này — DEP001 và DEP003 có thể bị hoán đổi với những gói mà nó tình cờ có.", "reviewInUninstall": "Xem trong Gỡ cài đặt…", - "notInstalled": "không cài ở đây", "vultureHint": "Độ tin cậy dưới 100% có thể là dương tính giả — hãy xem lại trước khi xoá.", "vultureWhitelist": "danh sách trắng của vulture", "fixableBadge": "sửa được", @@ -386,12 +375,10 @@ "engine": "Bộ máy", "engineDetail": "Bộ giải phụ thuộc mà PipDock điều khiển. Cả hai đều được hỗ trợ; uv nhanh hơn, pip thì luôn có sẵn.", "locale": "Ngôn ngữ", - "localeSystem": "Theo hệ thống", "pinThreshold": "Gợi ý ghim khi đạt", "pinThresholdDetail": "Cần bao nhiêu gói khác phụ thuộc vào một gói thì màn hình Ghim mới gợi ý ghim nó. Đặt 0 để tắt gợi ý.", "override": "Cho phép môi trường do hệ thống quản lý", "overrideDetail": "PEP 668 đánh dấu một số bản Python là do hệ điều hành quản lý. Cài vào đó có thể làm hỏng công cụ hệ thống, và không có cách hoàn tác nào ngoài ảnh chụp. Hãy để tắt trừ khi bạn biết rõ vì sao cần bật.", - "saved": "Đã lưu", "logs": "Nhật ký", "logsDetail": "PipDock giữ nhật ký của chính nó trong 14 ngày tại thư mục này. Không có gì trong đó được gửi đi; hãy sao chép vào báo lỗi nếu bạn muốn ai đó đọc.", "logsCopy": "Sao chép nhật ký gần đây", @@ -399,7 +386,8 @@ "logsEmpty": "Chưa có gì được ghi.", "overrideConfirmTitle": "Cho phép thay đổi các bản Python do hệ thống quản lý?", "overrideConfirmBody": "PipDock sẽ truyền --break-system-packages cho pip hoặc uv với mọi môi trường có đánh dấu EXTERNALLY-MANAGED. Cài vào một bản Python như vậy có thể làm hỏng công cụ mà hệ điều hành dựa vào, và khôi phục từ ảnh chụp có thể không sửa được. Môi trường ảo gần như luôn là lựa chọn tốt hơn.", - "overrideConfirm": "Cho phép" + "overrideConfirm": "Cho phép", + "engineMissing": "không tìm thấy" }, "legal": { "title": "Trước khi bắt đầu", diff --git a/ui/src/screens/PdSettings.test.tsx b/ui/src/screens/PdSettings.test.tsx index a2ad3f6..3fc3ca1 100644 --- a/ui/src/screens/PdSettings.test.tsx +++ b/ui/src/screens/PdSettings.test.tsx @@ -10,9 +10,9 @@ import { fireEvent, render, screen, waitFor, within } from '@testing-library/rea import { beforeEach, describe, expect, it, vi } from 'vitest' import * as ipc from '@/ipc' -import type { Settings } from '@/ipc' +import type { EnvRow, Settings } from '@/ipc' import { PdSettings } from '@/screens/PdSettings' -import { useSettingsStore } from '@/stores' +import { useEnvStore, useSettingsStore } from '@/stores' import { resetStore } from '@/test/stores' vi.mock('@/ipc', async () => { @@ -92,3 +92,43 @@ describe('the PEP 668 override', () => { ) }) }) + +describe('the engine radios', () => { + const ROW: EnvRow = { + interpreter: 'C:/work/.venv/Scripts/python.exe', + source: 'venv-scan', + envHash: 'hash-work', + env: { + interpreter: 'C:/work/.venv/Scripts/python.exe', + prefix: 'C:/work/.venv', + pythonVersion: '3.12.4', + externallyManaged: false, + hiddenUserSite: null, + source: 'venv-scan', + }, + } + + beforeEach(() => { + vi.clearAllMocks() + resetStore(useSettingsStore) + resetStore(useEnvStore) + }) + + it('show each engine’s version for the selected environment, and say which is missing', async () => { + useEnvStore.setState({ rows: [ROW], selected: ROW.interpreter }) + vi.mocked(ipc.engineInfo).mockResolvedValue([ + { id: 'pip', available: true, version: '26.2.1' }, + { id: 'uv', available: false }, + ]) + await setup() + + expect(await screen.findByText('26.2.1')).toBeInTheDocument() + expect(screen.getByText('not found')).toBeInTheDocument() + expect(ipc.engineInfo).toHaveBeenCalledWith(ROW.env) + }) + + it('ask nothing without an environment to ask about', async () => { + await setup() + expect(ipc.engineInfo).not.toHaveBeenCalled() + }) +}) diff --git a/ui/src/screens/PdSettings.tsx b/ui/src/screens/PdSettings.tsx index ff2a42c..3273dd1 100644 --- a/ui/src/screens/PdSettings.tsx +++ b/ui/src/screens/PdSettings.tsx @@ -17,10 +17,21 @@ import { PdDialog } from '@/components/PdDialog' import { PdErrorRow } from '@/components/PdErrorRow' import { PdLogs } from '@/components/PdLogs' import { SUPPORTED_LOCALES, type Locale } from '@/i18n' -import { useSettingsStore } from '@/stores' +import { engineInfo, type EngineInfo } from '@/ipc' +import { useEnvStore, useSettingsStore } from '@/stores' const ENGINES = ['pip', 'uv'] as const +function EngineVersion({ info }: { info: EngineInfo | undefined }) { + const { t } = useTranslation() + if (info === undefined) return null + return ( + + {info.available ? (info.version ?? '') : t('settings.engineMissing')} + + ) +} + export function PdSettings() { const { t } = useTranslation() const { @@ -43,6 +54,30 @@ export function PdSettings() { void load() }, [load]) + // ARCHITECTURE §7's `engine_info`: a version beside each radio, for the selected environment — + // pip's comes from ` -m pip --version`, so there is no answer without one. The wrapper + // shipped with no caller, so nothing said uv was missing until a plan failed for want of it. + // Keyed by interpreter, so a switch never shows one environment's versions under another. + const env = useEnvStore((s) => s.rows.find((r) => r.interpreter === s.selected)?.env) + const [engines, setEngines] = useState<{ for: string; info: EngineInfo[] } | null>(null) + useEffect(() => { + if (env === undefined) return undefined + let alive = true + void engineInfo(env).then( + (info) => { + if (alive) setEngines({ for: env.interpreter, info }) + }, + () => undefined, + ) + return () => { + alive = false + } + }, [env]) + const infoFor = (id: string) => + engines !== null && engines.for === env?.interpreter + ? engines.info.find((i) => i.id === id) + : undefined + return (

@@ -72,6 +107,8 @@ export function PdSettings() { /> {/* Engine names are product identifiers, never translated (I18N §2). */} {id} + {/* So is a version; only "not found" is copy. */} + ))} diff --git a/ui/src/stores/deps.ts b/ui/src/stores/deps.ts index 7f56bf4..7b3c383 100644 --- a/ui/src/stores/deps.ts +++ b/ui/src/stores/deps.ts @@ -17,7 +17,8 @@ import { create } from 'zustand' -import { depsGraph, isPdError, type DepsGraph, type DepsNode, type PdError, type PyEnv } from '@/ipc' +import { depsGraph, type DepsGraph, type DepsNode, type PdError, type PyEnv } from '@/ipc' +import { asPdError } from '@/ipc/errors' /** Where a fetch is. */ export type DepsPhase = 'idle' | 'loading' | 'ready' | 'failed' @@ -72,9 +73,6 @@ const NO_DEPS = { /** Which environment the load in flight is for, so a switch can start the next one. */ let loadingFor: string | null = null -const asPdError = (e: unknown): PdError => - isPdError(e) ? e : { code: 'PD-INT-001', message: String(e) } - export const useDepsStore = create((set, get) => ({ ...NO_DEPS, diff --git a/ui/src/stores/health.ts b/ui/src/stores/health.ts index 1a031f6..c1ecf9e 100644 --- a/ui/src/stores/health.ts +++ b/ui/src/stores/health.ts @@ -11,7 +11,6 @@ import { healthDirty, healthFix, healthRun, - isPdError, onHealthProgress, type HealthReport, type PdError, @@ -21,6 +20,7 @@ import { type RuffFinding, } from '@/ipc' import { apply, type ConsoleLine } from '@/stores/plan' +import { asPdError } from '@/ipc/errors' /** Which tab is showing. Deliberately the tool's own name — never translated (I18N §2). */ export type HealthTab = 'deptry' | 'vulture' | 'ruff' @@ -177,10 +177,6 @@ const NO_HEALTH = { } /** Turn an unknown rejection into something a screen can render with a code. */ -function asPdError(e: unknown): PdError { - return isPdError(e) ? e : { code: 'PD-INT-001', message: String(e) } -} - /** Subscription to `health-progress`, at module scope so a re-run cannot leak the previous one. */ let unlisten: (() => void) | undefined diff --git a/ui/src/stores/index-search.ts b/ui/src/stores/index-search.ts index ea3d715..12aca79 100644 --- a/ui/src/stores/index-search.ts +++ b/ui/src/stores/index-search.ts @@ -21,13 +21,13 @@ import { create } from 'zustand' import { indexRefresh, indexSearch, - isPdError, pkgMetadata, type Freshness, type Hit, type PackageMeta, type PdError, } from '@/ipc' +import { asPdError } from '@/ipc/errors' /** * Coalescing window, in ms. @@ -87,10 +87,6 @@ interface IndexState { refreshIndex: () => Promise } -function asPdError(e: unknown): PdError { - return isPdError(e) ? e : { code: 'PD-INT-001', message: String(e) } -} - /** * Sequence of the most recent search, and of the most recent one applied. * diff --git a/ui/src/stores/index.ts b/ui/src/stores/index.ts index 1b8d407..c3e1555 100644 --- a/ui/src/stores/index.ts +++ b/ui/src/stores/index.ts @@ -25,7 +25,6 @@ import i18n, { import { envProbe, envScan, - isPdError, legalConsentGet, legalConsentSet, pinAdd, @@ -57,13 +56,8 @@ import { joinRows, type LoadState, type PackageRow } from '@/screens/rows' export type EngineId = 'pip' | 'uv' /** Turn an unknown rejection into something a screen can render with a code. */ -export function asPdError(e: unknown): PdError { - return isPdError(e) - ? e - : // A rejection that is not a PdError can only be a bug in the bridge, and PD-INT-001 means - // exactly that. One honest internal code beats a blank error row. - { code: 'PD-INT-001', message: String(e) } -} +// One definition, in a Tauri-free module; re-exported for the components that import it here. +export { asPdError } from '@/ipc/errors' interface SettingsState { /** Active UI language — the choice when there is one, else what the OS resolved to. */ @@ -758,3 +752,4 @@ export { useIndexStore, type QueuedPackage, } from '@/stores/index-search' +import { asPdError } from '@/ipc/errors' diff --git a/ui/src/stores/plan.ts b/ui/src/stores/plan.ts index dbd1346..1c3de68 100644 --- a/ui/src/stores/plan.ts +++ b/ui/src/stores/plan.ts @@ -21,7 +21,6 @@ import { create } from 'zustand' import { - isPdError, onPlanProgress, planCancel, planDecide, @@ -41,6 +40,7 @@ import { type PyEnv, type RollbackPreview, } from '@/ipc' +import { asPdError } from '@/ipc/errors' /** * How many console lines to keep. @@ -153,10 +153,6 @@ interface PlanState { reset: () => void } -function asPdError(e: unknown): PdError { - return isPdError(e) ? e : { code: 'PD-INT-001', message: String(e) } -} - const EMPTY = { kind: null, env: null, diff --git a/ui/src/stores/security.ts b/ui/src/stores/security.ts index b4f7866..e7a6f5a 100644 --- a/ui/src/stores/security.ts +++ b/ui/src/stores/security.ts @@ -19,7 +19,6 @@ import { create } from 'zustand' import { auditCancel, auditRun, - isPdError, onAuditProgress, type AuditReport, type PdError, @@ -27,6 +26,7 @@ import { type PyEnv, } from '@/ipc' import { apply, type ConsoleLine } from '@/stores/plan' +import { asPdError } from '@/ipc/errors' /** Where a run is. */ export type SecurityPhase = 'idle' | 'running' | 'ready' | 'failed' @@ -80,9 +80,6 @@ const NO_SECURITY = { current: null, } -const asPdError = (e: unknown): PdError => - isPdError(e) ? e : { code: 'PD-INT-001', message: String(e) } - let unlisten: (() => void) | undefined export const useSecurityStore = create((set, get) => ({ diff --git a/ui/src/test/ipc.ts b/ui/src/test/ipc.ts index d2575e3..d5688d3 100644 --- a/ui/src/test/ipc.ts +++ b/ui/src/test/ipc.ts @@ -67,6 +67,7 @@ export interface IpcMock { appInfo: ReturnType settingsGet: ReturnType settingsSet: ReturnType + engineInfo: ReturnType isPdError: (value: unknown) => boolean } @@ -153,6 +154,8 @@ export function ipcMock(): IpcMock { pinSuggestThreshold: 5, }), settingsSet: vi.fn(), + // Nothing known by default: a version beside a radio is something a test asks for. + engineInfo: vi.fn().mockResolvedValue([]), // Real, not a spy: the stores decide whether a rejection carries a catalog code by asking it, // and a stub that always answered one way would make every error test agree with itself. And // the real one, not a lookalike — the lookalike accepted `{ code: 1, message: null }`. diff --git a/vite.config.ts b/vite.config.ts index c3204e1..4b44b18 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -21,7 +21,9 @@ export default defineConfig({ emptyOutDir: true, // Tauri ships its own WebView2; there is no legacy browser to support. target: 'esnext', - sourcemap: true, + // No source maps: Tauri embeds dist/ in the executable, so `sourcemap: true` shipped 2 MB of + // them to every user, and nothing in a release build ever reads one (X51). + sourcemap: false, }, server: { port: 1420, diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index 70efb0a..48052aa 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -13,4 +13,4 @@ publish = false workspace = true [dependencies] -pipdock-core = { path = "../crates/pipdock-core" } +pipdock-core = { path = "../crates/pipdock-core", features = ["fixtures"] }