gpui-rhai 0.2.1

A Rhai-authored declarative UI runtime for GPUI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
use std::collections::btree_map::Entry;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::sync::mpsc::Receiver;

use semver::{Version, VersionReq};
use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::{ModuleId, RUNTIME_API_VERSION, SchemaValidationError, UiValue, ValueSchema};

#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct CapabilityId(String);

impl CapabilityId {
    /// Parse a namespaced capability identifier such as `app.settings`.
    ///
    /// # Errors
    ///
    /// Returns [`CapabilityError::InvalidId`] for invalid identifiers.
    pub fn parse(value: impl Into<String>) -> Result<Self, CapabilityError> {
        let value = value.into();
        if value
            .split_once('.')
            .is_some_and(|(namespace, name)| is_identifier(namespace) && is_identifier(name))
        {
            Ok(Self(value))
        } else {
            Err(CapabilityError::InvalidId(value))
        }
    }

    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl TryFrom<String> for CapabilityId {
    type Error = CapabilityError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::parse(value)
    }
}

impl From<CapabilityId> for String {
    fn from(value: CapabilityId) -> Self {
        value.0
    }
}

fn is_identifier(value: &str) -> bool {
    !value.is_empty()
        && !value.starts_with('_')
        && !value.ends_with('_')
        && !value.contains("__")
        && value.chars().all(|character| {
            character.is_ascii_lowercase() || character.is_ascii_digit() || character == '_'
        })
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CapabilityMethod {
    pub input: ValueSchema,
    pub output: ValueSchema,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CapabilityDescriptor {
    pub id: CapabilityId,
    pub version: Version,
    pub methods: BTreeMap<String, CapabilityMethod>,
}

/// What a script invocation runs in response to.
///
/// The runtime sets it on each dispatch path; script code called from that
/// callback (including component events it emits and the render it causes)
/// shares it. Work that completes later carries the root that started it.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub enum InvocationOrigin {
    /// A platform input event dispatched to the view (`click`, `pointer_down`,
    /// `key_down`, ...), a Host key-binding action, or a window close.
    UserInput { event: String },
    /// An automation command (`AutomationCommand::Dispatch`, `Action`, ...).
    Automation,
    /// A timer that the root origin scheduled.
    Timer { started_by: Box<InvocationOrigin> },
    /// A task or asset load completing; `started_by` is the root origin.
    TaskCompletion { started_by: Box<InvocationOrigin> },
    /// A subscription delivering a value.
    Subscription,
    /// An effect's start or cleanup, or a motion timeline callback.
    Effect,
    /// Initialization, suspend, resume, reload or disposal.
    #[default]
    Lifecycle,
}

impl InvocationOrigin {
    /// The origin with timers and task completions followed back to what
    /// started them.
    #[must_use]
    pub fn root(&self) -> &Self {
        match self {
            Self::Timer { started_by } | Self::TaskCompletion { started_by } => started_by.root(),
            other => other,
        }
    }

    /// Whether the root origin is user input: the signal a Host gates
    /// user-activated capabilities on.
    #[must_use]
    pub fn is_user_input(&self) -> bool {
        matches!(self.root(), Self::UserInput { .. })
    }
}

/// The context of one capability call.
#[derive(Clone, Debug, PartialEq)]
pub struct InvocationContext {
    pub origin: InvocationOrigin,
    /// The view whose script made the call, when it runs in one.
    pub view_id: Option<String>,
    /// The component instance that made the call.
    pub component: crate::ComponentInstancePath,
}

impl InvocationContext {
    /// The context of a call the Host makes directly through the registry:
    /// `Lifecycle`, no view, the root component.
    fn host() -> Self {
        Self {
            origin: InvocationOrigin::default(),
            view_id: None,
            component: crate::ComponentInstancePath::root("App", "root"),
        }
    }
}

pub trait CapabilityHandler {
    /// Execute a schema-validated capability method.
    ///
    /// # Errors
    ///
    /// Returns a human-readable handler error. The registry validates the
    /// returned value against the declared output schema.
    fn call(&mut self, method: &str, input: UiValue) -> Result<UiValue, String>;

    /// Execute a method with the context of the call: what it runs in
    /// response to, the view and the component. Override it to gate a method
    /// on user input (`context.origin.is_user_input()`); the default forwards
    /// to [`Self::call`].
    ///
    /// # Errors
    ///
    /// As [`Self::call`].
    fn call_with(
        &mut self,
        context: &InvocationContext,
        method: &str,
        input: UiValue,
    ) -> Result<UiValue, String> {
        let _ = context;
        self.call(method, input)
    }
}

pub struct TaskWork {
    work: Box<dyn FnOnce(crate::TaskCancellation) -> Result<UiValue, String> + Send + 'static>,
}

impl TaskWork {
    #[must_use]
    pub fn new(work: impl FnOnce() -> Result<UiValue, String> + Send + 'static) -> Self {
        Self {
            work: Box::new(move |_| work()),
        }
    }

    #[must_use]
    pub fn cancellable(
        work: impl FnOnce(crate::TaskCancellation) -> Result<UiValue, String> + Send + 'static,
    ) -> Self {
        Self {
            work: Box::new(work),
        }
    }

    pub(crate) fn run(self, cancellation: crate::TaskCancellation) -> Result<UiValue, String> {
        (self.work)(cancellation)
    }
}

pub trait AsyncCapabilityHandler {
    /// Build one-shot background work after input validation.
    ///
    /// # Errors
    ///
    /// Returns a human-readable setup error before a task is spawned.
    fn start(&mut self, method: &str, input: UiValue) -> Result<TaskWork, String>;

    /// Build the work with the context of the call that starts the task, as
    /// [`CapabilityHandler::call_with`] receives it. Override it to gate work
    /// on user input before it runs (`context.origin.is_user_input()`); the
    /// default forwards to [`Self::start`].
    ///
    /// # Errors
    ///
    /// As [`Self::start`].
    fn start_with(
        &mut self,
        context: &InvocationContext,
        method: &str,
        input: UiValue,
    ) -> Result<TaskWork, String> {
        let _ = context;
        self.start(method, input)
    }
}

/// One continuous subscription producer.
///
/// The work owns the producer loop and should not return until the stream is
/// finished. Returning closes the subscription and invalidates every cloned
/// [`crate::SubscriptionEmitter`] with
/// [`crate::SubscriptionCloseReason::WorkReturned`].
pub struct SubscriptionWork {
    work: Box<dyn FnOnce(crate::SubscriptionEmitter) + Send + 'static>,
}

impl SubscriptionWork {
    /// Build a subscription from its complete blocking producer loop.
    #[must_use]
    pub fn new(work: impl FnOnce(crate::SubscriptionEmitter) + Send + 'static) -> Self {
        Self {
            work: Box::new(work),
        }
    }

    /// Forward values from a channel until its senders are dropped or the
    /// subscription is closed.
    #[must_use]
    pub fn from_receiver(receiver: Receiver<UiValue>) -> Self {
        Self::new(move |emitter| {
            loop {
                if emitter.close_reason().is_some() {
                    break;
                }
                match receiver.recv_timeout(std::time::Duration::from_millis(50)) {
                    Ok(value) => {
                        if emitter.emit_blocking(value).is_err() {
                            break;
                        }
                    }
                    Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,
                    Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
                }
            }
        })
    }

    pub(crate) fn run(self, emitter: crate::SubscriptionEmitter) {
        (self.work)(emitter);
    }
}

pub trait SubscriptionCapabilityHandler {
    /// Build continuous producer work after input validation.
    ///
    /// The returned [`SubscriptionWork`] is the producer loop. It must remain
    /// running for as long as external code may use the emitter; returning from
    /// it closes the subscription immediately.
    ///
    /// # Errors
    ///
    /// Returns a human-readable setup error before subscription startup.
    fn subscribe(&mut self, method: &str, input: UiValue) -> Result<SubscriptionWork, String>;

    /// Build the producer with the context of the call that starts the
    /// subscription: an effect start, with its view and component. The
    /// default forwards to [`Self::subscribe`].
    ///
    /// # Errors
    ///
    /// As [`Self::subscribe`].
    fn subscribe_with(
        &mut self,
        context: &InvocationContext,
        method: &str,
        input: UiValue,
    ) -> Result<SubscriptionWork, String> {
        let _ = context;
        self.subscribe(method, input)
    }
}

struct CapabilityEntry {
    descriptor: CapabilityDescriptor,
    sync: Option<Box<dyn CapabilityHandler>>,
    task: Option<Box<dyn AsyncCapabilityHandler>>,
    subscription: Option<Box<dyn SubscriptionCapabilityHandler>>,
}

#[derive(Default)]
pub struct CapabilityRegistry {
    entries: BTreeMap<CapabilityId, CapabilityEntry>,
    active: BTreeSet<CapabilityId>,
}

impl fmt::Debug for CapabilityRegistry {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CapabilityRegistry")
            .field("registered", &self.entries.keys().collect::<Vec<_>>())
            .field("active", &self.active)
            .finish()
    }
}

impl CapabilityRegistry {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a host implementation and its public schema.
    ///
    /// # Errors
    ///
    /// Returns [`CapabilityError`] for duplicate IDs, empty method sets, or
    /// invalid method names.
    pub fn register(
        &mut self,
        descriptor: CapabilityDescriptor,
        handler: impl CapabilityHandler + 'static,
    ) -> Result<(), CapabilityError> {
        validate_descriptor(&descriptor)?;
        let entry = self.entry_for_descriptor(descriptor)?;
        if entry.sync.is_some() {
            return Err(CapabilityError::DuplicateMode("sync"));
        }
        entry.sync = Some(Box::new(handler));
        Ok(())
    }

    /// Register one-shot task methods for a capability descriptor.
    ///
    /// # Errors
    ///
    /// Returns descriptor or duplicate-mode errors.
    pub fn register_async(
        &mut self,
        descriptor: CapabilityDescriptor,
        handler: impl AsyncCapabilityHandler + 'static,
    ) -> Result<(), CapabilityError> {
        validate_descriptor(&descriptor)?;
        let entry = self.entry_for_descriptor(descriptor)?;
        if entry.task.is_some() {
            return Err(CapabilityError::DuplicateMode("task"));
        }
        entry.task = Some(Box::new(handler));
        Ok(())
    }

    /// Register continuous subscription methods for a capability descriptor.
    ///
    /// # Errors
    ///
    /// Returns descriptor or duplicate-mode errors.
    pub fn register_subscription(
        &mut self,
        descriptor: CapabilityDescriptor,
        handler: impl SubscriptionCapabilityHandler + 'static,
    ) -> Result<(), CapabilityError> {
        validate_descriptor(&descriptor)?;
        let entry = self.entry_for_descriptor(descriptor)?;
        if entry.subscription.is_some() {
            return Err(CapabilityError::DuplicateMode("subscription"));
        }
        entry.subscription = Some(Box::new(handler));
        Ok(())
    }

    fn entry_for_descriptor(
        &mut self,
        descriptor: CapabilityDescriptor,
    ) -> Result<&mut CapabilityEntry, CapabilityError> {
        let id = descriptor.id.clone();
        match self.entries.entry(id.clone()) {
            Entry::Vacant(entry) => Ok(entry.insert(CapabilityEntry {
                descriptor,
                sync: None,
                task: None,
                subscription: None,
            })),
            Entry::Occupied(entry) => {
                if entry.get().descriptor == descriptor {
                    Ok(entry.into_mut())
                } else {
                    Err(CapabilityError::DescriptorMismatch(id))
                }
            }
        }
    }

    /// Validate and activate exactly the capabilities declared by an app.
    ///
    /// # Errors
    ///
    /// Returns [`CapabilityError::Missing`] or
    /// [`CapabilityError::VersionMismatch`].
    pub fn activate(
        &mut self,
        requirements: &BTreeMap<CapabilityId, VersionReq>,
    ) -> Result<(), CapabilityError> {
        let mut active = BTreeSet::new();
        for (id, requirement) in requirements {
            let entry = self
                .entries
                .get(id)
                .ok_or_else(|| CapabilityError::Missing(id.clone()))?;
            if !requirement.matches(&entry.descriptor.version) {
                return Err(CapabilityError::VersionMismatch {
                    id: id.clone(),
                    required: requirement.clone(),
                    actual: entry.descriptor.version.clone(),
                });
            }
            active.insert(id.clone());
        }
        self.active = active;
        Ok(())
    }

    /// Invoke an activated method through schema validation on both sides.
    ///
    /// # Errors
    ///
    /// Returns [`CapabilityError`] for undeclared access, unknown methods,
    /// invalid values, or a handler failure.
    pub fn call(
        &mut self,
        id: &CapabilityId,
        method: &str,
        input: UiValue,
    ) -> Result<UiValue, CapabilityError> {
        self.call_with(&InvocationContext::host(), id, method, input)
    }

    /// Invoke an activated method with the context of the call.
    ///
    /// # Errors
    ///
    /// As [`Self::call`].
    pub fn call_with(
        &mut self,
        context: &InvocationContext,
        id: &CapabilityId,
        method: &str,
        input: UiValue,
    ) -> Result<UiValue, CapabilityError> {
        if !self.active.contains(id) {
            return Err(CapabilityError::NotDeclared(id.clone()));
        }
        let entry = self
            .entries
            .get_mut(id)
            .ok_or_else(|| CapabilityError::Missing(id.clone()))?;
        let schema = entry
            .descriptor
            .methods
            .get(method)
            .cloned()
            .ok_or_else(|| CapabilityError::UnknownMethod {
                id: id.clone(),
                method: method.to_owned(),
            })?;
        schema
            .input
            .validate_ui_value(&input)
            .map_err(|source| CapabilityError::InvalidInput {
                id: id.clone(),
                method: method.to_owned(),
                source,
            })?;
        let handler = entry
            .sync
            .as_mut()
            .ok_or(CapabilityError::UnsupportedMode("sync"))?;
        let output = handler
            .call_with(context, method, input)
            .map_err(|message| CapabilityError::Handler {
                id: id.clone(),
                method: method.to_owned(),
                message,
            })?;
        schema.output.validate_ui_value(&output).map_err(|source| {
            CapabilityError::InvalidOutput {
                id: id.clone(),
                method: method.to_owned(),
                source,
            }
        })?;
        Ok(output)
    }

    /// Build schema-validated one-shot work for the task registry.
    ///
    /// # Errors
    ///
    /// Returns capability access, schema, mode, or handler setup errors.
    pub fn start_task(
        &mut self,
        id: &CapabilityId,
        method: &str,
        input: UiValue,
    ) -> Result<(TaskWork, ValueSchema), CapabilityError> {
        self.start_task_with(&InvocationContext::host(), id, method, input)
    }

    /// Build one-shot work with the context of the call that starts it.
    ///
    /// # Errors
    ///
    /// As [`Self::start_task`].
    pub fn start_task_with(
        &mut self,
        context: &InvocationContext,
        id: &CapabilityId,
        method: &str,
        input: UiValue,
    ) -> Result<(TaskWork, ValueSchema), CapabilityError> {
        let (entry, schema) = self.entry_and_method(id, method, &input)?;
        let handler = entry
            .task
            .as_mut()
            .ok_or(CapabilityError::UnsupportedMode("task"))?;
        let work = handler
            .start_with(context, method, input)
            .map_err(|message| CapabilityError::Handler {
                id: id.clone(),
                method: method.to_owned(),
                message,
            })?;
        Ok((work, schema.output))
    }

    /// Build schema-validated continuous work for the subscription registry.
    ///
    /// # Errors
    ///
    /// Returns capability access, schema, mode, or handler setup errors.
    pub fn start_subscription(
        &mut self,
        id: &CapabilityId,
        method: &str,
        input: UiValue,
    ) -> Result<(SubscriptionWork, ValueSchema), CapabilityError> {
        self.start_subscription_with(&InvocationContext::host(), id, method, input)
    }

    /// Build continuous work with the context of the call that starts it.
    ///
    /// # Errors
    ///
    /// As [`Self::start_subscription`].
    pub fn start_subscription_with(
        &mut self,
        context: &InvocationContext,
        id: &CapabilityId,
        method: &str,
        input: UiValue,
    ) -> Result<(SubscriptionWork, ValueSchema), CapabilityError> {
        let (entry, schema) = self.entry_and_method(id, method, &input)?;
        let handler = entry
            .subscription
            .as_mut()
            .ok_or(CapabilityError::UnsupportedMode("subscription"))?;
        let work = handler
            .subscribe_with(context, method, input)
            .map_err(|message| CapabilityError::Handler {
                id: id.clone(),
                method: method.to_owned(),
                message,
            })?;
        Ok((work, schema.output))
    }

    fn entry_and_method(
        &mut self,
        id: &CapabilityId,
        method: &str,
        input: &UiValue,
    ) -> Result<(&mut CapabilityEntry, CapabilityMethod), CapabilityError> {
        if !self.active.contains(id) {
            return Err(CapabilityError::NotDeclared(id.clone()));
        }
        let entry = self
            .entries
            .get_mut(id)
            .ok_or_else(|| CapabilityError::Missing(id.clone()))?;
        let schema = entry
            .descriptor
            .methods
            .get(method)
            .cloned()
            .ok_or_else(|| CapabilityError::UnknownMethod {
                id: id.clone(),
                method: method.to_owned(),
            })?;
        schema
            .input
            .validate_ui_value(input)
            .map_err(|source| CapabilityError::InvalidInput {
                id: id.clone(),
                method: method.to_owned(),
                source,
            })?;
        Ok((entry, schema))
    }
}

fn validate_descriptor(descriptor: &CapabilityDescriptor) -> Result<(), CapabilityError> {
    if descriptor.methods.is_empty() {
        return Err(CapabilityError::NoMethods(descriptor.id.clone()));
    }
    if let Some(method) = descriptor
        .methods
        .keys()
        .find(|method| !is_identifier(method))
    {
        return Err(CapabilityError::InvalidMethod(method.clone()));
    }
    Ok(())
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AppManifest {
    pub entry: ModuleId,
    pub runtime_api: u32,
    #[serde(default)]
    pub capabilities: BTreeMap<CapabilityId, VersionReq>,
}

impl AppManifest {
    #[must_use]
    pub fn new(entry: ModuleId) -> Self {
        Self {
            entry,
            runtime_api: RUNTIME_API_VERSION,
            capabilities: BTreeMap::new(),
        }
    }

    /// Add one namespaced capability requirement from generated or host code.
    ///
    /// # Errors
    ///
    /// Returns identifier or semantic-version requirement parse errors.
    pub fn with_capability(mut self, id: &str, requirement: &str) -> Result<Self, CapabilityError> {
        let id = CapabilityId::parse(id)?;
        let requirement = VersionReq::parse(requirement).map_err(|source| {
            CapabilityError::InvalidVersionRequirement {
                requirement: requirement.to_owned(),
                source,
            }
        })?;
        self.capabilities.insert(id, requirement);
        Ok(self)
    }

    /// Validate runtime compatibility and activate declared capabilities.
    ///
    /// # Errors
    ///
    /// Returns [`CapabilityError::RuntimeApiMismatch`] or an activation error.
    pub fn activate(&self, registry: &mut CapabilityRegistry) -> Result<(), CapabilityError> {
        if self.runtime_api != RUNTIME_API_VERSION {
            return Err(CapabilityError::RuntimeApiMismatch {
                required: self.runtime_api,
                actual: RUNTIME_API_VERSION,
            });
        }
        registry.activate(&self.capabilities)
    }

    /// Verify that every installed component capability is explicitly declared
    /// by the application with the same compatibility requirement.
    ///
    /// # Errors
    ///
    /// Returns missing or mismatched component capability declarations.
    pub fn validate_components(
        &self,
        components: &crate::ComponentRegistry,
    ) -> Result<(), CapabilityError> {
        for (component_id, component) in components.iter() {
            for (raw_id, required) in &component.metadata.capabilities {
                let id = CapabilityId::parse(raw_id)?;
                let Some(declared) = self.capabilities.get(&id) else {
                    return Err(CapabilityError::ComponentCapabilityMissing {
                        component: component_id.clone(),
                        capability: id,
                    });
                };
                if declared != required {
                    return Err(CapabilityError::ComponentCapabilityMismatch {
                        component: component_id.clone(),
                        capability: id,
                        component_required: required.clone(),
                        app_declared: declared.clone(),
                    });
                }
            }
        }
        Ok(())
    }
}

#[derive(Debug, Error)]
pub enum CapabilityError {
    #[error("capability ID `{0}` must be a namespaced `snake_case` identifier")]
    InvalidId(String),
    #[error("invalid capability version requirement `{requirement}`: {source}")]
    InvalidVersionRequirement {
        requirement: String,
        #[source]
        source: semver::Error,
    },
    #[error("capability `{0:?}` was registered with conflicting descriptors")]
    DescriptorMismatch(CapabilityId),
    #[error("capability handler mode `{0}` is already registered")]
    DuplicateMode(&'static str),
    #[error("capability does not implement `{0}` mode")]
    UnsupportedMode(&'static str),
    #[error("capability `{0:?}` must declare at least one method")]
    NoMethods(CapabilityId),
    #[error("capability method `{0}` must be a `snake_case` identifier")]
    InvalidMethod(String),
    #[error("required capability `{0:?}` is not registered")]
    Missing(CapabilityId),
    #[error("capability `{id:?}` requires {required}, host provides {actual}")]
    VersionMismatch {
        id: CapabilityId,
        required: VersionReq,
        actual: Version,
    },
    #[error("capability `{0:?}` was not declared by the application manifest")]
    NotDeclared(CapabilityId),
    #[error("capability `{id:?}` has no method `{method}`")]
    UnknownMethod { id: CapabilityId, method: String },
    #[error("input for `{id:?}.{method}` is invalid: {source}")]
    InvalidInput {
        id: CapabilityId,
        method: String,
        source: SchemaValidationError,
    },
    #[error("output from `{id:?}.{method}` is invalid: {source}")]
    InvalidOutput {
        id: CapabilityId,
        method: String,
        source: SchemaValidationError,
    },
    #[error("capability `{id:?}.{method}` failed: {message}")]
    Handler {
        id: CapabilityId,
        method: String,
        message: String,
    },
    #[error("application requires runtime API {required}, current API is {actual}")]
    RuntimeApiMismatch { required: u32, actual: u32 },
    #[error(
        "component `{component}` requires capability `{capability:?}` missing from the app manifest"
    )]
    ComponentCapabilityMissing {
        component: ModuleId,
        capability: CapabilityId,
    },
    #[error(
        "component `{component}` requires capability `{capability:?}` at {component_required}, but the app declares {app_declared}"
    )]
    ComponentCapabilityMismatch {
        component: ModuleId,
        capability: CapabilityId,
        component_required: VersionReq,
        app_declared: VersionReq,
    },
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        ComponentDefinition, ComponentMetadata, ComponentRegistry, ComponentSchema, RuntimeApiRange,
    };

    struct Echo;

    impl CapabilityHandler for Echo {
        fn call(&mut self, method: &str, input: UiValue) -> Result<UiValue, String> {
            if method == "echo" {
                Ok(input)
            } else {
                Err("unexpected method".to_owned())
            }
        }
    }

    struct AsyncEcho;

    impl AsyncCapabilityHandler for AsyncEcho {
        fn start(&mut self, method: &str, input: UiValue) -> Result<TaskWork, String> {
            if method == "echo" {
                Ok(TaskWork::new(move || Ok(input)))
            } else {
                Err("unexpected method".to_owned())
            }
        }
    }

    fn descriptor() -> CapabilityDescriptor {
        CapabilityDescriptor {
            id: CapabilityId::parse("app.echo").unwrap(),
            version: Version::new(1, 2, 0),
            methods: BTreeMap::from([(
                "echo".to_owned(),
                CapabilityMethod {
                    input: ValueSchema::string(),
                    output: ValueSchema::string(),
                },
            )]),
        }
    }

    #[test]
    fn manifest_controls_capability_access_and_versions() {
        let mut registry = CapabilityRegistry::new();
        registry.register(descriptor(), Echo).unwrap();
        assert!(matches!(
            registry.call(
                &CapabilityId::parse("app.echo").unwrap(),
                "echo",
                UiValue::String("no".to_owned()),
            ),
            Err(CapabilityError::NotDeclared(_))
        ));

        let manifest = AppManifest {
            entry: ModuleId::parse("main").unwrap(),
            runtime_api: RUNTIME_API_VERSION,
            capabilities: BTreeMap::from([(
                CapabilityId::parse("app.echo").unwrap(),
                VersionReq::parse("^1.0").unwrap(),
            )]),
        };
        manifest.activate(&mut registry).unwrap();
        assert_eq!(
            registry
                .call(
                    &CapabilityId::parse("app.echo").unwrap(),
                    "echo",
                    UiValue::String("yes".to_owned()),
                )
                .unwrap(),
            UiValue::String("yes".to_owned())
        );
    }

    #[test]
    fn manifest_must_cover_component_capability_requirements() {
        let component = ComponentDefinition::new(
            ComponentMetadata {
                id: ModuleId::parse("components/remote_status").unwrap(),
                export: "RemoteStatus".to_owned(),
                version: Version::new(0, 1, 0),
                runtime_api: RuntimeApiRange::new(3, 4),
                dependencies: BTreeSet::new(),
                capabilities: BTreeMap::from([(
                    "app.echo".to_owned(),
                    VersionReq::parse("^1.0").unwrap(),
                )]),
                assets: BTreeSet::new(),
                tokens: std::collections::BTreeSet::new(),
                environment: std::collections::BTreeSet::new(),
            },
            ComponentSchema::default(),
        )
        .unwrap();
        let mut components = ComponentRegistry::new();
        components.register(component, RUNTIME_API_VERSION).unwrap();
        let missing = AppManifest::new(ModuleId::parse("main").unwrap());
        assert!(matches!(
            missing.validate_components(&components),
            Err(CapabilityError::ComponentCapabilityMissing { .. })
        ));
        let declared = missing.with_capability("app.echo", "^1.0").unwrap();
        declared.validate_components(&components).unwrap();
    }

    #[test]
    fn output_is_validated_even_for_rust_handlers() {
        struct BadOutput;
        impl CapabilityHandler for BadOutput {
            fn call(&mut self, _: &str, _: UiValue) -> Result<UiValue, String> {
                Ok(UiValue::Bool(true))
            }
        }
        let mut registry = CapabilityRegistry::new();
        registry.register(descriptor(), BadOutput).unwrap();
        registry
            .activate(&BTreeMap::from([(
                CapabilityId::parse("app.echo").unwrap(),
                VersionReq::STAR,
            )]))
            .unwrap();
        assert!(matches!(
            registry.call(
                &CapabilityId::parse("app.echo").unwrap(),
                "echo",
                UiValue::String("input".to_owned()),
            ),
            Err(CapabilityError::InvalidOutput { .. })
        ));
    }

    #[test]
    fn async_handler_builds_validated_worker_without_moving_rhai_callbacks() {
        let mut registry = CapabilityRegistry::new();
        registry.register_async(descriptor(), AsyncEcho).unwrap();
        registry
            .activate(&BTreeMap::from([(
                CapabilityId::parse("app.echo").unwrap(),
                VersionReq::STAR,
            )]))
            .unwrap();
        let (work, output) = registry
            .start_task(
                &CapabilityId::parse("app.echo").unwrap(),
                "echo",
                UiValue::String("async".to_owned()),
            )
            .unwrap();
        let value = work.run(crate::TaskCancellation::default()).unwrap();
        output.validate_ui_value(&value).unwrap();
        assert_eq!(value, UiValue::String("async".to_owned()));
    }

    #[test]
    fn task_and_subscription_starts_receive_the_invocation_context() {
        type Seen = std::rc::Rc<std::cell::RefCell<Vec<InvocationOrigin>>>;
        struct Gated(Seen);
        impl AsyncCapabilityHandler for Gated {
            fn start(&mut self, _: &str, _: UiValue) -> Result<TaskWork, String> {
                Err("start_with is the entry point".to_owned())
            }
            fn start_with(
                &mut self,
                context: &InvocationContext,
                _: &str,
                input: UiValue,
            ) -> Result<TaskWork, String> {
                self.0.borrow_mut().push(context.origin.clone());
                if !context.origin.is_user_input() {
                    return Err("needs user input".to_owned());
                }
                Ok(TaskWork::new(move || Ok(input)))
            }
        }
        impl SubscriptionCapabilityHandler for Gated {
            fn subscribe(&mut self, _: &str, _: UiValue) -> Result<SubscriptionWork, String> {
                Err("subscribe_with is the entry point".to_owned())
            }
            fn subscribe_with(
                &mut self,
                context: &InvocationContext,
                _: &str,
                _: UiValue,
            ) -> Result<SubscriptionWork, String> {
                self.0.borrow_mut().push(context.origin.clone());
                Ok(SubscriptionWork::new(|_| {}))
            }
        }

        let seen = Seen::default();
        let id = CapabilityId::parse("app.echo").unwrap();
        let mut registry = CapabilityRegistry::new();
        registry
            .register_async(descriptor(), Gated(seen.clone()))
            .unwrap();
        registry
            .register_subscription(descriptor(), Gated(seen.clone()))
            .unwrap();
        registry
            .activate(&BTreeMap::from([(id.clone(), VersionReq::STAR)]))
            .unwrap();
        let click = InvocationContext {
            origin: InvocationOrigin::UserInput {
                event: "click".to_owned(),
            },
            view_id: Some("main".to_owned()),
            component: crate::ComponentInstancePath::root("App", "root"),
        };
        let input = || UiValue::String("value".to_owned());
        assert!(
            registry
                .start_task_with(&click, &id, "echo", input())
                .is_ok()
        );
        // Without a context the Host call is `Lifecycle`, not user input.
        assert!(matches!(
            registry.start_task(&id, "echo", input()),
            Err(CapabilityError::Handler { message, .. }) if message == "needs user input"
        ));
        let automation = InvocationContext {
            origin: InvocationOrigin::Automation,
            ..click.clone()
        };
        assert!(
            registry
                .start_task_with(&automation, &id, "echo", input())
                .is_err()
        );
        registry
            .start_subscription_with(&automation, &id, "echo", input())
            .unwrap();
        registry.start_subscription(&id, "echo", input()).unwrap();
        assert_eq!(
            *seen.borrow(),
            [
                click.origin,
                InvocationOrigin::Lifecycle,
                InvocationOrigin::Automation,
                InvocationOrigin::Automation,
                InvocationOrigin::Lifecycle,
            ]
        );
    }
}