Skip to main content

brep_render/engine_state/
plugins.rs

1//! Trusted package installations and document-scoped, asynchronous transactions.
2use super::EngineState;
3use crate::history::History;
4use brep_plugins::{PackageBundle, PluginPin, Runtime};
5use serde_json::{json, Value};
6use std::collections::VecDeque;
7
8#[derive(Default)]
9pub(super) struct Plugins {
10    packages: Vec<(PackageBundle, bool)>,
11    runtime: Option<Runtime>,
12    revision: u64,
13    next_action: u64,
14    pending: Option<PendingAction>,
15    results: VecDeque<Result<Value, String>>,
16    status: Value,
17    install_pending: Option<PendingInstall>,
18    install_status: Value,
19    deferred_run: bool,
20}
21
22struct PendingInstall {
23    id: u64,
24    revision: u64,
25    packages: Vec<(PackageBundle, bool)>,
26}
27
28fn parse_installations(packages: Value) -> Result<Vec<(PackageBundle, bool)>, String> {
29    let rows = packages
30        .as_array()
31        .ok_or("installed plugins must be an array")?;
32    let mut installed = Vec::new();
33    let mut seen = std::collections::BTreeSet::new();
34    for row in rows {
35        let bundle: PackageBundle = serde_json::from_value(row["bundle"].clone())
36            .map_err(|e| format!("plugin bundle: {e}"))?;
37        let pin = bundle.pin()?;
38        if !seen.insert((pin.id.clone(), pin.digest)) {
39            return Err(format!("duplicate installed package {}", pin.id));
40        }
41        let enabled = row["enabled"]
42            .as_bool()
43            .ok_or("plugin enabled must be boolean")?;
44        installed.push((bundle, enabled));
45    }
46    Ok(installed)
47}
48
49struct PendingAction {
50    id: u64,
51    revision: u64,
52    registry_revision: u64,
53    selection: String,
54    generation: u64,
55    pins: Vec<PluginPin>,
56    staged: Option<History>,
57    notifications: Vec<String>,
58    annotation_id: Option<String>,
59    allowed_annotation_errors: Vec<AnnotationFailure>,
60}
61
62impl Plugins {
63    fn bundles(&self) -> Vec<PackageBundle> {
64        self.packages
65            .iter()
66            .filter(|(_, enabled)| *enabled)
67            .map(|(p, _)| p.clone())
68            .collect()
69    }
70    fn rebuild(&mut self, packages: Vec<(PackageBundle, bool)>) -> Result<(), String> {
71        let enabled = packages
72            .iter()
73            .filter(|(_, enabled)| *enabled)
74            .map(|(p, _)| p.clone())
75            .collect();
76        let runtime = Runtime::new(enabled)?;
77        self.packages = packages;
78        self.runtime = Some(runtime);
79        self.revision = self.revision.wrapping_add(1);
80        Ok(())
81    }
82}
83
84impl EngineState {
85    /// Restore persisted installations in one atomic registry revision.
86    pub fn restore_plugins(&mut self, packages: Value) -> Result<(), String> {
87        self.plugins.rebuild(parse_installations(packages)?)?;
88        self.plugins_changed();
89        Ok(())
90    }
91
92    /// Submit a complete installation set to the runner for atomic validation.
93    /// Does not enable code or change an existing registry before the reply succeeds.
94    pub fn submit_plugin_installations(&mut self, installations: Value) -> Result<u64, String> {
95        if self.plugins.install_pending.is_some() {
96            return Err("plugin installation already pending".into());
97        }
98        let packages = parse_installations(installations)?;
99        self.plugins.next_action += 1;
100        let id = self.plugins.next_action;
101        let enabled: Vec<_> = packages
102            .iter()
103            .filter(|(_, enabled)| *enabled)
104            .map(|(p, _)| p)
105            .collect();
106        if !self
107            .runner
108            .submit_plugin_install(crate::runner::PluginInstallRequest {
109                id,
110                packages: json!(enabled),
111            })
112        {
113            return Err("runner does not support asynchronous plugin installation".into());
114        }
115        self.plugins.install_pending = Some(PendingInstall {
116            id,
117            revision: self.plugins.revision,
118            packages,
119        });
120        self.plugins.install_status = json!({"state":"pending","id":id});
121        self.pump();
122        Ok(id)
123    }
124
125    pub(super) fn defer_plugin_run(&mut self) -> bool {
126        if self.plugins.install_pending.is_none() {
127            return false;
128        }
129        self.plugins.deferred_run = true;
130        self.run_generation += 1;
131        true
132    }
133    pub(super) fn plugin_work_pending(&self) -> bool {
134        self.plugins.install_pending.is_some() || self.plugins.pending.is_some()
135    }
136
137    pub(super) fn plugin_installation_pending(&self) -> bool {
138        self.plugins.install_pending.is_some()
139    }
140
141    pub(super) fn plugin_runner_replaced(&mut self) {
142        if self.plugins.pending.take().is_some() {
143            self.plugin_result(Err(
144                "plugin transaction cancelled because runner changed".into()
145            ));
146        }
147        if let Some(pending) = &self.plugins.install_pending {
148            let enabled: Vec<_> = pending
149                .packages
150                .iter()
151                .filter(|(_, enabled)| *enabled)
152                .map(|(p, _)| p)
153                .collect();
154            if !self
155                .runner
156                .submit_plugin_install(crate::runner::PluginInstallRequest {
157                    id: pending.id,
158                    packages: json!(enabled),
159                })
160            {
161                self.plugins.install_pending = None;
162                self.plugins.install_status =
163                    json!({"state":"error","error":"replacement runner cannot validate plugins"});
164            }
165        }
166    }
167
168    pub fn plugin_installation_status(&self) -> Value {
169        self.plugins.install_status.clone()
170    }
171
172    pub(super) fn pump_plugin_installations(&mut self) {
173        while let Some(reply) = self.runner.poll_plugin_install() {
174            if !self
175                .plugins
176                .install_pending
177                .as_ref()
178                .is_some_and(|p| p.id == reply.id)
179            {
180                continue;
181            }
182            let pending = self.plugins.install_pending.take().unwrap();
183            let result = if pending.revision != self.plugins.revision {
184                Err("plugin installations changed during validation".to_string())
185            } else {
186                reply.result.and_then(|registry| {
187                    let enabled = pending
188                        .packages
189                        .iter()
190                        .filter(|(_, enabled)| *enabled)
191                        .map(|(p, _)| p.clone())
192                        .collect();
193                    Runtime::from_validated(enabled, registry)
194                })
195            };
196            let deferred = std::mem::take(&mut self.plugins.deferred_run);
197            match result {
198                Ok(runtime) => {
199                    self.plugins.runtime = Some(runtime);
200                    self.plugins.packages = pending.packages;
201                    self.plugins.revision = self.plugins.revision.wrapping_add(1);
202                    self.plugins.install_status = json!({"state":"complete","id":pending.id});
203                    self.plugins_changed();
204                }
205                Err(error) => {
206                    self.plugins.install_status =
207                        json!({"state":"error","id":pending.id,"error":error});
208                    if deferred {
209                        self.rerun_history();
210                    }
211                }
212            }
213        }
214    }
215
216    /// Restore explicitly installed/enabled packages, independently of loading a document.
217    pub fn set_plugin_packages(&mut self, packages: Vec<PackageBundle>) -> Result<(), String> {
218        self.plugins
219            .rebuild(packages.into_iter().map(|p| (p, true)).collect())?;
220        self.plugins_changed();
221        Ok(())
222    }
223
224    pub fn install_plugin(&mut self, package: Value) -> Result<Value, String> {
225        let package: PackageBundle =
226            serde_json::from_value(package).map_err(|e| format!("plugin package: {e}"))?;
227        let pin = package.pin()?;
228        let mut packages = self.plugins.packages.clone();
229        packages.retain(|(p, _)| p.pin().ok().as_ref() != Some(&pin));
230        packages.push((package, true));
231        self.plugins.rebuild(packages)?;
232        self.plugins_changed();
233        Ok(json!(pin))
234    }
235
236    pub fn installed_plugins(&self) -> Value {
237        Value::Array(
238            self.plugins
239                .packages
240                .iter()
241                .filter_map(|(p, enabled)| {
242                    p.pin().ok().map(|pin| {
243                        json!({"id":pin.id,"version":pin.version,"apiVersion":pin.api_version,
244                "digest":pin.digest,"name":p.manifest.name,"enabled":enabled})
245                    })
246                })
247                .collect(),
248        )
249    }
250
251    pub fn export_plugin(&self, id: &str, digest: &str) -> Result<Value, String> {
252        let (package, _) = self
253            .plugins
254            .packages
255            .iter()
256            .find(|(p, _)| {
257                p.pin()
258                    .is_ok_and(|pin| pin.id == id && pin.digest == digest)
259            })
260            .ok_or_else(|| format!("plugin {id} at {digest} is not installed"))?;
261        serde_json::to_value(package).map_err(|e| e.to_string())
262    }
263
264    pub fn enable_plugin(&mut self, id: &str, digest: &str, enabled: bool) -> Result<(), String> {
265        let mut packages = self.plugins.packages.clone();
266        let (_, state) = packages
267            .iter_mut()
268            .find(|(p, _)| {
269                p.pin()
270                    .is_ok_and(|pin| pin.id == id && pin.digest == digest)
271            })
272            .ok_or_else(|| format!("plugin {id} at {digest} is not installed"))?;
273        *state = enabled;
274        self.plugins.rebuild(packages)?;
275        self.plugins_changed();
276        Ok(())
277    }
278
279    pub fn remove_plugin(&mut self, id: &str, digest: &str) -> Result<(), String> {
280        let mut packages = self.plugins.packages.clone();
281        let before = packages.len();
282        packages.retain(|(p, _)| {
283            !p.pin()
284                .is_ok_and(|pin| pin.id == id && pin.digest == digest)
285        });
286        if packages.len() == before {
287            return Err(format!("plugin {id} at {digest} is not installed"));
288        }
289        self.plugins.rebuild(packages)?;
290        self.plugins_changed();
291        Ok(())
292    }
293
294    fn plugins_changed(&mut self) {
295        self.cancel_plugin_action();
296        self.runner.reset();
297        // A reset drops any answer still on its way.
298        self.session_requested = None;
299        self.rerun_history();
300    }
301
302    fn saved_plugin_pins(&self) -> Result<Vec<PluginPin>, String> {
303        serde_json::from_value(
304            self.history
305                .document_block("plugins")
306                .cloned()
307                .unwrap_or_else(|| json!([])),
308        )
309        .map_err(|e| format!("document plugin pins: {e}"))
310    }
311
312    /// Existing document pins always win; an unpinned package uses the last explicit install.
313    fn available_plugin_pins(&self) -> Result<Vec<PluginPin>, String> {
314        let mut pins = self.saved_plugin_pins()?;
315        for (package, enabled) in self.plugins.packages.iter().rev() {
316            if !enabled {
317                continue;
318            }
319            let pin = package.pin()?;
320            if !pins.iter().any(|p| p.id == pin.id) {
321                pins.push(pin);
322            }
323        }
324        Ok(pins)
325    }
326
327    pub fn plugin_catalogue(&self) -> Value {
328        let mut features = Vec::new();
329        let mut actions = Vec::new();
330        let mut workbenches = Vec::new();
331        let mut panels = Vec::new();
332        let mut annotations = Vec::new();
333        let mut errors = Vec::new();
334        if let Some(runtime) = &self.plugins.runtime {
335            match self.available_plugin_pins() {
336                Ok(pins) => {
337                    for pin in pins {
338                        if self.installed_pin(&pin.id, &pin.digest).as_ref() != Ok(&pin) {
339                            errors.push(format!(
340                                "plugin {} at {} is missing or disabled",
341                                pin.id, pin.digest
342                            ));
343                            continue;
344                        }
345                        // One unavailable dependency must not hide healthy package controls.
346                        match runtime.registry().for_document(&[pin]) {
347                            Ok(registry) => {
348                                features.extend(registry.features().iter().map(|f| {
349                                let mut schema = f.input_params_schema.clone();
350                                schema["id"] = json!({"type":"string","default_value":null});
351                                json!({"type":f.id,"id":f.id,"label":f.label,"longName":f.label,"ribbonPath":f.ribbon_path,"commandSize":f.command_size,"icon":f.glyph,
352                                    "shortName":if f.short_name.is_empty() { f.id.rsplit('/').next().unwrap_or("Plugin") } else { &f.short_name },
353                                    "inputParamsSchema":schema,"package":f.package})
354                            }));
355                                panels.extend(registry.panels().iter().map(|p| json!(p)));
356                                annotations.extend(registry.annotations().iter().map(|a| {
357                                    let mut schema = a.input_params_schema.clone();
358                                    schema["id"] = json!({"type":"string","default_value":null});
359                                    json!({"type":a.id,"id":a.id,"label":a.label,"longName":a.label,
360                                        "shortName":"ANN","inputParamsSchema":schema,"package":a.package})
361                                }));
362                                actions.extend(registry.actions().iter().map(|a| json!(a)));
363                                workbenches.extend(registry.workbenches().iter().map(|w| json!(w)));
364                            }
365                            Err(error) => errors.push(error),
366                        }
367                    }
368                }
369                Err(error) => errors.push(error),
370            }
371        } else if let Ok(pins) = self.saved_plugin_pins() {
372            errors.extend(pins.iter().map(|p| {
373                format!(
374                    "plugin {} at {} is not installed or enabled",
375                    p.id, p.digest
376                )
377            }));
378        }
379        json!({"revision":self.plugins.revision,"documentRevision":self.history.revision(),
380            "features":features,"actions":actions,"workbenches":workbenches,"panels":panels,"annotations":annotations,"errors":errors})
381    }
382
383    pub fn plugin_workbenches(&self) -> Value {
384        self.plugin_catalogue()["workbenches"].clone()
385    }
386
387    /// Engine-local schema overlay; never adds package schemas to the process-wide built-ins.
388    pub fn feature_catalogue(&self) -> Value {
389        let mut catalogue = crate::features::feature_catalogue();
390        if let Some(features) = catalogue["features"].as_array_mut() {
391            features.extend(
392                self.plugin_catalogue()["features"]
393                    .as_array()
394                    .into_iter()
395                    .flatten()
396                    .cloned(),
397            );
398        }
399        catalogue
400    }
401    pub fn feature_schema(&self, feature_type: &str) -> Option<Value> {
402        crate::features::feature_schema(feature_type).or_else(|| {
403            self.plugin_catalogue()["features"]
404                .as_array()?
405                .iter()
406                .find(|f| f["type"] == feature_type)
407                .cloned()
408        })
409    }
410    pub fn feature_form_fields(&self, feature_type: &str) -> Vec<crate::style::FormField> {
411        if let Some(schema) = crate::features::feature_schema(feature_type) {
412            return crate::features::form_fields_from_schema(&schema);
413        }
414        self.feature_schema(feature_type)
415            .as_ref()
416            .map(crate::features::plugin_form_fields_from_schema)
417            .unwrap_or_default()
418    }
419    pub fn feature_default_params(&self, feature_type: &str) -> Value {
420        let mut params = serde_json::Map::new();
421        if let Some(schema) = self.feature_schema(feature_type) {
422            if let Some(props) = schema["inputParamsSchema"].as_object() {
423                for (name, spec) in props {
424                    params.insert(name.clone(), spec["default_value"].clone());
425                }
426            }
427        }
428        Value::Object(params)
429    }
430
431    /// Selecting a first pin is undoable; replacing an existing pin requires migration.
432    pub fn select_plugin(&mut self, id: &str, digest: &str) -> Result<(), String> {
433        self.require_plugin_editable()?;
434        let pin = self.installed_pin(id, digest)?;
435        let mut pins = self.saved_plugin_pins()?;
436        if let Some(old) = pins.iter().find(|p| p.id == id) {
437            return if old == &pin {
438                Ok(())
439            } else {
440                Err("use migrate_plugin to validate a version change".into())
441            };
442        }
443        pins.push(pin);
444        self.history
445            .set_document_block("plugins", Some(json!(pins)), None);
446        self.rerun_history();
447        Ok(())
448    }
449
450    fn installed_pin(&self, id: &str, digest: &str) -> Result<PluginPin, String> {
451        self.plugins
452            .packages
453            .iter()
454            .filter(|(_, enabled)| *enabled)
455            .find_map(|(p, _)| {
456                p.pin()
457                    .ok()
458                    .filter(|pin| pin.id == id && pin.digest == digest)
459            })
460            .ok_or_else(|| format!("plugin {id} at {digest} is not installed and enabled"))
461    }
462    fn require_plugin_editable(&self) -> Result<(), String> {
463        if self.plugins.install_pending.is_some() {
464            return Err("wait for plugin installation validation".into());
465        }
466        if let Some(reason) = self.history.locked() {
467            return Err(format!("the document is read-only: {reason}"));
468        }
469        if self.plugins.pending.is_some() {
470            return Err("a plugin transaction is already pending".into());
471        }
472        if self.run_pending() {
473            return Err("wait for the current history recompute".into());
474        }
475        Ok(())
476    }
477
478    pub fn migrate_plugin(&mut self, id: &str, digest: &str) -> Result<u64, String> {
479        self.require_plugin_editable()?;
480        let pin = self.installed_pin(id, digest)?;
481        let mut pins = self.saved_plugin_pins()?;
482        pins.retain(|p| p.id != id);
483        pins.push(pin);
484        let pending = self.new_plugin_pending(pins.clone());
485        let action_id = pending.id;
486        let mut staged = self.history.clone();
487        staged.set_document_block_no_undo("plugins", Some(json!(pins)));
488        self.plugins.pending = Some(pending);
489        if let Err(error) = self.submit_plugin_candidate(staged) {
490            self.plugins.pending = None;
491            return Err(error);
492        }
493        self.pump();
494        Ok(action_id)
495    }
496
497    fn new_plugin_pending(&mut self, pins: Vec<PluginPin>) -> PendingAction {
498        self.plugins.next_action += 1;
499        PendingAction {
500            id: self.plugins.next_action,
501            revision: self.history.revision(),
502            registry_revision: self.plugins.revision,
503            selection: self.selection_json(),
504            generation: self.run_generation,
505            pins,
506            staged: None,
507            notifications: Vec::new(),
508            annotation_id: None,
509            allowed_annotation_errors: Vec::new(),
510        }
511    }
512
513    pub fn submit_plugin_action(&mut self, id: &str, params: Value) -> Result<(), String> {
514        let selection = serde_json::from_str(&self.selection_json()).unwrap_or(Value::Null);
515        self.plugin_action(id, params, selection).map(|_| ())
516    }
517
518    /// Submit a callback; neither callback commands nor recompute touch live history.
519    pub fn plugin_action(
520        &mut self,
521        id: &str,
522        params: Value,
523        selection: Value,
524    ) -> Result<u64, String> {
525        self.require_plugin_editable()?;
526        let pins = self.available_plugin_pins()?;
527        let runtime = self
528            .plugins
529            .runtime
530            .as_ref()
531            .ok_or("no plugins installed")?;
532        let registry = runtime.registry().for_document(&pins)?;
533        if !registry.actions().iter().any(|a| a.id == id) {
534            return Err(format!("plugin action {id} is unavailable"));
535        }
536        let pending = self.new_plugin_pending(pins.clone());
537        let action_id = pending.id;
538        let input = json!({"params":params,"selection":selection,
539            "document":serde_json::from_str::<Value>(&self.history.request_json()).map_err(|e| e.to_string())?});
540        self.sync_plugin_runner();
541        let request = crate::runner::PluginActionRequest {
542            id: action_id,
543            pins,
544            action: id.into(),
545            input,
546            script: None,
547        };
548        if !self.runner.submit_plugin_action(request) {
549            return Err("the installed runner does not support plugin actions".into());
550        }
551        self.plugins.pending = Some(pending);
552        self.plugins.status = json!({"state":"pending","id":action_id});
553        self.pump();
554        Ok(action_id)
555    }
556
557    pub fn plugin_action_status(&self) -> Value {
558        self.plugins.status.clone()
559    }
560
561    /// Run an editor script through the same worker and atomic undo transaction
562    /// as named actions, without installing the editor source as a dependency.
563    pub fn run_javascript(&mut self, source: &str) -> Result<u64, String> {
564        self.require_plugin_editable()?;
565        if source.len() > 1024 * 1024 {
566            return Err("script exceeds 1 MiB".into());
567        }
568        let pins = self.available_plugin_pins()?;
569        let pending = self.new_plugin_pending(pins.clone());
570        let id = pending.id;
571        let input = json!({"params":{},
572            "selection":serde_json::from_str::<Value>(&self.selection_json()).unwrap_or(Value::Null),
573            "document":serde_json::from_str::<Value>(&self.history.request_json()).map_err(|e| e.to_string())?});
574        self.sync_plugin_runner();
575        let request = crate::runner::PluginActionRequest {
576            id, pins, action: String::new(), input, script: Some(source.into()),
577        };
578        if !self.runner.submit_plugin_action(request) {
579            return Err("the installed runner does not support JavaScript execution".into());
580        }
581        self.plugins.pending = Some(pending);
582        self.plugins.status = json!({"state":"pending","id":id});
583        self.pump();
584        Ok(id)
585    }
586    pub fn poll_plugin_action(&mut self) -> Option<Result<Value, String>> {
587        self.pump();
588        self.plugins.results.pop_front()
589    }
590    pub fn cancel_plugin_action(&mut self) -> bool {
591        if self.plugins.pending.take().is_none() {
592            return false;
593        }
594        self.plugin_result(Err("plugin transaction cancelled".into()));
595        // Queued old outputs can no longer apply. Restore the live document's baseline.
596        self.run_generation += 1;
597        self.applied_generation = self.run_generation;
598        self.runner.reset();
599        // A reset drops any answer still on its way.
600        self.session_requested = None;
601        self.rerun_history();
602        true
603    }
604
605    pub(super) fn sync_plugin_runner(&mut self) {
606        let plugins = &self.plugins;
607        self.runner
608            .sync_plugins(plugins.revision, &mut || json!(plugins.bundles()));
609    }
610
611    fn plugin_result(&mut self, result: Result<Value, String>) {
612        self.plugins.status = match &result {
613            Ok(value) => json!({"state":"complete","result":value}),
614            Err(error) => json!({"state":"error","error":error}),
615        };
616        self.plugins.results.push_back(result);
617    }
618
619    fn plugin_pending_valid(&self, pending: &PendingAction) -> bool {
620        pending.revision == self.history.revision()
621            && pending.registry_revision == self.plugins.revision
622            && pending.selection == self.selection_json()
623            && pending.generation == self.run_generation
624            && self.history.locked().is_none()
625    }
626
627    pub(super) fn pump_plugin_callbacks(&mut self) {
628        if self
629            .plugins
630            .pending
631            .as_ref()
632            .is_some_and(|p| !self.plugin_pending_valid(p))
633        {
634            let staged = self.plugins.pending.take().unwrap().staged.is_some();
635            self.plugin_result(Err(
636                "plugin transaction invalidated by a document or selection change".into(),
637            ));
638            if staged {
639                self.runner.reset();
640                // A reset drops any answer still on its way.
641                self.session_requested = None;
642                self.rerun_history();
643            }
644        }
645        while let Some(reply) = self.runner.poll_plugin_action() {
646            let Some(pending) = self.plugins.pending.as_ref() else {
647                continue;
648            };
649            if pending.id != reply.id {
650                continue;
651            }
652            if !self.plugin_pending_valid(pending) {
653                self.plugins.pending = None;
654                self.plugin_result(Err(
655                    "plugin transaction invalidated by a document or selection change".into(),
656                ));
657                continue;
658            }
659            if let Ok(plan) = &reply.result {
660                if plan.commands.is_empty() {
661                    self.plugins.pending = None;
662                    self.plugin_result(Ok(
663                        json!({"id":reply.id,"notifications":plan.notifications}),
664                    ));
665                    continue;
666                }
667            }
668            let staged = reply.result.and_then(|plan| {
669                let mut staged = self.history.clone();
670                let pending = self.plugins.pending.as_mut().unwrap();
671                staged.set_document_block_no_undo("plugins", Some(json!(pending.pins)));
672                pending.notifications = plan.notifications;
673                // Use the serializable command contract to keep all validation at one door.
674                let commands = serde_json::to_value(plan.commands).map_err(|e| e.to_string())?;
675                for command in commands.as_array().ok_or("invalid action commands")? {
676                    match command["op"].as_str().unwrap_or("") {
677                        "addFeature" => {
678                            let ty = command["featureType"].as_str().ok_or("addFeature requires featureType")?;
679                            let schema = self.feature_schema(ty).ok_or_else(|| format!("unknown feature type {ty}"))?;
680                            let mut params = self.feature_default_params(ty);
681                            let supplied = command["inputParams"].as_object().ok_or("feature parameters must be an object")?;
682                            params.as_object_mut().unwrap().extend(supplied.clone());
683                            let id = staged.next_feature_id(schema["shortName"].as_str().unwrap_or(ty));
684                            params["id"] = json!(id);
685                            staged.push_feature(json!({"type":ty,"inputParams":params,"persistentData":command["persistentData"]}));
686                        }
687                        "updateFeature" => {
688                            let id = command["id"].as_str().ok_or("updateFeature requires id")?;
689                            let index = staged.index_of(id).ok_or_else(|| format!("feature {id} not found"))?;
690                            let mut params = command["inputParams"].clone();
691                            if !params.is_object() { return Err("feature parameters must be an object".into()); }
692                            params["id"] = json!(id);
693                            staged.set_feature_params(index, params);
694                        }
695                        "deleteFeature" => {
696                            let id = command["id"].as_str().ok_or("deleteFeature requires id")?;
697                            let index = staged.index_of(id).ok_or_else(|| format!("feature {id} not found"))?;
698                            staged.remove_feature(index);
699                        }
700                        op => return Err(format!("unsupported plugin document command {op}")),
701                    }
702                }
703                Ok(staged)
704            });
705            match staged.and_then(|staged| self.submit_plugin_candidate(staged)) {
706                Ok(()) => {}
707                Err(error) => {
708                    self.plugins.pending = None;
709                    self.plugin_result(Err(error));
710                }
711            }
712        }
713    }
714
715    fn submit_plugin_candidate(&mut self, mut staged: History) -> Result<(), String> {
716        staged.set_rollback(staged.len().saturating_sub(1));
717        let mut request: brep_kernel::HistoryRequest =
718            serde_json::from_value(staged.prefix_request()).map_err(|e| e.to_string())?;
719        request.display_lod = self.settings.lod_factor;
720        self.run_generation += 1;
721        let pending = self
722            .plugins
723            .pending
724            .as_mut()
725            .ok_or("plugin transaction disappeared")?;
726        pending.generation = self.run_generation;
727        pending.staged = Some(staged);
728        self.plugins.status = json!({"state":"pending","id":pending.id});
729        // Full delta means discarding an unsuccessful candidate cannot poison the display baseline.
730        self.runner.reset();
731        // A reset drops any answer still on its way.
732        self.session_requested = None;
733        self.sync_plugin_runner();
734        self.runner.sync_parts_library(
735            brep_kernel::parts_library_revision(),
736            &mut brep_kernel::parts_library_map,
737        );
738        self.runner.submit_run(request, self.run_generation);
739        Ok(())
740    }
741
742    /// Returns false when this candidate must be discarded, without applying its scene.
743    pub(super) fn accept_plugin_run(&mut self, reply: &crate::runner::RunReply) -> bool {
744        let Some(pending) = self.plugins.pending.as_ref() else {
745            return true;
746        };
747        if pending.staged.is_none() || pending.generation != reply.generation {
748            return true;
749        }
750        let valid = self.plugin_pending_valid(pending);
751        let mut pending = self.plugins.pending.take().unwrap();
752        let report = &reply.output.report;
753        let annotation_errors: Vec<_> = annotation_failures(report.pmi.as_ref())
754            .into_iter()
755            .filter(|failure| !pending.allowed_annotation_errors.contains(failure))
756            .map(|failure| format!("{}: {}", failure.id, failure.message))
757            .collect();
758        let result = if !valid {
759            Err("plugin transaction invalidated by a document or selection change".into())
760        } else if !report.feature_errors.is_empty()
761            || !report.unresolved.is_empty()
762            || !report.display_errors.is_empty()
763            || !annotation_errors.is_empty()
764        {
765            Err(format!(
766                "plugin transaction recompute failed: {}",
767                report
768                    .feature_errors
769                    .iter()
770                    .chain(&report.unresolved)
771                    .chain(&report.display_errors)
772                    .chain(&annotation_errors)
773                    .cloned()
774                    .collect::<Vec<_>>()
775                    .join("; ")
776            ))
777        } else {
778            fold_annotation_data(pending.staged.as_mut().unwrap(), report.pmi.as_ref());
779            self.history
780                .commit_staged(pending.staged.as_ref().unwrap())
781                .map(|_| json!({"id":pending.id,"notifications":pending.notifications,"annotationId":pending.annotation_id}))
782        };
783        let accepted = result.is_ok();
784        self.plugin_result(result);
785        if !accepted {
786            self.runner.reset();
787            // A reset drops any answer still on its way.
788            self.session_requested = None;
789            self.rerun_history();
790        }
791        accepted
792    }
793
794    /// Add package pins and features together so undo restores both.
795    pub(super) fn append_plugin_features(&mut self, features: &[Value]) -> Result<bool, String> {
796        if !features
797            .iter()
798            .any(|f| f["type"].as_str().is_some_and(|t| t.contains('/')))
799        {
800            return Ok(false);
801        }
802        if let Some(reason) = self.history.locked() {
803            return Err(format!("the document is read-only: {reason}"));
804        }
805        let mut pins = self.saved_plugin_pins()?;
806        for feature in features {
807            let ty = feature["type"].as_str().unwrap_or("");
808            if !ty.contains('/') {
809                continue;
810            }
811            let schema = self
812                .feature_schema(ty)
813                .ok_or_else(|| format!("plugin feature {ty} is unavailable"))?;
814            let pin: PluginPin =
815                serde_json::from_value(schema["package"].clone()).map_err(|e| e.to_string())?;
816            if !pins.iter().any(|p| p.id == pin.id) {
817                pins.push(pin);
818            }
819        }
820        let mut staged = self.history.clone();
821        staged.set_document_block_no_undo("plugins", Some(json!(pins)));
822        staged.push_features(features.to_vec());
823        staged.set_rollback(staged.len().saturating_sub(1));
824        self.history.commit_staged(&staged)?;
825        Ok(true)
826    }
827
828    pub(super) fn plugin_export_ready(&self) -> Result<(), String> {
829        fn uses_plugins(value: &Value) -> bool {
830            match value {
831                Value::Object(map) => {
832                    map.get("plugins")
833                        .and_then(Value::as_array)
834                        .is_some_and(|p| !p.is_empty())
835                        || map
836                            .get("type")
837                            .and_then(Value::as_str)
838                            .is_some_and(|ty| ty.contains('/'))
839                        || map.values().any(uses_plugins)
840                }
841                Value::Array(values) => values.iter().any(uses_plugins),
842                _ => false,
843            }
844        }
845        let document: Value =
846            serde_json::from_str(&self.history.request_json()).map_err(|e| e.to_string())?;
847        if !uses_plugins(&document) {
848            return Ok(());
849        }
850        if self.run_pending()
851            || self.plugins.pending.is_some()
852            || self.plugins.install_pending.is_some()
853        {
854            return Err("plugin geometry is pending; wait for recompute before export".into());
855        }
856        let annotation_errors = plugin_annotation_errors(self.pmi_report.as_ref());
857        if !annotation_errors.is_empty() {
858            return Err(format!(
859                "unavailable plugin annotations: {}",
860                annotation_errors.join("; ")
861            ));
862        }
863        let report: Value = serde_json::from_str(&self.history_report).unwrap_or(Value::Null);
864        if report.get("error").is_some()
865            || ["featureErrors", "unresolved", "displayErrors"]
866                .iter()
867                .any(|key| {
868                    report[*key]
869                        .as_array()
870                        .is_some_and(|items| !items.is_empty())
871                })
872        {
873            return Err("plugin document has failed or unavailable geometry; recompute successfully before export".into());
874        }
875        Ok(())
876    }
877
878    pub(super) fn plugin_resident_handles(
879        &self,
880        request: &brep_kernel::HistoryRequest,
881    ) -> Result<Vec<(String, u32)>, String> {
882        let result = self.execute_plugin_history(request);
883        let mut names = Vec::new();
884        let mut handles = std::collections::HashMap::new();
885        for feature in result.results {
886            if let Some(error) = feature.error {
887                return Err(format!("{}: {error}", feature.id));
888            }
889            for removed in feature.removed {
890                handles.remove(&removed);
891                names.retain(|n| n != &removed);
892            }
893            for added in feature.added {
894                if handles.insert(added.name.clone(), added.handle).is_none() {
895                    names.push(added.name);
896                }
897            }
898        }
899        Ok(names
900            .into_iter()
901            .map(|name| {
902                let handle = handles[&name];
903                (name, handle)
904            })
905            .collect())
906    }
907
908    pub(super) fn inherit_plugins(&mut self, parent: &Self) {
909        self.plugins.packages = parent.plugins.packages.clone();
910        self.plugins.runtime = parent.plugins.runtime.clone();
911        self.plugins.revision = parent.plugins.revision;
912    }
913
914    pub(super) fn with_plugin_provider<R>(&self, f: impl FnOnce() -> R) -> R {
915        match &self.plugins.runtime {
916            Some(runtime) => runtime.with_provider(f),
917            None => f(),
918        }
919    }
920
921    pub(super) fn execute_plugin_history(
922        &self,
923        request: &brep_kernel::HistoryRequest,
924    ) -> brep_kernel::HistoryResult {
925        match &self.plugins.runtime {
926            Some(runtime) => runtime.execute_history(request),
927            None => brep_kernel::execute_history(request),
928        }
929    }
930
931    pub(super) fn run_plugin_scene(
932        &mut self,
933        request: &brep_kernel::HistoryRequest,
934    ) -> Result<crate::pipeline::SceneBuildReport, String> {
935        match &self.plugins.runtime {
936            Some(runtime) => runtime.with_provider(|| {
937                crate::pipeline::update_scene_from_history(&mut self.scene, request)
938            }),
939            None => crate::pipeline::update_scene_from_history(&mut self.scene, request),
940        }
941    }
942}
943
944
945/// The exact error identity used by repair transactions. Other operations stay strict.
946#[derive(Clone, Debug, PartialEq, Eq)]
947struct AnnotationFailure {
948    view_id: String,
949    id: String,
950    kind: String,
951    message: String,
952}
953
954fn annotation_failures(report: Option<&brep_kernel::PmiReport>) -> Vec<AnnotationFailure> {
955    report
956        .into_iter()
957        .flat_map(|r| &r.views)
958        .flat_map(|view| {
959            view.annotations
960                .iter()
961                .filter(|a| {
962                    a.enabled && a.kind.contains('/') && a.status == brep_kernel::PmiStatus::Error
963                })
964                .map(|a| AnnotationFailure {
965                    view_id: view.id.clone(),
966                    id: a.id.clone(),
967                    kind: a.kind.clone(),
968                    message: a.message.clone(),
969                })
970        })
971        .collect()
972}
973
974/// Even tolerated repair errors continue to block exports.
975pub(super) fn plugin_annotation_errors(report: Option<&brep_kernel::PmiReport>) -> Vec<String> {
976    annotation_failures(report)
977        .into_iter()
978        .map(|a| format!("{}: {}", a.id, a.message))
979        .collect()
980}
981
982fn fold_annotation_data(history: &mut History, report: Option<&brep_kernel::PmiReport>) {
983    let Some(block) = history.pmi_block() else {
984        return;
985    };
986    let Ok(mut state) = serde_json::from_value::<brep_kernel::PmiState>(block.clone()) else {
987        return;
988    };
989    let mut changed = false;
990    for row in report
991        .into_iter()
992        .flat_map(|r| &r.views)
993        .flat_map(|v| &v.annotations)
994    {
995        if row.status != brep_kernel::PmiStatus::Ok || !row.kind.contains('/') {
996            continue;
997        }
998        if let (Some(data), Some(annotation)) =
999            (&row.persistent_data, state.find_annotation_mut(&row.id))
1000        {
1001            if annotation.kind == row.kind
1002                && (annotation.persistent_data != *data
1003                    || annotation.plugin_replay != row.plugin_replay)
1004            {
1005                annotation.persistent_data = data.clone();
1006                annotation.plugin_replay = row.plugin_replay.clone();
1007                changed = true;
1008            }
1009        }
1010    }
1011    if changed {
1012        history.set_pmi_block_no_undo(Some(json!(state)));
1013    }
1014}
1015
1016impl EngineState {
1017    pub fn plugin_panels(&self) -> Value {
1018        self.plugin_catalogue()["panels"].clone()
1019    }
1020
1021    pub fn plugin_annotation_catalogue(&self) -> Value {
1022        self.plugin_catalogue()["annotations"].clone()
1023    }
1024
1025    /// Built-ins and document-scoped providers share the normal annotation form shape.
1026    pub fn annotation_schema(&self, kind: &str) -> Option<Value> {
1027        brep_kernel::pmi_type(kind)
1028            .map(|d| (d.schema)())
1029            .or_else(|| {
1030                self.plugin_annotation_catalogue()
1031                    .as_array()?
1032                    .iter()
1033                    .find(|a| a["type"] == kind)
1034                    .cloned()
1035            })
1036    }
1037
1038    pub(super) fn fold_plugin_annotation_data(&mut self) {
1039        if self.expression_preview.is_none() {
1040            fold_annotation_data(&mut self.history, self.pmi_report.as_ref());
1041        }
1042    }
1043
1044    pub fn plugin_add_annotation(
1045        &mut self,
1046        view_id: &str,
1047        kind: &str,
1048        mut params: Value,
1049    ) -> Result<u64, String> {
1050        self.require_plugin_editable()?;
1051        let schema = self
1052            .plugin_annotation_catalogue()
1053            .as_array()
1054            .into_iter()
1055            .flatten()
1056            .find(|s| s["type"] == kind)
1057            .cloned()
1058            .ok_or_else(|| format!("unavailable plugin annotation {kind}"))?;
1059        if !params.is_object() {
1060            return Err("annotation parameters must be an object".into());
1061        }
1062        let mut state = self.pmi_state();
1063        let id = state.next_id("ANN");
1064        params["id"] = json!(id);
1065        state
1066            .find_view_mut(view_id)
1067            .ok_or_else(|| format!("no PMI view '{view_id}'"))?
1068            .annotations
1069            .push(brep_kernel::PmiAnnotation {
1070                kind: kind.into(),
1071                enabled: true,
1072                params,
1073                persistent_data: Value::Null,
1074                plugin_replay: None,
1075                label_world: None,
1076            });
1077        let pin: PluginPin =
1078            serde_json::from_value(schema["package"].clone()).map_err(|e| e.to_string())?;
1079        let mut pins = self.saved_plugin_pins()?;
1080        if let Some(old) = pins.iter().find(|p| p.id == pin.id) {
1081            if old != &pin {
1082                return Err("annotation package does not match document pin".into());
1083            }
1084        } else {
1085            pins.push(pin);
1086        }
1087        self.submit_annotation_state(state, pins, id, false)
1088    }
1089
1090    pub fn plugin_update_annotation(&mut self, id: &str, mut params: Value) -> Result<u64, String> {
1091        self.require_plugin_editable()?;
1092        if !params.is_object() {
1093            return Err("annotation parameters must be an object".into());
1094        }
1095        let mut state = self.pmi_state();
1096        let annotation = state
1097            .find_annotation_mut(id)
1098            .ok_or_else(|| format!("no PMI annotation '{id}'"))?;
1099        if !annotation.kind.contains('/') {
1100            return Err("annotation is not plugin-owned".into());
1101        }
1102        params["id"] = json!(id);
1103        annotation.params = params;
1104        self.submit_annotation_state(state, self.saved_plugin_pins()?, id.into(), false)
1105    }
1106
1107    pub fn plugin_delete_annotation(&mut self, id: &str) -> Result<u64, String> {
1108        self.require_plugin_editable()?;
1109        let mut state = self.pmi_state();
1110        let (v, a) = state
1111            .locate_annotation(id)
1112            .ok_or_else(|| format!("no PMI annotation '{id}'"))?;
1113        if !state.views[v].annotations[a].kind.contains('/') {
1114            return Err("annotation is not plugin-owned".into());
1115        }
1116        state.views[v].annotations.remove(a);
1117        self.submit_annotation_state(state, self.saved_plugin_pins()?, id.into(), true)
1118    }
1119
1120    pub fn plugin_set_annotation_enabled(
1121        &mut self,
1122        id: &str,
1123        enabled: bool,
1124    ) -> Result<u64, String> {
1125        self.require_plugin_editable()?;
1126        let mut state = self.pmi_state();
1127        let annotation = state
1128            .find_annotation_mut(id)
1129            .ok_or_else(|| format!("no PMI annotation '{id}'"))?;
1130        if !annotation.kind.contains('/') {
1131            return Err("annotation is not plugin-owned".into());
1132        }
1133        annotation.enabled = enabled;
1134        self.submit_annotation_state(state, self.saved_plugin_pins()?, id.into(), !enabled)
1135    }
1136
1137    fn submit_annotation_state(
1138        &mut self,
1139        state: brep_kernel::PmiState,
1140        pins: Vec<PluginPin>,
1141        annotation_id: String,
1142        repair: bool,
1143    ) -> Result<u64, String> {
1144        let mut pending = self.new_plugin_pending(pins.clone());
1145        if repair {
1146            let baseline = self.pmi_state();
1147            pending.allowed_annotation_errors = annotation_failures(self.pmi_report.as_ref())
1148                .into_iter()
1149                .filter(|failure| {
1150                    let old = baseline
1151                        .find_view(&failure.view_id)
1152                        .and_then(|v| v.annotations.iter().find(|a| a.id() == failure.id));
1153                    let survivor = state
1154                        .find_view(&failure.view_id)
1155                        .and_then(|v| v.annotations.iter().find(|a| a.id() == failure.id));
1156                    old.is_some() && old == survivor
1157                })
1158                .collect();
1159        }
1160        let id = pending.id;
1161        pending.annotation_id = Some(annotation_id);
1162        let mut staged = self.history.clone();
1163        staged.set_pmi_block_no_undo(Some(json!(state)));
1164        staged.set_document_block_no_undo("plugins", Some(json!(pins)));
1165        self.plugins.pending = Some(pending);
1166        if let Err(error) = self.submit_plugin_candidate(staged) {
1167            self.plugins.pending = None;
1168            return Err(error);
1169        }
1170        self.pump();
1171        Ok(id)
1172    }
1173}