Merge pull request #6888 from dotCooCoo/fix/read-roots-scripts-recovery

MCP: plug-in, recovery and script report replies leave out paths outside the read roots
This commit is contained in:
BFlat
2026-11-12 22:01:56 +07:00
committed by GitHub
11 changed files with 418 additions and 26 deletions
+84 -10
View File
@@ -62,13 +62,28 @@ fn err(e: vectorcraft_plugins::Error) -> EngineError {
}
}
/// Under automation read roots, a reply names a file or folder outside them by its name alone.
fn shown_file(path: &str) -> String {
super::fileio::shown_path(path).into_owned()
}
/// A plug-in turned off for the next launch, or the one a launch stopped at, as a reply shows it: a
/// file outside the automation read roots is named by its file name.
fn shown_item(item: &safe_mode::Item) -> Value {
let mut v = item.to_json();
if let Some(file) = item.file.as_deref() {
v["file"] = json!(shown_file(file));
}
v
}
/// JSON description of an installed plug-in.
pub fn describe(p: &Plugin) -> Value {
let m = p.manifest();
let mut v = json!({
"id": m.id, "name": m.name, "version": m.version, "kind": m.kind.name(), "author": m.author, "description": m.description,
"params": m.params_doc(), "paramsSchema": serde_json::to_value(m).ok().and_then(|v| v.get("params").cloned()),
"size": p.size(), "source": p.source(),
"size": p.size(), "source": p.source().map(shown_file),
"permissions": permissions::names(&m.permissions()), "hash": p.hash(), "api": m.api,
});
match m.kind {
@@ -932,9 +947,46 @@ fn describe_installed(p: &Plugin) -> Value {
v
}
/// The folder load `report` as a reply shows it: under automation read roots, a folder outside them
/// is `null` and a failed file outside them is named by its file name, in the errors too.
fn shown_report(mut report: Value) -> Value {
let mut hidden: Vec<(String, String)> = vec![];
if let Some(failed) = report.get_mut("failed").and_then(Value::as_array_mut) {
for row in failed {
let Some(file) = row.get("file").and_then(Value::as_str).map(str::to_string) else { continue };
let shown = shown_file(&file);
if shown != file {
row["file"] = json!(shown);
hidden.push((file, shown));
}
}
}
if let Some(folder) = report.get("folder").and_then(Value::as_str).map(str::to_string) {
let shown = shown_file(&folder);
if shown != folder {
report["folder"] = Value::Null;
hidden.push((folder, shown));
}
}
// A failed file's path holds its folder's: the longer paths are put back first.
hidden.sort_by_key(|(path, _)| std::cmp::Reverse(path.len()));
let unnamed = |text: &str| hidden.iter().fold(text.to_string(), |t, (path, name)| t.replace(path.as_str(), name));
if let Some(e) = report.get("error").and_then(Value::as_str).map(unnamed) {
report["error"] = json!(e);
}
if let Some(failed) = report.get_mut("failed").and_then(Value::as_array_mut) {
for row in failed {
if let Some(e) = row.get("error").and_then(Value::as_str).map(unnamed) {
row["error"] = json!(e);
}
}
}
report
}
fn list(_: &mut Session, _: &Value) -> Result<Value> {
let folder = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(_, _, r)| r.clone());
let disabled: Vec<Value> = safe_mode::disabled().iter().map(safe_mode::Item::to_json).collect();
let folder = FOLDER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(_, _, r)| shown_report(r.clone()));
let disabled: Vec<Value> = safe_mode::disabled().iter().map(shown_item).collect();
Ok(
json!({"plugins": registry::list().iter().map(|p| describe_installed(p)).collect::<Vec<_>>(), "folder": folder, "safeMode": safe_mode::active(), "disabled": disabled}),
)
@@ -946,11 +998,33 @@ fn safe_mode_state(_: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({
"active": safe_mode::active(),
"source": safe_mode::source().map(safe_mode::Source::name),
"disabled": safe_mode::disabled().iter().map(safe_mode::Item::to_json).collect::<Vec<_>>(),
"pendingItem": safe_mode::previous().map(|i| i.to_json()),
"disabled": safe_mode::disabled().iter().map(shown_item).collect::<Vec<_>>(),
"pendingItem": safe_mode::previous().map(|i| shown_item(&i)),
}))
}
/// The file of a plug-in `plugin.safeMode` lists as `file`, or `plugin.list` as `source`: one they name
/// by its file name (outside the automation read roots) is found by that name, when no other listed
/// file has it.
fn listed_file(file: String) -> String {
let mut listed: Vec<String> = safe_mode::disabled()
.into_iter()
.chain(safe_mode::previous())
.filter_map(|i| i.file)
.chain(registry::list().iter().filter_map(|p| p.source().map(str::to_string)))
.collect();
listed.sort();
listed.dedup();
if listed.contains(&file) {
return file;
}
let mut named = listed.into_iter().filter(|f| shown_file(f) == file);
match (named.next(), named.next()) {
(Some(f), None) => f,
_ => file,
}
}
/// `plugin.setEnabled`: turns a plug-in on or off for the next launch, by `id` or by `file` (a
/// plug-in that stopped a launch while loading may be known by its file alone). It neither loads
/// nor unloads anything now, and uninstalls nothing.
@@ -972,7 +1046,7 @@ fn set_enabled(s: &mut Session, p: &Value) -> Result<Value> {
let stored = if enabled { s.stored_plugin_file(&id).map(safe_mode::Item::file) } else { None };
(registry::get(&id).map(|p| safe_mode::Item::of(&p)).unwrap_or(safe_mode::Item { id: Some(id), ..Default::default() }), stored)
}
(None, Some(file)) => (safe_mode::Item::file(file), None),
(None, Some(file)) => (safe_mode::Item::file(listed_file(file)), None),
(None, None) => return Err(bad(C, "give `id` or `file` (see plugin.safeMode)")),
};
let items: Vec<&safe_mode::Item> = std::iter::once(&item).chain(stored.as_ref()).collect();
@@ -986,7 +1060,7 @@ fn set_enabled(s: &mut Session, p: &Value) -> Result<Value> {
// Without a plug-in folder (a session confined to automation roots), or when the list there
// can't take the change, the change stays in this process and goes with the next change that saves.
let saved = !changed || s.store_disabled_plugins();
Ok(json!({"changed": changed, "saved": saved, "disabled": safe_mode::disabled().iter().map(safe_mode::Item::to_json).collect::<Vec<_>>()}))
Ok(json!({"changed": changed, "saved": saved, "disabled": safe_mode::disabled().iter().map(shown_item).collect::<Vec<_>>()}))
}
fn info(_: &mut Session, p: &Value) -> Result<Value> {
@@ -1055,7 +1129,7 @@ pub fn specs() -> Vec<CommandSpec> {
"List Plug-ins",
[],
None,
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}]} | null, safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}]} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
always,
list
),
@@ -1127,7 +1201,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Safe Mode",
[],
None,
"{} → {active: bool (no plug-in loads or runs: plugin.install, .run, .reload and exporters fail, live effects draw their object's geometry unchanged and the objects keep their effects), source: \"flag\" (started with --safe-mode) | \"startup\" (the user chose Safe Mode, or hasn't chosen yet, after a launch that stopped while a plug-in was loading) | null, disabled: [{id, file, name, label}] (turned off for the next launch; id is null for one known only by its file), pendingItem: {id, file, name, label} | null (the plug-in the last launch was loading when it stopped, until the user chooses; it may not be what stopped it)}. Safe Mode is chosen at launch, never by a command",
"{} → {active: bool (no plug-in loads or runs: plugin.install, .run, .reload and exporters fail, live effects draw their object's geometry unchanged and the objects keep their effects), source: \"flag\" (started with --safe-mode) | \"startup\" (the user chose Safe Mode, or hasn't chosen yet, after a launch that stopped while a plug-in was loading) | null, disabled: [{id, file, name, label}] (turned off for the next launch; id is null for one known only by its file; under automation read roots, a file outside them is named by its file name here and in pendingItem, and plugin.setEnabled takes that name), pendingItem: {id, file, name, label} | null (the plug-in the last launch was loading when it stopped, until the user chooses; it may not be what stopped it)}. Safe Mode is chosen at launch, never by a command",
always,
safe_mode_state
),
@@ -1136,7 +1210,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Enable on Re-launch",
[],
None,
"{id | file: a plug-in as plugin.safeMode's disabled lists it, enabled: bool} turn a plug-in on or off for the next launch (Help › Safe Mode's Enable on Re-launch); nothing loads, unloads or is uninstalled now. Turning on by id also turns on the file the plug-in is stored in. Turning on one that isn't disabled is an error. plugin.install of a disabled plug-in turns it on → {changed, saved: false when the change isn't in the plug-in folder for the next launch (a session without one, or the list there can't be read or written or is full; it is saved with the next change that saves), disabled}",
"{id | file: a plug-in as plugin.safeMode's disabled lists it or as plugin.list's source (under automation read roots, a file outside them by the file name shown, when no other listed file has it), enabled: bool} turn a plug-in on or off for the next launch (Help › Safe Mode's Enable on Re-launch); nothing loads, unloads or is uninstalled now. Turning on by id also turns on the file the plug-in is stored in. Turning on one that isn't disabled is an error. plugin.install of a disabled plug-in turns it on → {changed, saved: false when the change isn't in the plug-in folder for the next launch (a session without one, or the list there can't be read or written or is full; it is saved with the next change that saves), disabled}",
always,
set_enabled
),
+32 -7
View File
@@ -97,6 +97,10 @@ pub trait RecoveryStore: Send + Sync {
fn remove(&self, name: &str) -> std::result::Result<(), String>;
/// Where the entries are, as the user knows it (a folder, "browser storage").
fn location(&self) -> String;
/// Is [`RecoveryStore::location`] a folder on this computer (default: no)?
fn in_folder(&self) -> bool {
false
}
/// The areas in the store (default: those with entries).
fn areas(&self) -> std::result::Result<Vec<String>, String> {
let names = self.list()?;
@@ -477,6 +481,9 @@ impl RecoveryStore for FolderStore {
fn location(&self) -> String {
self.0.to_string_lossy().into_owned()
}
fn in_folder(&self) -> bool {
true
}
fn areas(&self) -> std::result::Result<Vec<String>, String> {
Self::names(&self.0, true)
}
@@ -938,6 +945,21 @@ fn sweep(store: &dyn RecoveryStore, area: &str) {
}
}
/// The document's file `path` as a reply names it: under automation read roots, only inside them.
fn shown_path(path: Option<String>) -> Option<String> {
path.filter(|p| crate::file_access::check_read(p).is_ok())
}
/// Where `store` keeps its copies, as a reply names it: a recovery folder outside the automation
/// read roots is `null`.
fn shown_location(store: &dyn RecoveryStore) -> Value {
let location = store.location();
if store.in_folder() && crate::file_access::check_read(&location).is_err() {
return Value::Null;
}
json!(location)
}
fn read_meta(store: &dyn RecoveryStore, file: &str) -> Meta {
store.read(&format!("{file}{META_EXT}")).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default()
}
@@ -1235,7 +1257,7 @@ fn save(s: &mut Session, _: &Value) -> Result<Value> {
}
forget_clean(s);
heartbeat(s);
Ok(json!({ "saved": saved, "skipped": skipped, "location": store.location() }))
Ok(json!({ "saved": saved, "skipped": skipped, "location": shown_location(store.as_ref()) }))
}
/// Who an area of the store belongs to.
@@ -1361,7 +1383,7 @@ fn list(s: &mut Session, _: &Value) -> Result<Value> {
let meta = read_meta(store.as_ref(), f);
let title = if meta.title.is_empty() { f.rsplit('/').next().unwrap_or(f).to_string() } else { meta.title };
rows.push(json!({
"file": f, "title": title, "path": meta.path, "format": meta.format, "saved": meta.saved,
"file": f, "title": title, "path": shown_path(meta.path), "format": meta.format, "saved": meta.saved,
"open": (who == Owner::Mine && open.contains(f)) || left.contains(f), "running": who == Owner::Running,
}));
}
@@ -1370,7 +1392,7 @@ fn list(s: &mut Session, _: &Value) -> Result<Value> {
tidy(store.as_ref(), &area, hold);
}
}
Ok(json!({ "copies": rows, "location": store.location() }))
Ok(json!({ "copies": rows, "location": shown_location(store.as_ref()) }))
}
/// A gone app's area to act on: its name, the copies to act on, and its lock.
@@ -1483,7 +1505,10 @@ fn restore_one(s: &mut Session, store: &Arc<dyn RecoveryStore>, file: &str) -> R
// The copy stays until the document is saved or closed.
st.recovery = Some(RecoveryCopy { file: mine.clone(), doc: st.doc.clone() });
let title = st.title();
Ok(super::fileio::merge(json!({ "index": index, "title": title, "file": mine, "path": meta.path, "warnings": warnings }), links.to_json()))
Ok(super::fileio::merge(
json!({ "index": index, "title": title, "file": mine, "path": shown_path(meta.path), "warnings": warnings }),
links.to_json(),
))
}
fn restore(s: &mut Session, p: &Value) -> Result<Value> {
@@ -1527,7 +1552,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Save Recovery Data",
[],
None,
"{} write a recovery copy of every modified document changed since its last copy, in this app's own area of the store (the app does this every autosaveInterval minutes while autosaveRecovery is on; documents of more than 20000 objects are skipped while recoveryOffForComplex is on). Images are stored apart, each once while unchanged. A copy goes when its document is saved, reverted or closed → {saved: [{file, title, bytes, imageBytes (images written this time)}], skipped: [{title, reason}], location} (location: the recovery folder, or browser storage on the web)",
"{} write a recovery copy of every modified document changed since its last copy, in this app's own area of the store (the app does this every autosaveInterval minutes while autosaveRecovery is on; documents of more than 20000 objects are skipped while recoveryOffForComplex is on). Images are stored apart, each once while unchanged. A copy goes when its document is saved, reverted or closed → {saved: [{file, title, bytes, imageBytes (images written this time)}], skipped: [{title, reason}], location} (location: the recovery folder, or browser storage on the web; null under automation read roots when the folder is outside them)",
has_store,
save
),
@@ -1536,7 +1561,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Recovery Data",
[],
None,
"{} the recovery copies in the store → {copies: [{file (\"<area>/<name>\"), title, path (the document's file, if it had one), format, saved (Unix seconds or null), open (the copy of a document open here), running (kept by another VectorCraft that is running)}], location}; copies neither open nor running were left behind by a crash",
"{} the recovery copies in the store → {copies: [{file (\"<area>/<name>\"), title, path (the document's file, if it had one), format, saved (Unix seconds or null), open (the copy of a document open here), running (kept by another VectorCraft that is running)}], location}; copies neither open nor running were left behind by a crash; under automation read roots, path is null when the document's file is outside them, and location when the recovery folder is",
has_store,
list
),
@@ -1545,7 +1570,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Restore Recovered Documents",
[],
None,
"{file?} open a copy left behind by a crash (default: every one; a running VectorCraft's copies are never taken) as a new document titled \"<name> [Recovered]\": modified, and Save asks where to save it (suggesting its original file) → {restored: [{index, title, file, path, warnings, missingLinks, modifiedLinks, updatedLinks}], failed: [{file, error}] (damaged copies, when restoring every one; a named one fails the command)}. The copy moves to this app's area and stays until the document is saved or closed",
"{file?} open a copy left behind by a crash (default: every one; a running VectorCraft's copies are never taken) as a new document titled \"<name> [Recovered]\": modified, and Save asks where to save it (suggesting its original file) → {restored: [{index, title, file, path, warnings, missingLinks, modifiedLinks, updatedLinks}], failed: [{file, error}] (damaged copies, when restoring every one; a named one fails the command)}; under automation read roots, path is null when the original file is outside them. The copy moves to this app's area and stays until the document is saved or closed",
has_store,
restore
),
+44
View File
@@ -233,6 +233,43 @@ impl Session {
self.scripts_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32"))
}
/// The last run's report ([`Session::script_report`]) as a reply shows it: under automation read
/// roots, a file the run wrote outside them (`written`) and the file a failed run stopped in
/// (`file`, also in the run's error line in `console`) are named by their file name. What the
/// script wrote itself (`log`, its output lines) stays as written.
pub fn shown_script_report(&self) -> Option<Value> {
let mut report = self.script_report()?.clone();
if let Some(written) = report.get_mut("written").and_then(Value::as_array_mut) {
for path in written.iter_mut() {
if let Some(name) = path.as_str().and_then(hidden_name) {
*path = json!(name);
}
}
}
if let Some(file) = report.get("file").and_then(Value::as_str).map(str::to_string)
&& let Some(name) = hidden_name(&file)
{
// The run's error lines come after every line the script wrote. They are written again
// from the report with the file's name, which also covers a line the console cut inside
// the path. A console that dropped its oldest lines may hold only the last of them.
let before = script::error_lines(&report);
report["file"] = json!(name);
if let Some(message) = report.get("message").and_then(Value::as_str) {
report["message"] = json!(message.replace(&file, &name));
}
let after = script::error_lines(&report);
if let Some(lines) = report.pointer_mut("/console/lines").and_then(Value::as_array_mut) {
let kept = (1..=before.len().min(lines.len()))
.rev()
.find(|&n| lines.iter().rev().take(n).map(Value::as_str).eq(before.iter().rev().take(n).map(|l| Some(l.as_str()))))
.unwrap_or(0);
lines.truncate(lines.len() - kept);
lines.extend(after.iter().skip(after.len().saturating_sub(kept)).map(|l| json!(l)));
}
}
Some(report)
}
/// The text of the script at `path`, which a listing of the Scripts folder gave
/// ([`script::folder::read`]), checked as `script.run` checks a file's.
pub fn installed_script(&self, path: &str) -> Result<String> {
@@ -248,6 +285,13 @@ impl Session {
}
}
/// The file name a reply names `path` by when the file is outside the automation read roots; `None`
/// when a reply may name it whole.
fn hidden_name(path: &str) -> Option<String> {
let shown = super::fileio::shown_path(path);
(shown != path).then(|| shown.into_owned())
}
fn list_installed(s: &mut Session, _: &Value) -> Result<Value> {
let Some(root) = s.scripts_dir() else {
return Ok(json!({"folder": null, "scripts": [], "truncated": false, "unreadable": false}));