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        self.revive_runner_if_down();
730        // Full delta means discarding an unsuccessful candidate cannot poison the display baseline.
731        self.runner.reset();
732        // A reset drops any answer still on its way.
733        self.session_requested = None;
734        self.sync_plugin_runner();
735        self.runner.sync_parts_library(
736            brep_kernel::parts_library_revision(),
737            &mut brep_kernel::parts_library_map,
738        );
739        self.runner.submit_run(request, self.run_generation);
740        Ok(())
741    }
742
743    /// Returns false when this candidate must be discarded, without applying its scene.
744    pub(super) fn accept_plugin_run(&mut self, reply: &crate::runner::RunReply) -> bool {
745        let Some(pending) = self.plugins.pending.as_ref() else {
746            return true;
747        };
748        if pending.staged.is_none() || pending.generation != reply.generation {
749            return true;
750        }
751        let valid = self.plugin_pending_valid(pending);
752        let mut pending = self.plugins.pending.take().unwrap();
753        let report = &reply.output.report;
754        let annotation_errors: Vec<_> = annotation_failures(report.pmi.as_ref())
755            .into_iter()
756            .filter(|failure| !pending.allowed_annotation_errors.contains(failure))
757            .map(|failure| format!("{}: {}", failure.id, failure.message))
758            .collect();
759        let result = if !valid {
760            Err("plugin transaction invalidated by a document or selection change".into())
761        } else if !report.feature_errors.is_empty()
762            || !report.unresolved.is_empty()
763            || !report.display_errors.is_empty()
764            || !annotation_errors.is_empty()
765        {
766            Err(format!(
767                "plugin transaction recompute failed: {}",
768                report
769                    .feature_errors
770                    .iter()
771                    .chain(&report.unresolved)
772                    .chain(&report.display_errors)
773                    .chain(&annotation_errors)
774                    .cloned()
775                    .collect::<Vec<_>>()
776                    .join("; ")
777            ))
778        } else {
779            fold_annotation_data(pending.staged.as_mut().unwrap(), report.pmi.as_ref());
780            self.history
781                .commit_staged(pending.staged.as_ref().unwrap())
782                .map(|_| json!({"id":pending.id,"notifications":pending.notifications,"annotationId":pending.annotation_id}))
783        };
784        let accepted = result.is_ok();
785        self.plugin_result(result);
786        if !accepted {
787            self.runner.reset();
788            // A reset drops any answer still on its way.
789            self.session_requested = None;
790            self.rerun_history();
791        }
792        accepted
793    }
794
795    /// Add package pins and features together so undo restores both.
796    pub(super) fn append_plugin_features(&mut self, features: &[Value]) -> Result<bool, String> {
797        if !features
798            .iter()
799            .any(|f| f["type"].as_str().is_some_and(|t| t.contains('/')))
800        {
801            return Ok(false);
802        }
803        if let Some(reason) = self.history.locked() {
804            return Err(format!("the document is read-only: {reason}"));
805        }
806        let mut pins = self.saved_plugin_pins()?;
807        for feature in features {
808            let ty = feature["type"].as_str().unwrap_or("");
809            if !ty.contains('/') {
810                continue;
811            }
812            let schema = self
813                .feature_schema(ty)
814                .ok_or_else(|| format!("plugin feature {ty} is unavailable"))?;
815            let pin: PluginPin =
816                serde_json::from_value(schema["package"].clone()).map_err(|e| e.to_string())?;
817            if !pins.iter().any(|p| p.id == pin.id) {
818                pins.push(pin);
819            }
820        }
821        let mut staged = self.history.clone();
822        staged.set_document_block_no_undo("plugins", Some(json!(pins)));
823        staged.push_features(features.to_vec());
824        staged.set_rollback(staged.len().saturating_sub(1));
825        self.history.commit_staged(&staged)?;
826        Ok(true)
827    }
828
829    pub(super) fn plugin_export_ready(&self) -> Result<(), String> {
830        fn uses_plugins(value: &Value) -> bool {
831            match value {
832                Value::Object(map) => {
833                    map.get("plugins")
834                        .and_then(Value::as_array)
835                        .is_some_and(|p| !p.is_empty())
836                        || map
837                            .get("type")
838                            .and_then(Value::as_str)
839                            .is_some_and(|ty| ty.contains('/'))
840                        || map.values().any(uses_plugins)
841                }
842                Value::Array(values) => values.iter().any(uses_plugins),
843                _ => false,
844            }
845        }
846        let document: Value =
847            serde_json::from_str(&self.history.request_json()).map_err(|e| e.to_string())?;
848        if !uses_plugins(&document) {
849            return Ok(());
850        }
851        if self.run_pending()
852            || self.plugins.pending.is_some()
853            || self.plugins.install_pending.is_some()
854        {
855            return Err("plugin geometry is pending; wait for recompute before export".into());
856        }
857        let annotation_errors = plugin_annotation_errors(self.pmi_report.as_ref());
858        if !annotation_errors.is_empty() {
859            return Err(format!(
860                "unavailable plugin annotations: {}",
861                annotation_errors.join("; ")
862            ));
863        }
864        let report: Value = serde_json::from_str(&self.history_report).unwrap_or(Value::Null);
865        if report.get("error").is_some()
866            || ["featureErrors", "unresolved", "displayErrors"]
867                .iter()
868                .any(|key| {
869                    report[*key]
870                        .as_array()
871                        .is_some_and(|items| !items.is_empty())
872                })
873        {
874            return Err("plugin document has failed or unavailable geometry; recompute successfully before export".into());
875        }
876        Ok(())
877    }
878
879    pub(super) fn plugin_resident_handles(
880        &self,
881        request: &brep_kernel::HistoryRequest,
882    ) -> Result<Vec<(String, u32)>, String> {
883        let result = self.execute_plugin_history(request);
884        let mut names = Vec::new();
885        let mut handles = std::collections::HashMap::new();
886        for feature in result.results {
887            if let Some(error) = feature.error {
888                return Err(format!("{}: {error}", feature.id));
889            }
890            for removed in feature.removed {
891                handles.remove(&removed);
892                names.retain(|n| n != &removed);
893            }
894            for added in feature.added {
895                if handles.insert(added.name.clone(), added.handle).is_none() {
896                    names.push(added.name);
897                }
898            }
899        }
900        Ok(names
901            .into_iter()
902            .map(|name| {
903                let handle = handles[&name];
904                (name, handle)
905            })
906            .collect())
907    }
908
909    pub(super) fn inherit_plugins(&mut self, parent: &Self) {
910        self.plugins.packages = parent.plugins.packages.clone();
911        self.plugins.runtime = parent.plugins.runtime.clone();
912        self.plugins.revision = parent.plugins.revision;
913    }
914
915    pub(super) fn with_plugin_provider<R>(&self, f: impl FnOnce() -> R) -> R {
916        match &self.plugins.runtime {
917            Some(runtime) => runtime.with_provider(f),
918            None => f(),
919        }
920    }
921
922    pub(super) fn execute_plugin_history(
923        &self,
924        request: &brep_kernel::HistoryRequest,
925    ) -> brep_kernel::HistoryResult {
926        match &self.plugins.runtime {
927            Some(runtime) => runtime.execute_history(request),
928            None => brep_kernel::execute_history(request),
929        }
930    }
931
932    pub(super) fn run_plugin_scene(
933        &mut self,
934        request: &brep_kernel::HistoryRequest,
935    ) -> Result<crate::pipeline::SceneBuildReport, String> {
936        match &self.plugins.runtime {
937            Some(runtime) => runtime.with_provider(|| {
938                crate::pipeline::update_scene_from_history(&mut self.scene, request)
939            }),
940            None => crate::pipeline::update_scene_from_history(&mut self.scene, request),
941        }
942    }
943}
944
945
946/// The exact error identity used by repair transactions. Other operations stay strict.
947#[derive(Clone, Debug, PartialEq, Eq)]
948struct AnnotationFailure {
949    view_id: String,
950    id: String,
951    kind: String,
952    message: String,
953}
954
955fn annotation_failures(report: Option<&brep_kernel::PmiReport>) -> Vec<AnnotationFailure> {
956    report
957        .into_iter()
958        .flat_map(|r| &r.views)
959        .flat_map(|view| {
960            view.annotations
961                .iter()
962                .filter(|a| {
963                    a.enabled && a.kind.contains('/') && a.status == brep_kernel::PmiStatus::Error
964                })
965                .map(|a| AnnotationFailure {
966                    view_id: view.id.clone(),
967                    id: a.id.clone(),
968                    kind: a.kind.clone(),
969                    message: a.message.clone(),
970                })
971        })
972        .collect()
973}
974
975/// Even tolerated repair errors continue to block exports.
976pub(super) fn plugin_annotation_errors(report: Option<&brep_kernel::PmiReport>) -> Vec<String> {
977    annotation_failures(report)
978        .into_iter()
979        .map(|a| format!("{}: {}", a.id, a.message))
980        .collect()
981}
982
983fn fold_annotation_data(history: &mut History, report: Option<&brep_kernel::PmiReport>) {
984    let Some(block) = history.pmi_block() else {
985        return;
986    };
987    let Ok(mut state) = serde_json::from_value::<brep_kernel::PmiState>(block.clone()) else {
988        return;
989    };
990    let mut changed = false;
991    for row in report
992        .into_iter()
993        .flat_map(|r| &r.views)
994        .flat_map(|v| &v.annotations)
995    {
996        if row.status != brep_kernel::PmiStatus::Ok || !row.kind.contains('/') {
997            continue;
998        }
999        if let (Some(data), Some(annotation)) =
1000            (&row.persistent_data, state.find_annotation_mut(&row.id))
1001        {
1002            if annotation.kind == row.kind
1003                && (annotation.persistent_data != *data
1004                    || annotation.plugin_replay != row.plugin_replay)
1005            {
1006                annotation.persistent_data = data.clone();
1007                annotation.plugin_replay = row.plugin_replay.clone();
1008                changed = true;
1009            }
1010        }
1011    }
1012    if changed {
1013        history.set_pmi_block_no_undo(Some(json!(state)));
1014    }
1015}
1016
1017impl EngineState {
1018    pub fn plugin_panels(&self) -> Value {
1019        self.plugin_catalogue()["panels"].clone()
1020    }
1021
1022    pub fn plugin_annotation_catalogue(&self) -> Value {
1023        self.plugin_catalogue()["annotations"].clone()
1024    }
1025
1026    /// Built-ins and document-scoped providers share the normal annotation form shape.
1027    pub fn annotation_schema(&self, kind: &str) -> Option<Value> {
1028        brep_kernel::pmi_type(kind)
1029            .map(|d| (d.schema)())
1030            .or_else(|| {
1031                self.plugin_annotation_catalogue()
1032                    .as_array()?
1033                    .iter()
1034                    .find(|a| a["type"] == kind)
1035                    .cloned()
1036            })
1037    }
1038
1039    pub(super) fn fold_plugin_annotation_data(&mut self) {
1040        if self.expression_preview.is_none() {
1041            fold_annotation_data(&mut self.history, self.pmi_report.as_ref());
1042        }
1043    }
1044
1045    pub fn plugin_add_annotation(
1046        &mut self,
1047        view_id: &str,
1048        kind: &str,
1049        mut params: Value,
1050    ) -> Result<u64, String> {
1051        self.require_plugin_editable()?;
1052        let schema = self
1053            .plugin_annotation_catalogue()
1054            .as_array()
1055            .into_iter()
1056            .flatten()
1057            .find(|s| s["type"] == kind)
1058            .cloned()
1059            .ok_or_else(|| format!("unavailable plugin annotation {kind}"))?;
1060        if !params.is_object() {
1061            return Err("annotation parameters must be an object".into());
1062        }
1063        let mut state = self.pmi_state();
1064        let id = state.next_id("ANN");
1065        params["id"] = json!(id);
1066        state
1067            .find_view_mut(view_id)
1068            .ok_or_else(|| format!("no PMI view '{view_id}'"))?
1069            .annotations
1070            .push(brep_kernel::PmiAnnotation {
1071                kind: kind.into(),
1072                enabled: true,
1073                params,
1074                persistent_data: Value::Null,
1075                plugin_replay: None,
1076                label_world: None,
1077            });
1078        let pin: PluginPin =
1079            serde_json::from_value(schema["package"].clone()).map_err(|e| e.to_string())?;
1080        let mut pins = self.saved_plugin_pins()?;
1081        if let Some(old) = pins.iter().find(|p| p.id == pin.id) {
1082            if old != &pin {
1083                return Err("annotation package does not match document pin".into());
1084            }
1085        } else {
1086            pins.push(pin);
1087        }
1088        self.submit_annotation_state(state, pins, id, false)
1089    }
1090
1091    pub fn plugin_update_annotation(&mut self, id: &str, mut params: Value) -> Result<u64, String> {
1092        self.require_plugin_editable()?;
1093        if !params.is_object() {
1094            return Err("annotation parameters must be an object".into());
1095        }
1096        let mut state = self.pmi_state();
1097        let annotation = state
1098            .find_annotation_mut(id)
1099            .ok_or_else(|| format!("no PMI annotation '{id}'"))?;
1100        if !annotation.kind.contains('/') {
1101            return Err("annotation is not plugin-owned".into());
1102        }
1103        params["id"] = json!(id);
1104        annotation.params = params;
1105        self.submit_annotation_state(state, self.saved_plugin_pins()?, id.into(), false)
1106    }
1107
1108    pub fn plugin_delete_annotation(&mut self, id: &str) -> Result<u64, String> {
1109        self.require_plugin_editable()?;
1110        let mut state = self.pmi_state();
1111        let (v, a) = state
1112            .locate_annotation(id)
1113            .ok_or_else(|| format!("no PMI annotation '{id}'"))?;
1114        if !state.views[v].annotations[a].kind.contains('/') {
1115            return Err("annotation is not plugin-owned".into());
1116        }
1117        state.views[v].annotations.remove(a);
1118        self.submit_annotation_state(state, self.saved_plugin_pins()?, id.into(), true)
1119    }
1120
1121    pub fn plugin_set_annotation_enabled(
1122        &mut self,
1123        id: &str,
1124        enabled: bool,
1125    ) -> Result<u64, String> {
1126        self.require_plugin_editable()?;
1127        let mut state = self.pmi_state();
1128        let annotation = state
1129            .find_annotation_mut(id)
1130            .ok_or_else(|| format!("no PMI annotation '{id}'"))?;
1131        if !annotation.kind.contains('/') {
1132            return Err("annotation is not plugin-owned".into());
1133        }
1134        annotation.enabled = enabled;
1135        self.submit_annotation_state(state, self.saved_plugin_pins()?, id.into(), !enabled)
1136    }
1137
1138    fn submit_annotation_state(
1139        &mut self,
1140        state: brep_kernel::PmiState,
1141        pins: Vec<PluginPin>,
1142        annotation_id: String,
1143        repair: bool,
1144    ) -> Result<u64, String> {
1145        let mut pending = self.new_plugin_pending(pins.clone());
1146        if repair {
1147            let baseline = self.pmi_state();
1148            pending.allowed_annotation_errors = annotation_failures(self.pmi_report.as_ref())
1149                .into_iter()
1150                .filter(|failure| {
1151                    let old = baseline
1152                        .find_view(&failure.view_id)
1153                        .and_then(|v| v.annotations.iter().find(|a| a.id() == failure.id));
1154                    let survivor = state
1155                        .find_view(&failure.view_id)
1156                        .and_then(|v| v.annotations.iter().find(|a| a.id() == failure.id));
1157                    old.is_some() && old == survivor
1158                })
1159                .collect();
1160        }
1161        let id = pending.id;
1162        pending.annotation_id = Some(annotation_id);
1163        let mut staged = self.history.clone();
1164        staged.set_pmi_block_no_undo(Some(json!(state)));
1165        staged.set_document_block_no_undo("plugins", Some(json!(pins)));
1166        self.plugins.pending = Some(pending);
1167        if let Err(error) = self.submit_plugin_candidate(staged) {
1168            self.plugins.pending = None;
1169            return Err(error);
1170        }
1171        self.pump();
1172        Ok(id)
1173    }
1174}