feat(app): the plan session, and the four commands that drive it
The architectural centre of S3. `UpdateFlow` is a **resumable state machine** and IPC is stateless: `plan_resolve` builds the flow, the user reads the preview, and `plan_decide` or `plan_execute` arrives as a separate message seconds later. Something has to hold the flow in between, and that is `PlanSlot` in `AppState`. **One plan at a time, and `PD-RES-003` when a second arrives.** Nothing structurally prevents it — the calls are independent messages — and two concurrent plans would interleave engine commands against one environment while DATA-FLOW §9.3's staleness check compared against a set the other plan was busy changing. `claim()` takes the slot before any work, and **every** exit path releases it: a claim that leaks would leave the session refusing plans forever, which is the failure mode this design has to be careful about. `Busy` moves the flow out rather than borrowing it, because `execute` awaits for as long as the install takes and holding the slot's lock across that would block `plan_cancel` — the one command that must work precisely then. For the same reason the cancellation token lives in its own lock, held only long enough to read an `Option`. **`UpdateFlow::start` now takes the pins, not the `Store`.** Not a tidy-up: `Store` wraps a `rusqlite::Connection` and is `Send` but not `Sync`, so a future holding `&Store` across an await is not `Send` and a Tauri command cannot return one. It did not compile. Reading the pins first is one synchronous line at each call site, and the flow no longer reaches into a database at all — it can now be driven in a test without one. `plan_execute` returns the snapshot alongside the summary. The CLI prints the id *before* execution because DATA-FLOW §3 draws them as distinct states; the summary sheet needs it *after*, to offer the rollback. One envelope beats a second command to go and look it up. `PD-RES-003` went through the whole catalog process rather than round it: the "no code without a fixture" gate rejected it until it was listed as internally raised with the module that owns it, and both locale catalogs carry its copy — otherwise `PdErrorRow` would show `errors.unknown` for a condition PipDock raises itself. `Decision` joins SCHEMA_TYPES too, since `PdConflictRow` needs the 3-way type. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e57870b3d9
commit
1bc103bc75
21 files changed
+426
-14
No files matched your search
Generated
+1
@@ -3180,6 +3180,7 @@ dependencies = [
|
||||
"tauri-plugin-dialog",
|
||||
"tauri-plugin-opener",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
]
|
||||
|
||||
@@ -490,7 +490,10 @@ pub async fn plan_and_run(opts: &GlobalOpts, intent: Intent, dry_run: bool) -> R
|
||||
let env = select_env(opts).await?;
|
||||
let store = Store::open(&app_data_dir())?;
|
||||
|
||||
let (mut flow, mut step) = UpdateFlow::start(env, engine_for(opts), &intent, &store).await?;
|
||||
// Read before the flow starts: `UpdateFlow` takes the pins rather than the store they came
|
||||
// from, so its future stays `Send` for the GUI's sake.
|
||||
let env_pins = pins::list(&store, &envs::env_hash(&env.interpreter))?;
|
||||
let (mut flow, mut step) = UpdateFlow::start(env, engine_for(opts), &intent, &env_pins).await?;
|
||||
|
||||
// The flow returns the exclusion as data; the wording is the head's business (I18N §1).
|
||||
if !flow.excluded_pins().is_empty() && !opts.json {
|
||||
|
||||
@@ -45,6 +45,7 @@ const SCHEMA_TYPES: &[&str] = &[
|
||||
"PackageMeta",
|
||||
"ProgressEvent",
|
||||
"FlowStep",
|
||||
"Decision",
|
||||
"Intent",
|
||||
"Code",
|
||||
];
|
||||
|
||||
@@ -51,6 +51,11 @@ expression: out
|
||||
"description": "Plan older than 10 minutes, or the env's probe hash changed since the preview.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-RES-003",
|
||||
"description": "A plan is already resolving or executing in this session.\n\nThe GUI drives one resumable flow across several IPC calls, so \"start a plan\" and \"run the\nplan\" are different messages arriving at different times — nothing structurally stops a\nsecond one arriving in between. Refusing is the only safe answer: two concurrent plans\nwould interleave engine commands against one environment, and DATA-FLOW §9.3's staleness\ncheck would be comparing against a set the other plan is busy changing.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-BLD-001",
|
||||
"description": "MSVC build tools required but absent.",
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
---
|
||||
source: crates/pipdock-cli/tests/golden.rs
|
||||
expression: out
|
||||
---
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"description": "What the user chose for one package that needs a decision (DATA-FLOW §3, CLI-SPEC §4).",
|
||||
"oneOf": [
|
||||
{
|
||||
"const": "keep-compatible",
|
||||
"description": "Accept the resolver's compatible version. The safe default, and the one that needs no\nextra click in the 4-click budget (UI-SPEC §5).",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "skip",
|
||||
"description": "Drop the package from this plan entirely.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "force-latest",
|
||||
"description": "Take the latest anyway, knowingly breaking whatever declared the constraint\n(DISCLAIMER §2).",
|
||||
"type": "string"
|
||||
}
|
||||
],
|
||||
"title": "Decision"
|
||||
}
|
||||
@@ -91,6 +91,11 @@ expression: out
|
||||
"description": "Plan older than 10 minutes, or the env's probe hash changed since the preview.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-RES-003",
|
||||
"description": "A plan is already resolving or executing in this session.\n\nThe GUI drives one resumable flow across several IPC calls, so \"start a plan\" and \"run the\nplan\" are different messages arriving at different times — nothing structurally stops a\nsecond one arriving in between. Refusing is the only safe answer: two concurrent plans\nwould interleave engine commands against one environment, and DATA-FLOW §9.3's staleness\ncheck would be comparing against a set the other plan is busy changing.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-BLD-001",
|
||||
"description": "MSVC build tools required but absent.",
|
||||
|
||||
@@ -52,6 +52,11 @@ expression: out
|
||||
"description": "Plan older than 10 minutes, or the env's probe hash changed since the preview.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-RES-003",
|
||||
"description": "A plan is already resolving or executing in this session.\n\nThe GUI drives one resumable flow across several IPC calls, so \"start a plan\" and \"run the\nplan\" are different messages arriving at different times — nothing structurally stops a\nsecond one arriving in between. Refusing is the only safe answer: two concurrent plans\nwould interleave engine commands against one environment, and DATA-FLOW §9.3's staleness\ncheck would be comparing against a set the other plan is busy changing.",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"const": "PD-BLD-001",
|
||||
"description": "MSVC build tools required but absent.",
|
||||
|
||||
@@ -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, GuardReport, Diff, SnapshotMeta, Hit, PackageMeta, ProgressEvent, FlowStep, Intent, Code
|
||||
error[PD-PKG-002]: unknown type "NoSuchType"; known types: Dist, OutdatedDist, PyEnv, CheckReport, StepResult, PlanRequest, ResolutionReport, ExecutionSummary, Pin, GuardReport, Diff, SnapshotMeta, Hit, PackageMeta, ProgressEvent, FlowStep, Decision, Intent, Code
|
||||
@@ -99,6 +99,15 @@ pub enum Code {
|
||||
/// Plan older than 10 minutes, or the env's probe hash changed since the preview.
|
||||
#[serde(rename = "PD-RES-002")]
|
||||
ResPlanStale,
|
||||
/// A plan is already resolving or executing in this session.
|
||||
///
|
||||
/// The GUI drives one resumable flow across several IPC calls, so "start a plan" and "run the
|
||||
/// plan" are different messages arriving at different times — nothing structurally stops a
|
||||
/// second one arriving in between. Refusing is the only safe answer: two concurrent plans
|
||||
/// would interleave engine commands against one environment, and DATA-FLOW §9.3's staleness
|
||||
/// check would be comparing against a set the other plan is busy changing.
|
||||
#[serde(rename = "PD-RES-003")]
|
||||
ResPlanInFlight,
|
||||
|
||||
// -- PD-BLD: build ------------------------------------------------------
|
||||
/// MSVC build tools required but absent.
|
||||
@@ -195,6 +204,7 @@ impl Code {
|
||||
Self::EngUnclassified => "PD-ENG-999",
|
||||
Self::ResImpossible => "PD-RES-001",
|
||||
Self::ResPlanStale => "PD-RES-002",
|
||||
Self::ResPlanInFlight => "PD-RES-003",
|
||||
Self::BldMsvcMissing => "PD-BLD-001",
|
||||
Self::BldBackendFailed => "PD-BLD-002",
|
||||
Self::BldWheelFailed => "PD-BLD-003",
|
||||
@@ -230,7 +240,7 @@ impl Code {
|
||||
| Self::EngPipTooOld
|
||||
| Self::EngUvShapeUnknown
|
||||
| Self::EngUnclassified => Area::Eng,
|
||||
Self::ResImpossible | Self::ResPlanStale => Area::Res,
|
||||
Self::ResImpossible | Self::ResPlanStale | Self::ResPlanInFlight => Area::Res,
|
||||
Self::BldMsvcMissing | Self::BldBackendFailed | Self::BldWheelFailed => Area::Bld,
|
||||
Self::PkgRequiresPython
|
||||
| Self::PkgNotFound
|
||||
@@ -259,6 +269,7 @@ impl Code {
|
||||
Self::EngUvShapeUnknown,
|
||||
Self::ResImpossible,
|
||||
Self::ResPlanStale,
|
||||
Self::ResPlanInFlight,
|
||||
Self::BldMsvcMissing,
|
||||
Self::BldBackendFailed,
|
||||
Self::BldWheelFailed,
|
||||
@@ -535,7 +546,7 @@ mod tests {
|
||||
fn every_variant_is_listed_in_all() {
|
||||
// `ALL` drives the fixture-coverage gate, so a variant missing from it would silently
|
||||
// escape that gate. There is no derive for "enumerate variants", hence this count check.
|
||||
assert_eq!(Code::ALL.len(), 30, "add the new variant to Code::ALL");
|
||||
assert_eq!(Code::ALL.len(), 31, "add the new variant to Code::ALL");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -685,7 +696,7 @@ mod tests {
|
||||
// Rust has 30, docs/ERROR-CATALOG.md tabulates 28 (it folds PD-HLT-001..003 into one
|
||||
// row) and CLAUDE.md used to say 25. Pin the number so the next person adding a code has
|
||||
// to notice the docs exist.
|
||||
assert_eq!(Code::ALL.len(), 30);
|
||||
assert_eq!(Code::ALL.len(), 31);
|
||||
let wire: HashSet<&str> = Code::ALL.iter().map(|c| c.as_str()).collect();
|
||||
assert_eq!(
|
||||
wire.len(),
|
||||
|
||||
@@ -43,7 +43,6 @@ use crate::model::{Dist, OutdatedDist, PkgName, PyEnv, Spec};
|
||||
use crate::pins::{self, Pin};
|
||||
use crate::plan::{self, Decision, PlanRequest, ResolutionReport, Strategy};
|
||||
use crate::snapshot::{self, Snapshot, SnapshotProof};
|
||||
use crate::store::Store;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
/// What the user asked for, before it becomes a [`PlanRequest`].
|
||||
@@ -174,14 +173,20 @@ pub struct UpdateFlow {
|
||||
impl UpdateFlow {
|
||||
/// Probe, build the request, and resolve once.
|
||||
///
|
||||
/// Takes the pins rather than the [`Store`] they came from. That is not only tidier — it is
|
||||
/// required. `Store` wraps a `rusqlite::Connection` and is `Send` but **not `Sync`**, so a
|
||||
/// future holding a `&Store` across an await is not `Send`, and a Tauri command must be. The
|
||||
/// caller reads the pins first, which is one synchronous line, and the flow no longer reaches
|
||||
/// into a database at all — it can be driven in a test without one.
|
||||
///
|
||||
/// # Errors
|
||||
/// `PD-ENV-002` when the environment is externally managed (PEP 668), which is checked before
|
||||
/// any engine command runs. Otherwise propagates probe, pin-store and engine failures.
|
||||
/// any engine command runs. Otherwise propagates probe and engine failures.
|
||||
pub async fn start(
|
||||
env: PyEnv,
|
||||
engine: Box<dyn Engine>,
|
||||
intent: &Intent,
|
||||
store: &Store,
|
||||
pins: &[Pin],
|
||||
) -> Result<(Self, FlowStep)> {
|
||||
let env_hash = crate::envs::env_hash(&env.interpreter);
|
||||
|
||||
@@ -199,9 +204,7 @@ impl UpdateFlow {
|
||||
// it a `python_version < "3.11"` branch is reported as a blocker on 3.12 (SP-5 dogfood).
|
||||
let graph = ReverseDeps::build_for(&probed.dists, &probed.env.python_version);
|
||||
let outdated = engine.list_outdated(&env).await?;
|
||||
let pin_list = pins::list(store, &env_hash)?;
|
||||
|
||||
let (req, excluded_pins) = build_request(intent, &outdated, &pin_list)?;
|
||||
let (req, excluded_pins) = build_request(intent, &outdated, pins)?;
|
||||
let plan_id = format!("update-{env_hash:.8}");
|
||||
|
||||
let mut flow = Self {
|
||||
|
||||
@@ -274,6 +274,7 @@ pub fn json_schema(type_name: &str) -> Result<serde_json::Value> {
|
||||
"PackageMeta" => crate::index::PackageMeta,
|
||||
"ProgressEvent" => crate::engine::ProgressEvent,
|
||||
"FlowStep" => crate::flow::FlowStep,
|
||||
"Decision" => Decision,
|
||||
"Intent" => crate::flow::Intent,
|
||||
"Code" => crate::errors::Code,
|
||||
}
|
||||
@@ -297,6 +298,7 @@ pub const SCHEMA_TYPES: &[&str] = &[
|
||||
"PackageMeta",
|
||||
"ProgressEvent",
|
||||
"FlowStep",
|
||||
"Decision",
|
||||
"Intent",
|
||||
"Code",
|
||||
];
|
||||
|
||||
@@ -141,6 +141,10 @@ fn no_code_without_a_fixture() {
|
||||
"PD-RES-002",
|
||||
"plan: report older than PLAN_MAX_AGE or env drifted",
|
||||
),
|
||||
(
|
||||
"PD-RES-003",
|
||||
"app::state: a second plan arrived while one was already in flight",
|
||||
),
|
||||
(
|
||||
"PD-PKG-001",
|
||||
"compat: Requires-Python enforced by PipDock, not by the engine",
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
| PD-ENG-003 | uv output shape unrecognized | uv newer than adapter | Update PipDock; temporarily switch engine to pip |
|
||||
| PD-RES-001 | `ResolutionImpossible` / uv equivalent | constraints cannot be satisfied | Per-package Skip/Force choices in the preview |
|
||||
| PD-RES-002 | plan stale (>10 min) or env drift hash mismatch | env changed since preview | Re-run preview |
|
||||
| PD-RES-003 | a plan is already resolving or executing | another plan is in flight in this session | Wait for it, or cancel it |
|
||||
| PD-BLD-001 | `Microsoft Visual C++ 14.0 or greater is required` | missing MSVC build tools | Install VS Build Tools, or prefer a wheel-providing version |
|
||||
| PD-BLD-002 | `error in pyproject.toml` / `Backend … failed` / `metadata-generation-failed` | broken sdist build backend | Try previous version; report upstream (owner's example case) |
|
||||
| PD-BLD-003 | `error: Microsoft Visual C++`-absent + `Failed building wheel` generic | sdist-only build failed | Same as above; details in log |
|
||||
|
||||
@@ -31,5 +31,7 @@ serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
jiff = "0.2.35"
|
||||
tokio = { version = "1", features = ["rt-multi-thread"] }
|
||||
# `plan_cancel` trips the same `CancellationToken` the core threads through `exec`.
|
||||
tokio-util = "0.7"
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
+173
-1
@@ -10,11 +10,16 @@
|
||||
|
||||
use pipdock_core::engine;
|
||||
use pipdock_core::envs::{self, ScanProgress};
|
||||
use pipdock_core::errors::Code;
|
||||
use pipdock_core::flow;
|
||||
use pipdock_core::model::EnvSource;
|
||||
use pipdock_core::pins::{self, Pin};
|
||||
use pipdock_core::plan::{Decision, ExecutionSummary};
|
||||
use pipdock_core::settings::{self, Consent, Settings};
|
||||
use pipdock_core::{PdError, PyEnv};
|
||||
use pipdock_core::snapshot;
|
||||
use pipdock_core::{PdError, PkgName, PyEnv};
|
||||
use tauri::Emitter as _;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::state::AppState;
|
||||
|
||||
@@ -235,6 +240,173 @@ pub async fn pin_remove(
|
||||
Ok(pins::remove(&store, &env_hash, &name)?)
|
||||
}
|
||||
|
||||
/// What `plan_execute` returns: the summary, plus the snapshot it took first.
|
||||
///
|
||||
/// The snapshot id is not in `ExecutionSummary` because the CLI prints it *before* execution
|
||||
/// starts (DATA-FLOW §3 draws them as distinct states), and the summary sheet needs it afterwards
|
||||
/// to offer the rollback. One envelope beats a second command to go and look it up.
|
||||
#[derive(serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ExecutionOutcome {
|
||||
/// The summary (DATA-FLOW §6).
|
||||
pub summary: ExecutionSummary,
|
||||
/// The snapshot taken before anything was mutated, absent only when waived.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub snapshot: Option<snapshot::Meta>,
|
||||
}
|
||||
|
||||
/// Begin an update or install: resolve, and derive what needs a decision.
|
||||
///
|
||||
/// The first of the four calls that drive one `UpdateFlow` (DATA-FLOW §3). The flow is parked in
|
||||
/// `AppState` between them, because it is resumable and IPC is not.
|
||||
///
|
||||
/// # Errors
|
||||
/// `PD-RES-003` when a plan is already in flight, `PD-ENV-002` for a PEP 668 environment — checked
|
||||
/// before any engine command runs — and whatever the resolve itself raises.
|
||||
#[tauri::command]
|
||||
pub async fn plan_resolve(
|
||||
state: tauri::State<'_, AppState>,
|
||||
env: PyEnv,
|
||||
intent: flow::Intent,
|
||||
) -> Wire<flow::FlowStep> {
|
||||
// Claiming before any work means a second resolve is refused rather than racing this one.
|
||||
// Whatever flow was parked is dropped: starting a new plan abandons the old preview, which is
|
||||
// what the user just asked for.
|
||||
let _ = state.claim().await?;
|
||||
|
||||
let cancel = CancellationToken::new();
|
||||
state.set_cancel(Some(cancel));
|
||||
|
||||
// Both store reads happen up front and the guard is dropped before any await. `Store` is not
|
||||
// `Sync`, so a future holding one is not `Send` and a Tauri command cannot return it — which
|
||||
// is what forced `UpdateFlow::start` to take the pins rather than the store.
|
||||
let (engine, env_pins) = {
|
||||
let store = state.store.lock().await;
|
||||
let engine = engine::for_id(settings::load(&store)?.engine);
|
||||
let env_pins = pins::list(&store, &envs::env_hash(&env.interpreter))?;
|
||||
(engine, env_pins)
|
||||
};
|
||||
|
||||
match flow::UpdateFlow::start(env, engine, &intent, &env_pins).await {
|
||||
Ok((flow, step)) => {
|
||||
state.park(Box::new(flow)).await;
|
||||
Ok(step)
|
||||
}
|
||||
Err(e) => {
|
||||
// Every failure path releases the slot, or the session refuses plans forever.
|
||||
state.release().await;
|
||||
Err(e.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply the user's 3-way conflict choices and re-resolve (DATA-FLOW §3's decision loop).
|
||||
///
|
||||
/// # Errors
|
||||
/// `PD-RES-003` when another plan is in flight, `PD-PKG-002` for a name that is not a package,
|
||||
/// `PD-INT-001` when there is no plan to decide on.
|
||||
#[tauri::command]
|
||||
pub async fn plan_decide(
|
||||
state: tauri::State<'_, AppState>,
|
||||
decisions: std::collections::BTreeMap<String, Decision>,
|
||||
) -> Wire<flow::FlowStep> {
|
||||
let mut flow = state.claim().await?.ok_or_else(no_plan)?;
|
||||
|
||||
let parsed = decisions
|
||||
.into_iter()
|
||||
.map(|(name, decision)| PkgName::parse(&name).map(|pkg| (pkg, decision)))
|
||||
.collect::<pipdock_core::Result<std::collections::BTreeMap<_, _>>>();
|
||||
|
||||
let parsed = match parsed {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
// The flow is still good — only the argument was bad, so park it rather than losing
|
||||
// the preview the user is looking at.
|
||||
state.park(flow).await;
|
||||
return Err(e.into());
|
||||
}
|
||||
};
|
||||
|
||||
match flow.decide(&parsed).await {
|
||||
Ok(step) => {
|
||||
state.park(flow).await;
|
||||
Ok(step)
|
||||
}
|
||||
Err(e) => {
|
||||
state.release().await;
|
||||
Err(e.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Take the snapshot, then run the plan (ARCHITECTURE §8's two phases).
|
||||
///
|
||||
/// Streams `plan-progress` throughout. **The snapshot is not optional here** — `--no-snapshot` is
|
||||
/// a CLI waiver for disposable environments and has no GUI surface, so DATA-FLOW §9.2 holds
|
||||
/// unconditionally: a snapshot failure aborts with `PD-SNP-001` and executes nothing.
|
||||
///
|
||||
/// # Errors
|
||||
/// `PD-SNP-001` when the snapshot cannot be written, `PD-RES-002` when the preview went stale or
|
||||
/// the environment drifted, `PD-INT-001` when there is no plan to execute.
|
||||
#[tauri::command]
|
||||
pub async fn plan_execute(
|
||||
app: tauri::AppHandle,
|
||||
state: tauri::State<'_, AppState>,
|
||||
) -> Wire<ExecutionOutcome> {
|
||||
let mut flow = state.claim().await?.ok_or_else(no_plan)?;
|
||||
state.set_cancel(Some(flow.cancel_handle()));
|
||||
|
||||
let snapshot = match flow
|
||||
.take_snapshot(flow::SnapshotPolicy::Take, &state.app_data)
|
||||
.await
|
||||
{
|
||||
Ok(meta) => meta,
|
||||
Err(e) => {
|
||||
state.release().await;
|
||||
return Err(e.into());
|
||||
}
|
||||
};
|
||||
|
||||
// Forward every event to the webview. The receiver lives for the length of the execution and
|
||||
// the sender dies with it, so this task ends on its own.
|
||||
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
|
||||
let emitter = app.clone();
|
||||
tokio::spawn(async move {
|
||||
while let Some(event) = rx.recv().await {
|
||||
// A UI that stopped listening is not a reason to abandon the install.
|
||||
let _ = emitter.emit("plan-progress", &event);
|
||||
}
|
||||
});
|
||||
|
||||
let result = flow.execute(tx).await;
|
||||
state.release().await;
|
||||
|
||||
Ok(ExecutionOutcome {
|
||||
summary: result?,
|
||||
snapshot,
|
||||
})
|
||||
}
|
||||
|
||||
/// Stop the plan that is running (DATA-FLOW §3: allowed while resolving or executing).
|
||||
///
|
||||
/// Returns whether anything was actually in flight, so the UI can tell "stopped it" from "there
|
||||
/// was nothing to stop" rather than guessing.
|
||||
///
|
||||
/// Never fails: cancelling something that already finished is not an error, and making it one
|
||||
/// would mean the UI has to race the thing it is trying to stop.
|
||||
#[tauri::command]
|
||||
pub fn plan_cancel(state: tauri::State<'_, AppState>) -> bool {
|
||||
state.cancel_current()
|
||||
}
|
||||
|
||||
/// There is no parked plan — the UI called out of order, or a previous call already consumed it.
|
||||
fn no_plan() -> PdError {
|
||||
PdError::new(
|
||||
Code::IntUnexpected,
|
||||
"no plan is in progress; resolve one first",
|
||||
)
|
||||
}
|
||||
|
||||
/// Read the stored settings.
|
||||
///
|
||||
/// # Errors
|
||||
|
||||
@@ -40,6 +40,10 @@ pub fn run() {
|
||||
commands::pin_list,
|
||||
commands::pin_add,
|
||||
commands::pin_remove,
|
||||
commands::plan_resolve,
|
||||
commands::plan_decide,
|
||||
commands::plan_execute,
|
||||
commands::plan_cancel,
|
||||
commands::settings_get,
|
||||
commands::settings_set,
|
||||
commands::legal_consent_get,
|
||||
|
||||
+101
-1
@@ -7,10 +7,44 @@
|
||||
//! * `NameIndex` **must** be held across calls. Spike SP-3 measured scanning SQLite at 218 ms per
|
||||
//! keystroke against a 50 ms budget; loading it per `index_search` would reintroduce exactly the
|
||||
//! failure that spike ruled out.
|
||||
//!
|
||||
//! A third arrived with S3, and it is the reason the mutation spine works at all: `UpdateFlow` is
|
||||
//! a **resumable state machine** and IPC is stateless. `plan_resolve` builds the flow, the user
|
||||
//! looks at the preview, and `plan_decide` or `plan_execute` arrives as a separate message some
|
||||
//! seconds later. Something has to hold the flow in between, and that is [`PlanSlot`].
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use pipdock_core::errors::{Code, PdError, Result};
|
||||
use pipdock_core::flow::UpdateFlow;
|
||||
use pipdock_core::store::Store;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
/// Where the one plan this session may have has got to.
|
||||
///
|
||||
/// One at a time, deliberately. Two concurrent plans would interleave engine commands against a
|
||||
/// single environment, and DATA-FLOW §9.3's staleness check would be comparing the installed set
|
||||
/// against one the other plan is busy changing — so the second is refused with `PD-RES-003`
|
||||
/// rather than allowed to race.
|
||||
pub enum PlanSlot {
|
||||
/// No plan.
|
||||
Idle,
|
||||
/// A flow is waiting for the user: a decision, or the final confirm.
|
||||
Ready(Box<UpdateFlow>),
|
||||
/// Engine work is in flight, so the flow is owned by whichever command is driving it.
|
||||
///
|
||||
/// The flow is *moved out* for the duration rather than borrowed, because `execute` awaits for
|
||||
/// as long as the install takes and holding the slot's lock across that would block
|
||||
/// `plan_cancel` — the one command that must work precisely then.
|
||||
Busy,
|
||||
}
|
||||
|
||||
impl PlanSlot {
|
||||
/// True while engine work is in flight.
|
||||
pub const fn is_busy(&self) -> bool {
|
||||
matches!(*self, Self::Busy)
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything a command may need that outlives one call.
|
||||
pub struct AppState {
|
||||
@@ -18,6 +52,14 @@ pub struct AppState {
|
||||
pub app_data: PathBuf,
|
||||
/// Settings, pins, recents and the package index.
|
||||
pub store: tokio::sync::Mutex<Store>,
|
||||
/// The plan being driven across several IPC calls.
|
||||
pub plan: tokio::sync::Mutex<PlanSlot>,
|
||||
/// The token for whatever engine work is in flight.
|
||||
///
|
||||
/// Deliberately **not** inside [`PlanSlot`]: `plan_cancel` must be able to trip it while the
|
||||
/// slot is `Busy` and its flow is owned elsewhere. Its own lock is only ever held for the
|
||||
/// moment it takes to read or replace an `Option`, never across an await.
|
||||
pub cancel: std::sync::Mutex<Option<CancellationToken>>,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
@@ -25,12 +67,70 @@ impl AppState {
|
||||
///
|
||||
/// # Errors
|
||||
/// Propagates store failures, which at startup means the data directory is unusable.
|
||||
pub fn new() -> pipdock_core::Result<Self> {
|
||||
pub fn new() -> Result<Self> {
|
||||
let app_data = pipdock_core::store::default_app_data();
|
||||
let store = Store::open(&app_data)?;
|
||||
Ok(Self {
|
||||
app_data,
|
||||
store: tokio::sync::Mutex::new(store),
|
||||
plan: tokio::sync::Mutex::new(PlanSlot::Idle),
|
||||
cancel: std::sync::Mutex::new(None),
|
||||
})
|
||||
}
|
||||
|
||||
/// Claim the plan slot for engine work, returning whatever flow was waiting there.
|
||||
///
|
||||
/// # Errors
|
||||
/// `PD-RES-003` when a plan is already in flight.
|
||||
pub async fn claim(&self) -> Result<Option<Box<UpdateFlow>>> {
|
||||
let mut slot = self.plan.lock().await;
|
||||
if slot.is_busy() {
|
||||
return Err(PdError::new(
|
||||
Code::ResPlanInFlight,
|
||||
"a plan is already resolving or executing",
|
||||
));
|
||||
}
|
||||
Ok(match std::mem::replace(&mut *slot, PlanSlot::Busy) {
|
||||
PlanSlot::Ready(flow) => Some(flow),
|
||||
PlanSlot::Idle | PlanSlot::Busy => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Put a flow back for the next call to pick up.
|
||||
pub async fn park(&self, flow: Box<UpdateFlow>) {
|
||||
*self.plan.lock().await = PlanSlot::Ready(flow);
|
||||
}
|
||||
|
||||
/// Release the slot with no flow — the plan finished, or failed.
|
||||
///
|
||||
/// Called on **every** exit path out of a claimed slot. A claim that is never released leaves
|
||||
/// the session permanently refusing plans with `PD-RES-003`, which is the failure mode this
|
||||
/// design has to be careful about.
|
||||
pub async fn release(&self) {
|
||||
*self.plan.lock().await = PlanSlot::Idle;
|
||||
self.set_cancel(None);
|
||||
}
|
||||
|
||||
/// Record the token for the work about to start.
|
||||
pub fn set_cancel(&self, token: Option<CancellationToken>) {
|
||||
if let Ok(mut guard) = self.cancel.lock() {
|
||||
*guard = token;
|
||||
}
|
||||
}
|
||||
|
||||
/// Trip the in-flight token, if there is one. Returns whether anything was cancelled.
|
||||
pub fn cancel_current(&self) -> bool {
|
||||
let token: Option<CancellationToken> = self
|
||||
.cancel
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|guard| guard.as_ref().cloned());
|
||||
match token {
|
||||
Some(t) => {
|
||||
t.cancel();
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -81,6 +81,7 @@ export type Code =
|
||||
| 'PD-ENG-999'
|
||||
| 'PD-RES-001'
|
||||
| 'PD-RES-002'
|
||||
| 'PD-RES-003'
|
||||
| 'PD-BLD-001'
|
||||
| 'PD-BLD-002'
|
||||
| 'PD-BLD-003'
|
||||
@@ -113,6 +114,12 @@ export interface Counts {
|
||||
skipped: number;
|
||||
}
|
||||
|
||||
/** What the user chose for one package that needs a decision (DATA-FLOW §3, CLI-SPEC §4). */
|
||||
export type Decision =
|
||||
| 'keep-compatible'
|
||||
| 'skip'
|
||||
| 'force-latest';
|
||||
|
||||
/** The difference between two environment states. */
|
||||
export interface Diff {
|
||||
/** Present now, absent in the snapshot. */
|
||||
|
||||
+57
-1
@@ -14,7 +14,20 @@
|
||||
import { invoke } from '@tauri-apps/api/core'
|
||||
import { listen, type UnlistenFn } from '@tauri-apps/api/event'
|
||||
|
||||
import type { Dist, EngineId, EnvSource, OutdatedDist, Pin, PyEnv } from './generated'
|
||||
import type {
|
||||
Decision,
|
||||
Dist,
|
||||
EngineId,
|
||||
EnvSource,
|
||||
ExecutionSummary,
|
||||
FlowStep,
|
||||
Intent,
|
||||
OutdatedDist,
|
||||
Pin,
|
||||
ProgressEvent,
|
||||
PyEnv,
|
||||
SnapshotMeta,
|
||||
} from './generated'
|
||||
|
||||
export type * from './generated'
|
||||
|
||||
@@ -170,6 +183,49 @@ export const pinAdd = (envHash: string, pin: Pin): Promise<void> =>
|
||||
export const pinRemove = (envHash: string, pkg: string): Promise<boolean> =>
|
||||
invoke('pin_remove', { envHash, pkg })
|
||||
|
||||
/** What `planExecute` resolves to: the summary, and the snapshot taken before anything ran. */
|
||||
export interface ExecutionOutcome {
|
||||
summary: ExecutionSummary
|
||||
/** Absent only when the snapshot was waived, which the GUI never does. */
|
||||
snapshot?: SnapshotMeta
|
||||
}
|
||||
|
||||
/**
|
||||
* Begin an update or install: resolve, and derive what needs a decision.
|
||||
*
|
||||
* The first of four calls that drive **one** resumable flow held in Rust between them. Rejects
|
||||
* with `PD-RES-003` if a plan is already in flight — one at a time, deliberately, because two
|
||||
* would interleave engine commands against a single environment.
|
||||
*/
|
||||
export const planResolve = (env: PyEnv, intent: Intent): Promise<FlowStep> =>
|
||||
invoke('plan_resolve', { env, intent })
|
||||
|
||||
/** Apply the 3-way conflict choices and re-resolve. Keyed by package name. */
|
||||
export const planDecide = (decisions: Record<string, Decision>): Promise<FlowStep> =>
|
||||
invoke('plan_decide', { decisions })
|
||||
|
||||
/**
|
||||
* Snapshot, then run the plan. Streams `plan-progress` throughout.
|
||||
*
|
||||
* The snapshot is not optional: DATA-FLOW §9.2 aborts with `PD-SNP-001` rather than mutating
|
||||
* without one, and `--no-snapshot` is a CLI waiver with no GUI surface.
|
||||
*/
|
||||
export const planExecute = (): Promise<ExecutionOutcome> => invoke('plan_execute')
|
||||
|
||||
/** Stop the running plan. Resolves to whether anything was actually in flight. */
|
||||
export const planCancel = (): Promise<boolean> => invoke('plan_cancel')
|
||||
|
||||
/**
|
||||
* Subscribe to execution progress. Returns the unlisten function.
|
||||
*
|
||||
* Every step emits one `stepStarted`, any number of `line`s, and one `stepFinished` — which is
|
||||
* what lets the console drawer group by section and the live region count completions.
|
||||
*/
|
||||
export const onPlanProgress = (handler: (event: ProgressEvent) => void): Promise<UnlistenFn> =>
|
||||
listen<ProgressEvent>('plan-progress', (event) => {
|
||||
handler(event.payload)
|
||||
})
|
||||
|
||||
export const settingsGet = (): Promise<Settings> => invoke('settings_get')
|
||||
|
||||
export const settingsSet = (settings: Settings): Promise<Settings> =>
|
||||
|
||||
@@ -136,6 +136,8 @@
|
||||
"PD-ENV-001": "That interpreter is missing or cannot be run.",
|
||||
"PD-ENV-002": "This Python is managed by the operating system.",
|
||||
"PD-ENV-003": "PipDock could not read this environment.",
|
||||
"PD-RES-003": "A plan is already running. Wait for it to finish, or stop it first.",
|
||||
"PD-SNP-001": "The snapshot could not be written, so nothing was changed.",
|
||||
"PD-INT-001": "PipDock hit an internal error.",
|
||||
"unknown": "An unexpected error occurred."
|
||||
}
|
||||
|
||||
@@ -132,6 +132,8 @@
|
||||
"PD-ENV-001": "Không tìm thấy hoặc không chạy được trình thông dịch đó.",
|
||||
"PD-ENV-002": "Bản Python này do hệ điều hành quản lý.",
|
||||
"PD-ENV-003": "PipDock không đọc được môi trường này.",
|
||||
"PD-RES-003": "Đang có một kế hoạch chạy dở. Hãy đợi nó xong, hoặc dừng nó trước.",
|
||||
"PD-SNP-001": "Không ghi được ảnh chụp, nên không có gì bị thay đổi.",
|
||||
"PD-INT-001": "PipDock gặp lỗi nội bộ.",
|
||||
"unknown": "Đã xảy ra lỗi ngoài dự kiến."
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user