Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
131 changes: 93 additions & 38 deletions apps/desktop/src-tauri/src/project_inventory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,14 @@ fn unavailable() -> DesktopError {
)
}

pub(crate) fn revision_changed() -> DesktopError {
DesktopError::new(
"project_revision_changed",
"The project changed since confirmation",
"Review the current project again before removing it.",
)
}

fn uncertain() -> DesktopError {
DesktopError::new("project_unregister_uncertain", "The unregister outcome could not be confirmed", "Refresh the Runner inventory before taking further action. No automatic retry or folder deletion was attempted.")
}
Expand Down Expand Up @@ -67,50 +75,69 @@ pub async fn observe_many(
return Err(unavailable());
}
}
let value = crate::workspace::post(
let exact = |project: &str| json!({"project":project,"limit":1,"summary_only":false});
let params = if projects.len() == 1 {
exact(&projects[0])
} else {
json!({"client_id":target.client_id,"limit":100,"summary_only":false})
};
let page = list_for_removal(runtime, params).await?;
let rows = page
.get("projects")
.and_then(Value::as_array)
.ok_or_else(unavailable)?;
let mut observations = Vec::with_capacity(projects.len());
for project in projects {
let exact_page;
let row = match rows.iter().find(|row| row["id"].as_str() == Some(project)) {
Some(row) => row,
None if projects.len() > 1 && page["truncated"].as_bool() == Some(true) => {
exact_page = list_for_removal(runtime, exact(project)).await?;
exact_page["projects"]
.as_array()
.and_then(|rows| rows.iter().find(|row| row["id"].as_str() == Some(project)))
.ok_or_else(unavailable)?
}
None => return Err(unavailable()),
};
let revision = row
.get("revision")
.and_then(Value::as_str)
.filter(|s| {
s.len() == 71
&& s.starts_with("sha256:")
&& s[7..].bytes().all(|b| b.is_ascii_hexdigit())
})
.ok_or_else(unavailable)?;
let path = row
.get("path")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.ok_or_else(unavailable)?;
observations.push(UnregisterObservation {
target: target.clone(),
project: project.clone(),
expected_revision: revision.to_owned(),
path: path.to_owned(),
});
}
Ok(observations)
}

async fn list_for_removal(runtime: &StoredRuntime, params: Value) -> DesktopResult<Value> {
let mut value = crate::workspace::post(
runtime,
"/api/tools/call",
json!({"tool":"list_projects","params":{}}),
json!({"tool":"list_projects","params":params}),
Duration::from_secs(12),
)
.await?;
if value.get("success").and_then(Value::as_bool) != Some(true) {
return Err(unavailable());
}
let rows = value
.pointer("/output/projects")
.and_then(Value::as_array)
.ok_or_else(unavailable)?;
projects
.iter()
.map(|project| {
let row = rows
.iter()
.find(|row| row.get("id").and_then(Value::as_str) == Some(project))
.ok_or_else(unavailable)?;
let revision = row
.get("revision")
.and_then(Value::as_str)
.filter(|s| {
s.len() == 71
&& s.starts_with("sha256:")
&& s[7..].bytes().all(|b| b.is_ascii_hexdigit())
})
.ok_or_else(unavailable)?;
let path = row
.get("path")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.ok_or_else(unavailable)?;
Ok(UnregisterObservation {
target: target.clone(),
project: project.clone(),
expected_revision: revision.to_owned(),
path: path.to_owned(),
})
})
.collect()
Ok(value["output"].take())
}

pub async fn unregister(
runtime: &StoredRuntime,
request: &UnregisterRequest,
Expand All @@ -121,12 +148,37 @@ pub async fn unregister(
}
let observation = observe(runtime, &request.project).await?;
if observation.expected_revision != request.expected_revision {
return Err(unavailable());
return Err(revision_changed());
}
let value = crate::workspace::post(runtime, "/api/tools/call", json!({"tool":"unregister_project", "params":{"project":request.project,"expected_revision":request.expected_revision}}), Duration::from_secs(40)).await.map_err(|_| uncertain())?;
if value.get("success").and_then(Value::as_bool) != Some(true) {
// Do not expose arbitrary upstream text or infer that a failed response had no effects.
return Err(uncertain());
return Err(
match value.pointer("/output/error/code").and_then(Value::as_str) {
Some("project_projection_reconcile_required")
if value.pointer("/output/project").and_then(Value::as_str)
== Some(&request.project)
&& matches!(
value
.pointer("/output/authoritative_outcome")
.and_then(Value::as_str),
Some("unregistered" | "already_unregistered")
) =>
{
DesktopError::new(
"project_projection_reconcile_required",
"Runner confirmed removal but Server inventory is pending",
"Refresh the inventory before taking further action.",
)
}
Some("active_jobs_conflict") => DesktopError::new(
"active_jobs_conflict",
"The project still has active jobs",
"Wait for those jobs to finish before removing the project.",
),
Some("revision_conflict") => revision_changed(),
_ => uncertain(),
},
);
}
let output = value.get("output").ok_or_else(uncertain)?;
if output.get("project").and_then(Value::as_str) != Some(&request.project)
Expand Down Expand Up @@ -242,6 +294,9 @@ pub async fn unregister_batch(
Some("not_attempted_after_uncertain_outcome") => {
"not_attempted_after_uncertain_outcome"
}
Some("project_projection_reconcile_required") => {
"project_projection_reconcile_required"
}
Some("active_jobs_conflict") => "active_jobs_conflict",
Some("revision_conflict") => "revision_conflict",
Some("project_not_found") => "project_not_found",
Expand Down
47 changes: 45 additions & 2 deletions apps/desktop/src-tauri/src/project_inventory/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,29 @@ async fn observe_many_uses_one_inventory_request() {
.unwrap();
assert_eq!(rows.len(), 1);
assert_eq!(rows[0].path, "D:\\repo");
assert_eq!(task.await.unwrap().len(), 1);
let calls = task.await.unwrap();
assert_eq!(calls.len(), 1);
assert_eq!(calls[0]["params"]["project"], "agent:mini:repo");
}

#[tokio::test]
async fn batch_observation_finds_a_selected_registration_beyond_the_first_page() {
let mut page = inventory();
page["output"]["truncated"] = json!(true);
let mut exact = inventory();
exact["output"]["projects"][0]["id"] = json!("agent:mini:last");
let (url, calls) = server(vec![page, exact]).await;
let fixture = Fixture::new(url);
let rows = observe_many(
&fixture.runtime,
&["agent:mini:repo".into(), "agent:mini:last".into()],
)
.await
.unwrap();
assert_eq!(rows[1].project, "agent:mini:last");
let calls = calls.await.unwrap();
assert_eq!(calls.len(), 2);
assert_eq!(calls[1]["params"]["project"], "agent:mini:last");
}

#[tokio::test]
Expand Down Expand Up @@ -161,7 +183,8 @@ async fn changed_revision_never_dispatches_removal() {
let fixture = Fixture::new(url);
let mut request = fixture.request();
request.expected_revision = format!("sha256:{}", "b".repeat(64));
assert!(unregister(&fixture.runtime, &request).await.is_err());
let error = unregister(&fixture.runtime, &request).await.unwrap_err();
assert_eq!(error.code, "project_revision_changed");
assert_eq!(task.await.unwrap().len(), 1);
}

Expand Down Expand Up @@ -192,6 +215,26 @@ async fn rejection_and_wrong_project_outcomes_are_not_retried() {
}
}

#[tokio::test]
async fn projection_failure_reports_only_an_exact_confirmed_removal() {
for (project, code) in [
("agent:mini:repo", "project_projection_reconcile_required"),
("agent:other:repo", "project_unregister_uncertain"),
] {
let response = json!({"success":false,"output":{
"error":{"code":"project_projection_reconcile_required"},
"authoritative_outcome":"unregistered","project":project
}});
let (url, calls) = server(vec![inventory(), response]).await;
let fixture = Fixture::new(url);
let error = unregister(&fixture.runtime, &fixture.request())
.await
.unwrap_err();
assert_eq!(error.code, code);
assert_eq!(calls.await.unwrap().len(), 2);
}
}

#[test]
fn forget_only_removes_exact_runner_registration_and_clears_default() {
let fixture = Fixture::new("http://127.0.0.1:1".into());
Expand Down
6 changes: 4 additions & 2 deletions apps/desktop/src-tauri/src/state/app_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,8 +120,10 @@ impl AppState {
"Choose an existing directory that this account can access.",
)
})?;
let canonical_roots =
webcodex_runner_config::paths::canonicalize_usable_allowed_roots(&effective_roots);
let canonical_roots = webcodex_runner_config::paths::canonicalize_usable_allowed_roots(
&effective_roots,
&canonical_project,
);
Ok::<_, DesktopError>(
webcodex_runner_config::paths::validate_project_path_policy(
&canonical_project,
Expand Down
39 changes: 30 additions & 9 deletions apps/desktop/src-tauri/src/state/environment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -378,12 +378,12 @@ pub(super) fn adopt_saved_environment(config: &mut StoredDesktopConfig) {
.find(|entry| entry.path == *path)
.map(|entry| format!("agent:{client}:{}", entry.id))
});
ProjectSelection {
path: path.to_string_lossy().into_owned(),
allowed_root: path.to_string_lossy().into_owned(),
is_git_repository: path.join(".git").exists(),
runtime_project_id,
let mut selected = saved_project_selection(path, config.project.as_ref());
if webcodex_runner_config::paths::project_path_probe_allowed(path, None) {
selected.is_git_repository = path.join(".git").exists();
}
selected.runtime_project_id = runtime_project_id;
selected
});
config.persistent_environment = Some(record.environment_id);
config.topology = Some(RuntimeTopology {
Expand Down Expand Up @@ -509,10 +509,27 @@ pub(super) fn legacy_inventory_projects(
Ok(projects)
}

fn saved_project_selection(path: &Path, previous: Option<&ProjectSelection>) -> ProjectSelection {
let spelling = path.to_string_lossy().into_owned();
ProjectSelection {
path: spelling.clone(),
allowed_root: spelling,
is_git_repository: previous.is_some_and(|project| {
webcodex_runner_config::paths::paths_equal(Path::new(&project.path), path)
&& project.is_git_repository
}),
runtime_project_id: None,
}
}

fn same_desktop_path(left: &Path, right: &Path) -> bool {
use webcodex_runner_config::paths::project_path_probe_allowed;
if left == right {
return true;
}
if !project_path_probe_allowed(left, None) || !project_path_probe_allowed(right, None) {
return false;
}
match (std::fs::canonicalize(left), std::fs::canonicalize(right)) {
(Ok(a), Ok(b)) => a == b,
_ => false,
Expand Down Expand Up @@ -1407,10 +1424,14 @@ impl DesktopCore {
.cloned()
});
let project = if let Some(path) = selected.as_ref() {
let mut project = self
.adapter
.inspect_project(&path.to_string_lossy())
.await?;
let mut project =
if webcodex_runner_config::paths::project_path_probe_allowed(path, None) {
self.adapter
.inspect_project(&path.to_string_lossy())
.await?
} else {
saved_project_selection(path, self.config.project.as_ref())
};
if let (Some(client), Some(entry)) = (
record.runner_client_id.as_deref(),
record
Expand Down
12 changes: 3 additions & 9 deletions apps/desktop/src-tauri/src/state/workspace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ impl AppState {
let observations = crate::project_inventory::observe_many(&runtime, &ids).await?;
for (item, observed) in request.items.iter().zip(observations.iter()) {
if observed.expected_revision != item.expected_revision {
return Err(crate::workspace::unavailable());
return Err(crate::project_inventory::revision_changed());
}
}
let items =
Expand Down Expand Up @@ -178,14 +178,8 @@ impl AppState {
crate::webcodex::settings::verify_target(&runtime, &request.target)?;
let observed =
crate::project_inventory::observe(&runtime, &request.project).await?;
if observed.expected_revision != request.expected_revision
|| observed.path.is_empty()
{
return Err(DesktopError::new(
"project_revision_changed",
"The project changed since confirmation",
"Review the current project again before removing it.",
));
if observed.expected_revision != request.expected_revision {
return Err(crate::project_inventory::revision_changed());
}
let store = super::environment::store()?;
let mut native = webcodex_environment::NativeEnvironment::new()
Expand Down
11 changes: 11 additions & 0 deletions apps/desktop/src-tauri/src/webcodex/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,17 @@ fn validate(paths: &[String]) -> DesktopResult<()> {
}

fn validate_allowed_roots(current: &[String], roots: &[String]) -> DesktopResult<()> {
// A config written by the CLI can already exceed the Desktop add limit.
// An exact deletion preserves the spelling and order of every survivor
// and needs no filesystem access (including for unavailable WSL shares).
let mut existing = current.iter();
if roots.len() < current.len()
&& roots
.iter()
.all(|root| existing.by_ref().any(|old| old == root))
{
return Ok(());
}
validate(roots)?;
for root in roots {
if current.iter().any(|existing| {
Expand Down
18 changes: 18 additions & 0 deletions apps/desktop/src-tauri/src/webcodex/settings/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,24 @@ fn file_access_can_remove_stale_roots_one_at_a_time() {
assert_eq!(projection.file_access.configured_roots, vec![stale_b]);
}

#[test]
fn file_access_can_revoke_from_oversized_configuration_without_adding_authority() {
let f = Fixture::new();
let original = (0..23)
.map(|i| {
f.dir
.join(format!("stale-{i}"))
.to_string_lossy()
.into_owned()
})
.collect::<Vec<_>>();
let mut remaining = original.clone();
remaining.remove(10);
validate_allowed_roots(&original, &remaining).unwrap();
remaining[0] = f.dir.to_string_lossy().into_owned();
assert!(validate_allowed_roots(&original, &remaining).is_err());
}

#[cfg(windows)]
#[test]
fn file_access_accepts_existing_windows_drive_root() {
Expand Down
Loading
Loading