8 Commits
Author SHA1 Message Date
poli0981andClaude Opus 5 f770e9c85f fix(deps): h2 0.4.16 — RUSTSEC-2026-0258
Unrelated to this slice, and blocking its required `cargo audit` gate.
`main` is equally affected: the advisory was published 2026-08-17 and
reached the RustSec database at 10:23+02:00 on the 18th, while main's
last audit ran at 07:08 that morning and passed. The next push to main
would have failed on it regardless of this branch.

Low severity, denial-of-service: h2 accepted and queued empty DATA
frames without limit, so an undrained stream could grow memory without
bound or panic on length overflow. Reached transitively through
reqwest and hyper; PipDock's only network use is the package index and
metadata fetches, both to pypi.org, so nothing here is exposed to an
attacker-chosen peer. Fixed rather than ignored anyway, because
SECURITY.md is explicit that the vulnerability gate is never relaxed —
the `.cargo/audit.toml` ignore list is for *informational* advisories
on crates we cannot influence, and this one has a patch release.

`cargo update -p h2 --precise 0.4.16` and nothing else. The lockfile
diff looks alarming and is not: sixteen of its eighteen lines are
dependency *edges* re-pointing between `windows-sys` copies that
already coexist in the lock — five of them before this change and five
after. No package is added, removed or downgraded, and the only version
that moves is h2's own. `cargo check --workspace --all-targets` and the
full test suite pass on it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-21 08:35:15 +07:00
poli0981andClaude Opus 5 02cc17d95d docs: the dependency view recorded, and 1.3.0
UI-SPEC §4 gains the screen and **loses the sentence it contradicted**.
It said the third row action folds all three into a `⋮` menu "with the
budget intact"; that makes uninstall four clicks where §5's table
records three, hand-counted. The correction is written as a correction
rather than an overwrite, because the reason it slipped through is the
useful part: four is under the ceiling of five, and a ceiling is not a
ratchet — a table of measured counts is. §5 gains the row, §6 the
component, ARCHITECTURE §4 the forward direction and the whole-graph
value.

**The dangling cross-reference is repaired by writing what it promised.**
`ROADMAP.md` has pointed at "the analysis above" for what blocks P1-6
and P1-7 since 1.2.0, and no such analysis was anywhere in the document
— the survey lived only outside the repository, and the sentence had
been copied into CLAUDE.md as well. P1-6's half is its slice record.
P1-7's is now written too, and counted against the tree rather than
recalled: no toast component, no notification/autostart/tray dependency,
one plan-scoped `tokio::spawn` and zero intervals in either head, and no
surface that can report a failure at 03:00 while `logs_tail` is still
`NOT_YET`. Drafting this commit I nearly shipped a CLAUDE.md line
claiming that survey existed before I had written it, which is the same
defect one layer up.

Version in five places, moved together: the workspace inherits it, so
`Cargo.toml`, `package.json` and `tauri.conf.json` are the only hand
edits and the two lockfiles are regenerated. Hand-editing `Cargo.lock`
would have been wrong twice over — `scopeguard` and `simd_cesu8` are
also at 1.2.0 and `fs_extra` was already at 1.3.0. `cargo metadata
--locked` passes, which is the one-command check.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-21 08:35:15 +07:00
poli0981andClaude Opus 5 8609518a37 test(ui): drive the shell against a logging bridge
The jsdom form of the recipe that has found more real defects here than
any suite: render the app, log every command that crosses, read back
what actually happened. Stage 2 found every screen fetching twice this
way and Stage 4 found a plan resolving into a screen that does not
render it — both faults *between* components, which is the one place a
component suite cannot look.

It proves the premise the slice is built on where it can actually be
observed: `deps_graph` crosses **once** when the view opens and **zero**
times on a re-centre. It also covers the seam nothing else did — the
row's new button through the table, the screen, the store and out to the
bridge — and pins the three row actions with none of them a tab stop.

Writing it found the trap the browser recipe already records, in its
jsdom form. `App` calls `checkConsent()` on mount and
`useLegalStore.check` **fails closed**, so setting `accepted: true` in
the store is undone a tick later by the real command rejecting and the
legal gate replaces the entire shell. The store reached `phase: 'ready'`
with the graph in hand and every assertion was reading a licence
agreement. Both halves have to be stubbed; the comment says so.

The browser pane could not reach localhost in this session, so this
stands in for the live drive rather than replacing it — the Rust side
of a command and the real window still want a human.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-21 08:35:15 +07:00
poli0981andClaude Opus 5 6ef677bc01 feat(ui): the dependency view, drawn at the one depth that survives the data
A mode of the package screen, not a tenth tab. `PdEnvironments` switches
to `PdEnvDetail` on `openFor`; this switches on `focus`, for UI-SPEC §4's
reason: `Ctrl+1..9` is positional over `NAV_KEYS`, appending is free and
inserting is not, and a Dependencies tab would have to sit beside
Installed to read as related. `NAV_KEYS` is already nine, so a tenth
entry would have no digit at all.

Three columns at depth 1, and depth is navigated by re-centring rather
than drawn. That is a measurement, not a preference: on the 352-package
fixture a depth-1 neighbourhood is a median of 7 nodes, and depth 2 is a
median of 172 and exceeds 60 for 212 of 352 packages. No layout
algorithm makes 172 nodes legible, so the eleventh runtime dependency, a
THIRD-PARTY-NOTICES edit that re-shows the legal gate, and a CSP
argument all buy a picture nobody can use. Transitive reach is two
numbers instead, and paths are not offered at all — `setuptools` has
more than 2000 distinct paths to a root in that environment.

**UI-SPEC §4 said the third row action folds all three into a `⋮` menu.
It does not.** A menu spends one click opening and one choosing, so
uninstall becomes four clicks where §5's table records three,
hand-counted. Four is under the ceiling of 5, which is exactly why the
budget alone would have let it through. A third inline button costs
nothing: the row is the only tab stop, so the controls are a roving
sequence and a third is one more arrow step, not 200 more stops.

Nothing is carried by colour. `styles.css` rebinds every `--color-*` to
a system keyword in forced-colors, so every edge states its specifier as
text and the columns are told apart by heading and position.

`deps_graph.json` is computed by `fixtures::deps_graph`, never written —
`numpy_blockers`' lesson. It turned out to carry two dependents with two
different specifiers *and* two packages with unsatisfied requirements,
which is more than a hand-written one would have thought to include.

Two defects the tests found by being run against mutations rather than
by being written: a column helper keyed on copy silently matched nothing
once the heading pluralised ("2 packages require this", not "requires"),
and a name-only comparison of the dependents column passed a mutation
that dropped the version and the specifier from every row.

The invalidation is the one this slice was warned about: `freshGraph`
keys on `envHash`, which a mutation does not change, so `App.tsx` resets
the slice in `onFinished`. Health and Security guard and never reset
because nothing they read is altered by an install. Edges are exactly
what an install alters.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-21 08:35:15 +07:00
poli0981andClaude Opus 5 c58fcac523 feat: deps_graph, and the shape it deliberately is not
`pin_suggestions`' shape, not `audit_run`'s. No `Sessions` slot, no
progress channel, no cancellation: those exist because an audit is
18-68 seconds, and a probe is 605 ms. Borrowing them here would be a
constant carrying its original units — the mistake `AUDIT_TIMEOUT`
already records.

One call per environment rather than one per package, which is the
whole reason the value is shaped this way. The view re-centres on a
click; a `deps_for(pkg)` command would read more naturally and pay a
probe for every click to answer a question the previous probe already
held the data for.

No store read, so there is no guard to drop — `pkg_list` is the same
and for the same reason. All five sites: the command, the handler list,
`COMMANDS`, the wrapper with `DepsGraph` added to the `import type`
list (`export type *` does not bring it into scope for a wrapper's own
signature), the `test/ipc.ts` mock, and ARCHITECTURE §7 — with its
trailing pipe, which the test added two commits ago now checks.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-21 08:35:15 +07:00
poli0981andClaude Opus 5 4ddec61ebb feat(wire): DepsGraph is a schema type
Registered in `schema_for!` and `SCHEMA_TYPES`, and in `golden.rs`'s own
copy of that list — the deliberate second list, which
`schema_lists_exactly_the_documented_types` holds in step by reading the
real one back out of the binary.

Only the root type, as the comment beside `HealthReport` says: the
generator hoists every `$defs` entry, so `DepEdge` and `DepsNode` arrive
as their own TS declarations without being listed, and listing them
would emit each twice.

`golden__schema-unknown-type.snap` churns because the error message
enumerates every known type, which is a real behaviour change rather
than noise. 67 snapshots.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-21 08:35:15 +07:00
poli0981andClaude Opus 5 bf2947b6c3 feat(core): the forward direction, and the graph as one value
`ReverseDeps` has been reverse-only since S3. Three features read it and
all three look exactly one edge out, so nothing ever needed to ask what
a package requires. PRD P1-6 does.

`forward` is built in the same pass, from the same parse, and filtered
by the same `applies_in` rule — a second traversal is how the two
directions would come to disagree. `edges_to` goes further and projects
`breaking_dependents` rather than walking `edges` again, so the
dependents column and the uninstall guard are the same set by
construction; the test asserts it whole rather than by name, after a
mutation that dropped the version and the constraint passed a name-only
comparison.

`unsatisfied` is the one thing this can say that the package list
cannot, and it is only trustworthy because the markers are evaluated.
Measured on the 352-package fixture: counting raw `Requires-Dist` names
reports **7** missing packages; evaluating markers reports **1**. The
other six are backports gated on a Python this environment is not. That
gap is the whole argument for this living in Rust.

`view` crosses the bridge whole rather than a package at a time,
because the alternative pays a 605 ms probe on every re-centring click.
Uncapped on purpose: the window is bounded in the view, but the
"+ N more" count has to come from the full set or a capped view
misreports a total.

Measured in --release against C:\Python314, 352 packages: build 1.8 ms,
view 42.9 ms, payload 249 KB, 1858 in-force edges, impact median 20 /
p90 111 / max 178. Having `reach` walk `forward` itself takes the view
to 31.4 ms — 1.8% of the probe the user is already waiting for, bought
with a second copy of the in-force rule. Declined, and the number is in
the doc so it is not re-litigated.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-21 08:35:15 +07:00
poli0981andClaude Opus 5 3152c55eaa fix(docs): three things main was carrying, and the gate that missed one
Found while surveying P1-6. None is caught by any suite, which is the
common thread rather than a coincidence.

`docs/ARCHITECTURE.md`'s `audit_run` row was the only row in the §7
command table missing its trailing pipe, so the table rendered wrong
from 1.2.0. Every gate passed: the command is registered, declared and
documented, and `documented()` strips only the *leading* pipe, so the
row parsed correctly and nothing looked at its shape. A spec sentence
is not a test — and neither is a spec table. The new
`the_architecture_table_is_well_formed` asserts the shape as well as the
contents, and was mutation-checked against the row it was written for.

`catalog.rs`'s comment read "Rust has 33; docs tabulates 30" three
lines above `assert_eq!(Code::ALL.len(), 34)`. Both numbers were one
behind; the doc tabulates 31, folding PD-HLT-001..004 into one row.

CLAUDE.md's error-code checklist named three schemas embedding `Code`
while saying "four", and 1.2.0 made it genuinely four by adding
`AuditReport` via `ToolProblem.code` — five snapshot files in all. So
anyone adding a code today would leave `golden__schema-AuditReport.snap`
stale. The line now says to grep `PD-ENV-001` across the snapshots
rather than trust the list, because that is how the omission was found.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-21 08:35:15 +07:00
38 changed files with 2023 additions and 55 deletions

No files matched your search

+12 -8
View File
@@ -1,7 +1,7 @@
# PipDock — working notes for Claude
Windows GUI + CLI for bulk-managing Python packages. Tauri 2 + Rust core + React 19.
Repo `poli0981/pipdock` · GPL-3.0-only · **Status: 1.2.0. M1, M2, Phase 3, Phase 4, the P1 wave and the Security tab are all complete.** 1.0.0 shipped the release pipeline, a protected `main`, the manual charter and legal documents that match the code; 1.1.0 added pin auto-suggest, requirements export/import, the cache manager and the `Ctrl+K` palette; 1.2.0 added the Security tab (PRD P1-1), which was the last major P1 item. **What is left of Post-1.0 is two things** — the dependency-graph view (P1-6) and the scheduled check (P1-7) — and neither is near P1-1's readiness; see `docs/ROADMAP.md`.
Repo `poli0981/pipdock` · GPL-3.0-only · **Status: 1.3.0. M1, M2, Phase 3, Phase 4, the P1 wave, the Security tab and the dependency view are all complete.** 1.0.0 shipped the release pipeline, a protected `main`, the manual charter and legal documents that match the code; 1.1.0 added pin auto-suggest, requirements export/import, the cache manager and the `Ctrl+K` palette; 1.2.0 added the Security tab (PRD P1-1); 1.3.0 added the dependency view (P1-6), which is a *mode of the package screen* rather than a tab and adds no runtime dependency — read its ROADMAP record before touching `graph/`, because the shape of the screen is a consequence of measurements rather than of taste. **What is left of Post-1.0 is one thing** — the scheduled check (P1-7) — and `docs/ROADMAP.md` now carries the survey of what blocks it, which for two versions it was cited for and did not contain: no toast component, no notification/autostart/tray plugin, nothing on a timer, and no surface that can report a background failure.
## Read the docs before changing anything
@@ -14,13 +14,17 @@ The design is fully specified. Read in this order; do not invent behaviour that
5. `docs/CLI-SPEC.md` — commands, flags, exit codes, JSON contracts
6. `docs/ERROR-CATALOG.md` — the launch codes and their stderr classifiers. **34 in Rust**
(`Code::ALL`, pinned by two tests); the doc tabulates fewer rows because it folds
`PD-HLT-001..004` into one. Adding a code means the catalog, `Code::ALL`, both counts, the
"no code without a fixture" gate in `classifier_corpus.rs`, **both `locales/*/errors.json`**,
a regenerated `codes.json` (`cargo run -p xtask -- ipc-fixtures`), regenerated bindings, and
re-blessed goldens — `golden__schema-Code.snap` **and every schema that embeds it**, which
since P3 is **four**: `StepResult`, `ExecutionSummary` and `HealthReport`, the last via
`ToolProblem.code`. Nine places; the gates will tell you which you forgot, including
`i18n.test.ts`, which fails on a code with no copy in either language
`PD-HLT-001..004` into one, so it shows **31 rows**. Adding a code means the catalog,
`Code::ALL`, both counts, the "no code without a fixture" gate in `classifier_corpus.rs`,
**both `locales/*/errors.json`**, a regenerated `codes.json`
(`cargo run -p xtask -- ipc-fixtures`), regenerated bindings, and re-blessed goldens —
`golden__schema-Code.snap` **and every schema that embeds it**, which since 1.2.0 is
**four**: `StepResult`, `ExecutionSummary`, `HealthReport` and `AuditReport`, the last two
via `ToolProblem.code`. **Five snapshot files in all.** This line named three while saying
four, and stayed that way through 1.2.0 — grep `PD-ENV-001` across
`crates/pipdock-cli/tests/snapshots/` rather than trusting the list. Nine places; the
gates will tell you which you forgot, including `i18n.test.ts`, which fails on a code with
no copy in either language
7. `docs/CODE-HEALTH-SPEC.md`, `docs/SECURITY.md`, `docs/TESTING.md`, `docs/RELEASE-CI.md`, `docs/I18N.md`, `docs/ROADMAP.md`
8. `legal/` — EULA, Disclaimer, Privacy, Third-Party Notices (public; the in-app legal gate links to these GitHub URLs)
Generated
+22 -22
View File
@@ -77,7 +77,7 @@ version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
dependencies = [
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -88,7 +88,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
dependencies = [
"anstyle",
"once_cell_polyfill",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -1074,7 +1074,7 @@ dependencies = [
"libc",
"option-ext",
"redox_users",
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -1287,7 +1287,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -1833,9 +1833,9 @@ dependencies = [
[[package]]
name = "h2"
version = "0.4.15"
version = "0.4.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6cb093c84e8bd9b188d4c4a8cb6579fc016968d14c99882163cd3ff402a4f155"
checksum = "a9f37a958b41b3b19ee2707c06439c0e9e547e847223eb791ecb0cb821c65e27"
dependencies = [
"atomic-waker",
"bytes",
@@ -2675,7 +2675,7 @@ dependencies = [
"png 0.18.1",
"serde",
"thiserror 2.0.20",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -2723,7 +2723,7 @@ version = "0.50.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
dependencies = [
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -3033,7 +3033,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.45.0",
]
[[package]]
@@ -3168,7 +3168,7 @@ checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]]
name = "pipdock-app"
version = "1.2.0"
version = "1.3.0"
dependencies = [
"jiff",
"pipdock-core",
@@ -3188,7 +3188,7 @@ dependencies = [
[[package]]
name = "pipdock-cli"
version = "1.2.0"
version = "1.3.0"
dependencies = [
"assert_cmd",
"clap",
@@ -3203,7 +3203,7 @@ dependencies = [
[[package]]
name = "pipdock-core"
version = "1.2.0"
version = "1.3.0"
dependencies = [
"async-trait",
"insta",
@@ -3493,7 +3493,7 @@ dependencies = [
"once_cell",
"socket2",
"tracing",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -3758,7 +3758,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -3815,7 +3815,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -4251,7 +4251,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -4820,7 +4820,7 @@ dependencies = [
"getrandom 0.4.3",
"once_cell",
"rustix",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -5257,7 +5257,7 @@ dependencies = [
"png 0.18.1",
"serde",
"thiserror 2.0.20",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -5297,7 +5297,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"
dependencies = [
"memoffset",
"tempfile",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -5801,7 +5801,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -6254,7 +6254,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10"
dependencies = [
"cfg-if",
"windows-sys 0.61.2",
"windows-sys 0.59.0",
]
[[package]]
@@ -6371,7 +6371,7 @@ checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"
[[package]]
name = "xtask"
version = "1.2.0"
version = "1.3.0"
dependencies = [
"pipdock-core",
]
+1 -1
View File
@@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/pipdock-core", "crates/pipdock-cli", "src-tauri", "xtask"]
[workspace.package]
version = "1.2.0"
version = "1.3.0"
edition = "2024"
rust-version = "1.94"
license = "GPL-3.0-only"
+30
View File
@@ -3,6 +3,36 @@
Newest first. See [`README.md`](README.md) for the conventions, and `docs/ROADMAP.md` for what each
slice cost and what it taught — that is a different document for a different reader.
## 1.3.0 — 2026-08-20
The **dependency view** — what depends on a package, what it depends on, and what a removal would
cost.
### Added
- **Dependencies**, from any package row: the `⇄` button beside pin and remove. The package sits
between two columns — everything that requires it and everything it requires — and every row
carries the version specifier written on that edge, so you can see *why* something is held where
it is rather than only *that* it is. Click any neighbour to move the view onto it.
- **The two numbers underneath**: how many packages a removal would leave with a missing
dependency, counted all the way through rather than one hop, and how many packages this one
pulls in itself. This is the part the package list could never tell you.
- **Requirements nothing satisfies.** If something in the environment declares a dependency that
is not installed, the view says so. Nothing else in PipDock reports this, and it only counts
requirements that actually apply to your Python — a backport gated on 3.9 is not a hole.
- The environment's dependencies are read **once** when you open the view, so moving from package
to package is instant.
### Changed
- **Package rows now have three buttons instead of two.** Removing a package is still three
clicks; the new one does not sit in front of it.
- **There is no node-link diagram, and there was never going to be a useful one.** Drawn as a
picture, a real environment is unreadable: on a 352-package install the average package has 172
others within two steps, and more than 200 of them exceed 60. So the view shows one step at a
time and lets you walk it, and answers the "everything downstream" question with a number
instead. No new third-party code was added to the application for this.
## 1.2.0 — 2026-08-18
The **Security tab**, which the sidebar has shown greyed out since M2.
+1
View File
@@ -46,6 +46,7 @@ const SCHEMA_TYPES: &[&str] = &[
"CacheUsage",
"CacheTarget",
"GuardReport",
"DepsGraph",
"Diff",
"SnapshotMeta",
"EngineInfo",
@@ -0,0 +1,105 @@
---
source: crates/pipdock-cli/tests/golden.rs
expression: out
---
{
"$defs": {
"DepEdge": {
"description": "One edge of the dependency graph, seen from a focused package.\n\n`pkg` is always the **other end** of the edge and `constraint` always the specifier written on\nit, so one type serves both directions: in a dependents column `pkg` is who requires the focus,\nin a dependencies column it is what the focus requires. `version` is that package's installed\nversion.\n\nThree fields identical to [`BrokenDependent`], and deliberately a separate type. That one is\nabout *breakage* — its doc is written for the uninstall dialog and its `Ord` exists for the\ndedup in [`ReverseDeps::breaking_dependents`] — so reusing it here would have a dependencies\ncolumn claim every dependency is a broken dependent. The `From` impl below is the bridge, and\n[`ReverseDeps::edges_to`] goes through it precisely so the two cannot drift.\n\n`constraint` is the **bare specifier tail** — `\"<2,>=1.26.0\"`, never `\"numpy<2,>=1.26.0\"` — for\n[`BrokenDependent`]'s reason. The other half of the sentence is the focused package, which the\ncaller already has; Rust emits data and each head writes its own sentence (I18N §1). An empty\nstring means unconstrained, which is a different statement from \"no edge\" and the view says so.",
"properties": {
"constraint": {
"description": "The version specifier written on the edge. Empty when unconstrained.",
"type": "string"
},
"pkg": {
"$ref": "#/$defs/PkgName",
"description": "The package at the other end of the edge."
},
"version": {
"description": "Its installed version, when the graph knows it.",
"type": [
"string",
"null"
]
}
},
"required": [
"pkg",
"constraint"
],
"type": "object"
},
"DepsNode": {
"description": "Everything a focus view needs about one installed package.\n\n`impact` and `reach` are the pair the view exists for. Every other question PipDock answers\nabout the graph is single-hop — the uninstall guard, blocker attribution and pin auto-suggest\nall look one edge out — so the only thing a dependency view adds over shipped behaviour is\n**transitive** reach, and it is a number rather than a picture because the picture does not\nsurvive the scale: measured on the 352-package fixture, a depth-2 neighbourhood is a median of\n172 nodes and exceeds 60 for 212 of 352 packages.",
"properties": {
"dependencies": {
"description": "Installed packages this one requires, in force.",
"items": {
"$ref": "#/$defs/DepEdge"
},
"type": "array"
},
"dependents": {
"description": "Installed packages that require this one, with the constraint each declared.",
"items": {
"$ref": "#/$defs/DepEdge"
},
"type": "array"
},
"impact": {
"description": "How many packages would be left broken if this one went, transitively. The size of\n[`ReverseDeps::removal_closure`] without the package itself.",
"format": "uint",
"minimum": 0,
"type": "integer"
},
"reach": {
"description": "How many installed packages this one pulls in, transitively.",
"format": "uint",
"minimum": 0,
"type": "integer"
},
"unsatisfied": {
"description": "In-force requirements with nothing installed to satisfy them.",
"items": {
"$ref": "#/$defs/PkgName"
},
"type": "array"
},
"version": {
"description": "The package's own installed version.",
"type": [
"string",
"null"
]
}
},
"required": [
"dependents",
"dependencies",
"impact",
"reach"
],
"type": "object"
},
"PkgName": {
"description": "A PEP 503-normalized distribution name.\n\nConstructing one is the *only* way a package name reaches an argv array, which is what makes\nSECURITY §2's \"validated before it reaches argv\" claim structural rather than aspirational.",
"type": "string"
}
},
"$schema": "https://json-schema.org/draft/2020-12/schema",
"description": "The in-force dependency graph of one environment (PRD P1-6).\n\nKeyed by package name, one entry per installed distribution. Produced by\n[`ReverseDeps::view`]; see its doc for why this crosses the bridge whole rather than a package\nat a time, and why nothing here is capped.",
"properties": {
"nodes": {
"additionalProperties": {
"$ref": "#/$defs/DepsNode"
},
"description": "Every installed package, including those with no edges in either direction.",
"type": "object"
}
},
"required": [
"nodes"
],
"title": "DepsGraph",
"type": "object"
}
@@ -2,4 +2,4 @@
source: crates/pipdock-cli/tests/golden.rs
expression: "stderr_of(&[\"schema\", \"NoSuchType\"])"
---
error[PD-PKG-002]: unknown type "NoSuchType"; known types: Dist, OutdatedDist, PyEnv, CheckReport, StepResult, PlanRequest, ResolutionReport, ExecutionSummary, Pin, PinSuggestion, ParsedRequirements, CacheUsage, CacheTarget, GuardReport, Diff, SnapshotMeta, EngineInfo, RollbackPlan, RollbackPreview, Hit, PackageMeta, Freshness, RefreshReport, ProgressEvent, FlowStep, Decision, Intent, Code, HealthReport, AuditReport, FixReport
error[PD-PKG-002]: unknown type "NoSuchType"; known types: Dist, OutdatedDist, PyEnv, CheckReport, StepResult, PlanRequest, ResolutionReport, ExecutionSummary, Pin, PinSuggestion, ParsedRequirements, CacheUsage, CacheTarget, GuardReport, DepsGraph, Diff, SnapshotMeta, EngineInfo, RollbackPlan, RollbackPreview, Hit, PackageMeta, Freshness, RefreshReport, ProgressEvent, FlowStep, Decision, Intent, Code, HealthReport, AuditReport, FixReport
+1 -1
View File
@@ -739,7 +739,7 @@ mod tests {
#[test]
fn every_documented_code_has_exactly_one_variant() {
// Rust has 33; docs/ERROR-CATALOG.md tabulates 30, because it folds PD-HLT-001..004 into
// Rust has 34; docs/ERROR-CATALOG.md tabulates 31, because it folds PD-HLT-001..004 into
// one row. Pin the number so the next person adding a code has to notice the docs exist.
assert_eq!(Code::ALL.len(), 34);
let wire: HashSet<&str> = Code::ALL.iter().map(|c| c.as_str()).collect();
+15
View File
@@ -229,6 +229,20 @@ fn guard_report() -> crate::graph::GuardReport {
])
}
/// What `deps_graph` returns for the same scenario — PRD P1-6.
///
/// **Computed, not written**, for [`guard_report`]'s reason and with [`numpy_blockers`]'s lesson
/// behind it. Hand-writing this map would let the graph's rules — marker evaluation, the
/// extra-only exclusion, the dedup, the split between a dependency and an unsatisfied requirement
/// — drift away from what `PdDepsFocus` is tested against, and the drift would be invisible
/// because the test would still assert something plausible.
///
/// The SP-5 tangle is the right set for it: `numpy` has two dependents declaring two different
/// specifiers, which is the case both columns exist to show.
fn deps_graph() -> crate::graph::DepsGraph {
crate::graph::ReverseDeps::build_for(&pkg_list(), "3.12.4").view()
}
/// What `snapshot_list` returns: one of each trigger, newest first.
///
/// All three on purpose. A `Rollback` entry *restoring* the `Plan` entry above it is the shape
@@ -575,6 +589,7 @@ pub fn ipc_fixtures() -> serde_json::Result<Vec<(&'static str, String)>> {
("flow_step.json", render(&flow_step())?),
("execution_summary.json", render(&execution_summary())?),
("guard_report.json", render(&guard_report())?),
("deps_graph.json", render(&deps_graph())?),
("snapshot_list.json", render(&snapshot_list())?),
("rollback_preview.json", render(&rollback_preview())?),
("health_report.json", render(&health_report())?),
+487
View File
@@ -111,6 +111,13 @@ fn is_specifier_start(c: char) -> bool {
pub struct ReverseDeps {
/// `dependency -> [(dependent, the requirement it declared)]`.
edges: BTreeMap<PkgName, Vec<(PkgName, Requirement)>>,
/// `dependent -> [the requirements it declared]` — the same edges the other way up.
///
/// Held rather than derived because deriving it means scanning every value of `edges` for
/// one package, which is O(edges) per lookup where this is O(1); the whole-graph view asks
/// once per installed package. Built in the same pass, from the same parse, filtered by the
/// same rule — a second traversal is how the two directions would come to disagree.
forward: BTreeMap<PkgName, Vec<Requirement>>,
/// Installed versions, so attribution can name `apiclient 1.4` rather than bare `apiclient`.
versions: BTreeMap<PkgName, String>,
/// The interpreter these requirements are read against, when known. `None` disables marker
@@ -135,6 +142,7 @@ impl ReverseDeps {
#[must_use]
pub fn build(dists: &[Dist]) -> Self {
let mut edges: BTreeMap<PkgName, Vec<(PkgName, Requirement)>> = BTreeMap::new();
let mut forward: BTreeMap<PkgName, Vec<Requirement>> = BTreeMap::new();
let mut versions = BTreeMap::new();
for dist in dists {
@@ -148,6 +156,10 @@ impl ReverseDeps {
if req.name == dist.name {
continue;
}
forward
.entry(dist.name.clone())
.or_default()
.push(req.clone());
edges
.entry(req.name.clone())
.or_default()
@@ -157,6 +169,7 @@ impl ReverseDeps {
Self {
edges,
forward,
versions,
env: None,
}
@@ -312,6 +325,132 @@ impl ReverseDeps {
seen.into_iter().collect()
}
/// What `pkg` requires: in force, and installed.
///
/// The forward mirror of [`Self::dependents_of`]. The two must filter by one rule or a focus
/// view's two columns describe the same edge differently, so both go through
/// [`Requirement::applies_in`] — which is also why neither can be recomputed in the frontend.
/// That restriction is not about phrasing (I18N §1); it is that PEP 508 marker evaluation and
/// the extra-gating rule live in [`markers`], and a second implementation would drift from the
/// guard the user is warned by.
///
/// Requirements that are in force but **not installed** are excluded here and reported by
/// [`Self::unsatisfied`] instead. Two disjoint sets whose union is the in-force requirement
/// list, so no row has to carry an "is it actually there?" flag the reader must then interpret.
#[must_use]
pub fn requires_of(&self, pkg: &PkgName) -> Vec<DepEdge> {
let mut out: BTreeSet<DepEdge> = BTreeSet::new();
for req in self.forward.get(pkg).into_iter().flatten() {
if !req.applies_in(self.env.as_ref()) {
continue;
}
if let Some(version) = self.versions.get(&req.name) {
out.insert(DepEdge {
pkg: req.name.clone(),
version: Some(version.clone()),
constraint: req.constraint.clone(),
});
}
}
out.into_iter().collect()
}
/// Who requires `pkg`, each with the constraint it declared.
///
/// Deliberately a projection of [`Self::breaking_dependents`] rather than a second walk of
/// `edges`: the dependents column and the uninstall guard are then the same set by
/// construction, and cannot come to disagree about which edges count. That is the failure
/// this module exists to prevent — `ReverseDeps::build`'s doc records the last time two
/// features nearly applied two edge rules.
#[must_use]
pub fn edges_to(&self, pkg: &PkgName) -> Vec<DepEdge> {
self.breaking_dependents(pkg)
.into_iter()
.map(DepEdge::from)
.collect()
}
/// In-force requirements of `pkg` that no installed distribution satisfies.
///
/// Nothing else in PipDock reports this. It is the one thing a dependency view can say that
/// the package list cannot, and it is only trustworthy because the markers are evaluated:
/// counting raw `Requires-Dist` names would report every `python_version < "3.11"` backport
/// as missing on 3.12 and make a healthy environment look broken.
#[must_use]
pub fn unsatisfied(&self, pkg: &PkgName) -> Vec<PkgName> {
let mut out: BTreeSet<PkgName> = BTreeSet::new();
for req in self.forward.get(pkg).into_iter().flatten() {
if req.applies_in(self.env.as_ref()) && !self.versions.contains_key(&req.name) {
out.insert(req.name.clone());
}
}
out.into_iter().collect()
}
/// How many installed packages `pkg` pulls in, transitively, excluding itself.
///
/// The forward mirror of [`Self::removal_closure`], and cycle-safe for its reason: a package
/// enters the frontier at most once. `pkg` itself is never counted, so a dependency cycle
/// through it reports the same number an acyclic graph would.
///
/// Goes through [`Self::requires_of`] rather than walking `forward` itself, and that was
/// measured rather than assumed. Walking `forward` directly takes the whole-graph
/// [`Self::view`] from **42.4 ms to 31.4 ms** on the 352-package fixture in `--release` — 11 ms
/// against a probe that costs 605 ms, so **1.8% of an operation the user waits for**, bought
/// with a second copy of the in-force-and-installed rule. This module exists because two
/// features applying two edge rules is the failure worth designing against; a 1.8% saving does
/// not buy that risk back.
#[must_use]
pub fn reach(&self, pkg: &PkgName) -> usize {
let mut seen: BTreeSet<PkgName> = BTreeSet::new();
let mut frontier = vec![pkg.clone()];
while let Some(current) = frontier.pop() {
for edge in self.requires_of(&current) {
if edge.pkg != *pkg && seen.insert(edge.pkg.clone()) {
frontier.push(edge.pkg);
}
}
}
seen.len()
}
/// The whole graph, precomputed once per environment (PRD P1-6).
///
/// **One value rather than one call per package**, because the alternative pays a 605 ms
/// probe on every re-centring click. Everything a focus view needs is decided here, in Rust,
/// with markers evaluated; the frontend indexes this map by name and computes nothing about
/// which edges are in force.
///
/// Uncapped on purpose. `setuptools` has 150 dependents in the 352-package fixture, and the
/// view shows a bounded window — but the "+ N more" count has to come from the full set or a
/// capped view misreports a total, which is the rule `SUGGESTIONS_SHOWN` and `RUFF_ROWS_SHOWN`
/// already follow. Capping here would put that count out of reach.
///
/// Every installed package gets a node, including the leaves: a package with no edges in
/// either direction is a fact worth rendering, not an absence to fall through on.
#[must_use]
pub fn view(&self) -> DepsGraph {
let nodes = self
.versions
.iter()
.map(|(pkg, version)| {
let node = DepsNode {
version: Some(version.clone()),
dependents: self.edges_to(pkg),
dependencies: self.requires_of(pkg),
impact: self
.removal_closure(std::slice::from_ref(pkg))
.len()
.saturating_sub(1),
reach: self.reach(pkg),
unsatisfied: self.unsatisfied(pkg),
};
(pkg.clone(), node)
})
.collect();
DepsGraph { nodes }
}
/// Evaluate the uninstall guard against a removal set (DATA-FLOW §5).
#[must_use]
pub fn guard(&self, removing: &[PkgName]) -> GuardReport {
@@ -403,6 +542,99 @@ impl GuardReport {
}
}
/// One edge of the dependency graph, seen from a focused package.
///
/// `pkg` is always the **other end** of the edge and `constraint` always the specifier written on
/// it, so one type serves both directions: in a dependents column `pkg` is who requires the focus,
/// in a dependencies column it is what the focus requires. `version` is that package's installed
/// version.
///
/// Three fields identical to [`BrokenDependent`], and deliberately a separate type. That one is
/// about *breakage* — its doc is written for the uninstall dialog and its `Ord` exists for the
/// dedup in [`ReverseDeps::breaking_dependents`] — so reusing it here would have a dependencies
/// column claim every dependency is a broken dependent. The `From` impl below is the bridge, and
/// [`ReverseDeps::edges_to`] goes through it precisely so the two cannot drift.
///
/// `constraint` is the **bare specifier tail** — `"<2,>=1.26.0"`, never `"numpy<2,>=1.26.0"` — for
/// [`BrokenDependent`]'s reason. The other half of the sentence is the focused package, which the
/// caller already has; Rust emits data and each head writes its own sentence (I18N §1). An empty
/// string means unconstrained, which is a different statement from "no edge" and the view says so.
#[derive(
Debug,
Clone,
PartialEq,
Eq,
PartialOrd,
Ord,
serde::Serialize,
serde::Deserialize,
schemars::JsonSchema,
)]
#[serde(rename_all = "camelCase")]
pub struct DepEdge {
/// The package at the other end of the edge.
pub pkg: PkgName,
/// Its installed version, when the graph knows it.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
/// The version specifier written on the edge. Empty when unconstrained.
pub constraint: String,
}
impl From<BrokenDependent> for DepEdge {
fn from(d: BrokenDependent) -> Self {
Self {
pkg: d.pkg,
version: d.version,
constraint: d.constraint,
}
}
}
/// Everything a focus view needs about one installed package.
///
/// `impact` and `reach` are the pair the view exists for. Every other question PipDock answers
/// about the graph is single-hop — the uninstall guard, blocker attribution and pin auto-suggest
/// all look one edge out — so the only thing a dependency view adds over shipped behaviour is
/// **transitive** reach, and it is a number rather than a picture because the picture does not
/// survive the scale: measured on the 352-package fixture, a depth-2 neighbourhood is a median of
/// 172 nodes and exceeds 60 for 212 of 352 packages.
#[derive(
Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
)]
#[serde(rename_all = "camelCase")]
pub struct DepsNode {
/// The package's own installed version.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
/// Installed packages that require this one, with the constraint each declared.
pub dependents: Vec<DepEdge>,
/// Installed packages this one requires, in force.
pub dependencies: Vec<DepEdge>,
/// How many packages would be left broken if this one went, transitively. The size of
/// [`ReverseDeps::removal_closure`] without the package itself.
pub impact: usize,
/// How many installed packages this one pulls in, transitively.
pub reach: usize,
/// In-force requirements with nothing installed to satisfy them.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub unsatisfied: Vec<PkgName>,
}
/// The in-force dependency graph of one environment (PRD P1-6).
///
/// Keyed by package name, one entry per installed distribution. Produced by
/// [`ReverseDeps::view`]; see its doc for why this crosses the bridge whole rather than a package
/// at a time, and why nothing here is capped.
#[derive(
Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
)]
#[serde(rename_all = "camelCase")]
pub struct DepsGraph {
/// Every installed package, including those with no edges in either direction.
pub nodes: BTreeMap<PkgName, DepsNode>,
}
/// Does `version` satisfy the PEP 440 specifier set `constraint`?
///
/// Reuses [`crate::compat`]'s evaluator: a `Requires-Dist` specifier and a `Requires-Python`
@@ -807,4 +1039,259 @@ mod tests {
let g = ReverseDeps::build(&[dist("x", "1.0", &[]), dist("y", "2.0", &["x>=1"])]);
assert!(g.guard(&[pkg("x"), pkg("y")]).is_clear());
}
// --- P1-6: the dependency view -------------------------------------------------------
/// The environment the view tests share: a diamond, an extra-gated edge, a marker for
/// another Python, a requirement nothing satisfies, and a leaf.
fn env() -> Vec<Dist> {
vec![
dist(
"app",
"1.0",
&["lib>=2", "plot; extra == \"charts\"", "gone>=9"],
),
dist("also", "1.0", &["lib<3"]),
dist("lib", "2.5", &["core", "old; python_version < \"3.0\""]),
dist("core", "0.9", &[]),
dist("plot", "4.0", &[]),
dist("leaf", "1.0", &[]),
]
}
#[test]
fn the_two_directions_agree_edge_for_edge() {
// One rule, two directions. If these ever disagree, a focus view describes the same edge
// twice and differently, and its dependents column stops matching the guard the user is
// actually warned by.
let g = ReverseDeps::build_for(&env(), "3.12.10");
let all: Vec<PkgName> = env().iter().map(|d| d.name.clone()).collect();
for from in &all {
for edge in g.requires_of(from) {
let back = g.edges_to(&edge.pkg);
assert!(
back.iter()
.any(|e| e.pkg == *from && e.constraint == edge.constraint),
"{from} -> {} is missing from edges_to({})",
edge.pkg,
edge.pkg
);
}
for edge in g.edges_to(from) {
let fwd = g.requires_of(&edge.pkg);
assert!(
fwd.iter()
.any(|e| e.pkg == *from && e.constraint == edge.constraint),
"{} -> {from} is missing from requires_of({})",
edge.pkg,
edge.pkg
);
}
}
}
#[test]
fn an_extra_gated_edge_appears_in_neither_direction() {
// `plot` is installed, but `app` wants it only under `extra == "charts"`. Counting it
// would have the view claim a dependency the environment does not rely on — the rule
// `dependents_of` already applies, which is why both directions go through `applies_in`.
let g = ReverseDeps::build_for(&env(), "3.12.10");
assert!(
!g.requires_of(&pkg("app"))
.iter()
.any(|e| e.pkg == pkg("plot"))
);
assert!(g.edges_to(&pkg("plot")).is_empty());
}
#[test]
fn a_marker_for_another_python_is_not_a_missing_dependency() {
// `lib` wants `old` only below Python 3.0, and `old` is not installed. Reporting it as
// unsatisfied on 3.12 would make a healthy environment look broken, which is exactly why
// this cannot be recomputed in the frontend from the raw strings.
let g = ReverseDeps::build_for(&env(), "3.12.10");
assert!(g.unsatisfied(&pkg("lib")).is_empty());
// ...while a genuinely absent requirement still is one.
assert_eq!(g.unsatisfied(&pkg("app")), [pkg("gone")]);
}
#[test]
fn an_unsatisfied_requirement_is_never_also_a_dependency_row() {
// The two sets are disjoint by construction, so no row carries an "is it installed?"
// flag for the reader to interpret.
let g = ReverseDeps::build_for(&env(), "3.12.10");
let deps: Vec<PkgName> = g
.requires_of(&pkg("app"))
.into_iter()
.map(|e| e.pkg)
.collect();
for missing in g.unsatisfied(&pkg("app")) {
assert!(!deps.contains(&missing), "{missing} is in both sets");
}
}
#[test]
fn reach_and_impact_count_transitively_and_exclude_the_package() {
let g = ReverseDeps::build_for(&env(), "3.12.10");
// app -> lib -> core: two, not one, and `plot` is extra-gated so not three.
assert_eq!(g.reach(&pkg("app")), 2);
// core <- lib <- {app, also}: three.
assert_eq!(g.removal_closure(&[pkg("core")]).len() - 1, 3);
// A leaf is zero in both directions, which is a fact to render, not an absence.
assert_eq!(g.reach(&pkg("leaf")), 0);
assert_eq!(g.removal_closure(&[pkg("leaf")]).len() - 1, 0);
}
#[test]
fn reach_terminates_on_a_cycle_and_does_not_count_the_package_itself() {
// `removal_closure` has had this test since S3. `reach` is the same walk the other way
// and needs its own: a cycle through the focus would otherwise count it as its own
// transitive dependency.
let g = ReverseDeps::build(&[
dist("a", "1.0", &["b"]),
dist("b", "1.0", &["c"]),
dist("c", "1.0", &["a"]),
]);
assert_eq!(g.reach(&pkg("a")), 2);
assert_eq!(g.removal_closure(&[pkg("a")]).len() - 1, 2);
}
#[test]
fn the_view_has_a_node_for_every_installed_package() {
// Including `leaf`, which has no edge in either direction. A view that fell through on
// those would leave 32 of the 352-package fixture with nothing to render.
let g = ReverseDeps::build_for(&env(), "3.12.10");
let view = g.view();
assert_eq!(view.nodes.len(), env().len());
for d in env() {
assert!(view.nodes.contains_key(&d.name), "{} has no node", d.name);
}
let leaf = &view.nodes[&pkg("leaf")];
assert!(leaf.dependents.is_empty() && leaf.dependencies.is_empty());
assert_eq!(leaf.version.as_deref(), Some("1.0"));
}
#[test]
fn the_view_agrees_with_the_methods_it_is_built_from() {
// The view is what crosses the bridge; the methods are what every test above pins. If
// the two can differ, all of that is proved about something the user never sees — which
// is the shape of the fixture bug Slice 0 found.
let g = ReverseDeps::build_for(&env(), "3.12.10");
for (name, node) in &g.view().nodes {
assert_eq!(node.dependents, g.edges_to(name), "{name} dependents");
assert_eq!(
node.dependencies,
g.requires_of(name),
"{name} dependencies"
);
assert_eq!(node.reach, g.reach(name), "{name} reach");
assert_eq!(node.unsatisfied, g.unsatisfied(name), "{name} unsatisfied");
assert_eq!(
node.impact,
g.removal_closure(std::slice::from_ref(name)).len() - 1,
"{name} impact"
);
}
}
#[test]
fn the_dependents_column_is_the_set_the_guard_warns_about() {
// `edges_to` projects `breaking_dependents` rather than walking `edges` again, so this
// holds by construction. Asserted anyway: it is the property that makes the projection
// worth having, and an "optimisation" that inlined the walk would break it silently.
let g = ReverseDeps::build_for(&env(), "3.12.10");
// Compared whole, not by name. Comparing names alone passed a mutation that dropped the
// version and the constraint from every row — the two halves of the sentence the column
// exists to show.
for d in env() {
let guarded: Vec<DepEdge> = g
.breaking_dependents(&d.name)
.into_iter()
.map(DepEdge::from)
.collect();
assert_eq!(g.edges_to(&d.name), guarded, "{} disagrees", d.name);
}
}
/// The shape of a real environment, which no synthetic fixture can supply.
///
/// Everything above is built from six hand-written dists. This one runs the probe against a
/// live interpreter and reports what the graph actually looks like — the numbers that decided
/// the view is drawn at depth 1 and navigated beyond it. Opt-in, like `audit`'s live tests:
///
/// ```text
/// PIPDOCK_GRAPH_PYTHON=C:\Python314\python.exe \
/// cargo test -p pipdock-core --release --lib graph::tests::the_real_environment -- --ignored --nocapture
/// ```
///
/// `--release` is not optional. A debug build measures bounds checks; the same slice measured
/// an index load at 572 ms in debug and 140 ms in release, and a design was justified on the
/// larger number before anyone noticed.
#[tokio::test]
#[ignore = "needs a real interpreter; run with --ignored and PIPDOCK_GRAPH_PYTHON"]
async fn the_real_environment() {
let Ok(exe) = std::env::var("PIPDOCK_GRAPH_PYTHON") else {
panic!("set PIPDOCK_GRAPH_PYTHON to an interpreter path");
};
let probed =
crate::envs::probe(std::path::Path::new(&exe), crate::model::EnvSource::Manual)
.await
.expect("probe succeeds");
let built = std::time::Instant::now();
let g = ReverseDeps::build_for(&probed.dists, &probed.env.python_version);
let build_ms = built.elapsed();
let viewed = std::time::Instant::now();
let view = g.view();
let view_ms = viewed.elapsed();
let json = serde_json::to_string(&view).expect("serializes");
let edges: usize = view.nodes.values().map(|n| n.dependencies.len()).sum();
let mut fan_in: Vec<usize> = view.nodes.values().map(|n| n.dependents.len()).collect();
let mut impacts: Vec<usize> = view.nodes.values().map(|n| n.impact).collect();
fan_in.sort_unstable();
impacts.sort_unstable();
let p = |v: &[usize], q: f64| v[((v.len() as f64 * q) as usize).min(v.len() - 1)];
let leaves = view
.nodes
.values()
.filter(|n| n.dependents.is_empty())
.count();
let missing: usize = view.nodes.values().map(|n| n.unsatisfied.len()).sum();
eprintln!("packages {}", view.nodes.len());
eprintln!("in-force edges {edges}");
eprintln!("build {build_ms:?}");
eprintln!("view {view_ms:?}");
eprintln!("payload {} KB", json.len() / 1024);
eprintln!(
"fan-in median {} p90 {} max {}",
p(&fan_in, 0.5),
p(&fan_in, 0.9),
fan_in.last().copied().unwrap_or(0)
);
eprintln!(
"impact median {} p90 {} max {}",
p(&impacts, 0.5),
p(&impacts, 0.9),
impacts.last().copied().unwrap_or(0)
);
eprintln!("leaves {leaves}");
eprintln!("unsatisfied {missing}");
// Not a benchmark assertion — those belong in `tests/`, and this number is a report. What
// is asserted is the invariant a benchmark cannot state: every installed package has a
// node, and no edge points anywhere but at another node.
assert_eq!(view.nodes.len(), probed.dists.len());
for (name, node) in &view.nodes {
for edge in node.dependencies.iter().chain(&node.dependents) {
assert!(
view.nodes.contains_key(&edge.pkg),
"{name} has an edge to {}, which has no node",
edge.pkg
);
}
}
}
}
+2
View File
@@ -286,6 +286,7 @@ pub fn json_schema(type_name: &str) -> Result<serde_json::Value> {
"CacheUsage" => crate::cache::Usage,
"CacheTarget" => crate::cache::Target,
"GuardReport" => crate::graph::GuardReport,
"DepsGraph" => crate::graph::DepsGraph,
"Diff" => crate::snapshot::Diff,
"SnapshotMeta" => crate::snapshot::Meta,
"EngineInfo" => crate::model::EngineInfo,
@@ -325,6 +326,7 @@ pub const SCHEMA_TYPES: &[&str] = &[
"CacheUsage",
"CacheTarget",
"GuardReport",
"DepsGraph",
"Diff",
"SnapshotMeta",
"EngineInfo",
+7 -2
View File
@@ -84,7 +84,11 @@ Rust cannot cheaply read a foreign env's installed metadata. PipDock embeds a si
`hidden_user_site` is non-null only when `-I` is actually hiding packages from the listing — see SECURITY §2 for the decision and the UI note it drives.
From `requires_dist` the core builds the **reverse-dependency graph** used by: held-back attribution, uninstall guard, and pin auto-suggest. The helper is written to a temp file per invocation and never installed into the env. Compatibility floor: Python 3.10 (uses `importlib.metadata` only).
From `requires_dist` the core builds the **reverse-dependency graph** used by: held-back attribution, uninstall guard, pin auto-suggest, and the dependency view (P1-6). The helper is written to a temp file per invocation and never installed into the env. Compatibility floor: Python 3.10 (uses `importlib.metadata` only).
`ReverseDeps` holds **both directions** as of 1.3.0. The first three consumers each look exactly one edge out and only ever asked "who depends on this", so the forward map was never needed; the dependency view asks the other question. Both are built in the same pass from the same parse and filtered by the same `Requirement::applies_in`, and `edges_to` is a projection of `breaking_dependents` rather than a second walk — so the dependents column and the uninstall guard are the same set **by construction**. Two features applying two edge rules is the failure this module exists to prevent, and a second traversal is how it would happen.
**The graph crosses the bridge whole, once per environment** (`deps_graph` → `DepsGraph`), not a package at a time. The view re-centres on a click, so a per-package command would pay the probe again for each one; measured in `--release` on a 352-package environment, the probe is 605 ms while building the graph is 1.8 ms and computing every node's transitive counts is 43 ms, for a 249 KB payload. Nothing about which edges are in force is recomputed in the frontend — marker evaluation and extra-gating live in `graph/markers.rs`, and a JavaScript reimplementation would drift from the guard the user is warned by.
## 5. Index & metadata
@@ -132,6 +136,7 @@ This table is the surface. A command that is not listed here does not exist; add
| `pin_list` | `Pin[]` | Pins for an environment. |
| `pin_add` | `()` | Add or replace a pin. |
| `pin_remove` | `bool` | Remove a pin; reports whether one existed. |
| `deps_graph` | `DepsGraph` | The in-force dependency graph of one environment (PRD P1-6): every installed package, its dependents and dependencies with the specifier on each edge, and its transitive `impact` and `reach`. **One call per environment, not one per package** — the view re-centres on a click, and a per-package command would pay a 605 ms probe for each one. 249 KB and 45 ms on the 352-package fixture. Uncapped, because the view's "+ N more" count has to come from the full set. |
| `pin_suggestions` | `PinSuggestion[]` | Packages worth pinning, by in-force reverse-dependency count (PRD P1-2). **One probe per call**, which is why UI-SPEC §4 puts this on the Pins screen rather than a sidebar badge — the cost is paid only by someone who opened the tab. |
| `snapshot_list` | `SnapshotMeta[]` | Snapshots for an environment, newest first. Takes the `env_hash`, not a `PyEnv`: snapshots outlive the interpreter that made them, and an environment whose Python is gone still has a history worth showing. |
| `snapshot_create` | `SnapshotMeta` | Take a snapshot on demand, outside any plan. |
@@ -142,7 +147,7 @@ This table is the surface. A command that is not listed here does not exist; add
| `health_fix` | `FixReport` | Apply the gated `ruff` fix (P5). **Not `ExecutionSummary`** — there is no plan, no phase and no per-package counts in a fix, and inventing them would be four lies for one operation. Same correction §7 needed for `pip_upgrade`. |
| `health_dirty` | `number \| null` | Uncommitted entries in the parked report's project, so the fix confirm can name one. `null` means no repository, no git, or git failed — a courtesy, not a precondition. Asked again inside `health_fix`: this decides what to render, that decides what to allow. |
| `health_save_report` | `string[]` | Write a finished report as Markdown **and** JSON beside a user-chosen path, returning both. Rust-side rather than a filesystem capability: `dialog:allow-save` lets the webview ask for a path and nothing more. |
| `audit_run` | `AuditReport` | pip-audit over an environment (PRD P1-1). Takes the freeze itself, because pip is invoked with `--all` and uv is not, so the configured engine changes what is audited. Syncs its **own** venv on first use — a `msgpack` wheel gap fails this and leaves Code Health working. pip-audit failing is not an error: it lands in `problems` and the report still returns.
| `audit_run` | `AuditReport` | pip-audit over an environment (PRD P1-1). Takes the freeze itself, because pip is invoked with `--all` and uv is not, so the configured engine changes what is audited. Syncs its **own** venv on first use — a `msgpack` wheel gap fails this and leaves Code Health working. pip-audit failing is not an error: it lands in `problems` and the report still returns. |
| `audit_cancel` | `bool` | Stop a running audit, reporting whether there was one. Exists where `health_run` has no equivalent because an audit is **18-68 s** rather than 1.3 s, dominated by a one-off advisory-database fetch. A cancel is a *state* on the report, never `PD-INT-001`. |
| `audit_save_report` | `string[]` | Write a finished audit as Markdown **and** JSON beside a user-chosen path, returning both. `health_save_report`'s shape, for its reasons: `dialog:allow-save` asks for a path and grants no `fs`, and the report comes from the frontend because what the user asked to save is what is on their screen. |
| `engine_info` | `EngineInfo[]` | Detected version and availability per engine. Settings shows both, so this returns both. |
+1 -1
View File
@@ -65,7 +65,7 @@ PipDock's thesis: **don't reimplement the resolver — explain it.** Wrap pip/uv
| P1-3 | **Shipped 1.1.0.** Export / import | `requirements.txt` and `constraints.txt` export; import-as-queue. |
| P1-4 | **Partly shipped, 1.1.0.** Cache manager | Shows and clears **PipDock's own** disk usage: snapshots and the Code Health tools venv. `index.db` is reported but not clearable — it holds settings, pins and the consent record in the same file, so "clear the cache" must never take them. **The engine caches (`pip cache`, `uv cache`) are not covered** and are a separate item: they belong to the engine, live outside `%LOCALAPPDATA%\PipDock\`, and purging them is a subprocess rather than a file delete. |
| P1-5 | **Shipped 1.1.0.** Command palette | Ctrl+K fuzzy action launcher (terminal-tech signature feature). |
| P1-6 | Dependency graph view | Visual "who holds this back" graph for a selected package. |
| P1-6 | **Shipped 1.3.0.** Dependency view | "Who holds this back" for a selected package: the focused package between its dependents and its dependencies, each edge carrying the specifier written on it, each neighbour clickable to re-centre, plus the two transitive counts and any requirement nothing installed satisfies. **Not a node-link diagram, and that is a measurement rather than a shortcut** — on a 352-package environment a depth-1 neighbourhood is a median of 7 nodes but depth 2 is a median of 172 and exceeds 60 for 212 of 352 packages, and there are over 2000 distinct paths from `setuptools` to a root. So it is drawn at depth 1, depth is navigated by re-centring, and the transitive answer is a count. Added no runtime dependency. |
| P1-7 | Scheduled check | Optional background outdated-check with toast (no auto-apply, ever). |
### P2 — later
+104 -3
View File
@@ -959,9 +959,110 @@ mode that is *silent*, and the reason SECURITY §4 requires the widening in pros
has always said audit never applies anything; "update to fixed version" is the ordinary Update flow,
reached by the user.
**What is left of Post-1.0 is two items**: the dependency-graph view (PRD P1-6) and the scheduled
check (PRD P1-7). Both were surveyed on 2026-08-18 and neither is close to P1-1's readiness — see
the analysis above for what blocks each.
**What is left of Post-1.0 is one item**: the scheduled check (PRD P1-7). The dependency view
shipped as 1.3.0; its record is below.
*This paragraph used to point at "the analysis above" for what blocked each of two items. There was
no such analysis anywhere in this document* — the survey existed only outside the repository, and
the sentence had been repeated into `CLAUDE.md`. What actually separated P1-1 from the other two was
that it had a Phase-0 spike behind it (SP-4) and they did not; P1-6 has one now, in the shape of
measurements taken before the screen was designed. The P1-7 half of the missing survey is below, so
that the pointer finally has something to point at.
#### What blocks P1-7 — the scheduled check
Nine words of PRD, and **every prerequisite is absent.** Counted against the tree on 2026-08-20:
- **No toast.** `ui/src/components/` has none. UI-SPEC states a policy for a mechanism that has
never been built.
- **No plugin.** `src-tauri/Cargo.toml` carries no notification, autostart or tray dependency, and
each would need a capability entry with SECURITY §4's prose justification.
- **Nothing runs on a timer.** One `tokio::spawn` in the whole Tauri crate, plan-scoped, and zero
occurrences of `tokio::time::interval` or `setInterval` in either head.
- **No surface can report a background failure.** `⚠ n` counts mounted `PdErrorRow`s, the `LogRing`
is cleared per plan, `logs_tail` is still one of the two `NOT_YET` entries, and the console toggle
is disabled while idle. A check that failed at 03:00 has nowhere to say so.
It is also the item whose users are already served: the PRD's automation persona wants the **CLI in
an external scheduler**, and `docs/CLI-SPEC.md` already ships the Task Scheduler recipe — zero code,
zero dependencies, zero legal edit, no toast. Whoever picks this up should first say what the GUI
version gives that the recipe does not, because the honest answer may be "a notification", and that
is one plugin and a permanent background process for one line of text.
### Post-1.0 · P1-6 — the dependency view — **done 2026-08-20**
Six commits, and **1.3.0**. PRD P1-6 was twelve words and had no UI-SPEC screen, no §6 component,
no nav slot, no CLI command and no decomposition here.
| | What landed |
|---|---|
| **Preflight** | ARCHITECTURE §7's `audit_run` row regains its trailing pipe; `the_architecture_table_is_well_formed`; `catalog.rs`'s stale 33/30 comment; CLAUDE.md's three-named-as-four schema list |
| **Core** | `ReverseDeps.forward`; `requires_of`, `edges_to`, `unsatisfied`, `reach`, `view`; `DepEdge`, `DepsNode`, `DepsGraph`; nine tests plus an opt-in live one |
| **Wire** | `DepsGraph` in `schema_for!`, `SCHEMA_TYPES` and `golden.rs`'s own copy. 32 types, 67 goldens |
| **Bridge** | `deps_graph` — `pin_suggestions`' shape, not `audit_run`'s. `NOT_YET` unchanged at two |
| **UI** | `PdDeps` (a mode of the package screen), `PdDepsFocus`, `stores/deps.ts`, a third row button, both catalogues |
| **Docs** | UI-SPEC §4/§5/§6, ARCHITECTURE §4, PRD P1-6, this section |
**The measurements decided the design, and they were taken first.** Against `C:\Python314` — 352
packages, the scale fixture — and a 29-package venv, by running `probe.py` directly:
| | 352-pkg | 29-pkg |
|---|---|---|
| Depth-1 neighbourhood | median **7**, p90 25, max 151 | median 2, max 11 |
| Depth-2 neighbourhood | median **172**, p90 209 | max 25 |
| Over 60 nodes at depth 2 | **212 of 352** | 0 of 29 |
| Transitive reverse closure | median 20, p90 111, max 178 | — |
| Distinct paths to a root, `setuptools` | **>2000** | — |
So: **depth 1 is drawable and depth 2 is a hairball**, and paths cannot be enumerated at all. The
view is drawn at depth 1, depth is navigated by re-centring, and the transitive question is answered
by two numbers. A graph library would have been the eleventh runtime dependency, a
`THIRD-PARTY-NOTICES.md` edit that re-shows the legal gate, an npm-audit surface and a CSP argument
— and would not have made 172 nodes readable. **Zero new dependencies.**
**Rust's answer differed from the prototype's, which is the argument for where this lives.** The
throwaway Python that took the measurements skipped only extra-gated edges. Rust, evaluating
`python_version` as well, reports **1858** in-force edges rather than 1893 — and **one** unsatisfied
requirement rather than seven. The other six are backports gated on a Python this environment is
not. Counting raw `Requires-Dist` names would have shipped a healthy environment described as
broken.
**Measured in `--release`** on that environment: probe 605 ms, graph build **1.8 ms**, whole-view
computation **43 ms**, payload **249 KB**. Having `reach` walk `forward` itself takes the view to
31.4 ms — 11 ms, or **1.8% of a probe the user is already waiting for**, in exchange for a second
copy of the in-force-and-installed rule. Declined; the number is in `reach`'s doc so it is not
re-litigated.
**UI-SPEC §4 was corrected rather than followed.** It said the third row action would fold
pin/uninstall/details into a `⋮` menu "with the budget intact". It does not: a menu makes uninstall
four clicks where §5's table records three, hand-counted, for the second most destructive action in
the app. Four is under the ceiling of five, which is precisely why the ceiling alone would have
allowed it — **a ceiling is not a ratchet, and a table of measured counts is.** Three inline buttons
cost nothing, because the row is the only tab stop and its controls are a roving sequence.
**Three defects found by mutation rather than by writing tests.** A column helper keyed on copy
matched nothing once the heading pluralised — "2 packages *require* this", not "requires" — and the
test passed by finding the singular case. A name-only comparison of the dependents column survived
a mutation that dropped the version and the specifier from every row. And the App-level test's
first draft asserted against a **licence agreement**: `App` calls `checkConsent()` on mount and
`useLegalStore.check` fails closed, so `accepted: true` in the store is undone a tick later and the
gate replaces the whole shell. The store had reached `phase: 'ready'` with the graph in hand the
entire time. That is the browser recipe's own warning, met in its jsdom form.
**The invalidation this slice was warned about, and hit.** `freshGraph` keys on `envHash`, which a
mutation does not change, so an install would have left last-hour's edges on screen looking correct.
`App.tsx` resets the slice in `onFinished`. Health and Security guard and never reset because
nothing they read is altered by an install; edges are exactly what an install alters.
**Deliberately not done.** No `pipdock deps` — the P1-A..D precedent, and the core functions are in
`graph/` so a subcommand is later trivial. No tree widget: re-centring already navigates depth. No
node-link diagram at any depth. No graph for packages that are not installed — there is no
`Requires-Dist` to read.
**Still owner-verifiable only.** The browser pane could not reach `localhost` in this session, so
the live drive was replaced by an App-level test against a logging bridge. That reaches everything
except the Rust side of the command and the real window; `deps_graph`'s argument name is the usual
runtime-only risk, and it is the same `{ env }` shape `pkg_list` has shipped since M2.
### Four items decomposed, easiest first
+42 -4
View File
@@ -75,10 +75,21 @@ empty panel would be the same empty gesture the plain-text version was. The **co
**Environments.** Auto-discovered list (source chip: registry / py launcher / uv / manual) with python version and package count; PEP 668 envs carry a red `MANAGED` chip and a disabled state explaining PD-ENV-002. Actions: *Browse…*, *Rescan*, star-as-default.
**Installed.** Virtualized table: name (mono) · version · latest · size · chips. When the env's `hidden_user_site` is non-null (non-venv system Pythons only — see SECURITY §2), an inline `--color-info` note above the table says user-account packages are not listed and names the path; it is informational, never a block, and never appears for a venv. Up-to-date rows use `--color-text-dim` (owner's "dimmed" requirement); outdated rows show an `UPDATE` badge; pinned rows a 🔒 `--color-info` chip. Row actions: pin/unpin and uninstall, as two inline buttons rather than a `⋮` menu. A menu would
spend one click opening and one choosing, leaving one of §5's three for a confirm that has to name
what breaks; "details" has no panel to open yet, and when it does all three fold into a menu with the
budget intact. Neither button is a tab stop — the row is (see §8). Multi-select via checkboxes; bulk action bar appears on selection.
**Installed.** Virtualized table: name (mono) · version · latest · size · chips. When the env's `hidden_user_site` is non-null (non-venv system Pythons only — see SECURITY §2), an inline `--color-info` note above the table says user-account packages are not listed and names the path; it is informational, never a block, and never appears for a venv. Up-to-date rows use `--color-text-dim` (owner's "dimmed" requirement); outdated rows show an `UPDATE` badge; pinned rows a 🔒 `--color-info` chip. Row actions: pin/unpin, uninstall, and **details**, as three inline buttons rather than a `⋮`
menu. A menu would spend one click opening and one choosing, leaving one of §5's three for a confirm
that has to name what breaks.
**This paragraph used to say the opposite**, and the correction is worth keeping rather than
overwriting. It said "details" had no panel to open yet, "and when it does all three fold into a
menu with the budget intact". P1-6 built the panel and the fold was wrong: it makes uninstall
`Installed → ⋮ → ✕ → Remove`, four clicks where §5's table records **three**, hand-counted, for the
second most destructive action in the application. Four is under the ceiling of 5, which is exactly
why the budget alone would have waved it through — a ceiling is not a ratchet, and a table of
measured counts is. The third button costs nothing instead: the row is the only tab stop (§8), so
its controls are a roving sequence rather than tab stops, and a third is one more arrow step, not
200 more stops. Ordered non-destructive first — details, pin, remove.
No button is a tab stop — the row is (see §8). Multi-select via checkboxes; bulk action bar appears on selection.
**Updates.** Same table filtered to outdated, badge count in sidebar. Header: *Select all* (excludes pinned; shows "3 pinned excluded"), *Update selected*. After resolve → **Preview panel** replaces the table: grouped sections — *Will upgrade* (A `1.2 → 2.0`), *Will downgrade*, *Will install*, *New dependencies*, *Needs decision* (held-back in `--color-warn` with one-line blocker sentence; impossible in `--color-danger`). Each needs-decision row hosts a segmented control: **Keep compatible · Skip · Force latest** (Force opens an inline confirm naming what breaks). Footer: `Confirm (n changes)` / `Back`.
@@ -116,6 +127,30 @@ thing on it. Counts come from `graph::dependent_count`, which counts in-force ed
set the uninstall guard warns about, because a user pinning on one rule and being warned on another
is the failure worth designing against.
**Dependencies** (surfaced under Installed → row → details): the focused package between two
columns — what requires it, and what it requires — each row carrying the specifier written on that
edge, and each clickable to re-centre. Below them, the two transitive counts: how many packages a
removal would leave with a missing dependency, and how many the package pulls in itself. A
requirement that nothing installed satisfies is called out; nothing else in PipDock reports one.
**Drawn at depth 1, and depth is navigated rather than drawn.** Measured on the 352-package fixture
before the screen was designed: a depth-1 neighbourhood is a median of **7** nodes and a p90 of 25,
while depth 2 is a median of **172** and exceeds 60 nodes for **212 of 352 packages**. No layout
algorithm makes 172 nodes legible, so the node-link diagram PRD P1-6's wording suggests would have
cost an eleventh runtime dependency, a `THIRD-PARTY-NOTICES.md` edit that re-shows the legal gate,
and a CSP argument — `tauri.conf.json` sets no `script-src`, so anything reaching for `eval` is
refused — to buy a picture nobody could read. Paths are not offered at all: `setuptools` has more
than **2000** distinct paths to a root in that environment, so "why is this here" has no
path-shaped answer at this scale, and the honest answer is a count.
Like Snapshots, it is a **mode** rather than a tab, for the reason below: `NAV_KEYS` is already
nine, and a Dependencies entry would have to sit beside Installed to read as related — an insert.
Columns are capped at `DEPS_ROWS_SHOWN` with the overflow counted from the **full** set, the
`SUGGESTIONS_SHOWN` rule for its reason: `setuptools` has 150 dependents, and a column of 150 is a
second package list. Nothing is carried by colour — §8's `forced-colors` block collapses `warn`,
`danger` and `info` to `CanvasText`, so every specifier is present as text.
**Snapshots** (surfaced under Environments → env detail): timeline of snapshots with trigger label, diff viewer (added/removed/changed in mono), `Rollback…` with its own preview per DATA-FLOW §8.
The detail view is a **mode of the Environments tab**, not a sidebar entry of its own. The reason is
@@ -179,6 +214,7 @@ app lands. Counted by hand in the running app, never inferred from the markup.
| Run Code Health | **3** | Health → Run (folder persisted) → view (**4** the first time in a project: Health → *Choose folder…* → the OS dialog, which is not PipDock's click → Run → view. The folder is remembered per environment from then on.) |
| Fix ruff findings | **3** | ruff tab → *Fix N…* → *Fix* (from a report already on screen; **5** from the landing screen with a folder remembered, which is the owner's ceiling). Cancel holds default focus, so `Enter` without `Tab` cancels. |
| Run a security audit | **2** | Security → *Run audit*. Counted in the running app against a stubbed bridge. The first run also builds the audit environment, which is a wait rather than a click. |
| See what depends on a package | **2** | Installed → row `⇄` (Installed is not the landing screen, so its tab click counts). Re-centring on a neighbour is one more click and no fetch — the graph is one value per environment. |
| Upgrade pip | **2** | *Upgrade pip* → *Upgrade* (Environments is the landing screen, so no tab click). The button appears only when pip is below the 22.2 planner floor — the case the ordinary Updates path cannot fix, because the planner it needs will not run. |
### Shell rules established by the first installed build (2026-08-13)
@@ -220,6 +256,8 @@ modal §7's destructive confirms need), `PdUninstallDialog` (§5's three options
🔒 chip, shared by the table and the Pins screen), `PdRollbackPreview` (DATA-FLOW §8's preview,
including its `PD-SNP-002` list) and `PdAuditReport` (P1-1's advisory list). Three more shipped in
1.1.0 and are named nowhere in this section: `PdCacheUsage`, `PdPalette` and `PdRequirements`.
`PdDepsFocus` (1.3.0, PRD P1-6's focus view) makes **ten** off-list components; it is written here
in the same breath as the count so the two cannot drift apart again.
## 7. States & feedback
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "pipdock",
"version": "1.2.0",
"version": "1.3.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "pipdock",
"version": "1.2.0",
"version": "1.3.0",
"license": "GPL-3.0-only",
"dependencies": {
"@tanstack/react-virtual": "^3.14.9",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "pipdock",
"version": "1.2.0",
"version": "1.3.0",
"private": true,
"description": "A friendly dock for your Python environments — bulk inspect, install, update and clean up Python packages.",
"license": "GPL-3.0-only",
+30
View File
@@ -377,6 +377,36 @@ pub async fn pin_suggestions(
))
}
/// The in-force dependency graph of one environment — PRD P1-6.
///
/// **One probe, one value, one call per environment.** The alternative shape — a command taking a
/// package and returning its neighbours — reads more naturally and is the wrong design: the view
/// re-centres on a click, so every click would pay a 605 ms probe to answer a question the
/// previous probe already had the data for. The whole graph is 249 KB on the 352-package fixture
/// and takes 45 ms to build, against the 605 ms the probe costs either way.
///
/// It is [`pin_suggestions`]'s shape rather than [`audit_run`]'s: a subprocess measured in
/// hundreds of milliseconds needs no `Sessions` slot, no progress channel and no cancellation.
/// Those exist for `audit_run` because an audit is 18-68 seconds; borrowing them here would be a
/// constant carrying its original units, which is the mistake `AUDIT_TIMEOUT` records.
///
/// Nothing is capped. The view shows a bounded window per column, but its "+ N more" count has to
/// come from the full set or a capped view misreports a total — the rule `SUGGESTIONS_SHOWN` and
/// `RUFF_ROWS_SHOWN` already follow.
///
/// # Errors
/// `PD-ENV-001` when the interpreter has gone, `PD-ENV-003` when the probe output is unreadable.
#[tauri::command]
pub async fn deps_graph(env: PyEnv) -> Wire<pipdock_core::graph::DepsGraph> {
// No store read at all, so there is no guard to drop — the graph depends on the interpreter
// and on nothing the user has configured. `pkg_list` is the same, and for the same reason.
let probed = envs::probe(&env.interpreter, env.source).await?;
Ok(
pipdock_core::graph::ReverseDeps::build_for(&probed.dists, &probed.env.python_version)
.view(),
)
}
/// Write the environment out as a `requirements.txt` — PRD P1-3.
///
/// **The document is `Engine::freeze`'s**, byte for byte, which is the same one a snapshot
+23
View File
@@ -71,6 +71,7 @@ pub fn run() {
commands::pin_add,
commands::pin_remove,
commands::pin_suggestions,
commands::deps_graph,
commands::env_export,
commands::requirements_read,
commands::cache_usage,
@@ -251,4 +252,26 @@ mod tests {
"NOT_YET lists commands that exist: {stale:?}"
);
}
#[test]
fn the_architecture_table_is_well_formed() {
// [`documented`] strips only the *leading* pipe, so a row missing its trailing one
// parses fine and renders wrong. `audit_run` shipped that way in 1.2.0 and no gate
// could see it: the command was registered, declared and documented, and the only
// thing broken was the markdown. Assert the shape as well as the contents.
let src = include_str!("../../docs/ARCHITECTURE.md");
let start = src
.find("| Command | Returns | Purpose |")
.expect("ARCHITECTURE §7's command table exists");
let ragged: Vec<&str> = src[start..]
.lines()
.skip(2)
.take_while(|l| l.starts_with("| `"))
.filter(|l| !l.trim_end().ends_with('|'))
.collect();
assert!(
ragged.is_empty(),
"ARCHITECTURE §7 rows missing a trailing pipe: {ragged:?}"
);
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "PipDock",
"version": "1.2.0",
"version": "1.3.0",
"identifier": "com.skullmute.pipdock",
"build": {
"beforeDevCommand": "npm run dev",
+182
View File
@@ -0,0 +1,182 @@
/**
* The shell, driven end to end against a bridge that logs every command — PRD P1-6.
*
* This is the jsdom form of the recipe that has caught more real defects in this project than any
* suite: run the app, stub `invoke`, push every `cmd` into an array, and read back exactly what
* crossed. Stage 2 found every screen fetching twice on mount that way, and Stage 4 found a plan
* started from Search resolving into a screen that does not render it — the command ran, the flow
* parked, and the user saw nothing change. Neither was visible in a passing component suite,
* because a component test renders one component and these are faults *between* them.
*
* The seam under test here is the one no other file covers: `PdPackageRow`'s new details button →
* `PdPackageTable` → `PdPackages` → `useDepsStore` → `PdDeps` → the bridge. `PdDepsFocus.test.tsx`
* proves what a node renders and `PdDeps.test.tsx` proves the fetch behaviour; only this proves a
* user can get there at all, and in how many clicks.
*/
import { fireEvent, render, screen, within } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { App } from '@/App'
import type { DepsGraph, Dist } from '@/ipc'
import { useDepsStore, useEnvStore, useLegalStore, useUiStore } from '@/stores'
import graphFixture from '@/test/fixtures/deps_graph.json'
import listFixture from '@/test/fixtures/pkg_list.json'
/** Every command that crossed the bridge, in order — the whole point of this file. */
const crossed: string[] = []
const { depsGraph, pkgList, pkgOutdated, pinList, legalConsentGet } = vi.hoisted(() => ({
depsGraph: vi.fn(),
pkgList: vi.fn(),
pkgOutdated: vi.fn(),
pinList: vi.fn(),
legalConsentGet: vi.fn(),
}))
vi.mock('@/ipc', async () => {
const actual = await vi.importActual<typeof import('@/ipc')>('@/ipc')
return {
...actual,
depsGraph,
pkgList,
pkgOutdated,
pinList,
// Not optional, and the reason is the same one the browser recipe records: `App` calls
// `checkConsent()` on mount, and `useLegalStore.check` **fails closed** — an unreadable
// consent record must never skip the gate. Setting `accepted: true` in the store is undone a
// tick later by the real command rejecting, and the gate replaces the whole shell. The first
// draft of this file did exactly that: the row rendered, the click landed, the store went to
// `phase: 'ready'` with the graph in hand, and every assertion looked at a licence agreement.
legalConsentGet,
}
})
const GRAPH = graphFixture as DepsGraph
const DISTS = listFixture as Dist[]
const ENV_HASH = 'abc123'
const INTERPRETER = String.raw`C:\proj\.venv\Scripts\python.exe`
const ROW = {
interpreter: INTERPRETER,
source: 'venv' as const,
envHash: ENV_HASH,
env: {
interpreter: INTERPRETER,
prefix: String.raw`C:\proj\.venv`,
pythonVersion: '3.12.10',
externallyManaged: false,
source: 'venv' as const,
},
}
beforeEach(() => {
crossed.length = 0
// Each mock records its own name on the way in. A generic wrapper reads better and does
// not typecheck: `ReturnType<typeof vi.fn>` is `Mock<Procedure | Constructable>`, which is
// not directly callable.
const record = <T,>(name: string, value: T) => () => {
crossed.push(name)
return Promise.resolve(value)
}
depsGraph.mockReset().mockImplementation(record('deps_graph', GRAPH))
pkgList.mockReset().mockImplementation(record('pkg_list', DISTS))
pkgOutdated.mockReset().mockImplementation(record('pkg_outdated', []))
pinList.mockReset().mockImplementation(record('pin_list', []))
// Past the gate, and it takes both halves. The store field is what the first render reads; the
// command is what the mount effect overwrites it with.
legalConsentGet.mockReset().mockResolvedValue({ current: true, recorded: true })
useLegalStore.setState({ accepted: true, review: false })
useUiStore.setState({ nav: 'installed' })
useDepsStore.setState({
phase: 'idle',
graph: null,
graphFor: null,
focus: null,
error: null,
})
useEnvStore.setState({
rows: [ROW],
selected: INTERPRETER,
packages: DISTS.map((d) => ({
name: d.name,
version: d.version,
latest: null,
sizeBytes: d.sizeBytes ?? null,
pinned: null,
state: 'unknown' as const,
})),
listing: 'ready',
outdatedStatus: 'ready',
selection: new Set<string>(),
} as never)
})
/** A package row by name, in the virtualized table. */
const rowFor = (name: string) => {
const row = screen.getByText(name).closest('[role="row"]')
if (row === null) throw new Error(`no row rendered for ${name}`)
return row as HTMLElement
}
describe('the dependency view, reached the way a user reaches it', () => {
it('opens from a package row in one click, and shows that package', async () => {
// UI-SPEC §5: Installed is already the screen, so this is click 1 of 2. The second is nothing —
// the view is there. A `⋮` menu would have made it 1 of 3 and pushed uninstall to 4.
render(<App />)
fireEvent.click(within(rowFor('numpy')).getByLabelText('Show dependencies'))
expect(await screen.findByText('pandas')).toBeInTheDocument()
expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('Dependencies')
// The focused package, and both its dependents with their differing specifiers.
expect(screen.getByText(/<2,>=1\.26\.0/)).toBeInTheDocument()
expect(screen.getByText(/<1\.28\.0,>=1\.21\.6/)).toBeInTheDocument()
})
it('crosses the bridge once for the graph, and not again on a re-centre', async () => {
// The design the whole slice turns on, asserted where it can actually be observed. A
// `deps_for(pkg)` command would read more naturally and put a 605 ms probe behind this click.
render(<App />)
fireEvent.click(within(rowFor('numpy')).getByLabelText('Show dependencies'))
await screen.findByText('pandas')
expect(crossed.filter((c) => c === 'deps_graph')).toHaveLength(1)
fireEvent.click(screen.getByText('pandas'))
await screen.findByText(/python-dateutil/)
expect(crossed.filter((c) => c === 'deps_graph')).toHaveLength(1)
})
it('does not ask for the graph until someone opens the view', async () => {
// It costs a probe. `pin_suggestions` is on the Pins screen for this reason and says so; a
// graph fetched on mount would tax every environment open for a screen most users never open.
render(<App />)
await screen.findByText('numpy')
expect(crossed).not.toContain('deps_graph')
})
it('goes back to the table, and the table is still there', async () => {
render(<App />)
fireEvent.click(within(rowFor('numpy')).getByLabelText('Show dependencies'))
await screen.findByText('pandas')
fireEvent.click(screen.getByText('Back to packages'))
expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('Installed')
expect(rowFor('numpy')).toBeInTheDocument()
})
it('leaves the row\u2019s other two actions where they were', () => {
// The reason there are three inline buttons rather than a menu. If this ever regresses to a
// `⋮`, uninstall goes from three hand-counted clicks to four.
render(<App />)
const row = within(rowFor('numpy'))
expect(row.getByLabelText('Remove this package')).toBeInTheDocument()
expect(row.getByLabelText('Pin this package')).toBeInTheDocument()
expect(row.getByLabelText('Show dependencies')).toBeInTheDocument()
// ...and none of the three is a tab stop; the row is.
for (const button of row.getAllByRole('button')) {
expect(button).toHaveAttribute('tabindex', '-1')
}
})
})
+8 -1
View File
@@ -19,7 +19,7 @@ import { PdSearch } from '@/screens/PdSearch'
import { PdSecurity } from '@/screens/PdSecurity'
import { PdSettings } from '@/screens/PdSettings'
import { PANEL_PHASES } from '@/stores/plan'
import { useEnvStore, useLegalStore, usePlanStore, useUiStore } from '@/stores'
import { useDepsStore, useEnvStore, useLegalStore, usePlanStore, useUiStore } from '@/stores'
/**
* Which screen each tab shows. A lookup rather than a ternary chain: the chain's last branch was a
@@ -66,6 +66,7 @@ export function App() {
const widen = usePlanStore((s) => s.widen)
const confirmUninstall = usePlanStore((s) => s.confirmUninstall)
const resetPlan = usePlanStore((s) => s.reset)
const resetDeps = useDepsStore((s) => s.reset)
const guardOpen = planPhase === 'guard' && guard !== null
const mainRef = useRef<HTMLElement>(null)
// Shell state, like `nav` — but local, because nothing outside this component reads it.
@@ -181,6 +182,12 @@ export function App() {
// panel is stale the moment the run finishes. `force`, because `snapshotsFor`
// still matches and would suppress the refetch.
void loadSnapshots(true)
// The graph is stale too, and this is the one slice whose freshness guard cannot
// see it: `freshGraph` keys on `envHash`, which a mutation does not change. Health
// and Security guard and never reset because nothing they read is altered by an
// install; edges are exactly what an install alters. Cleared rather than
// refetched, so the probe is paid again only if the view is opened again.
resetDeps()
}}
/>
) : (SCREENS[nav] ?? (
+148
View File
@@ -0,0 +1,148 @@
/**
* `PdDepsFocus` against the **computed** fixture — PRD P1-6.
*
* `deps_graph.json` is produced by `crate::fixtures::deps_graph`, which runs the real
* `ReverseDeps::view` over the real `pkg_list()`. Hand-writing it would let the graph's rules drift
* from what this file asserts while the assertions stayed plausible, which is exactly how the
* held-back preview shipped a doubled sentence from S3 to 1.1.0 with every suite green.
*
* No store and no `vi.mock('@/ipc')`: the component takes props. `PdDeps.test.tsx` covers the
* screen that feeds it — the seam between a tested component and its untested parent is where the
* `PdPlanPanel` bug lived.
*/
import { fireEvent, render, screen, within } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import { PdDepsFocus } from '@/components/PdDepsFocus'
import type { DepsGraph, DepsNode } from '@/ipc'
import graphFixture from '@/test/fixtures/deps_graph.json'
const GRAPH = graphFixture as DepsGraph
const nodeFor = (pkg: string): DepsNode => {
const node = GRAPH.nodes[pkg]
if (node === undefined) throw new Error(`fixture has no node for ${pkg}`)
return node
}
function setup(pkg: string, overrides: Partial<Parameters<typeof PdDepsFocus>[0]> = {}) {
const onFocus = vi.fn()
render(<PdDepsFocus pkg={pkg} node={nodeFor(pkg)} onFocus={onFocus} {...overrides} />)
return { onFocus }
}
/**
* A column by its `aria-labelledby`, not by its accessible name.
*
* Keying on copy costs a rewrite every time the copy moves, and the first draft of this file
* proved it: the heading pluralises, so `/requires this/` matched the singular and silently found
* nothing for the two-dependent case the fixture exists to exercise. The id is the stable thing.
*/
const column = (which: 'dependents' | 'dependencies'): HTMLElement => {
const el = document.querySelector(`section[aria-labelledby="deps-${which}"]`)
if (el === null) throw new Error(`no ${which} column rendered`)
return el as HTMLElement
}
const dependents = () => column('dependents')
const dependencies = () => column('dependencies')
/** A column's heading text, which reports the full count rather than the visible window. */
const heading = (which: 'dependents' | 'dependencies') =>
document.getElementById(`deps-${which}`)?.textContent
describe('PdDepsFocus', () => {
it('names both dependents and the specifier each declared', () => {
// The case both columns exist for: two dependents of `numpy` with two *different* specifiers.
// A column listing names alone would say these two packages are in the same position, and
// they are not — one excludes 2.x and the other excludes 1.28+.
setup('numpy')
const column = within(dependents())
expect(column.getByText('pandas')).toBeInTheDocument()
expect(column.getByText(/<2,>=1\.26\.0/)).toBeInTheDocument()
expect(column.getByText('scipy')).toBeInTheDocument()
expect(column.getByText(/<1\.28\.0,>=1\.21\.6/)).toBeInTheDocument()
})
it('carries each neighbour version, so a specifier can be checked by hand', () => {
setup('numpy')
expect(within(dependents()).getByText(/2\.1\.4/)).toBeInTheDocument()
})
it('re-centres on a neighbour rather than fetching', () => {
// The whole reason `deps_graph` returns one value per environment: this click is a lookup.
const { onFocus } = setup('numpy')
fireEvent.click(within(dependents()).getByText('pandas'))
expect(onFocus).toHaveBeenCalledWith('pandas')
})
it('states the transitive counts, which is what the view adds over a single hop', () => {
setup('numpy')
expect(screen.getByText(/Removing this would leave 2 packages/)).toBeInTheDocument()
expect(screen.getByText(/pulls in 0 packages/)).toBeInTheDocument()
})
it('reports a requirement nothing satisfies', () => {
// `pandas` declares `python-dateutil` and the fixture set does not install it. Nothing else in
// PipDock says so, and it is only trustworthy because Rust evaluated the markers first.
setup('pandas')
expect(screen.getByText(/python-dateutil/)).toBeInTheDocument()
})
it('says nothing about unsatisfied requirements when there are none', () => {
// The other direction of P4's defect: a screen that reports an empty list as a finding.
setup('scipy')
expect(screen.queryByText(/nothing installed to satisfy/)).toBeNull()
})
it('renders a leaf as an honest empty rather than falling through', () => {
// 32 of the 352-package fixture have no edge in either direction. "Nothing here" twice is the
// correct answer; a blank panel is the P4 defect wearing a different hat.
setup('certifi')
expect(within(dependents()).getByText('Nothing here')).toBeInTheDocument()
expect(within(dependencies()).getByText('Nothing here')).toBeInTheDocument()
})
it('caps a column and counts the overflow from the full set', () => {
// `setuptools` has 150 dependents in the real 352-package environment. `rowsShown` is
// overridable so this can be proved on a fixture with two.
setup('numpy', { rowsShown: 1 })
const column = within(dependents())
expect(column.getByText('pandas')).toBeInTheDocument()
expect(column.queryByText('scipy')).toBeNull()
expect(column.getByText('1 more not shown')).toBeInTheDocument()
// ...and the heading still reports the total, not the window.
expect(heading('dependents')).toBe('2 packages require this')
})
it('says a package it has never heard of is not in the listing', () => {
// A row can be clicked after the package left the environment. An answer, not a crash.
const onFocus = vi.fn()
render(<PdDepsFocus pkg="ghost" node={null} onFocus={onFocus} />)
expect(screen.getByText(/ghost is not in this environment/)).toBeInTheDocument()
})
it('states every constraint as text, so forced-colors mode loses nothing', () => {
// `styles.css` rebinds every --color-* token to a system keyword, collapsing warn, danger and
// info to CanvasText. A row that leaned on colour to say "this one constrains you" would say
// nothing at all in that mode, so the specifier is always present as characters.
setup('numpy')
for (const edge of nodeFor('numpy').dependents) {
expect(within(dependents()).getByText(new RegExp(escape(edge.constraint)))).toBeInTheDocument()
}
})
it('spells out an unconstrained edge instead of leaving a gap', () => {
// An empty specifier means "any version", which is a different statement from "no edge". A
// blank would read as the second.
const node: DepsNode = {
...nodeFor('numpy'),
dependents: [{ pkg: 'anything', version: '1.0', constraint: '' }],
}
render(<PdDepsFocus pkg="numpy" node={node} onFocus={vi.fn()} />)
expect(within(dependents()).getByText(/any version/)).toBeInTheDocument()
})
})
/** Escape a PEP 440 specifier for use inside a RegExp. */
function escape(s: string): string {
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}
+198
View File
@@ -0,0 +1,198 @@
/**
* The dependency focus view — PRD P1-6's "who holds this back", UI-SPEC §4.
*
* Three columns: what requires the focused package, the package, and what it requires. Clicking a
* neighbour re-centres, so **depth is navigated rather than drawn**.
*
* # Why depth 1, and why this is not a node-link diagram
*
* Measured against the 352-package fixture before any of this was designed. A depth-1
* neighbourhood is a **median of 7 nodes** and a p90 of 25 — small enough to read at a glance.
* Depth 2 is a **median of 172** and exceeds 60 nodes for **212 of 352 packages**. No layout
* algorithm makes 172 nodes legible, so a graph library would have bought an eleventh runtime
* dependency, a `THIRD-PARTY-NOTICES.md` edit that re-shows the legal gate, and a CSP argument —
* `tauri.conf.json` sets no `script-src`, so anything reaching for `eval` is refused — in exchange
* for a picture nobody can use.
*
* The transitive question is answered by **numbers**: `impact` and `reach` come from Rust's own
* closures. Paths are not offered at all, because there are more than 2000 distinct paths from
* `setuptools` to a root in that same environment; "why is this here" has no path-shaped answer at
* this scale.
*
* # Rendering rules this had to obey
*
* This is the first visual primitive in the app, and `styles.css`'s `forced-colors` block rebinds
* every `--color-*` token to a system keyword — `warn`, `danger` and `info` all collapse to
* `CanvasText`. So **nothing here is carried by colour alone**: every edge states its constraint
* as text, and the two columns are told apart by their headings and their position, not their
* hue. The connectors are borders rather than SVG strokes, which keeps them visible in that mode
* and needs no `viewBox` to stay right at the 1600×1100 window ceiling.
*
* Prop-driven and store-free, like `PdAuditReport`: it can be tested against a fixture with no
* store at all, and `rowsShown` is overridable so the cap can be exercised without 150 rows.
*/
import { useTranslation } from 'react-i18next'
import type { DepEdge, DepsNode } from '@/ipc'
/**
* Rows per column before the "+ N more" line.
*
* `SUGGESTIONS_SHOWN`'s rule, for its reason: `setuptools` has **150** dependents in the
* 352-package fixture, and a column of 150 is not a view, it is a second package list. The count
* in the overflow line comes from the **full** array, so a capped column never misreports a total.
*/
export const DEPS_ROWS_SHOWN = 8
interface PdDepsFocusProps {
/** The focused package's name. */
pkg: string
/** Its node, or null when the graph has never heard of it. */
node: DepsNode | null
/** Re-centre on a neighbour. */
onFocus: (pkg: string) => void
/** Overridable so a test can exercise the cap without a 150-row fixture. */
rowsShown?: number
}
function Column({
labelId,
heading,
edges,
rowsShown,
onFocus,
side,
}: {
labelId: string
heading: string
edges: DepEdge[]
rowsShown: number
onFocus: (pkg: string) => void
/** Which way the connector points. Decoration only — the heading carries the meaning. */
side: 'left' | 'right'
}) {
const { t } = useTranslation()
const shown = edges.slice(0, rowsShown)
const hidden = edges.length - shown.length
return (
<section aria-labelledby={labelId} className="min-w-0 flex-1">
<h2 id={labelId} className="text-data text-text-dim">
{heading}
</h2>
<ul className="mt-2 flex flex-col gap-1">
{shown.map((edge) => (
<li key={edge.pkg} className="flex min-w-0 items-center gap-2">
{side === 'right' ? (
<span aria-hidden="true" className="shrink-0 text-text-dim">
{'─'}
</span>
) : null}
<button
type="button"
onClick={() => {
onFocus(edge.pkg)
}}
title={t('deps.focusOn', { pkg: edge.pkg })}
className="min-w-0 flex-1 truncate rounded-pd border border-border px-2 py-0.5 text-left font-mono text-data"
>
<span className="text-text">{edge.pkg}</span>
{edge.version === null || edge.version === undefined ? null : (
<span className="text-text-dim">{` ${edge.version}`}</span>
)}
{/* The specifier, always as text. In forced-colors every token above collapses to
CanvasText, so a row that leaned on colour to say "this one constrains you"
would say nothing at all. */}
<span className="text-text-dim">
{edge.constraint === ''
? ` ${t('deps.unconstrained')}`
: ` ${edge.constraint}`}
</span>
</button>
{side === 'left' ? (
<span aria-hidden="true" className="shrink-0 text-text-dim">
{'─'}
</span>
) : null}
</li>
))}
</ul>
{hidden > 0 ? (
<p className="mt-2 text-data text-text-dim">{t('deps.more', { count: hidden })}</p>
) : null}
{edges.length === 0 ? (
<p className="mt-2 text-data text-text-dim">{t('deps.none')}</p>
) : null}
</section>
)
}
export function PdDepsFocus({
pkg,
node,
onFocus,
rowsShown = DEPS_ROWS_SHOWN,
}: PdDepsFocusProps) {
const { t } = useTranslation()
// A package can leave the environment between the fetch and the click that focuses it. Saying
// so is a real answer; throwing would turn a stale row into a crash.
if (node === null) {
return (
<p className="text-data text-text-dim">{t('deps.unknownPackage', { pkg })}</p>
)
}
return (
<div className="flex flex-col gap-4">
{/* Stacks below `md`. The window tops out at 1600×1100 and cannot be maximized, so this is
not a phone breakpoint — it is the narrow end of a real window, where three columns of
package names would each be too narrow to read a version in. */}
<div className="flex flex-col items-stretch gap-4 md:flex-row md:items-center">
<Column
labelId="deps-dependents"
heading={t('deps.dependents', { count: node.dependents.length })}
edges={node.dependents}
rowsShown={rowsShown}
onFocus={onFocus}
side="left"
/>
<div className="shrink-0 rounded-pd border border-accent px-4 py-2 text-center">
<p className="font-mono text-data text-accent">{pkg}</p>
{node.version === null || node.version === undefined ? null : (
<p className="font-mono text-data text-text-dim">{node.version}</p>
)}
</div>
<Column
labelId="deps-dependencies"
heading={t('deps.dependencies', { count: node.dependencies.length })}
edges={node.dependencies}
rowsShown={rowsShown}
onFocus={onFocus}
side="right"
/>
</div>
{/* The transitive answer, and the only thing this view adds over what the app already did
single-hop. `impact` is `removal_closure` without the package itself; `reach` is its
forward mirror. Both are counts rather than a drawing, for the reason in the module doc. */}
<p className="text-data text-text-dim">
<span>{t('deps.impact', { count: node.impact })}</span>
<span>{' '}</span>
<span>{t('deps.reach', { count: node.reach })}</span>
</p>
{node.unsatisfied !== undefined && node.unsatisfied.length > 0 ? (
<p className="text-data text-warn">
{t('deps.unsatisfied', {
count: node.unsatisfied.length,
packages: node.unsatisfied.join(', '),
})}
</p>
) : null}
</div>
)
}
+27 -6
View File
@@ -29,6 +29,8 @@ interface PdPackageRowProps {
onToggle: (name: string) => void
onPinToggle: (name: string) => void
onUninstall: (name: string) => void
/** Open the dependency view focused on this package — UI-SPEC §4's "details" (PRD P1-6). */
onDetails: (name: string) => void
/** The virtualizer's absolute positioning. */
style: React.CSSProperties
}
@@ -41,6 +43,7 @@ function Row({
onToggle,
onPinToggle,
onUninstall,
onDetails,
style,
}: PdPackageRowProps) {
const { t, i18n } = useTranslation()
@@ -144,13 +147,31 @@ function Row({
</span>
{/* UI-SPEC §5's 3-click uninstall: this is the first click, *Remove* in the dialog is the
third. Two inline buttons rather than the `⋮` menu §4 describes — a menu would spend the
first click opening it and the second choosing, leaving one for a confirm that has to
name what breaks, and §4's third entry ("details") has no panel to open yet. When it
does, these fold into the menu and the budget still holds.
third.
Neither is a tab stop: the row is (see onKeyDown). Two hundred rows times three stops is
not traversal. They stay clickable and stay announced. */}
§4 used to say the third action would fold all three into a `⋮` menu. **It does not**,
and that is a deliberate correction rather than an oversight. A menu spends one click
opening and one choosing, so uninstall would become Installed → ⋮ → ✕ → *Remove*: four
clicks where §5's table records three, hand-counted, for the second most destructive
thing in the app. The ceiling is 5 and 4 would still be under it, which is exactly why
the budget alone would have let this through.
A third inline button costs nothing instead. The row is the only tab stop (see
onKeyDown), so the controls are a roving sequence rather than tab stops — a third one
adds a left/right step, not 200 more stops. Ordered non-destructive first: details, pin,
remove. */}
<button
type="button"
tabIndex={-1}
onClick={() => {
onDetails(row.name)
}}
aria-label={t('packages.actions.details')}
title={t('packages.actions.details')}
className="shrink-0 rounded-pd border border-border px-2 py-0.5 text-data text-text-dim"
>
{'⇄'}
</button>
<button
type="button"
tabIndex={-1}
@@ -33,6 +33,7 @@ function setup(overrides: Partial<Parameters<typeof PdPackageTable>[0]> = {}) {
onToggle: vi.fn(),
onPinToggle: vi.fn(),
onUninstall: vi.fn(),
onDetails: vi.fn(),
onSelectAll: vi.fn(),
initialRect: { width: 1280, height: 600 },
...overrides,
+4
View File
@@ -26,6 +26,8 @@ interface PdPackageTableProps {
onToggle: (name: string) => void
onPinToggle: (name: string) => void
onUninstall: (name: string) => void
/** Open the dependency view focused on a package — PRD P1-6. */
onDetails: (name: string) => void
/**
* Select every selectable row in the **current filtered set**, not just the rendered window.
*
@@ -48,6 +50,7 @@ export function PdPackageTable({
onToggle,
onPinToggle,
onUninstall,
onDetails,
onSelectAll,
initialRect,
}: PdPackageTableProps) {
@@ -127,6 +130,7 @@ export function PdPackageTable({
onToggle={onToggle}
onPinToggle={onPinToggle}
onUninstall={onUninstall}
onDetails={onDetails}
style={{
height: `${String(ROW_HEIGHT)}px`,
transform: `translateY(${String(item.start)}px)`,
+68
View File
@@ -267,6 +267,74 @@ export type DeclaredSource =
| { files: string[]; kind: 'requirements' }
| { kind: 'none' };
/**
* One edge of the dependency graph, seen from a focused package.
*
* `pkg` is always the **other end** of the edge and `constraint` always the specifier written on
* it, so one type serves both directions: in a dependents column `pkg` is who requires the focus,
* in a dependencies column it is what the focus requires. `version` is that package's installed
* version.
*
* Three fields identical to [`BrokenDependent`], and deliberately a separate type. That one is
* about *breakage* — its doc is written for the uninstall dialog and its `Ord` exists for the
* dedup in [`ReverseDeps::breaking_dependents`] — so reusing it here would have a dependencies
* column claim every dependency is a broken dependent. The `From` impl below is the bridge, and
* [`ReverseDeps::edges_to`] goes through it precisely so the two cannot drift.
*
* `constraint` is the **bare specifier tail** — `"<2,>=1.26.0"`, never `"numpy<2,>=1.26.0"` — for
* [`BrokenDependent`]'s reason. The other half of the sentence is the focused package, which the
* caller already has; Rust emits data and each head writes its own sentence (I18N §1). An empty
* string means unconstrained, which is a different statement from "no edge" and the view says so.
*/
export interface DepEdge {
/** The version specifier written on the edge. Empty when unconstrained. */
constraint: string;
/** The package at the other end of the edge. */
pkg: PkgName;
/** Its installed version, when the graph knows it. */
version?: string | null;
}
/**
* The in-force dependency graph of one environment (PRD P1-6).
*
* Keyed by package name, one entry per installed distribution. Produced by
* [`ReverseDeps::view`]; see its doc for why this crosses the bridge whole rather than a package
* at a time, and why nothing here is capped.
*/
export interface DepsGraph {
/** Every installed package, including those with no edges in either direction. */
nodes: Record<string, DepsNode>;
}
/**
* Everything a focus view needs about one installed package.
*
* `impact` and `reach` are the pair the view exists for. Every other question PipDock answers
* about the graph is single-hop — the uninstall guard, blocker attribution and pin auto-suggest
* all look one edge out — so the only thing a dependency view adds over shipped behaviour is
* **transitive** reach, and it is a number rather than a picture because the picture does not
* survive the scale: measured on the 352-package fixture, a depth-2 neighbourhood is a median of
* 172 nodes and exceeds 60 for 212 of 352 packages.
*/
export interface DepsNode {
/** Installed packages this one requires, in force. */
dependencies: DepEdge[];
/** Installed packages that require this one, with the constraint each declared. */
dependents: DepEdge[];
/**
* How many packages would be left broken if this one went, transitively. The size of
* [`ReverseDeps::removal_closure`] without the package itself.
*/
impact: number;
/** How many installed packages this one pulls in, transitively. */
reach: number;
/** In-force requirements with nothing installed to satisfy them. */
unsatisfied?: PkgName[];
/** The package's own installed version. */
version?: string | null;
}
/**
* One deptry violation, grouped by the dependency it is about.
*
+12
View File
@@ -18,6 +18,7 @@ import { open, save } from '@tauri-apps/plugin-dialog'
import type {
AuditReport,
Decision,
DepsGraph,
Dist,
Freshness,
Hit,
@@ -69,6 +70,7 @@ export const COMMANDS = [
'pin_add',
'pin_remove',
'pin_suggestions',
'deps_graph',
'env_export',
'requirements_read',
'cache_usage',
@@ -255,6 +257,16 @@ export const pinRemove = (envHash: string, pkg: string): Promise<boolean> =>
export const pinSuggestions = (env: PyEnv): Promise<PinSuggestion[]> =>
invoke('pin_suggestions', { env })
/**
* The in-force dependency graph of the environment — PRD P1-6.
*
* **Costs one probe, and is asked once per environment rather than once per package.** The focus
* view re-centres by indexing `nodes`, so a per-package command would pay that probe on every
* click. Everything about which edges are in force — PEP 508 markers, extra-gating — is decided
* in Rust; this side looks up a key and never parses a requirement.
*/
export const depsGraph = (env: PyEnv): Promise<DepsGraph> => invoke('deps_graph', { env })
/**
* Write the environment out as a `requirements.txt`, resolving to the path written (PRD P1-3).
*
+22
View File
@@ -97,6 +97,7 @@
"actions": {
"pin": "Pin this package",
"unpin": "Remove this pin",
"details": "Show dependencies",
"uninstall": "Remove this package",
"updateSelected": "Update selected",
"clearSelection": "Clear"
@@ -117,6 +118,27 @@
"orphanOutdated_one": "{{count}} package has an update but is not in this listing.",
"orphanOutdated_other": "{{count}} packages have updates but are not in this listing."
},
"deps": {
"title": "Dependencies",
"back": "Back to packages",
"loading": "Reading this environment's dependencies\u2026",
"dependents_one": "{{count}} package requires this",
"dependents_other": "{{count}} packages require this",
"dependencies_one": "Requires {{count}} package",
"dependencies_other": "Requires {{count}} packages",
"more_one": "{{count}} more not shown",
"more_other": "{{count}} more not shown",
"none": "Nothing here",
"unconstrained": "(any version)",
"focusOn": "Show {{pkg}}",
"impact_one": "Removing this would leave {{count}} package with a missing dependency.",
"impact_other": "Removing this would leave {{count}} packages with a missing dependency.",
"reach_one": "It pulls in {{count}} package of its own.",
"reach_other": "It pulls in {{count}} packages of its own.",
"unsatisfied_one": "{{count}} requirement has nothing installed to satisfy it: {{packages}}",
"unsatisfied_other": "{{count}} requirements have nothing installed to satisfy them: {{packages}}",
"unknownPackage": "{{pkg}} is not in this environment's listing."
},
"plan": {
"section": {
"upgrade": "Will upgrade ({{count}})",
+16
View File
@@ -96,6 +96,7 @@
"actions": {
"pin": "Ghim gói này",
"unpin": "Bỏ ghim",
"details": "Xem phụ thuộc",
"uninstall": "Gỡ gói này",
"updateSelected": "Cập nhật các gói đã chọn",
"clearSelection": "Bỏ chọn"
@@ -113,6 +114,21 @@
"outdatedFailed": "Không kiểm tra được cập nhật, nên chưa gói nào được gắn nhãn.",
"orphanOutdated_other": "{{count}} gói có bản cập nhật nhưng không có trong danh sách này."
},
"deps": {
"title": "Ph\u1ee5 thu\u1ed9c",
"back": "Quay l\u1ea1i danh s\u00e1ch g\u00f3i",
"loading": "\u0110ang \u0111\u1ecdc ph\u1ee5 thu\u1ed9c c\u1ee7a m\u00f4i tr\u01b0\u1eddng n\u00e0y\u2026",
"dependents_other": "{{count}} g\u00f3i c\u1ea7n g\u00f3i n\u00e0y",
"dependencies_other": "C\u1ea7n {{count}} g\u00f3i",
"more_other": "C\u00f2n {{count}} m\u1ee5c kh\u00f4ng hi\u1ec3n th\u1ecb",
"none": "Kh\u00f4ng c\u00f3 g\u00ec \u1edf \u0111\u00e2y",
"unconstrained": "(phi\u00ean b\u1ea3n b\u1ea5t k\u1ef3)",
"focusOn": "Xem {{pkg}}",
"impact_other": "G\u1ee1 g\u00f3i n\u00e0y s\u1ebd l\u00e0m {{count}} g\u00f3i thi\u1ebfu ph\u1ee5 thu\u1ed9c.",
"reach_other": "G\u00f3i n\u00e0y k\u00e9o theo {{count}} g\u00f3i kh\u00e1c.",
"unsatisfied_other": "{{count}} y\u00eau c\u1ea7u kh\u00f4ng c\u00f3 g\u00f3i n\u00e0o \u0111\u00e1p \u1ee9ng: {{packages}}",
"unknownPackage": "{{pkg}} kh\u00f4ng c\u00f3 trong danh s\u00e1ch c\u1ee7a m\u00f4i tr\u01b0\u1eddng n\u00e0y."
},
"plan": {
"section": {
"upgrade": "Sẽ nâng cấp ({{count}})",
+132
View File
@@ -0,0 +1,132 @@
/**
* The dependency screen — the states around the focus view, and the fetch behind it.
*
* `PdDepsFocus.test.tsx` covers what a node renders. This covers what `PdDepsFocus` never sees:
* that the graph is fetched **once per environment and never per click**, that a graph belonging to
* another environment is not shown under this one's name, and that a mutation invalidates it. The
* seam between a tested component and its untested parent is where `PdPlanPanel`'s duplicate
* button lived.
*/
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { PdDeps } from '@/screens/PdDeps'
import type { DepsGraph } from '@/ipc'
import { useDepsStore, useEnvStore } from '@/stores'
import graphFixture from '@/test/fixtures/deps_graph.json'
const { depsGraph } = vi.hoisted(() => ({ depsGraph: vi.fn() }))
vi.mock('@/ipc', async () => {
const actual = await vi.importActual<typeof import('@/ipc')>('@/ipc')
return { ...actual, depsGraph }
})
const GRAPH = graphFixture as DepsGraph
const ENV_HASH = 'abc123'
const ROW = {
interpreter: String.raw`C:\proj\.venv\Scripts\python.exe`,
source: 'venv' as const,
envHash: ENV_HASH,
env: {
interpreter: String.raw`C:\proj\.venv\Scripts\python.exe`,
prefix: String.raw`C:\proj\.venv`,
pythonVersion: '3.12.10',
externallyManaged: false,
source: 'venv' as const,
},
}
beforeEach(() => {
depsGraph.mockReset()
depsGraph.mockResolvedValue(GRAPH)
useDepsStore.setState({
phase: 'idle',
graph: null,
graphFor: null,
focus: 'numpy',
error: null,
})
useEnvStore.setState({ rows: [ROW], selected: ROW.interpreter } as never)
})
describe('PdDeps', () => {
it('fetches the graph once per environment, not once per package', async () => {
// The design this whole slice turns on. A per-package command would read more naturally and
// pay a 605 ms probe on every re-centring click.
render(<PdDeps />)
await screen.findByText('pandas')
expect(depsGraph).toHaveBeenCalledTimes(1)
fireEvent.click(screen.getByText('pandas'))
await screen.findByText(/python-dateutil/)
expect(useDepsStore.getState().focus).toBe('pandas')
// Still one. The re-centre was an object lookup.
expect(depsGraph).toHaveBeenCalledTimes(1)
})
it('does not refetch when the screen remounts with the graph already in hand', async () => {
const { unmount } = render(<PdDeps />)
await screen.findByText('pandas')
unmount()
render(<PdDeps />)
await screen.findByText('pandas')
expect(depsGraph).toHaveBeenCalledTimes(1)
})
it('says it is loading rather than rendering an empty view first', async () => {
// P4's defect and its inverse: a screen must not say "nothing here" before anything has been
// read, and must not say "loading" over a graph it already holds.
let release: (g: DepsGraph) => void = () => undefined
depsGraph.mockReturnValue(
new Promise<DepsGraph>((resolve) => {
release = resolve
}),
)
render(<PdDeps />)
expect(screen.getByText(/Reading this environment/)).toBeInTheDocument()
expect(screen.queryByText('Nothing here')).toBeNull()
release(GRAPH)
await screen.findByText('pandas')
expect(screen.queryByText(/Reading this environment/)).toBeNull()
})
it('does not show one environment\u2019s graph under another\u2019s name', async () => {
// `freshGraph`'s whole job. Without it the previous environment's edges stay on screen, named
// as if they described the new one.
useDepsStore.setState({ graph: GRAPH, graphFor: 'a-different-env', phase: 'ready' })
render(<PdDeps />)
expect(screen.queryByText('pandas')).toBeNull()
// ...and it goes and gets the right one.
await waitFor(() => {
expect(depsGraph).toHaveBeenCalledTimes(1)
})
await screen.findByText('pandas')
})
it('drops the graph when the probe fails, rather than keeping a stale one', async () => {
depsGraph.mockRejectedValue({ code: 'PD-ENV-001', message: 'no interpreter' })
render(<PdDeps />)
await screen.findByText(/PD-ENV-001/)
expect(useDepsStore.getState().graph).toBeNull()
})
it('leaves the mode on Back, and keeps the graph so reopening is free', async () => {
render(<PdDeps />)
await screen.findByText('pandas')
fireEvent.click(screen.getByText('Back to packages'))
expect(useDepsStore.getState().focus).toBeNull()
// The environment's edges did not become wrong because the view closed.
expect(useDepsStore.getState().graph).not.toBeNull()
})
it('renders an h1, which the tab shortcut moves focus to', () => {
// `App.tsx` finds `main h1` on every nav change and focuses it. A screen without one announces
// nothing to a screen reader after Ctrl+2.
render(<PdDeps />)
expect(document.querySelector('h1')?.id).toBe('deps-title')
})
})
+85
View File
@@ -0,0 +1,85 @@
/**
* The dependency view — a **mode of the package screen**, not a tenth tab (PRD P1-6, UI-SPEC §4).
*
* `PdEnvironments` switches to `PdEnvDetail` on `openFor`; this switches on `focus`, for the same
* reason UI-SPEC §4 gives for Snapshots: `Ctrl+1..9` is positional over `NAV_KEYS`, so appending
* is free and **inserting is not**. A Dependencies tab would have to sit beside Installed to read
* as related, which renumbers every shortcut after it — and `NAV_KEYS` is already nine, so a tenth
* entry has no `Ctrl+` digit at all (`App.tsx` reads `NAV_KEYS[key - 1]`, and `Ctrl+0` is index
* `-1`).
*
* Which package is focused lives in `useDepsStore`, not in component state, for `PdEnvDetail`'s
* reason: the plan panel replaces the whole content area while a run is in flight, so local state
* would be unmounted with it and the user would land back on the flat table the moment their
* install finished.
*/
import { useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import { PdDepsFocus } from '@/components/PdDepsFocus'
import { PdErrorRow } from '@/components/PdErrorRow'
import { freshGraph, nodeOf, useDepsStore, useEnvStore } from '@/stores'
export function PdDeps() {
const { t } = useTranslation()
// Per-field selectors, as everywhere else: destructuring re-renders on every unrelated change.
const selected = useEnvStore((s) => s.selected)
const rows = useEnvStore((s) => s.rows)
const focus = useDepsStore((s) => s.focus)
const graph = useDepsStore((s) => s.graph)
const graphFor = useDepsStore((s) => s.graphFor)
const phase = useDepsStore((s) => s.phase)
const error = useDepsStore((s) => s.error)
const load = useDepsStore((s) => s.load)
const refocus = useDepsStore((s) => s.refocus)
const close = useDepsStore((s) => s.close)
const row = rows.find((r) => r.interpreter === selected)
const envHash = row?.envHash
useEffect(() => {
if (row?.env === undefined || envHash === undefined) return
void load(row.env, envHash)
}, [load, row?.env, envHash])
// Only when it describes *this* environment. A plain `graph` read would show one environment's
// edges after the user switched to another.
const shown = envHash === undefined ? null : freshGraph({ graph, graphFor }, envHash)
const node = nodeOf(shown, focus)
return (
<section aria-labelledby="deps-title" className="h-full overflow-auto p-6">
<div className="flex flex-wrap items-center justify-between gap-2">
<h1 id="deps-title" className="min-w-0 truncate text-accent">
{t('deps.title')}
</h1>
<button
type="button"
onClick={close}
className="rounded-pd border border-border px-3 py-1 text-data"
>
{t('deps.back')}
</button>
</div>
{error === null ? null : (
<div className="mt-4">
<PdErrorRow error={error} />
</div>
)}
<div className="mt-4">
{/* Three states, and the middle one is the one P4 got wrong in the other direction: a
screen that says "nothing found" while a fetch is in flight is a lie, and so is one
that says "loading" over a graph it already has. `phase` decides, not the data. */}
{phase === 'loading' && shown === null ? (
<p className="text-data text-text-dim">{t('deps.loading')}</p>
) : focus === null ? null : (
<PdDepsFocus pkg={focus} node={node} onFocus={refocus} />
)}
</div>
</section>
)
}
+12 -1
View File
@@ -16,9 +16,10 @@ import { useTranslation } from 'react-i18next'
import { PdEmptyState } from '@/components/PdEmptyState'
import { PdErrorRow } from '@/components/PdErrorRow'
import { PdPackageTable } from '@/components/PdPackageTable'
import { PdDeps } from '@/screens/PdDeps'
import { outdatedOnly, selectableForUpdate } from '@/screens/rows'
import { useEnvPackages } from '@/screens/useEnvPackages'
import { useEnvStore, usePlanStore } from '@/stores'
import { useDepsStore, useEnvStore, usePlanStore } from '@/stores'
interface PdPackagesProps {
mode: 'installed' | 'updates'
@@ -38,6 +39,10 @@ export function PdPackages({ mode }: PdPackagesProps) {
const outdatedStatus = useEnvStore((s) => s.outdatedStatus)
const outdatedError = useEnvStore((s) => s.outdatedError)
const selection = useEnvStore((s) => s.selection)
// UI-SPEC §4's "details", which had no panel to open until P1-6. A *mode* of this screen rather
// than a tab, exactly as Snapshots is a mode of Environments — see `PdDeps` for why.
const depsFocus = useDepsStore((s) => s.focus)
const openDeps = useDepsStore((s) => s.open)
const toggle = useEnvStore((s) => s.toggle)
const selectAll = useEnvStore((s) => s.selectAll)
const clearSelection = useEnvStore((s) => s.clearSelection)
@@ -73,6 +78,11 @@ export function PdPackages({ mode }: PdPackagesProps) {
useEnvPackages()
// Before the `selected === null` branch below: the dependency view reads the same environment
// and renders its own "no environment" case, and putting it after would flash the table's empty
// state over a view the user had open.
if (depsFocus !== null) return <PdDeps />
const visible = mode === 'updates' ? outdatedOnly(packages) : packages
const { selectable, pinnedExcluded } = selectableForUpdate(visible)
const title = mode === 'updates' ? t('packages.updatesTitle') : t('packages.installedTitle')
@@ -204,6 +214,7 @@ export function PdPackages({ mode }: PdPackagesProps) {
onToggle={toggle}
onPinToggle={pinToggle}
onUninstall={uninstall}
onDetails={openDeps}
onSelectAll={() => {
selectAll(selectable)
}}
+134
View File
@@ -0,0 +1,134 @@
/**
* The dependency view — PRD P1-6, UI-SPEC §4.
*
* Its own file, re-exported from `@/stores`, for the reason `health.ts` and `security.ts` are: a
* domain that owns a screen owns a file.
*
* **One fetch per environment, not one per package.** `graph` holds every installed package's
* edges at once, so re-centring the view is an object lookup rather than a round trip. That is the
* whole reason `deps_graph` is shaped the way it is — a per-package command would pay a 605 ms
* probe on every click.
*
* Nothing here parses a requirement or evaluates a marker. Which edges are in force, which are
* gated behind an extra, and which requirements nothing satisfies are all decided in Rust and
* arrive decided. A second implementation on this side would drift from the uninstall guard, and
* two features disagreeing about one edge is the failure `graph/mod.rs` exists to prevent.
*/
import { create } from 'zustand'
import { depsGraph, isPdError, type DepsGraph, type DepsNode, type PdError, type PyEnv } from '@/ipc'
/** Where a fetch is. */
export type DepsPhase = 'idle' | 'loading' | 'ready' | 'failed'
export interface DepsState {
phase: DepsPhase
/** Every installed package's edges, or null when nothing has been fetched. */
graph: DepsGraph | null
/**
* Which environment `graph` describes.
*
* Held separately so one environment's edges can never be shown under another's name — the
* reason `useSecurityStore` keeps `reportFor` and `useHealthStore` keeps `reportFor`.
*/
graphFor: string | null
/**
* The package the view is centred on, and the thing that makes this a *mode*.
*
* `null` means the package table is showing. `PdPackages` switches on it exactly as
* `PdEnvironments` switches on `openFor` — UI-SPEC §4 puts Snapshots under Environments for the
* same reason a dependency view belongs under Installed: `Ctrl+1..9` is positional over
* `NAV_KEYS`, so a tenth tab beside Installed would be an *insert* and would rebind every
* shortcut after it.
*/
focus: string | null
error: PdError | null
/** Enter the view centred on `pkg`. */
open: (pkg: string) => void
/** Re-centre without leaving. */
refocus: (pkg: string) => void
/** Back to the package table. */
close: () => void
load: (env: PyEnv, envHash: string) => Promise<void>
reset: () => void
}
/**
* Cleared when the selected environment changes.
*
* `focus` is inside it, unlike `security.ts`'s `consoleOpen`: which package you were looking at is
* a fact about an environment, not a preference about the screen, and a name carried across a
* switch would centre the view on a package the new environment may not have.
*/
const NO_DEPS = {
phase: 'idle' as DepsPhase,
graph: null,
graphFor: null,
focus: null,
error: null,
}
const asPdError = (e: unknown): PdError =>
isPdError(e) ? e : { code: 'PD-INT-001', message: String(e) }
export const useDepsStore = create<DepsState>((set, get) => ({
...NO_DEPS,
open: (pkg) => {
set({ focus: pkg })
},
refocus: (pkg) => {
set({ focus: pkg })
},
close: () => {
// The graph is kept. Leaving the view does not make the environment's edges wrong, and
// dropping them here would make re-opening a row pay the probe again.
set({ focus: null })
},
load: async (env, envHash) => {
const { phase, graphFor } = get()
if (phase === 'loading') return
// Already have this environment's graph. Not a cache so much as the answer to "never render a
// state you have not loaded" read the other way: a second fetch would replace an identical
// value and flash a loading state over a view that was already correct.
if (graphFor === envHash && get().graph !== null) return
set({ phase: 'loading', error: null })
try {
const graph = await depsGraph(env)
set({ graph, graphFor: envHash, phase: 'ready' })
} catch (e) {
// The graph is dropped, not kept: a failure here means the probe could not read the
// environment, so whatever is in hand describes an environment that may no longer exist.
set({ graph: null, graphFor: null, error: asPdError(e), phase: 'failed' })
}
},
reset: () => {
set({ ...NO_DEPS })
},
}))
/**
* The graph, but only when it describes `envHash`.
*
* A plain `graph` read would show one environment's edges after the user switched to another —
* the shape `freshReport` and `freshAudit` already guard against. A function rather than a hook
* so a component can call it inside a render without adding a subscription.
*/
export const freshGraph = (
s: Pick<DepsState, 'graph' | 'graphFor'>,
envHash: string,
): DepsGraph | null => (s.graphFor === envHash ? s.graph : null)
/**
* One package's node, or null when the graph has never heard of it.
*
* `null` is a real answer rather than an error: a package can leave the environment between the
* fetch and the click that focuses it, and a view that threw there would turn a stale row into a
* crash.
*/
export const nodeOf = (graph: DepsGraph | null, pkg: string | null): DepsNode | null =>
graph === null || pkg === null ? null : (graph.nodes[pkg] ?? null)
+9
View File
@@ -696,6 +696,15 @@ export {
type SecurityState,
} from '@/stores/security'
// The dependency view, in its own file for the same reason as Code Health.
export {
freshGraph,
nodeOf,
useDepsStore,
type DepsPhase,
type DepsState,
} from '@/stores/deps'
// Search and the dock bay, in their own file for the same reason as the plan store.
export {
SEARCH_DEBOUNCE_MS,
+75
View File
@@ -0,0 +1,75 @@
{
"nodes": {
"certifi": {
"version": "2024.2.2",
"dependents": [],
"dependencies": [],
"impact": 0,
"reach": 0
},
"editable-lib": {
"version": "0.3.0",
"dependents": [],
"dependencies": [],
"impact": 0,
"reach": 0
},
"numpy": {
"version": "1.26.4",
"dependents": [
{
"pkg": "pandas",
"version": "2.1.4",
"constraint": "<2,>=1.26.0"
},
{
"pkg": "scipy",
"version": "1.11.4",
"constraint": "<1.28.0,>=1.21.6"
}
],
"dependencies": [],
"impact": 2,
"reach": 0
},
"pandas": {
"version": "2.1.4",
"dependents": [],
"dependencies": [
{
"pkg": "numpy",
"version": "1.26.4",
"constraint": "<2,>=1.26.0"
}
],
"impact": 0,
"reach": 1,
"unsatisfied": [
"python-dateutil"
]
},
"requests": {
"version": "2.28.0",
"dependents": [],
"dependencies": [],
"impact": 0,
"reach": 0,
"unsatisfied": [
"urllib3"
]
},
"scipy": {
"version": "1.11.4",
"dependents": [],
"dependencies": [
{
"pkg": "numpy",
"version": "1.26.4",
"constraint": "<1.28.0,>=1.21.6"
}
],
"impact": 0,
"reach": 1
}
}
}
+2
View File
@@ -32,6 +32,7 @@ export interface IpcMock {
pinAdd: ReturnType<typeof vi.fn>
pinRemove: ReturnType<typeof vi.fn>
pinSuggestions: ReturnType<typeof vi.fn>
depsGraph: ReturnType<typeof vi.fn>
envExport: ReturnType<typeof vi.fn>
requirementsRead: ReturnType<typeof vi.fn>
cacheUsage: ReturnType<typeof vi.fn>
@@ -78,6 +79,7 @@ export function ipcMock(): IpcMock {
// Empty by default: a screen that renders a suggestion section must not get one for free, or
// a test asserting the section is absent passes for the wrong reason.
pinSuggestions: vi.fn().mockResolvedValue([]),
depsGraph: vi.fn().mockResolvedValue({ nodes: {} }),
envExport: vi.fn().mockResolvedValue('C:/out/requirements.txt'),
requirementsRead: vi.fn().mockResolvedValue({ specs: [], skipped: [] }),
cacheUsage: vi.fn().mockResolvedValue({