diff --git a/crates/assistant/src/agent.rs b/crates/assistant/src/agent.rs
index 8fbf658f79..984a390592 100644
--- a/crates/assistant/src/agent.rs
+++ b/crates/assistant/src/agent.rs
@@ -297,6 +297,22 @@ impl Agent {
self.access
}
+ /// The map as the model is told of it, with the folder Project folder access works in: it
+ /// needs full paths to name files there.
+ fn map_context(&self, s: &Session) -> String {
+ let mut context = tools::context(s);
+ if self.access == AssistantAccess::ProjectFolder
+ && let Ok(folder) = s.assistant_project_folder()
+ && let Some(folder) = folder.to_str()
+ {
+ context.push_str(&format!(
+ "\nProject folder access: adding data from files in {} and exporting to new files there need no approval; give full paths. Overwriting a file, hidden files and files elsewhere ask.",
+ serde_json::json!(folder)
+ ));
+ }
+ compact::escape_user(&context)
+ }
+
fn local_delegation(&self, call: &ToolCall) -> bool {
if call.name != "delegate"
|| self.depth != 0
@@ -357,7 +373,7 @@ impl Agent {
));
}
// The agent may have changed the map: its context goes along when it did.
- let ctx = compact::escape_user(&tools::context(s));
+ let ctx = a.map_context(s);
let message = if ctx == a.last_context { message } else { format!("\n{ctx}\n \n\n{message}") };
a.last_context = ctx;
// A user turn still waiting (a summary, or a message whose request failed) takes the
@@ -636,7 +652,7 @@ impl Agent {
self.transcript.push(Entry::Note(Note::new(PICTURES_AS_NAMES)));
}
let text = compact::escape_user(text);
- let ctx = compact::escape_user(&tools::context(s));
+ let ctx = self.map_context(s);
let message = if ctx == self.last_context { text.to_string() } else { format!("\n{ctx}\n \n\n{text}") };
self.last_context = ctx;
// After a compaction the summary waits in a user turn of its own, and after a failed
diff --git a/crates/assistant/src/tests.rs b/crates/assistant/src/tests.rs
index d9d2b090fb..4188c32cd4 100644
--- a/crates/assistant/src/tests.rs
+++ b/crates/assistant/src/tests.rs
@@ -6167,3 +6167,28 @@ fn full_access_applies_from_the_next_call_to_the_assistant_and_its_subagent() {
a.clear();
assert_eq!(a.access(), crate::AssistantAccess::Full);
}
+
+/// Project folder access tells the model the saved project's folder and runs an export to a new
+/// file there, in a subagent too; a file elsewhere still asks.
+#[test]
+fn project_folder_access_says_the_folder_and_runs_new_files_in_it() {
+ let dir = tempfile::tempdir().unwrap();
+ let project = dir.path().join("project");
+ std::fs::create_dir(&project).unwrap();
+ let mut s = sample();
+ s.run("project.saveAs", &json!({"path": project.join("atlas.rgis")})).unwrap();
+ let mut a = Agent::new(cfg("openai"), &s);
+ a.set_access(crate::AssistantAccess::ProjectFolder);
+ let export = |path: std::path::PathBuf| calls("run_command", json!({"command": "share.exportMap", "params": {"path": path}}));
+ let Step::Send(req) = a.ask("export maps", &s) else { panic!("expected a request") };
+ let sent = body(&req)["messages"][1]["content"].as_str().unwrap_or_default().to_string();
+ assert!(sent.contains("Project folder access") && sent.contains(&json!(project.canonicalize().unwrap()).to_string()), "{sent}");
+ assert!(matches!(a.receive(a.generation(), ok(export(project.join("a.png"))), &mut s), Step::Send(_)));
+ assert!(project.join("a.png").is_file());
+ let delegate = calls("delegate", json!({"task": "Export two maps"}));
+ assert!(matches!(a.receive(a.generation(), ok(delegate), &mut s), Step::Send(_)));
+ assert!(matches!(a.receive(a.generation(), ok(export(project.join("b.png"))), &mut s), Step::Send(_)));
+ assert!(project.join("b.png").is_file());
+ assert_eq!(a.receive(a.generation(), ok(export(dir.path().join("c.png"))), &mut s), Step::Confirm);
+ assert!(!dir.path().join("c.png").exists());
+}
diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs
index a42f7c4212..6fd9037ac8 100644
--- a/crates/engine/src/cmd/layer.rs
+++ b/crates/engine/src/cmd/layer.rs
@@ -25,10 +25,10 @@ pub fn commands() -> Vec {
C::new("layer.addPhotos", "Add Photos", "Home › Add", add_photos).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).params(
r#"{"paths"?: [JPEG photo files], "folder"?: "a folder of photos (every JPEG in it)", "name"?: "the layer (default Photos; photos join it when it exists)"}"#,
),
- C::new("info.fileLayers", "List Layers in File", "Home › Add › Add Data", file_layers).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files))
+ C::new("info.fileLayers", "List Layers in File", "Home › Add › Add Data", file_layers).inputs(add_data_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files))
.view()
.params(r#"{"path": string, "crs"?: "EPSG:… for a CityJSON model (.city.json, a .json, or in a zip) or a CityGML model (.gml, .xml, or in a zip): it replaces the system a model file names; in a zip, it is used for a model naming none RustGIS knows (as layer.addData)", "link"?: "bool: for a file Add Data can link instead of copying (GeoPackage, GeoParquet, FlatGeobuf, Shapefile, .geojson; desktop), also say how it would take it, as link: linked (what it does without stream; for a .geojson, by its size alone, so Add Data sends the answer, as layer.addData unasked also looks at its count) and copy (whether it can be read whole); it opens the tables, up to the first read in place, so only when asked"}"#),
- C::new("info.fileColumns", "List Columns in File", "Home › Add › Add Data › Delimited Text", file_columns).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).view().params(
+ C::new("info.fileColumns", "List Columns in File", "Home › Add › Add Data › Delimited Text", file_columns).inputs(file_columns_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).view().params(
r#"{"path": "a delimited text file (CSV, TSV, TXT, DAT, or gzip-compressed text) or a spreadsheet", "delimiter"?: ","|";"|"\\t"|"|", "layer"?: "a spreadsheet's sheet (the first by default)", "crs"?: "EPSG:… (or WKT), as layer.addData: a projected system keeps the columns found by name"}"#,
),
C::new("layer.addSql", "Add Data From SQL", "Home › Add", add_sql)
@@ -2053,11 +2053,28 @@ fn add_data_inputs(_: &super::InputContext<'_>, p: &Value) -> Result bool {
+ path.extension()
+ .and_then(|ext| ext.to_str())
+ .is_some_and(|ext| matches!(ext.to_ascii_lowercase().as_str(), "csv" | "tsv" | "dat" | "txt" | "xlsx"))
+}
+
+fn file_columns_inputs(_: &super::InputContext<'_>, p: &Value) -> Result {
+ let mut inputs = super::Inputs::layers(std::iter::empty());
+ inputs.file_places = Some(vec![s_req(p, "path")?.into()]);
+ Ok(inputs)
+}
+
/// Opens a file through its format's reader. A Shapefile CRS override is applied before any
/// conversion in both whole-file and streamed paths; the source file is never rewritten.
/// DBF picks with geometry follow the full Shapefile import path.
diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs
index d4c70d1e60..fcd947b52c 100644
--- a/crates/engine/src/cmd/share.rs
+++ b/crates/engine/src/cmd/share.rs
@@ -30,20 +30,26 @@ fn map_inputs(s: &super::InputContext<'_>, p: &Value) -> Result, p: &Value) -> Result {
let mut inputs = super::whole::read_inputs(s, p)?;
- let path = Path::new(ps(p, "path").ok_or("path is required")?);
- inputs.file_places = inputs.file_places.and_then(|mut places| {
- let ext = path.extension().and_then(|ext| ext.to_str()).unwrap_or("").to_ascii_lowercase();
- match ext.as_str() {
- "gpkg" => places.extend(super::gpkg::file_places(path)),
- // The declaration comparison also reads existing sidecars with case variants.
- "shp" => return None,
- _ => places.push(path.to_path_buf()),
- }
- Some(places)
+ ps(p, "path").ok_or("path is required")?;
+ inputs.file_places = inputs.file_places.zip(export_file_places(p)).map(|(mut source, dest)| {
+ source.extend(dest);
+ source
});
Ok(inputs)
}
+/// The writer's local destinations, including possible GeoPackage companions.
+pub(crate) fn export_file_places(p: &Value) -> Option> {
+ let path = Path::new(ps(p, "path")?);
+ let ext = path.extension().and_then(|ext| ext.to_str()).unwrap_or("").to_ascii_lowercase();
+ match ext.as_str() {
+ "gpkg" => Some(super::gpkg::file_places(path)),
+ // The declaration comparison also reads existing sidecars with case variants.
+ "shp" => None,
+ _ => Some(vec![path.to_path_buf()]),
+ }
+}
+
pub fn commands() -> Vec {
vec![
C::new("share.exportMap", "Export Map", "Publish › Output", |s, p| {
diff --git a/crates/engine/src/policy/decide.rs b/crates/engine/src/policy/decide.rs
index d81fc28519..2cb393d19e 100644
--- a/crates/engine/src/policy/decide.rs
+++ b/crates/engine/src/policy/decide.rs
@@ -57,16 +57,28 @@ fn kind(s: &Session, k: &Kind, node: &Node, context: &DecisionContext) -> Decisi
}
Kind::Assistant(access) => {
let full = *access == AssistantAccess::Full;
- if full && node.id().starts_with("connection.") && !node.effects.contains(Unreviewed) {
+ #[cfg(not(target_arch = "wasm32"))]
+ let folder = (*access == AssistantAccess::ProjectFolder && node.effects.contains(Files))
+ .then(|| s.assistant_project_folder().ok())
+ .flatten();
+ #[cfg(target_arch = "wasm32")]
+ let folder: Option = None;
+ if (full || folder.is_some()) && node.id().starts_with("connection.") && !node.effects.contains(Unreviewed) {
return Ask;
}
- if full && node.effects.contains(Files) && !node.effects.contains(Unreviewed) && context.file_access_needs_approval(node) {
+ if (full || folder.is_some())
+ && node.effects.contains(Files)
+ && !node.effects.contains(Unreviewed)
+ && (full_access_asks(node.id()) || context.file_access_needs_approval(node))
+ {
return Ask;
}
+ let in_folder = folder.as_deref().is_some_and(|folder| super::folder::stays_inside(s, node, folder));
node.effects
.iter()
.map(|e| match e {
Edits | History => Allow,
+ Files if in_folder => Allow,
Files | Network | Plugin | Automation if full && !full_access_asks(node.id()) => Allow,
Files | Network if full => Ask,
Reserved if full && full_access_runs(node.id()) => Allow,
diff --git a/crates/engine/src/policy/dispatch.rs b/crates/engine/src/policy/dispatch.rs
index 22443f2389..02b2d29e59 100644
--- a/crates/engine/src/policy/dispatch.rs
+++ b/crates/engine/src/policy/dispatch.rs
@@ -70,8 +70,9 @@ struct Cursor {
made_tables: Vec,
}
/// Workflows the planner can expand before any of their steps run.
-fn preflights_automation(node: &Node) -> bool {
- matches!(node.id(), "script" | "script.run" | "task.run" | "notebook.run" | "model.run")
+fn preflights_automation(scope: &Scope, node: &Node) -> bool {
+ matches!(scope.kind, Kind::Assistant(AssistantAccess::Full | AssistantAccess::ProjectFolder))
+ && matches!(node.id(), "script" | "script.run" | "task.run" | "notebook.run" | "model.run")
}
impl Session {
@@ -447,10 +448,10 @@ impl Session {
let context = DecisionContext::default();
let full_access = matches!(scope.kind, Kind::Assistant(AssistantAccess::Full));
let (plan, decision) = if node.decision_with(self, scope, &context)? == Decision::Allow {
- if !full_access || !preflights_automation(&node) {
+ if !preflights_automation(scope, &node) {
return Ok(Outcome::Allowed);
}
- let Some((plan, decision)) = self.plan_full_access(scope, call, &context)? else { return Ok(Outcome::Allowed) };
+ let Some((plan, decision)) = self.plan_assistant_workflow(scope, call, &context)? else { return Ok(Outcome::Allowed) };
if decision == Decision::Allow {
return Ok(Outcome::Allowed);
}
@@ -482,14 +483,14 @@ impl Session {
})();
result.unwrap_or_else(Outcome::Refused)
}
- /// Only the byte limit permits an otherwise allowed workflow to fall back to stage checks.
- fn plan_full_access(&self, scope: &Scope, call: &Call, context: &DecisionContext) -> Result, String> {
+ /// Full access may fall back to stage checks at the byte limit. Project folder needs a complete plan.
+ fn plan_assistant_workflow(&self, scope: &Scope, call: &Call, context: &DecisionContext) -> Result , String> {
match self.plan(scope, call) {
Ok(plan) => {
let decision = plan.root.decision_with(self, scope, context)?;
Ok(Some((plan, decision)))
}
- Err(super::plan::PlanError::TooLarge) => Ok(None),
+ Err(super::plan::PlanError::TooLarge) if matches!(scope.kind, Kind::Assistant(AssistantAccess::Full)) => Ok(None),
Err(error) => Err(error.into()),
}
}
@@ -622,17 +623,13 @@ impl Session {
let scope = self.scope();
let context = DecisionContext::default();
let decision = node.decision_with(self, &scope, &context)?;
- if self.policy.cursor.is_none()
- && decision == Decision::Allow
- && matches!(scope.kind, Kind::Assistant(AssistantAccess::Full))
- && preflights_automation(&node)
- {
+ if self.policy.cursor.is_none() && decision == Decision::Allow && preflights_automation(&scope, &node) {
let call = match &node.op {
Op::Command(spec) => Call::command(spec.id, node.params.clone()),
Op::Adapter("script") => Call::script(node.params.get("script").and_then(Value::as_str).ok_or("script is required")?),
_ => return Err("this operation's steps cannot be planned".into()),
};
- if self.plan_full_access(&scope, &call, &context)?.is_some_and(|(_, decision)| decision != Decision::Allow) {
+ if self.plan_assistant_workflow(&scope, &call, &context)?.is_some_and(|(_, decision)| decision != Decision::Allow) {
return Err("this operation needs your approval".into());
}
}
diff --git a/crates/engine/src/policy/folder.rs b/crates/engine/src/policy/folder.rs
new file mode 100644
index 0000000000..eccafdba88
--- /dev/null
+++ b/crates/engine/src/policy/folder.rs
@@ -0,0 +1,248 @@
+//! The assistant's Project folder access (#3568): which file commands stay inside the saved
+//! project's folder. Everything not shown to stay inside asks, so each rule here fails closed: an
+//! unlisted command, format or parameter, a path that can't be resolved, a link.
+
+use super::{
+ Effect,
+ plan::{Node, Op},
+};
+use crate::Session;
+use serde_json::Value;
+use std::path::{Component, Path, PathBuf};
+
+/// Why the assistant's Project folder access has no folder to work in, so it asks as Ask does.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum NoProjectFolder {
+ /// The project has no file of its own, or its folder is gone.
+ Unsaved,
+ /// The project's file is in the home folder or above it, so "inside" would be everything.
+ TooBroad,
+}
+
+/// What a command does with the one file its `path` names.
+#[derive(Clone, Copy)]
+enum Use {
+ /// Reads it, with the files of the same name beside it.
+ Read,
+ /// Writes it, with files of the same name beside it, none of which may be there yet.
+ Create,
+}
+
+/// Native readers whose files can all be bound. Readers with unresolved companion files or
+/// external references (including KML ground overlays) still ask.
+const READ: &[&str] = &["csv", "dat", "fgb", "geojson", "geoparquet", "gpkg", "gpx", "json", "parquet", "tsv", "txt", "xlsx"];
+/// What Export Map writes.
+const PICTURES: &[&str] = &["png", "tif", "tiff"];
+/// What Export Features and Export Table write.
+const DATA: &[&str] = &["csv", "fgb", "geojson", "gpkg", "gpx", "kml", "kmz", "parquet", "zip"];
+/// The most entries of a folder looked through for files of the same name; a fuller one asks.
+const MOST_ENTRIES: usize = 100_000;
+
+/// The file commands the level runs: what each does with `path`, and the extensions it takes
+/// there. Each reads or writes nothing its other parameters name.
+fn file_command(id: &str) -> Option<(Use, &'static [&'static str])> {
+ Some(match id {
+ "layer.addData" | "info.fileLayers" | "info.fileColumns" => (Use::Read, READ),
+ "share.exportMap" => (Use::Create, PICTURES),
+ "share.exportLayer" | "share.exportTable" => (Use::Create, DATA),
+ _ => return None,
+ })
+}
+
+impl Session {
+ /// The folder of the saved project's file, resolved through links: where the assistant's
+ /// Project folder access works.
+ pub fn assistant_project_folder(&self) -> Result {
+ let folder = self
+ .path
+ .as_deref()
+ .filter(|file| file.is_absolute())
+ .and_then(Path::parent)
+ .and_then(|folder| folder.canonicalize().ok())
+ .ok_or(NoProjectFolder::Unsaved)?;
+ let home = std::env::home_dir().and_then(|home| home.canonicalize().ok());
+ if too_broad(&folder, home.as_deref()) {
+ return Err(NoProjectFolder::TooBroad);
+ }
+ Ok(folder)
+ }
+}
+
+/// Whether `folder` holds so much that working in it would not be working in a project's folder:
+/// a filesystem's root, the home folder or one above it.
+fn too_broad(folder: &Path, home: Option<&Path>) -> bool {
+ folder.parent().is_none() || home.is_some_and(|home| home.starts_with(folder))
+}
+
+/// Whether `node` is a command that only reads files in the project's folder, or only makes new
+/// ones there.
+pub(super) fn stays_inside(s: &Session, node: &Node, folder: &Path) -> bool {
+ let Op::Command(spec) = &node.op else { return false };
+ let Some((how, extensions)) = file_command(spec.id) else { return false };
+ if !node.children.is_empty() || node.effects.iter().any(|e| !matches!(e, Effect::Files | Effect::Edits | Effect::History)) {
+ return false;
+ }
+ let Some(params) = node.params.as_object() else { return false };
+ let Some(text) = params.get("path").and_then(Value::as_str) else { return false };
+ let places = super::effects::PLACE_KEYS;
+ if params
+ .iter()
+ .filter(|(key, _)| key.as_str() != "path")
+ .any(|(key, value)| places.iter().any(|place| key.eq_ignore_ascii_case(place)) || crate::cmd::items::names_place(value, places, 0))
+ {
+ return false;
+ }
+ // Use the owner's binding, including inputs an export reopens. A generated or unresolved
+ // input cannot be substituted for a path that was checked here.
+ let Some(bound) = &node.file_places else { return false };
+ let path = Path::new(text);
+ let Some(saved_folder) = s.path.as_deref().and_then(Path::parent) else { return false };
+ if !bound.iter().any(|place| place == path)
+ || !path.extension().and_then(|ext| ext.to_str()).is_some_and(|ext| extensions.iter().any(|known| ext.eq_ignore_ascii_case(known)))
+ {
+ return false;
+ }
+ let Some((parent, name)) = local_path(saved_folder, folder, path) else { return false };
+ if !siblings_allow(&parent, name, how) {
+ return false;
+ }
+ bound.iter().all(|place| {
+ if place != path && local_path(saved_folder, folder, place).is_none() {
+ return false;
+ }
+ match std::fs::symlink_metadata(place) {
+ Ok(metadata) => (place != path || matches!(how, Use::Read)) && visible_file(&metadata),
+ Err(error) => error.kind() == std::io::ErrorKind::NotFound && (place != path || matches!(how, Use::Create)),
+ }
+ })
+}
+
+/// Validates an original spelling before following any directory below the project root.
+fn local_path<'a>(saved_folder: &Path, folder: &Path, path: &'a Path) -> Option<(PathBuf, &'a str)> {
+ let text = path.to_str()?;
+ if text.trim() != text
+ || text.chars().any(char::is_control)
+ || text.ends_with(['/', '\\'])
+ || text.contains("://")
+ || rustgis_data::source::is_remote_name(text)
+ || !path.is_absolute()
+ || path.components().any(|component| match component {
+ Component::ParentDir => true,
+ Component::Normal(part) if cfg!(windows) => part.to_str().is_none_or(|part| part.contains(':') || part.ends_with(['.', ' '])),
+ _ => false,
+ })
+ {
+ return None;
+ }
+ let parent = path.parent()?;
+ let name = path.file_name()?.to_str()?;
+ let (root, below) = [folder, saved_folder].into_iter().find_map(|root| parent.strip_prefix(root).ok().map(|below| (root, below)))?;
+ if name.starts_with('.') || !visible_directories(root, below) {
+ return None;
+ }
+ let resolved = parent.canonicalize().ok()?;
+ let below = resolved.strip_prefix(folder).ok()?;
+ (!below.iter().any(hidden)).then_some((resolved, name))
+}
+
+fn hidden(part: &std::ffi::OsStr) -> bool {
+ part.to_str().is_none_or(|part| part.starts_with('.'))
+}
+
+/// Check each original directory for links before traversing into it.
+fn visible_directories(root: &Path, below: &Path) -> bool {
+ let mut directory = root.to_path_buf();
+ if !visible_directory(&directory) {
+ return false;
+ }
+ for part in below {
+ directory.push(part);
+ if hidden(part) || !visible_directory(&directory) {
+ return false;
+ }
+ }
+ true
+}
+
+fn visible_directory(path: &Path) -> bool {
+ std::fs::symlink_metadata(path).is_ok_and(|metadata| metadata.is_dir() && visible_metadata(&metadata))
+}
+
+fn visible_metadata(metadata: &std::fs::Metadata) -> bool {
+ #[cfg(windows)]
+ {
+ use std::os::windows::fs::MetadataExt;
+ // Hidden files and reparse points can have ordinary names on Windows.
+ const HIDDEN: u32 = 0x2;
+ const REPARSE_POINT: u32 = 0x400;
+ metadata.file_attributes() & (HIDDEN | REPARSE_POINT) == 0
+ }
+ #[cfg(not(windows))]
+ {
+ let _ = metadata;
+ true
+ }
+}
+
+/// A regular visible file with no other hard link on Unix.
+fn visible_file(metadata: &std::fs::Metadata) -> bool {
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::MetadataExt;
+ if metadata.nlink() != 1 {
+ return false;
+ }
+ }
+ metadata.is_file() && visible_metadata(metadata)
+}
+
+/// Looks at the file and those of the same name beside it:
+/// to read, the file is there and none of them is a link or anything but a file; to create, none
+/// of them is there.
+fn siblings_allow(parent: &Path, name: &str, how: Use) -> bool {
+ let name = name.to_lowercase();
+ let stem = name.rsplit_once('.').map_or(name.as_str(), |(stem, _)| stem);
+ let prefix = format!("{stem}.");
+ let sqlite = name.ends_with(".gpkg");
+ let sqlite_parts = ["-journal", "-wal", "-shm"].map(|suffix| format!("{name}{suffix}"));
+ let Ok(entries) = std::fs::read_dir(parent) else { return false };
+ let mut found = false;
+ for (n, entry) in entries.enumerate() {
+ let Ok(entry) = entry else { return false };
+ let other = entry.file_name().to_string_lossy().to_lowercase();
+ if n >= MOST_ENTRIES {
+ return false;
+ }
+ if !(other == name || other.starts_with(&prefix) || sqlite && sqlite_parts.contains(&other)) {
+ continue;
+ }
+ // The entry's own type: a link is not followed.
+ if matches!(how, Use::Create) || !entry.metadata().is_ok_and(|metadata| visible_file(&metadata)) {
+ return false;
+ }
+ found |= other == name;
+ }
+ match how {
+ Use::Read => found,
+ Use::Create => true,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// The home folder, those above it and a filesystem's root are no project folder; one inside
+ /// home, or beside it, is.
+ #[test]
+ fn the_home_folder_and_those_above_it_are_too_broad() {
+ let home = Path::new("/home/someone");
+ for folder in ["/", "/home", "/home/someone"] {
+ assert!(too_broad(Path::new(folder), Some(home)), "{folder}");
+ }
+ for folder in ["/home/someone/maps", "/home/other", "/data"] {
+ assert!(!too_broad(Path::new(folder), Some(home)), "{folder}");
+ }
+ assert!(too_broad(Path::new("/"), None));
+ }
+}
diff --git a/crates/engine/src/policy/mod.rs b/crates/engine/src/policy/mod.rs
index e8adefe5e9..4a33f78824 100644
--- a/crates/engine/src/policy/mod.rs
+++ b/crates/engine/src/policy/mod.rs
@@ -7,6 +7,8 @@ mod dispatch;
pub(crate) mod downloads;
pub use downloads::WINDOW_KEYS;
mod effects;
+mod folder;
+pub use folder::NoProjectFolder;
pub mod handler;
mod plan;
#[cfg(not(target_arch = "wasm32"))]
diff --git a/crates/engine/src/policy/plan.rs b/crates/engine/src/policy/plan.rs
index 83033775a8..80f31a0a13 100644
--- a/crates/engine/src/policy/plan.rs
+++ b/crates/engine/src/policy/plan.rs
@@ -995,6 +995,14 @@ impl<'a> Builder<'a> {
Ok(i) => {
if let Some(t) = self.s.project.tables.get(i) {
n.targets.push(Target::Table { id: t.id, source: reads.then(|| json!(t.dataset.source)) });
+ // Export Table writes the resident rows through the same writer as
+ // Export Features. A table produced by this plan is not bound yet.
+ if n.id() == "share.exportTable" && n.wires.is_empty() {
+ n.file_places = crate::cmd::share::export_file_places(params);
+ for path in n.file_places.iter().flatten() {
+ self.charge(&path.to_string_lossy())?;
+ }
+ }
}
}
Err(e)
diff --git a/crates/engine/src/policy/scope.rs b/crates/engine/src/policy/scope.rs
index 83e28276ac..be10126af2 100644
--- a/crates/engine/src/policy/scope.rs
+++ b/crates/engine/src/policy/scope.rs
@@ -55,6 +55,9 @@ pub enum AssistantAccess {
/// Project edits run; files and the internet ask, and may be remembered; the rest asks.
#[default]
Ask,
+ /// Also adds data from files in the saved project's folder and exports to new files there
+ /// ([`crate::Session::assistant_project_folder`]); without a folder, as [`Self::Ask`].
+ ProjectFolder,
/// Files, the internet, SQL, scripts and installed plugins run too. Installing plugins and
/// other programs, sign-ins, saved credentials, app settings and replacing the project still ask.
Full,
diff --git a/crates/engine/src/tests/permission_policy.rs b/crates/engine/src/tests/permission_policy.rs
index 5fc5404eaf..ad22dfe5fe 100644
--- a/crates/engine/src/tests/permission_policy.rs
+++ b/crates/engine/src/tests/permission_policy.rs
@@ -2604,3 +2604,203 @@ fn permission_policy_assistant_full_access_protects_plugin_files() {
std::fs::remove_dir_all(source_dir).unwrap();
std::fs::remove_dir_all(dir).unwrap();
}
+
+/// A saved project in a folder of its own: files in it, beside it, hidden and, where links can be
+/// made, linked out of it.
+#[cfg(not(target_arch = "wasm32"))]
+fn saved_in_a_folder(name: &str) -> (Session, std::path::PathBuf) {
+ let root = std::env::temp_dir().join(format!("rustgis-engine-folder-{}-{name}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&root);
+ let (project, outside) = (root.join("project"), root.join("outside"));
+ for dir in [project.join("sub"), project.join(".git"), outside.clone()] {
+ std::fs::create_dir_all(dir).unwrap();
+ }
+ let csv = "name,lon,lat\na,1,2\n";
+ for file in ["project/data.csv", "project/sub/inner.csv", "project/parts.csv", "project/.secret.csv", "project/.git/x.csv"] {
+ std::fs::write(root.join(file), csv).unwrap();
+ }
+ std::fs::write(outside.join("out.csv"), csv).unwrap();
+ std::fs::write(project.join("refs.vrt"), " ").unwrap();
+ std::fs::write(project.join("overlays.kml"), " ").unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::symlink;
+ symlink(outside.join("out.csv"), project.join("linked.csv")).unwrap();
+ std::fs::hard_link(outside.join("out.csv"), project.join("hardlink.csv")).unwrap();
+ symlink(&outside, project.join("elsewhere")).unwrap();
+ symlink(project.join("sub"), project.join("linked-inside")).unwrap();
+ symlink(&project, root.join("project-alias")).unwrap();
+ symlink(outside.join("new.geojson"), project.join("dangling.geojson")).unwrap();
+ symlink(outside.join("out.csv"), project.join("parts.prj")).unwrap();
+ }
+ let mut s = world();
+ s.run("project.saveAs", &json!({"path": project.join("atlas.rgis")})).unwrap();
+ (s, root)
+}
+
+/// Project folder access adds data from the saved project's folder and exports to new files there
+/// without asking; the default still asks for each, and so does an unsaved project.
+#[cfg(not(target_arch = "wasm32"))]
+#[test]
+fn permission_policy_assistant_project_folder_reads_and_creates_inside() {
+ let (mut s, root) = saved_in_a_folder("inside");
+ let project = root.join("project");
+ assert_eq!(s.assistant_project_folder().unwrap(), project.canonicalize().unwrap());
+ let (ask, _) = assistant(35690);
+ let folder = ask.clone().with_access(AssistantAccess::ProjectFolder);
+ let at = |name: &str| project.join(name);
+ let rows = s.map().layer_by_name("Cities").unwrap().dataset.clone();
+ let table = s.project.add_table(rows);
+ let calls = [
+ Call::command("layer.addData", json!({"path": at("data.csv")})),
+ Call::command("info.fileLayers", json!({"path": at("data.csv")})),
+ Call::command("info.fileColumns", json!({"path": at("sub/inner.csv")})),
+ Call::command("share.exportLayer", json!({"layer": "Cities", "path": at("sub/new.geojson")})),
+ Call::command("share.exportMap", json!({"path": at("map.png")})),
+ Call::command("share.exportTable", json!({"table": table, "path": at("observations.csv")})),
+ Call::script(&format!("share.exportLayer {}", json!({"layer": "Cities", "path": at("second.geojson")}))),
+ ];
+ for call in &calls {
+ assert!(pending(&s, &ask, call).review().remember);
+ assert!(matches!(s.review(&folder, call), Outcome::Allowed));
+ s.run_scoped(folder.clone(), call).unwrap();
+ }
+ for made in ["sub/new.geojson", "map.png", "observations.csv", "second.geojson"] {
+ assert!(at(made).is_file(), "{made}");
+ }
+ // What was just made is there now: writing it again is overwriting.
+ pending(&s, &folder, &calls[3]);
+ // The same session with no file of its own has no folder.
+ let mut unsaved = world();
+ assert_eq!(unsaved.assistant_project_folder(), Err(crate::policy::NoProjectFolder::Unsaved));
+ pending(&unsaved, &folder, &calls[0]);
+ assert!(unsaved.run_scoped(folder.clone(), &calls[0]).is_err());
+ std::fs::remove_dir_all(root).unwrap();
+}
+
+/// Everything else still asks: elsewhere, `..`, links leading out, hidden files, files already
+/// there, other formats and other commands, the internet, SQL and scripts.
+#[cfg(not(target_arch = "wasm32"))]
+#[test]
+fn permission_policy_assistant_project_folder_asks_about_the_rest() {
+ let (mut s, root) = saved_in_a_folder("rest");
+ let project = root.join("project");
+ let folder = assistant(35691).0.with_access(AssistantAccess::ProjectFolder);
+ let at = |name: &str| project.join(name).display().to_string();
+ let read = |path: String| Call::command("layer.addData", json!({ "path": path }));
+ let write = |path: String| Call::command("share.exportLayer", json!({"layer": "Cities", "path": path}));
+ #[cfg_attr(not(any(unix, windows)), expect(unused_mut, reason = "platform-specific hidden files and links"))]
+ let mut calls = vec![
+ read("data.csv".into()),
+ read(at("sub/../data.csv")),
+ read(at("../outside/out.csv")),
+ read(root.join("outside/out.csv").display().to_string()),
+ read(at(".secret.csv")),
+ read(at(".git/x.csv")),
+ read(format!("{} ", at("data.csv"))),
+ read(at("missing.csv")),
+ read(at("refs.vrt")),
+ read(at("overlays.kml")),
+ read(project.display().to_string()),
+ read("https://example.com/data.csv".into()),
+ write(root.join("outside/new.geojson").display().to_string()),
+ write(at("../outside/new.geojson")),
+ write(at("data.csv")),
+ // A file of the same name beside it: one of them could be a part the export writes.
+ write(at("data.geojson")),
+ write(at(".new.geojson")),
+ write(at("nowhere/new.geojson")),
+ write(at("new.txt")),
+ write(at("new")),
+ Call::command(
+ "share.exportLayer",
+ json!({"layer": "Cities", "path": at("extra.geojson"), "options": [{"output": at("../outside/extra.geojson")}]}),
+ ),
+ Call::command("project.save", Value::Null),
+ Call::command("project.saveAs", json!({"path": at("copy.rgis")})),
+ Call::command("layout.export", json!({"path": at("layout.png")})),
+ Call::command("map.addTiles", json!({"url": "https://example.com/{z}/{x}/{y}.png"})),
+ Call::command("sql.query", json!({"sql": format!("SELECT * FROM '{}'", at("data.csv"))})),
+ Call::command("script.run", json!({"script": "select.clear"})),
+ Call::script(&format!("layer.addData {}", json!({"path": root.join("outside/out.csv")}))),
+ ];
+ #[cfg(unix)]
+ calls.extend([
+ read(at("linked.csv")),
+ read(at("hardlink.csv")),
+ read(at("elsewhere/out.csv")),
+ read(at("linked-inside/inner.csv")),
+ read(root.join("project-alias/data.csv").display().to_string()),
+ // Its .prj is a link out of the folder.
+ read(at("parts.csv")),
+ write(at("dangling.geojson")),
+ write(at("elsewhere/new.geojson")),
+ ]);
+ #[cfg(windows)]
+ {
+ let hidden = project.join("hidden.csv");
+ std::fs::write(&hidden, b"name,lon,lat\na,1,2\n").unwrap();
+ assert!(std::process::Command::new("attrib").arg("+h").arg(&hidden).status().unwrap().success());
+ calls.push(read(at("hidden.csv")));
+ }
+ s.run("layout.new", &json!({"name":"Page"})).unwrap();
+ let layers = s.map().layers.len();
+ for (n, call) in calls.iter().enumerate() {
+ assert!(!matches!(s.review(&folder, call), Outcome::Allowed), "call {n} would run without asking");
+ assert!(s.run_scoped(folder.clone(), call).is_err(), "call {n} ran");
+ }
+ assert_eq!(s.map().layers.len(), layers);
+ assert!(!root.join("outside/new.geojson").exists());
+ assert!(!project.join("copy.rgis").exists());
+ std::fs::remove_dir_all(root).unwrap();
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+#[test]
+fn permission_policy_assistant_project_folder_checks_bound_sources_and_protected_files() {
+ if isolate_process_test("tests::permission_policy::permission_policy_assistant_project_folder_checks_bound_sources_and_protected_files")
+ {
+ return;
+ }
+ let (mut s, root) = saved_in_a_folder("bound");
+ let project = root.join("project");
+ let plugins = project.join("plugins");
+ std::fs::create_dir(&plugins).unwrap();
+ rustgis_plugins::store::set_dir(Some(plugins.clone()));
+ let folder = assistant(35692).0.with_access(AssistantAccess::ProjectFolder);
+ let fixture = grid_fgb("policy-project-folder-bound", 2);
+ for (dir, name) in [(&project, "Inside"), (&root.join("outside"), "Outside"), (&plugins, "Protected")] {
+ let path = dir.join("sites.fgb");
+ std::fs::copy(&fixture, &path).unwrap();
+ s.run("layer.addData", &json!({"path":path,"name":name,"stream":true})).unwrap();
+ assert!(s.map().layer_by_name(name).unwrap().is_streamed());
+ }
+ let dest = project.join("out.geojson");
+ let export = |layer| Call::command("share.exportLayer", json!({"layer":layer,"path":dest}));
+ pending(&s, &folder, &export("Outside"));
+ assert!(s.run_scoped(folder.clone(), &export("Outside")).is_err());
+ assert!(!pending(&s, &folder, &export("Protected")).review().remember);
+ assert!(s.run_scoped(folder.clone(), &export("Protected")).is_err());
+ let protected_dest = Call::command("share.exportLayer", json!({"layer":"Cities","path":plugins.join("out.geojson")}));
+ let ask = folder.clone().with_access(AssistantAccess::Ask);
+ let prior = pending(&s, &ask, &protected_dest).remember().unwrap();
+ assert!(s.run_remembered(folder.clone(), &prior, &protected_dest).is_err());
+ assert!(!dest.exists());
+ assert!(!plugins.join("out.geojson").exists());
+ assert!(matches!(s.review(&folder, &export("Inside")), Outcome::Allowed));
+ s.run_scoped(folder.clone(), &export("Inside")).unwrap();
+ assert!(dest.is_file());
+
+ let import = Call::command("project.importQgis", json!({"text":" "}));
+ assert!(matches!(s.review(&folder, &import), Outcome::Refused(why) if why.contains("import it yourself")));
+ let bad_script = Call::script(&format!(
+ "share.exportLayer {}\nlayer.rename {}",
+ json!({"layer":"Cities","path":project.join("partial.geojson")}),
+ json!({"layer":"Missing","name":"New"})
+ ));
+ assert!(matches!(s.review(&folder, &bad_script), Outcome::Refused(_)));
+ assert!(s.run_scoped(folder, &bad_script).is_err());
+ assert!(!project.join("partial.geojson").exists());
+ std::fs::remove_file(fixture).unwrap();
+ std::fs::remove_dir_all(root).unwrap();
+}
diff --git a/crates/ui-egui/src/assistant.rs b/crates/ui-egui/src/assistant.rs
index 46d10dd619..1066d7f1ed 100644
--- a/crates/ui-egui/src/assistant.rs
+++ b/crates/ui-egui/src/assistant.rs
@@ -17,6 +17,7 @@
//! browser's fetch) on the web. Their replies are taken in by [`RustGisApp::logic`] each frame.
use rustgis_assistant::{Agent, AssistantAccess, Config, Entry, HttpRequest, HttpResponse, Step, chatgpt, provider};
+use rustgis_engine::policy::NoProjectFolder;
use crate::{RustGisApp, Slot};
@@ -110,8 +111,11 @@ pub struct AssistantState {
pub(crate) retry: Option<(u64, web_time::Instant)>,
/// The user lets the assistant hand tasks to local agents (Claude Code, Codex).
pub(crate) local_agents: bool,
- /// What the assistant runs without asking ([`set_access`]). Never saved: a launch asks.
+ /// What the assistant runs without asking ([`set_access`]). Full access is never saved.
access: AssistantAccess,
+ /// Whether the project saved at this path gives Project folder access a folder, looked up
+ /// when the path changes rather than each frame.
+ folder: Option<(Option, Result<(), NoProjectFolder>)>,
/// The tokens a message took are left out of the conversation (shown unless the user says).
pub(crate) hide_tokens: bool,
/// Each call has a line of its own instead of sharing one ([`lines`]).
@@ -281,19 +285,65 @@ pub fn access(app: &RustGisApp) -> AssistantAccess {
app.assistant.access
}
-/// Chooses what the assistant runs without asking, from its next call on. Only the user's own
-/// controls call this: it is no command, so nothing the assistant or an agent runs can widen it.
-/// It isn't saved, and it leaves connected agents and agent threads as their settings have them.
+/// The preference that remembers Ask or Project folder ("project"). Full access is not one.
+const ACCESS_PREF: &str = "assistant_access";
+
+/// The level a launch starts at: Project folder where that was the choice, else Ask. A value
+/// this version doesn't know asks, and is kept until another choice is made.
+fn remembered_access(app: &RustGisApp) -> AssistantAccess {
+ match pref(app, ACCESS_PREF).as_deref() {
+ Some("project") if !cfg!(target_arch = "wasm32") => AssistantAccess::ProjectFolder,
+ _ => AssistantAccess::Ask,
+ }
+}
+
+/// Chooses what the assistant runs without asking, from its next call on, and remembers a choice
+/// other than full access. Only the user's own controls call this: it is no command, so nothing
+/// the assistant or an agent runs can widen it. It leaves connected agents and agent threads as
+/// their settings have them.
pub fn set_access(app: &mut RustGisApp, access: AssistantAccess) {
+ match access {
+ AssistantAccess::Ask => save_pref(app, ACCESS_PREF, "ask"),
+ AssistantAccess::ProjectFolder => save_pref(app, ACCESS_PREF, "project"),
+ AssistantAccess::Full => {}
+ }
+ apply_access(app, access);
+}
+
+/// [`set_access`] without remembering it.
+fn apply_access(app: &mut RustGisApp, access: AssistantAccess) {
app.assistant.access = access;
if let Some(agent) = app.assistant.agent.as_mut() {
agent.set_access(access);
}
}
-/// The access levels offered, with their names.
-pub fn access_choices() -> [(AssistantAccess, &'static str); 2] {
- [(AssistantAccess::Ask, tl!("Ask")), (AssistantAccess::Full, tl!("Full access, for this session"))]
+/// The access levels offered, with their names. A browser has no project folder.
+pub fn access_choices() -> Vec<(AssistantAccess, &'static str)> {
+ let mut choices = vec![(AssistantAccess::Ask, tl!("Ask"))];
+ if !cfg!(target_arch = "wasm32") {
+ choices.push((AssistantAccess::ProjectFolder, tl!("Project folder")));
+ }
+ choices.push((AssistantAccess::Full, tl!("Full access, for this session")));
+ choices
+}
+
+/// Why the chosen level acts as Ask just now, if it does: Project folder without a folder.
+pub fn access_note(app: &mut RustGisApp) -> Option<&'static str> {
+ if app.assistant.access != AssistantAccess::ProjectFolder {
+ return None;
+ }
+ if app.assistant.folder.as_ref().is_none_or(|(path, _)| *path != app.session.path) {
+ let found = app.session.assistant_project_folder().map(|_| ());
+ app.assistant.folder = Some((app.session.path.clone(), found));
+ }
+ match app.assistant.folder.as_ref()?.1 {
+ Ok(()) => None,
+ Err(NoProjectFolder::Unsaved) => Some(tl!("This project isn't saved, so it has no folder: the assistant asks, as at Ask.")),
+ Err(NoProjectFolder::TooBroad) => {
+ Some(tl!("The project is saved in your home folder or above it, so the assistant asks, as at Ask."))
+ }
+ }
}
/// What a level lets run without asking, for the control's explanation.
@@ -302,6 +352,9 @@ pub fn access_explanation(access: AssistantAccess) -> &'static str {
AssistantAccess::Ask => {
tl!("Project edits run without asking. Files, the internet, SQL, scripts and plugins wait for your approval.")
}
+ AssistantAccess::ProjectFolder => tl!(
+ "Adding data from files in the saved project's folder, and exporting maps, layers and tables to new files there, run without asking. It still asks before overwriting a file, using files elsewhere or hidden ones, the internet, SQL, scripts and plugins. The assistant is told the folder's path. This choice is remembered."
+ ),
#[cfg(not(target_arch = "wasm32"))]
AssistantAccess::Full => tl!(
"The assistant can use files, the internet, scripts and installed plugins without asking. It still asks about protected or unidentified file paths, SQL queries, plugin installs, connections, sign-ins, saved credentials, app settings and replacing the project. It lasts until RustGIS closes."
@@ -455,6 +508,7 @@ pub(crate) fn ensure_loaded(app: &mut RustGisApp, ctx: &egui::Context) {
}
// The skills switched on (the plugins' too), and the local agents the user allows (desktop).
agent.set_skills(rustgis_assistant::skills::installed());
+ app.assistant.access = remembered_access(app);
agent.set_access(app.assistant.access);
#[cfg(not(target_arch = "wasm32"))]
agent.set_agents_auto(app.assistant.agents_auto);
@@ -917,9 +971,11 @@ pub(crate) fn turned_off(app: &mut RustGisApp) {
let signing_in = false;
// A message not sent yet stays in the message box.
app.assistant.hold();
- // Full access ends with the assistant: turned on again, it asks.
+ // Full access ends with the assistant: turned on again, it is back at the remembered level.
let had_full = app.assistant.access == AssistantAccess::Full;
- set_access(app, AssistantAccess::Ask);
+ if had_full {
+ apply_access(app, remembered_access(app));
+ }
if let Some(agent) = app.assistant.agent.as_mut() {
agent.suspend();
}
@@ -931,7 +987,7 @@ pub(crate) fn turned_off(app: &mut RustGisApp) {
|| app.assistant.pictures.any();
let mut said = Vec::new();
if had_full {
- said.push(tl!("The AI Assistant's full access ended: turned on again, it asks.").to_string());
+ said.push(tl!("The AI Assistant's full access ended.").to_string());
}
if busy {
said.push(tl!("The AI Assistant's running request was stopped; what it had already done stays.").to_string());
diff --git a/crates/ui-egui/src/assistantpane.rs b/crates/ui-egui/src/assistantpane.rs
index 3d68231a5e..6e33c71e00 100644
--- a/crates/ui-egui/src/assistantpane.rs
+++ b/crates/ui-egui/src/assistantpane.rs
@@ -732,6 +732,8 @@ fn account_row(_app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, _cfg: &mut Config
fn access_row(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) {
let held = assistant::access(app);
let mut chosen = held;
+ // A pick saves even the level shown: Ask stands in for a saved value this version doesn't know.
+ let mut picked = false;
let mine = tl!("For the assistant in this pane. Connected agents and agent windows keep their own settings.");
let explain = |level| crate::i18n::fmt("{access}\n{scope}", &[("access", assistant::access_explanation(level)), ("scope", mine)]);
ui.horizontal(|ui| {
@@ -743,13 +745,16 @@ fn access_row(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) {
.truncate()
.show_ui(ui, |ui| {
for (level, name) in assistant::access_choices() {
- ui.selectable_value(&mut chosen, level, name).on_hover_text(explain(level));
+ picked |= ui.selectable_value(&mut chosen, level, name).on_hover_text(explain(level)).clicked();
}
})
.response
.labelled_by(label.id)
.on_hover_text(explain(held));
});
+ if let Some(note) = assistant::access_note(app) {
+ ui.add(egui::Label::new(RichText::new(note).small().color(t.amber)).wrap());
+ }
if held == AssistantAccess::Full {
egui::Frame::NONE.fill(t.red.gamma_multiply(0.12)).corner_radius(6).inner_margin(6).stroke(egui::Stroke::new(1.0, t.red)).show(
ui,
@@ -764,7 +769,7 @@ fn access_row(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) {
},
);
}
- if chosen != held {
+ if picked || chosen != held {
assistant::set_access(app, chosen);
}
}
@@ -2876,7 +2881,65 @@ pub(crate) mod tests {
h.run_steps(4);
assert_eq!(level(&h), (AssistantAccess::Ask, AssistantAccess::Ask));
assert!(h.state().session.notices_since(mark).iter().any(|n| n.text.contains("full access ended")));
- assert!(!saved.lock().unwrap().iter().any(|(k, _)| k.contains("access")), "never saved");
+ assert!(saved.lock().unwrap().iter().all(|(k, v)| !k.contains("access") || v == "ask"), "full access is never saved");
+ }
+
+ /// Project folder is chosen like the others, remembered for the next launch, says why it asks
+ /// while the project has no file, and is what full access returns to when it ends.
+ #[test]
+ fn project_folder_access_is_remembered_and_says_when_it_asks() {
+ use egui_kittest::kittest::Queryable;
+ use rustgis_assistant::AssistantAccess;
+ use std::sync::{Arc, Mutex};
+ let mut h = chat(Vec::new(), "m");
+ let saved = Arc::new(Mutex::new(std::collections::HashMap::::new()));
+ let (read, write) = (saved.clone(), saved.clone());
+ let app = h.state_mut();
+ app.services.load_pref = Some(Box::new(move |k| read.lock().unwrap().get(k).cloned()));
+ app.services.save_pref = Some(Box::new(move |k, v| {
+ write.lock().unwrap().insert(k.to_string(), v.to_string());
+ }));
+ h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Access").click();
+ h.run_steps(4);
+ h.get_by_label("Project folder").click();
+ h.run_steps(4);
+ assert_eq!(assistant::access(h.state()), AssistantAccess::ProjectFolder);
+ assert_eq!(saved.lock().unwrap().get("assistant_access").map(String::as_str), Some("project"));
+ const UNSAVED: &str = "This project isn't saved, so it has no folder: the assistant asks, as at Ask.";
+ h.get_by_label(UNSAVED);
+ let dir = tempfile::tempdir().unwrap();
+ h.state_mut().session.run("project.saveAs", &serde_json::json!({"path": dir.path().join("atlas.rgis")})).unwrap();
+ h.run_steps(4);
+ assert!(h.query_by_label(UNSAVED).is_none());
+ // The next launch starts there.
+ h.state_mut().assistant.loaded = false;
+ h.state_mut().assistant.agent = None;
+ h.run_steps(4);
+ assert_eq!(h.state().assistant.agent.as_ref().unwrap().access(), AssistantAccess::ProjectFolder);
+ // Full access isn't remembered, and ending it with the extension goes back to the folder.
+ assistant::set_access(h.state_mut(), AssistantAccess::Full);
+ assert_eq!(saved.lock().unwrap().get("assistant_access").map(String::as_str), Some("project"));
+ h.state_mut().session.run("extension.disable", &serde_json::json!({"id": "assistant"})).unwrap();
+ h.run_steps(4);
+ assert_eq!(assistant::access(h.state()), AssistantAccess::ProjectFolder);
+ // A level a newer RustGIS saved asks, and is left as it was.
+ saved.lock().unwrap().insert("assistant_access".into(), "websites".into());
+ h.state_mut().session.run("extension.enable", &serde_json::json!({"id": "assistant"})).unwrap();
+ h.state_mut().assistant.loaded = false;
+ h.state_mut().assistant.agent = None;
+ h.state_mut().run("ui.pane.assistant", serde_json::Value::Null).unwrap();
+ h.run_steps(4);
+ assert_eq!(assistant::access(h.state()), AssistantAccess::Ask);
+ assert_eq!(saved.lock().unwrap().get("assistant_access").map(String::as_str), Some("websites"));
+ // Choosing Ask, the level already shown, is still a choice, and replaces it. The notice that
+ // full access ended can still be up on a slow machine, over the list: it goes first.
+ h.state_mut().map.toasts.clear();
+ h.run_steps(2);
+ h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Access").click();
+ h.run_steps(4);
+ h.get_all_by_label("Ask").last().unwrap().click();
+ h.run_steps(4);
+ assert_eq!(saved.lock().unwrap().get("assistant_access").map(String::as_str), Some("ask"));
}
/// #307: a reply wider than the pane pushed its edge off the window, so the map covered the
diff --git a/crates/ui-touch/src/assistant.rs b/crates/ui-touch/src/assistant.rs
index f34efa4976..c0aebbc30d 100644
--- a/crates/ui-touch/src/assistant.rs
+++ b/crates/ui-touch/src/assistant.rs
@@ -247,7 +247,7 @@ pub(crate) fn strip(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) {
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Show the Assistant")));
let (doing, ink) = match assistant::access(app) {
AssistantAccess::Full => (i18n::fmt("Full access · {step}", &[("step", &doing(app))]), t.red),
- AssistantAccess::Ask => (doing(app), t.text),
+ AssistantAccess::Ask | AssistantAccess::ProjectFolder => (doing(app), t.text),
};
let mut job = egui::text::LayoutJob::simple_singleline(doing, egui::FontId::proportional(14.0), ink);
job.wrap = egui::text::TextWrapping::truncate_at_width(rect.width().max(0.0));
@@ -366,8 +366,12 @@ fn full_access(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) {
});
}
-/// What the assistant runs without asking, as two chips over the message box.
+/// What the assistant runs without asking, as chips over the message box, with why the chosen
+/// level asks when it has to.
fn access_chips(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) {
+ if let Some(note) = assistant::access_note(app) {
+ ui.add(egui::Label::new(RichText::new(note).size(13.0).color(t.amber)).wrap());
+ }
let held = assistant::access(app);
let choices = assistant::access_choices();
ui.horizontal(|ui| {
@@ -378,7 +382,8 @@ fn access_chips(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) {
let text = RichText::new(name).size(13.0).color(if on { t.accent_text } else { t.text });
// Wrapped in its share of the row, so a long name never pushes the sheet wider.
let chip = egui::Button::new(text).fill(if on { t.checked } else { t.input }).wrap();
- if ui.add_sized(Vec2::new(width, TARGET), chip).clicked() && !on {
+ // A tap saves even the level shown: Ask stands in for a value this version doesn't know.
+ if ui.add_sized(Vec2::new(width, TARGET), chip).clicked() {
assistant::set_access(app, level);
}
}
@@ -1604,4 +1609,22 @@ mod tests {
assert_eq!(assistant::access(&held.app), AssistantAccess::Ask);
assert!(held.find(SAID).is_none());
}
+
+ /// The phone's third chip: Project folder, which says why it asks while the project has no file.
+ #[test]
+ fn project_folder_access_is_a_chip_that_says_when_it_asks() {
+ let mut held = Held::new();
+ provider(&mut held, "custom", "test");
+ raise(&held.ctx, Height::Full);
+ held.frame(Vec::new());
+ const UNSAVED: &str = "This project isn't saved, so it has no folder: the assistant asks, as at Ask.";
+ assert!(held.find(UNSAVED).is_none());
+ let chip = held.find("Project folder").expect("the chip");
+ let send = held.find("Send").expect("Send");
+ assert!(chip.max.x <= held.screen.x && send.max.x <= held.screen.x, "the chips fit: {chip:?}, {send:?}");
+ held.touch(&[chip.center()]);
+ held.frame(Vec::new());
+ assert_eq!(assistant::access(&held.app), AssistantAccess::ProjectFolder);
+ assert!(held.find(UNSAVED).is_some());
+ }
}
diff --git a/docs/user-guide/assistant.md b/docs/user-guide/assistant.md
index 55739cb7e8..31cc101f39 100644
--- a/docs/user-guide/assistant.md
+++ b/docs/user-guide/assistant.md
@@ -54,15 +54,31 @@ From the command line, `rustgis-cli ask` sends one request (see
| Level | Runs without asking | Still asks |
| --- | --- | --- |
| **Ask** | Project edits | Files, the internet, SQL, scripts, tasks, notebooks, models, plugins, app settings and replacing the project |
+| **Project folder** | Also Add Data (and listing a file's layers or columns) for files in the saved project's folder, and Export Map, Export Features and Export Table to new files there | Everything else Ask asks about: overwriting a file, files elsewhere, hidden or linked ones, every other file command, the internet, SQL, scripts and plugins |
| **Full access, for this session** | Also file operations with known, ordinary inputs and destinations, the internet, scripts, tasks, notebooks, models and installed plugins | Protected file paths, operations whose file inputs or destinations RustGIS cannot fully identify in advance, SQL queries, and changes to plugins, the GeoLibre tools, connections, sign-ins, saved credentials or app settings. The session log, S3 bucket listings that use a connection, and replacing the project also require approval. |
-Full access is never saved: RustGIS always starts at **Ask**, and turning the assistant off also
-returns to it. While it is on, a warning above the message box and **Assistant: full access** in
+**Project folder** needs a saved project: it works in the folder holding the `.rgis` file, and the
+assistant is told that folder's path. An unsaved project (or one opened from a package) has no
+folder, and one saved in your home folder or above it is too broad: the level then asks as **Ask**
+does, and says so under the choice. Use full paths inside that folder tree, without parent
+traversals, hidden names or links. An export needs an unused basename. Every file the operation
+might open, including a linked layer's source that an export reopens, must be identified and
+inside the tree. Protected app files and paths that cannot be identified need fresh approval.
+
+Add Data runs without approval for CSV, TSV, TXT, DAT, XLSX, GeoJSON, JSON, GPX, GeoPackage,
+FlatGeobuf and Parquet files within the folder. Formats with unresolved companion files or
+external references, such as Shapefile, GeoTIFF and KML, still ask. Saving a project directly in
+Documents makes the whole Documents tree available for these operations. Checks are made just
+before the command runs. They exclude hard-linked files on Unix, and cannot prevent concurrent
+changes to files or links after the check. Ask is the default, and RustGIS remembers Project
+folder if you choose it. The browser has no project folder to offer.
+
+Full access is never saved: a launch returns to the remembered level, and turning the assistant off ends it. While it is on, a warning above the message box and **Assistant: full access** in
the status bar say so; **Back to Ask**, or a click on the status bar, ends it, from the
assistant's next action on. On a phone, a warning and **Back to Ask** also appear above the bar
when the assistant is idle and its sheet is closed. Subagents work at the same level.
-Both levels ask before changing the default raster style (`raster.setDefaultStyle`), which is an
+All levels ask before changing the default raster style (`raster.setDefaultStyle`), which is an
app setting. When an operation still asks at Full access, it needs fresh approval even if you
previously approved it in Ask. Import QGIS and GeoLibre projects yourself because the files and
web addresses they name cannot be reviewed before opening them.
@@ -90,7 +106,7 @@ dictation), then **Send**. The sheet stands half up, to see the map with the con
for reading and typing: the arrow beside its **×** switches, and a swipe up or down on its heading
moves it a step. Lowered while the assistant works, a strip over the bar says what it is doing and
has **Stop**; tap its words to raise the sheet again. Approvals are a card with **Allow** and
-**Decline**. The two [Access](#access) buttons are above the message box. With Full access, the
+**Decline**. The [Access](#access) buttons are above the message box. With Full access, the
sheet shows a warning and **Back to Ask**. The gear in the heading opens settings. Set up ChatGPT
sign-in in the desktop interface.