Open Recent lists an automation open where the file is on disk (#16098)

app.open is requested by a path relative to the automation read root. It went
into Open Recent as is, where it names nothing: Home drew a blank card and
clicking it failed. The workspace now reports the file's location below the
root that holds it, and app.open (also the directory .pcraft path) lists that.
The document's save-back path stays root-relative; without a location the open
is not listed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
David Mann
2026-11-21 12:50:56 +01:00
co-authored by Claude Opus 5.5
parent 42c853396d
commit 779b20eeb0
8 changed files with 108 additions and 12 deletions
+5 -1
View File
@@ -429,6 +429,9 @@ pub fn automation(workspace: Option<photocraft_automation::AuthorizedWorkspace>)
Ok(opened.map(|doc| (name, doc)))
}) as photocraft_ui_egui::AutomationOpenPcraftFn
});
let locate = workspace.clone().map(|workspace| {
Box::new(move |path: &str| workspace.location(path).map(|location| location.to_string_lossy().into_owned())) as photocraft_ui_egui::AutomationLocateFn
});
let save = workspace.clone().map(|workspace| {
std::sync::Arc::new(move |doc: &Document, path: &str, settings: &photocraft_ui_egui::ExportSettings, ctl: &photocraft_ui_egui::jobs_ui::SaveCtl| {
save_through(doc, path, settings, ctl, |p, encoded, _| workspace.write_stream(p, &mut |w| encoded.write_to(w)).map_err(|e| e.to_string()))
@@ -441,7 +444,7 @@ pub fn automation(workspace: Option<photocraft_automation::AuthorizedWorkspace>)
photocraft_automation::workspace::authorize_desktop_engine_command(id, params).map_err(|error| error.to_string())
}) as photocraft_ui_egui::AutomationCommandFn
});
photocraft_ui_egui::AutomationServices { read, write, open_pcraft, save, command, authorize }
photocraft_ui_egui::AutomationServices { read, write, open_pcraft, locate, save, command, authorize }
}
/// What agent requests may read, write and run with the agent settings' folders
@@ -486,6 +489,7 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>, wa
automation_read: automation.read,
automation_write: automation.write,
automation_open_pcraft: automation.open_pcraft,
automation_locate: automation.locate,
automation_save: automation.save,
automation_command: automation.command,
automation_authorize: automation.authorize,
+12
View File
@@ -103,6 +103,18 @@ impl AuthorizedWorkspace {
Ok((bytes, save_path))
}
/// Where the file or `.pcraft` folder that `path` names is on disk: below the first read
/// root that holds it (the root `read` and `open_pcraft` pick), as that root was configured
/// at launch. Open Recent lists this, since the person reopens the file outside automation,
/// where a root-relative request path names nothing. It grants no access.
pub fn location(&self, path: &str) -> Option<PathBuf> {
self.read.iter().find_map(|root| {
let relative = scoped_path(path, root).ok()??;
root.dir.metadata(&relative).ok()?;
Some(root.configured_path.join(relative))
})
}
fn open_read(&self, path: &str) -> Result<(cap_std::fs::File, &RootCapability), AutomationError> {
if self.read.is_empty() {
return Err(AutomationError::BadRequest(format!("{DENIED}: read authority is absent")));
+19
View File
@@ -64,6 +64,25 @@ fn read_growth_is_rejected_at_the_observed_length() {
assert!(read_to_observed_length(&mut empty, 0).is_err());
}
#[test]
fn location_names_the_file_below_the_root_that_holds_it() {
let (library, work, _) = roots("location");
std::fs::create_dir_all(work.join("shots")).unwrap();
std::fs::write(work.join("shots/a.png"), b"a").unwrap();
std::fs::write(library.join("same.png"), b"first").unwrap();
std::fs::write(work.join("same.png"), b"second").unwrap();
let workspace = AuthorizedWorkspace::with_read_roots([library.as_path(), work.as_path()], Some(&work)).unwrap();
// A root-relative request names the file below the root that holds it, as an absolute path.
assert_eq!(workspace.location("shots/a.png"), Some(work.join("shots").join("a.png")));
// The first root that holds the name wins, as for `read`.
assert_eq!(workspace.location("same.png"), Some(library.join("same.png")));
// An absolute request below a root keeps naming that file.
assert_eq!(workspace.location(&work.join("same.png").to_string_lossy()), Some(work.join("same.png")));
assert_eq!(workspace.location("missing.png"), None);
assert_eq!(workspace.location("../outside.png"), None, "a path escaping the roots has no location");
assert_eq!(AuthorizedWorkspace::default().location("shots/a.png"), None, "no read root, no location");
}
#[test]
fn open_pcraft_loads_a_directory_below_the_read_root() {
let (inside, _, workspace) = roots("pcraft-dir");
+12 -2
View File
@@ -1362,7 +1362,8 @@ fn app_open(app: &mut PhotocraftApp, path: &str, approved: bool) -> Reply {
let warnings = app.open_automation_bytes_with_approval(&name, &bytes, approved)?;
// Brushes/gradients go to the preset libraries: no document, no Open Recent entry.
if !crate::preset_files_ui::is_preset_file(&name) {
app.opened_from(path);
let recent = automation_location(app, path);
app.opened_from_listed(path, recent.as_deref());
if let Some(state) = app.session.active_mut()
&& state.path.is_some()
{
@@ -1373,6 +1374,13 @@ fn app_open(app: &mut PhotocraftApp, path: &str, approved: bool) -> Reply {
}))
}
/// Where the file an automation open read is on disk, for Open Recent. The request path is
/// relative to an automation root, so it names nothing when the person reopens it from Open
/// Recent or Home; without a location the open is not listed there.
fn automation_location(app: &PhotocraftApp, path: &str) -> Option<String> {
app.services.automation_locate.as_ref().and_then(|locate| locate(path))
}
/// Directory .pcraft (the native on-disk form) loads through a capability-scoped
/// source; the single-file (zip) form falls back to the bytes path, as do all
/// other formats. `None` means "not a directory .pcraft".
@@ -1386,7 +1394,9 @@ fn open_pcraft_directory(app: &mut PhotocraftApp, path: &str) -> Option<Reply> {
app.session.add_document(doc, None);
// Recent files, but no save-back target: the capability writer
// replaces files, never directories.
app.push_recent(path);
if let Some(recent) = automation_location(app, path) {
app.push_recent(&recent);
}
app.sync_views();
app.ui.status = crate::i18n::fmt(tl!("Opened {name}"), &[("name", &name)]);
app.ui.status_error = false;
+35 -3
View File
@@ -1198,6 +1198,34 @@ fn automation_save_passes_dds_options_without_asking() {
assert_eq!(asked.borrow().len(), 2, "a bad ddsCompression writes nothing");
}
#[test]
fn an_automation_open_without_a_location_is_not_listed_in_open_recent() {
use photocraft_color::{ColorMode, SampleType};
use photocraft_doc::Document;
use photocraft_geom::Size;
let services = crate::Services {
import: Some(Box::new(|name: &str, _b: &[u8], _opts: &photocraft_io::ImportOptions| {
Ok((Document::new(name, Size::new(4, 4), ColorMode::Rgb, SampleType::U8), Vec::new()))
})),
automation_read: Some(Box::new(|path: &str| {
Ok(crate::AutomationReadResult {
name: path.rsplit('/').next().unwrap_or(path).to_string(),
bytes: b"x".to_vec(),
save_path: Some(path.to_string()),
})
})),
..Default::default()
};
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services);
let ctx = app.ctx().clone();
let r = call(&mut app, &ctx, "app.open", json!({"path": "shots/gk_25.png"}));
assert_eq!(r["ok"], true, "{r}");
assert_eq!(app.session.active().unwrap().path.as_deref(), Some("shots/gk_25.png"), "the save-back target stays the root-relative path");
// A root-relative path names no file for Open Recent or Home, so nothing is listed.
assert!(app.ui.recent_files.is_empty(), "{:?}", app.ui.recent_files);
}
#[test]
fn automation_open_and_save_use_the_roots_and_reply_with_warnings() {
use photocraft_color::{ColorMode, SampleType};
@@ -1234,6 +1262,7 @@ fn automation_open_and_save_use_the_roots_and_reply_with_warnings() {
save_path: Some(path.to_string()),
})
})),
automation_locate: Some(Box::new(|path: &str| Some(format!("/work/{path}")))),
automation_write: Some(Box::new(move |path: &str, _b: &[u8]| {
w.borrow_mut().push(path.to_string());
Ok(())
@@ -1245,7 +1274,8 @@ fn automation_open_and_save_use_the_roots_and_reply_with_warnings() {
assert_eq!(r["result"]["warnings"], json!(["Adjustment layer flattened"]), "{r}");
assert_eq!(r["result"]["name"], "warn.psd");
assert_eq!(app.session.active().unwrap().path.as_deref(), Some("in/warn.psd"));
assert_eq!(app.ui.recent_files, vec!["in/warn.psd".to_string()]);
// Open Recent lists where the file is, not the root-relative request path, which names nothing outside automation.
assert_eq!(app.ui.recent_files, vec!["/work/in/warn.psd".to_string()]);
let r = call(&mut app, &ctx, "app.save", json!({"path": "out.png"}));
assert_eq!(r["result"], json!({"path": "out.png", "warnings": ["Layers were flattened"]}), "{r}");
assert_eq!(*written.borrow(), vec!["out.png".to_string()]);
@@ -1457,6 +1487,7 @@ fn app_open_opens_a_directory_pcraft_and_falls_back_for_the_zip_form() {
Err(format!("no such path: {path}"))
}
})),
automation_locate: Some(Box::new(|path: &str| Some(format!("/work/{path}")))),
..Default::default()
};
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services);
@@ -1465,7 +1496,7 @@ fn app_open_opens_a_directory_pcraft_and_falls_back_for_the_zip_form() {
let r = call(&mut app, &ctx, "app.open", json!({"path": "native.pcraft"}));
assert_eq!(r["result"], json!({"path": "native.pcraft", "name": "native.pcraft", "warnings": []}), "{r}");
assert_eq!(app.session.active().unwrap().doc.name, "Native");
assert_eq!(app.ui.recent_files, vec!["native.pcraft".to_string()], "the open is recorded in recent files");
assert_eq!(app.ui.recent_files, vec!["/work/native.pcraft".to_string()], "the open is recorded in recent files, where it is on disk");
assert_eq!(app.session.active().unwrap().path, None, "no save-back target: the automation writer replaces files, never directories");
let r = call(&mut app, &ctx, "app.save", json!({}));
assert!(r["error"].as_str().unwrap().contains("pass `path`"), "an in-place save is refused up front: {r}");
@@ -2120,6 +2151,7 @@ fn automation_library_open_requires_explicit_save_as_before_implicit_save() {
save_path: path.starts_with("work/").then(|| path.to_owned()),
})
})),
automation_locate: Some(Box::new(|path: &str| Some(format!("/roots/{path}")))),
automation_write: Some(Box::new(move |path: &str, _: &[u8]| {
if path == "failed.psd" {
return Err("test write failure".into());
@@ -2135,7 +2167,7 @@ fn automation_library_open_requires_explicit_save_as_before_implicit_save() {
let opened = call(&mut app, &ctx, "app.open", json!({"path": "library/same.psd"}));
assert_eq!(opened["ok"], true, "{opened}");
assert_eq!(app.session.active().unwrap().path, None);
assert_eq!(app.ui.recent_files, vec!["library/same.psd"]);
assert_eq!(app.ui.recent_files, vec!["/roots/library/same.psd"]);
app.run("layer.new.layer", json!({"name": "edit"})).unwrap();
assert!(app.session.active().unwrap().is_dirty());
let refused = call(&mut app, &ctx, "app.save", json!({}));
+10 -1
View File
@@ -230,6 +230,13 @@ impl PhotocraftApp {
/// Record that the active document was just opened from `path`: File › Save writes back to it
/// (unless it's a template or derivative preview) and it goes to the top of Open Recent.
pub(crate) fn opened_from(&mut self, path: &str) {
self.opened_from_listed(path, Some(path));
}
/// [`Self::opened_from`], with `recent` the path Open Recent lists for it (`None`: not listed).
/// An automation open is requested by a root-relative path, which names nothing outside
/// automation, so it lists where the file is on disk instead.
pub(crate) fn opened_from_listed(&mut self, path: &str, recent: Option<&str>) {
if !is_template(path)
&& let Some(st) = self.session.active_mut()
&& !st.source_read_only
@@ -238,7 +245,9 @@ impl PhotocraftApp {
let doc = st.doc.id;
self.remember_stamp(doc, path);
}
self.push_recent(path);
if let Some(recent) = recent {
self.push_recent(recent);
}
}
/// The name a file called `name` opens under: its own, or the first free "Untitled-N" for a
+5 -5
View File
@@ -236,11 +236,11 @@ pub(crate) use services::SAVE_OPTIONS_OPEN;
#[cfg(test)]
pub(crate) use services::saved_revision_after_write;
pub use services::{
AdoptAutosaveFn, AppendTextFn, AutomationAuthorizeFn, AutomationCommandFn, AutomationOpenPcraftFn, AutomationReadFn, AutomationServices, AutomationWriteFn,
AutosaveFn, AutosaveResultsFn, CapsLockFn, ClipboardGetFn, ClipboardGetSvgFn, ClipboardSetFn, ClipboardUnreadableFn, CursorPosFn, DiscardAutosaveFn,
ExportFn, ExportSettings, ExternalSvgEditor, ExternalSvgSession, ExternalVectorSave, ExternalVectorSource, FileStamp, FileStampFn, FormatChoices, ImportFn,
Inbox, LoadTextFn, OpenExternalSvgFn, OpenUrlFn, OsEventsFn, PenEndFn, PhotoshopShortcutsFn, PlaceInbox, RecoverFn, Recoverable, RightButtonDownFn,
SameFileFn, SaveFileFn, SaveTextFn, Services, SystemThemeFn, TabletPollFn, WindowFrameFn, WriteFn,
AdoptAutosaveFn, AppendTextFn, AutomationAuthorizeFn, AutomationCommandFn, AutomationLocateFn, AutomationOpenPcraftFn, AutomationReadFn,
AutomationServices, AutomationWriteFn, AutosaveFn, AutosaveResultsFn, CapsLockFn, ClipboardGetFn, ClipboardGetSvgFn, ClipboardSetFn, ClipboardUnreadableFn,
CursorPosFn, DiscardAutosaveFn, ExportFn, ExportSettings, ExternalSvgEditor, ExternalSvgSession, ExternalVectorSave, ExternalVectorSource, FileStamp,
FileStampFn, FormatChoices, ImportFn, Inbox, LoadTextFn, OpenExternalSvgFn, OpenUrlFn, OsEventsFn, PenEndFn, PhotoshopShortcutsFn, PlaceInbox, RecoverFn,
Recoverable, RightButtonDownFn, SameFileFn, SaveFileFn, SaveTextFn, Services, SystemThemeFn, TabletPollFn, WindowFrameFn, WriteFn,
};
pub(crate) use services::{opaque_layer, saves_flat_in_place};
pub use text::cjk_fonts;
+10
View File
@@ -338,6 +338,11 @@ pub type AutomationWriteFn = Box<dyn FnMut(&str, &[u8]) -> Result<(), String>>;
/// caller falls back to the bytes path for the zip form.
pub type AutomationOpenPcraftFn = Box<dyn FnMut(&str) -> Result<Option<(String, Document)>, String>>;
/// Where a path an automation read opened is on disk (absolute), for Open Recent: the person
/// reopens it outside automation, where a root-relative request path names nothing. `None`
/// when no read root holds it.
pub type AutomationLocateFn = Box<dyn Fn(&str) -> Option<String>>;
/// Reject engine commands which still perform ambient filesystem I/O.
pub type AutomationCommandFn = Box<dyn Fn(&str, &Value) -> Result<(), String>>;
/// Same policy as [`AutomationCommandFn`] for each step a command runs (`actions.play`).
@@ -351,6 +356,7 @@ pub struct AutomationServices {
pub read: Option<AutomationReadFn>,
pub write: Option<AutomationWriteFn>,
pub open_pcraft: Option<AutomationOpenPcraftFn>,
pub locate: Option<AutomationLocateFn>,
pub save: Option<SaveFileFn>,
pub command: Option<AutomationCommandFn>,
pub authorize: Option<AutomationAuthorizeFn>,
@@ -546,6 +552,9 @@ pub struct Services {
pub automation_read: Option<AutomationReadFn>,
pub automation_write: Option<AutomationWriteFn>,
pub automation_open_pcraft: Option<AutomationOpenPcraftFn>,
/// Where an automation open's file is on disk, for Open Recent. Without it an automation
/// open is not listed there.
pub automation_locate: Option<AutomationLocateFn>,
pub automation_command: Option<AutomationCommandFn>,
/// Same policy as [`Self::automation_command`], as a function pointer the engine calls for
/// each step of `actions.play`. Installed on the session only while a control request or
@@ -657,6 +666,7 @@ impl Services {
self.automation_read = a.read;
self.automation_write = a.write;
self.automation_open_pcraft = a.open_pcraft;
self.automation_locate = a.locate;
self.automation_save = a.save;
self.automation_command = a.command;
self.automation_authorize = a.authorize;