Skip to main content

sapphire_framework_bridge_api/
lib.rs

1//! What an app server says to the bridge, and how it says it.
2//!
3//! Kept separate from `sapphire-framework-bridge` so that an app server can talk to the
4//! bridge without linking iroh: Cargo unifies features across a workspace build, so a
5//! feature flag on one crate would not have been enough.
6//!
7//! See `docs/superpowers/specs/2026-09-16-process-architecture-design.md` §4.3 and §5.
8
9#![warn(missing_docs)]
10
11use std::path::PathBuf;
12
13use serde::{Deserialize, Serialize};
14
15pub use grain_id::GrainId;
16
17/// How an app server process came to exist, as it tells the bridge in [`REGISTER`].
18///
19/// The same shape as `sapphire_ipc::ManagedBy`, defined here so this crate does not
20/// depend on the transport.
21#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
22#[serde(rename_all = "lowercase")]
23pub enum ManagedBy {
24    /// Started by the OS service manager. The bridge never starts it.
25    Service,
26    /// Started on demand.
27    Spawned,
28}
29
30mod config;
31pub use config::{
32    ConfigEntry, ConfigFieldError, ConfigFieldErrors, ConfigGetParams, ConfigListParams,
33    ConfigListResult, ConfigSchemaResult, ConfigSetParams, ConfigUnsetParams, ConfigWriteResult,
34};
35pub mod settings;
36pub use settings::{Apply, Entry, EntryValue, Kind, Origin, Scope, SecretState, SettingDef, Value};
37
38mod embed;
39pub use embed::{
40    ApiKey, DEFAULT_DIMENSION, DEFAULT_MAX_TOKENS, DeviceSettings, EmbedDeviceSetParams,
41    EmbedKeySetParams, EmbedModelSetParams, EmbedNote, EmbedRequest, EmbedSettingsResult,
42    LOCAL_MODEL, LocalModel, MAX_TOKENS, ModelSettings, ModelSource, QType, RemoteModel, Slot,
43    SlotModel, describe,
44};
45
46#[cfg(feature = "cli")]
47mod cli;
48#[cfg(feature = "cli")]
49pub use cli::{
50    ConfigCommand, EmbeddingCommand, KeyCommand, LocalCommand, RemoteCommand, ScopeFlags, Switch,
51    describe_entries, parse_entries, read_key, read_secret,
52};
53
54/// The version of the bridge's control-plane API: the methods below and their types.
55///
56/// It is this crate's major version, parsed at compile time, so the two cannot drift: a
57/// breaking change to a method, a parameter or a result here is a major release of this
58/// crate, and that release is the new API version. The handshake compares this number.
59pub const API_VERSION: u32 = parse_major(env!("CARGO_PKG_VERSION_MAJOR"));
60
61/// `CARGO_PKG_VERSION_MAJOR` as a number. Cargo guarantees it is decimal digits.
62const fn parse_major(s: &str) -> u32 {
63    let bytes = s.as_bytes();
64    let mut i = 0;
65    let mut n = 0u32;
66    while i < bytes.len() {
67        n = n * 10 + (bytes[i] - b'0') as u32;
68        i += 1;
69    }
70    n
71}
72
73/// The endpoint name the bridge's control plane listens under.
74pub const BRIDGE_NAME: &str = "bridge";
75/// The endpoint name the bridge's data plane listens under.
76pub const BRIDGE_DATA_NAME: &str = "bridge-data";
77/// The application-layer protocol name used on every peer connection.
78pub const ALPN: &[u8] = b"sapphire/ws/1";
79
80/// Announce which workspaces this app server owns.
81pub const REGISTER: &str = "bridge.register";
82/// Stop owning one workspace.
83pub const UNREGISTER: &str = "bridge.unregister";
84/// List the workgroup's devices and whether they are connected.
85pub const PEERS: &str = "bridge.peers";
86/// Describe the bridge.
87pub const STATUS: &str = "bridge.status";
88/// Notification: a peer wants a workspace this app server owns.
89pub const INCOMING: &str = "bridge.incoming";
90/// Create an invite, and get the ticket to hand to the joining device.
91pub const INVITE: &str = "bridge.invite";
92/// Join the workgroup a ticket names.
93pub const JOIN: &str = "bridge.join";
94/// List the workspaces the workgroup knows about.
95pub const WORKSPACES: &str = "bridge.workspaces";
96/// Found a workgroup on this host, as its first device.
97pub const WORKGROUP_CREATE: &str = "bridge.workgroup_create";
98/// Retire a device of this host's workgroup.
99pub const DEVICE_RETIRE: &str = "bridge.device_retire";
100/// Ask the bridge which embedding model it serves, if any.
101pub const EMBED_INFO: &str = "embed.info";
102/// Embed texts with the bridge's embedding model.
103pub const EMBED: &str = "embed.embed";
104/// Embed images with the bridge's embedding model, into the texts' space. Served only when
105/// [`EmbedModelInfo::images`] is set; absent from bridges before 2.4.
106pub const EMBED_IMAGES: &str = "embed.embed_images";
107/// Read the embedding settings and what they resolve to.
108pub const EMBED_SETTINGS: &str = "embed.settings";
109/// Set or clear one model slot.
110pub const EMBED_MODEL_SET: &str = "embed.model_set";
111/// Switch one slot on or off on this device.
112pub const EMBED_DEVICE_SET: &str = "embed.device_set";
113/// Store the remote slot's API key on this device.
114pub const EMBED_KEY_SET: &str = "embed.key_set";
115/// Remove the remote slot's API key from this device.
116pub const EMBED_KEY_CLEAR: &str = "embed.key_clear";
117
118/// The settings the bridge knows: every key's definition.
119pub const CONFIG_SCHEMA: &str = "config.schema";
120/// The settings' effective values, or what one scope's file holds.
121pub const CONFIG_LIST: &str = "config.list";
122/// One setting's effective value.
123pub const CONFIG_GET: &str = "config.get";
124/// Set settings, as one batch.
125pub const CONFIG_SET: &str = "config.set";
126/// Remove settings, as one batch.
127pub const CONFIG_UNSET: &str = "config.unset";
128/// Restart the bridge, so that restart-only settings take effect.
129pub const RESTART: &str = "bridge.restart";
130
131/// Set a device's election priority.
132pub const DEVICE_PRIORITY_SET: &str = "bridge.device_priority_set";
133
134/// The error code an app server's relay answers with when no bridge is running, or the
135/// connection to it drops mid-call. In the server-defined range of JSON-RPC codes.
136///
137/// A [`BridgeClient`] over an app-server connection turns it back into the not-running
138/// error a direct connection would have produced.
139///
140/// [`BridgeClient`]: https://docs.rs/sapphire-framework-bridge-client
141pub const BRIDGE_NOT_RUNNING: i32 = -32001;
142
143/// The methods an app server relays to the bridge for its clients, under their own names.
144pub const RELAYED: &[&str] = &[
145    STATUS,
146    PEERS,
147    WORKSPACES,
148    WORKGROUP_CREATE,
149    INVITE,
150    JOIN,
151    DEVICE_RETIRE,
152    DEVICE_PRIORITY_SET,
153    EMBED_SETTINGS,
154    EMBED_MODEL_SET,
155    EMBED_DEVICE_SET,
156    EMBED_KEY_SET,
157    EMBED_KEY_CLEAR,
158    RESTART,
159];
160
161/// The methods an app server answers itself, merging its own settings with the bridge's
162/// where both have some, instead of relaying them.
163pub const ANSWERED_BY_APP_SERVER: &[&str] = &[
164    CONFIG_SCHEMA,
165    CONFIG_LIST,
166    CONFIG_GET,
167    CONFIG_SET,
168    CONFIG_UNSET,
169];
170
171/// The methods an app server does not relay, because only an app server or the HTTP
172/// listener calls them on its own behalf.
173pub const NOT_RELAYED: &[&str] = &[
174    REGISTER,
175    UNREGISTER,
176    INCOMING,
177    EMBED_INFO,
178    EMBED,
179    EMBED_IMAGES,
180];
181
182/// A device's priority when its record names none. Mirrors the registry's own constant;
183/// this crate does not depend on the registry.
184pub const DEFAULT_PRIORITY: u8 = 1;
185
186fn default_priority() -> u8 {
187    DEFAULT_PRIORITY
188}
189
190/// Parameters of [`DEVICE_PRIORITY_SET`].
191#[derive(Clone, Debug, Deserialize, Serialize)]
192pub struct DevicePrioritySetParams {
193    /// The device's name or id.
194    pub selector: String,
195    /// `0..=255`. `0` takes the device out of the election.
196    pub priority: u8,
197}
198
199/// Result of [`DEVICE_PRIORITY_SET`].
200#[derive(Clone, Debug, Deserialize, Serialize)]
201pub struct DevicePrioritySetResult {
202    /// The device's id.
203    pub device_id: GrainId,
204    /// Its name.
205    pub name: String,
206    /// Its priority now.
207    pub priority: u8,
208}
209
210/// Parameters of [`INVITE`].
211#[derive(Clone, Debug, Deserialize, Serialize)]
212pub struct InviteParams {
213    /// What the joining device will be called in the ledger.
214    pub name: String,
215    /// How long the invite stays good, in seconds. `None` uses the bridge's default.
216    #[serde(default, skip_serializing_if = "Option::is_none")]
217    pub ttl: Option<u64>,
218    /// The workgroup to invite into, by name or id. `None` uses this host's only one.
219    #[serde(default, skip_serializing_if = "Option::is_none")]
220    pub workgroup: Option<String>,
221}
222
223/// Result of [`INVITE`].
224#[derive(Clone, Debug, Deserialize, Serialize)]
225pub struct InviteResult {
226    /// The ticket, in the text form a user copies to the joining device.
227    pub ticket: String,
228}
229
230/// Parameters of [`WORKGROUP_CREATE`].
231#[derive(Clone, Debug, Deserialize, Serialize)]
232pub struct WorkgroupCreateParams {
233    /// The workgroup's name.
234    pub name: String,
235    /// This host's device name inside it.
236    pub device_name: String,
237}
238
239/// Result of [`WORKGROUP_CREATE`].
240#[derive(Clone, Debug, Deserialize, Serialize)]
241pub struct WorkgroupCreateResult {
242    /// The new workgroup's id.
243    pub workgroup_id: GrainId,
244    /// Its name.
245    pub name: String,
246    /// This host's device id in it.
247    pub device_id: GrainId,
248}
249
250/// Parameters of [`DEVICE_RETIRE`].
251#[derive(Clone, Debug, Deserialize, Serialize)]
252pub struct DeviceRetireParams {
253    /// The device's name or id.
254    pub selector: String,
255}
256
257/// Result of [`DEVICE_RETIRE`].
258#[derive(Clone, Debug, Deserialize, Serialize)]
259pub struct DeviceRetireResult {
260    /// The retired device's id.
261    pub device_id: GrainId,
262    /// Its name.
263    pub name: String,
264}
265
266/// Parameters of [`JOIN`].
267#[derive(Clone, Debug, Deserialize, Serialize)]
268pub struct JoinParams {
269    /// The ticket the inviter produced.
270    pub ticket: String,
271    /// The name this device will carry in the ledger. `None` uses the host name.
272    #[serde(default, skip_serializing_if = "Option::is_none")]
273    pub device_name: Option<String>,
274}
275
276/// Result of [`JOIN`].
277#[derive(Clone, Debug, Deserialize, Serialize)]
278pub struct JoinResult {
279    /// The workgroup that was joined.
280    pub workgroup_id: GrainId,
281    /// Its name, as the founding device chose it.
282    pub workgroup_name: String,
283    /// This device's own record inside it.
284    pub device_id: GrainId,
285}
286
287/// One workspace the workgroup knows about.
288#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
289pub struct WorkgroupWorkspaceInfo {
290    /// Its identity across devices.
291    pub workspace_id: GrainId,
292    /// The application that owns it.
293    pub app_name: String,
294    /// The name the workgroup lists it under.
295    pub name: String,
296}
297
298/// Result of [`WORKSPACES`].
299#[derive(Clone, Debug, Deserialize, Serialize)]
300pub struct WorkspacesResult {
301    /// Every workspace the workgroup knows about.
302    pub workspaces: Vec<WorkgroupWorkspaceInfo>,
303}
304
305/// The success payload of a call that returns nothing.
306#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)]
307pub struct Ack {}
308
309/// One workspace an app server owns.
310#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
311pub struct WorkspaceRegistration {
312    /// The workspace's sync identity, shared across devices.
313    pub workspace_id: GrainId,
314    /// Where it lives on this host.
315    pub root: PathBuf,
316}
317
318/// Parameters of [`REGISTER`].
319#[derive(Clone, Debug, Deserialize, Serialize)]
320pub struct RegisterParams {
321    /// Which application this server belongs to.
322    pub app_name: String,
323    /// The executable to run when a peer wants a workspace and this server is not running.
324    pub exe_path: PathBuf,
325    /// How this server was started. A `Service` server is never started by the bridge.
326    pub managed_by: ManagedBy,
327    /// The workspaces it owns. Registering again replaces the previous list for this app.
328    pub workspaces: Vec<WorkspaceRegistration>,
329}
330
331/// Result of [`REGISTER`].
332#[derive(Clone, Debug, Deserialize, Serialize)]
333pub struct RegisterResult {
334    /// This host's device id inside the workgroup, used as `Entry.author`.
335    pub device_id: GrainId,
336    /// This host's iroh node id.
337    pub node_id: String,
338    /// The workgroup these workspaces belong to.
339    pub workgroup_id: GrainId,
340}
341
342/// Parameters of [`UNREGISTER`].
343#[derive(Clone, Debug, Deserialize, Serialize)]
344pub struct UnregisterParams {
345    /// The workspace to stop owning.
346    pub workspace_id: GrainId,
347}
348
349/// Who the bridge elected for one workspace this host's app servers own.
350#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
351pub struct WorkspaceRoles {
352    /// The workspace.
353    pub workspace_id: GrainId,
354    /// The primary device, if any candidate exists.
355    #[serde(default)]
356    pub primary: Option<GrainId>,
357    /// The secondary device, if a second candidate exists.
358    #[serde(default)]
359    pub secondary: Option<GrainId>,
360}
361
362/// One device of the workgroup.
363#[derive(Clone, Debug, Deserialize, Serialize)]
364pub struct PeerInfo {
365    /// Its device id.
366    pub device_id: GrainId,
367    /// Its name.
368    pub name: String,
369    /// Its iroh node id.
370    pub node_id: String,
371    /// Whether the bridge currently holds a connection to it.
372    pub connected: bool,
373    /// Its election priority, as its ledger record says.
374    #[serde(default = "default_priority")]
375    pub priority: u8,
376    /// Its availability tier, as its own Hello reports it (#190). `None` until measured.
377    #[serde(default, skip_serializing_if = "Option::is_none")]
378    pub availability: Option<u8>,
379}
380
381/// Result of [`PEERS`].
382#[derive(Clone, Debug, Deserialize, Serialize)]
383pub struct PeersResult {
384    /// Every non-retired device of the workgroup, this host included.
385    pub peers: Vec<PeerInfo>,
386    /// The elected roles of every workspace this host's app servers own. Empty from a
387    /// bridge older than 2.1, which means a full mesh.
388    #[serde(default)]
389    pub roles: Vec<WorkspaceRoles>,
390}
391
392impl PeersResult {
393    /// The roles for `workspace_id`, if the bridge elected any.
394    pub fn roles_for(&self, workspace_id: GrainId) -> Option<&WorkspaceRoles> {
395        self.roles.iter().find(|r| r.workspace_id == workspace_id)
396    }
397}
398
399/// One row of the routing table.
400#[derive(Clone, Debug, Deserialize, Serialize)]
401pub struct RouteStatus {
402    /// The workspace.
403    pub workspace_id: GrainId,
404    /// The application that owns it.
405    pub app_name: String,
406    /// Where it lives on this host.
407    pub root: PathBuf,
408    /// Whether that application's server is connected right now.
409    pub owner_online: bool,
410}
411
412/// The workgroup this host belongs to.
413#[derive(Clone, Debug, Deserialize, Serialize)]
414pub struct WorkgroupStatus {
415    /// Its id.
416    pub workgroup_id: GrainId,
417    /// Its name.
418    pub name: String,
419    /// How many non-retired devices it has.
420    pub devices: usize,
421}
422
423/// The embedding model a bridge serves.
424#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
425pub struct EmbedModelInfo {
426    /// The model's name.
427    pub model: String,
428    /// Its vector dimension.
429    pub dimension: u32,
430    /// The version of the text template applied before embedding.
431    pub template_version: u32,
432    /// The model's pinned revision, when the bridge pins one.
433    #[serde(default, skip_serializing_if = "Option::is_none")]
434    pub revision: Option<String>,
435    /// Content tokens kept before embedding, when the bridge truncates (the local model).
436    #[serde(default, skip_serializing_if = "Option::is_none")]
437    pub max_tokens: Option<u32>,
438    /// Whether the model embeds images too ([`EMBED_IMAGES`]). Absent from bridges before
439    /// 2.4: false.
440    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
441    pub images: bool,
442}
443
444/// Result of [`EMBED_INFO`].
445#[derive(Clone, Debug, Default, Deserialize, Serialize)]
446pub struct EmbedInfoResult {
447    /// Whether this bridge embeds at all.
448    pub enabled: bool,
449    /// The model, when enabled.
450    #[serde(default, skip_serializing_if = "Option::is_none")]
451    pub model: Option<EmbedModelInfo>,
452    /// Whether the model is in memory right now (local provider); always true for REST.
453    #[serde(default)]
454    pub loaded: bool,
455    /// Why embedding is off, or what it lacks while on. Absent from bridges before 2.3.
456    #[serde(default, skip_serializing_if = "Option::is_none")]
457    pub note: Option<EmbedNote>,
458}
459
460/// Parameters of [`EMBED`].
461#[derive(Clone, Debug, Deserialize, Serialize)]
462pub struct EmbedParams {
463    /// The texts to embed.
464    pub texts: Vec<String>,
465}
466
467/// Parameters of [`EMBED_IMAGES`].
468#[derive(Clone, Debug, Deserialize, Serialize)]
469pub struct EmbedImagesParams {
470    /// The images, each a file's bytes (PNG, JPEG, WebP or GIF) in standard base64.
471    pub images: Vec<String>,
472}
473
474impl EmbedImagesParams {
475    /// The parameters for `images`, each a file's bytes.
476    pub fn new<B: AsRef<[u8]>>(images: &[B]) -> EmbedImagesParams {
477        use base64::Engine as _;
478        EmbedImagesParams {
479            images: images
480                .iter()
481                .map(|i| base64::engine::general_purpose::STANDARD.encode(i))
482                .collect(),
483        }
484    }
485
486    /// The images' bytes; the error names the first that is not base64.
487    pub fn decode(&self) -> Result<Vec<Vec<u8>>, String> {
488        use base64::Engine as _;
489        self.images
490            .iter()
491            .enumerate()
492            .map(|(i, b64)| {
493                base64::engine::general_purpose::STANDARD
494                    .decode(b64)
495                    .map_err(|e| format!("image {i}: {e}"))
496            })
497            .collect()
498    }
499}
500
501/// Result of [`EMBED`] and [`EMBED_IMAGES`].
502#[derive(Clone, Debug, Deserialize, Serialize)]
503pub struct EmbedResult {
504    /// The model that produced the vectors.
505    pub model: String,
506    /// Their dimension.
507    pub dimension: u32,
508    /// One vector per input, in order.
509    pub vectors: Vec<Vec<f32>>,
510}
511
512/// Result of [`STATUS`].
513#[derive(Clone, Debug, Deserialize, Serialize)]
514pub struct StatusResult {
515    /// The bridge's version.
516    pub version: String,
517    /// This host's iroh node id.
518    pub node_id: String,
519    /// The workgroup, if this host has joined one.
520    pub workgroup: Option<WorkgroupStatus>,
521    /// Every registered workspace.
522    pub routes: Vec<RouteStatus>,
523    /// The embedding service, when this bridge reports one.
524    #[serde(default, skip_serializing_if = "Option::is_none")]
525    pub embedding: Option<EmbedInfoResult>,
526}
527
528/// Parameters of the [`INCOMING`] notification.
529#[derive(Clone, Debug, Deserialize, Serialize)]
530pub struct IncomingParams {
531    /// The workspace the peer asked for.
532    pub workspace_id: GrainId,
533    /// Which device asked.
534    pub peer_device_id: GrainId,
535    /// A single-use token naming the waiting stream.
536    ///
537    /// Useless to anyone who did not receive this notification, and consumed the first time
538    /// it is presented.
539    pub ticket: String,
540}
541
542/// The first line of a data-plane connection.
543#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
544#[serde(tag = "kind", rename_all = "lowercase", deny_unknown_fields)]
545pub enum DataHeader {
546    /// The app server wants a stream to `device_id` for `workspace_id`.
547    Open {
548        /// The workspace being synced.
549        workspace_id: GrainId,
550        /// The peer to reach.
551        device_id: GrainId,
552    },
553    /// The app server is answering a [`INCOMING`] notification.
554    Accept {
555        /// The ticket from that notification.
556        ticket: String,
557    },
558}
559
560/// The bridge's answer to a [`DataHeader`], sent as one line before the raw bytes begin.
561#[derive(Clone, Debug, Deserialize, Serialize)]
562pub struct DataAck {
563    /// Whether the stream is open.
564    pub ok: bool,
565    /// Why not, when it is not.
566    #[serde(default, skip_serializing_if = "Option::is_none")]
567    pub error: Option<String>,
568}
569
570#[cfg(test)]
571mod tests {
572    use super::*;
573
574    fn round_trip<T: serde::Serialize + serde::de::DeserializeOwned>(v: &T) -> T {
575        serde_json::from_value(serde_json::to_value(v).unwrap()).unwrap()
576    }
577
578    fn id() -> GrainId {
579        GrainId::random()
580    }
581
582    #[test]
583    fn embed_info_round_trips() {
584        let info = EmbedInfoResult {
585            enabled: true,
586            model: Some(EmbedModelInfo {
587                model: "m".into(),
588                dimension: 384,
589                template_version: 1,
590                revision: None,
591                max_tokens: None,
592                images: false,
593            }),
594            loaded: true,
595            note: Some(EmbedNote::KeyMissing),
596        };
597        let back = round_trip(&info);
598        assert_eq!(back.note, Some(EmbedNote::KeyMissing));
599        assert!(back.enabled && back.loaded);
600        assert_eq!(back.model, info.model);
601        let off = serde_json::to_value(EmbedInfoResult::default()).unwrap();
602        assert_eq!(off, serde_json::json!({"enabled": false, "loaded": false}));
603    }
604
605    #[test]
606    fn status_without_embedding_deserializes() {
607        let json = serde_json::json!({
608            "version": "1", "node_id": "n", "workgroup": null, "routes": []
609        });
610        let status: StatusResult = serde_json::from_value(json).unwrap();
611        assert!(status.embedding.is_none());
612    }
613
614    #[test]
615    fn embed_params_wire_shape() {
616        let v = serde_json::to_value(EmbedParams {
617            texts: vec!["a".into()],
618        })
619        .unwrap();
620        assert_eq!(v, serde_json::json!({"texts": ["a"]}));
621        let r = round_trip(&EmbedResult {
622            model: "m".into(),
623            dimension: 2,
624            vectors: vec![vec![1.0, 2.0]],
625        });
626        assert_eq!(r.vectors, vec![vec![1.0, 2.0]]);
627    }
628
629    #[test]
630    fn registration_round_trips() {
631        let params = RegisterParams {
632            app_name: "sapphire-journal".into(),
633            exe_path: "/usr/bin/sapphire-journal".into(),
634            managed_by: ManagedBy::Spawned,
635            workspaces: vec![WorkspaceRegistration {
636                workspace_id: id(),
637                root: "/home/me/journal".into(),
638            }],
639        };
640        let back = round_trip(&params);
641        assert_eq!(back.app_name, "sapphire-journal");
642        assert_eq!(back.workspaces.len(), 1);
643    }
644
645    #[test]
646    fn invite_params_carry_the_cli_arguments() {
647        let params = InviteParams {
648            name: "phone".into(),
649            ttl: Some(600),
650            workgroup: None,
651        };
652        // Serialisation shape is the contract with the bridge's handler; pin it.
653        let json = serde_json::to_value(&params).unwrap();
654        assert_eq!(json["name"], "phone");
655        assert_eq!(json["ttl"], 600);
656        assert!(json.get("workgroup").is_none());
657    }
658
659    #[test]
660    fn workspaces_result_round_trips() {
661        let raw = serde_json::json!({ "workspaces": [] });
662        let parsed: WorkspacesResult = serde_json::from_value(raw).unwrap();
663        assert!(parsed.workspaces.is_empty());
664    }
665
666    #[test]
667    fn an_open_header_round_trips_and_is_tagged() {
668        let header = DataHeader::Open {
669            workspace_id: id(),
670            device_id: id(),
671        };
672        let value = serde_json::to_value(&header).unwrap();
673        assert_eq!(value["kind"], "open");
674        assert_eq!(round_trip(&header), header);
675    }
676
677    #[test]
678    fn an_accept_header_round_trips_and_is_tagged() {
679        let header = DataHeader::Accept {
680            ticket: "t-123".into(),
681        };
682        let value = serde_json::to_value(&header).unwrap();
683        assert_eq!(value["kind"], "accept");
684        assert_eq!(round_trip(&header), header);
685    }
686
687    #[test]
688    fn an_unknown_header_kind_is_refused() {
689        let value = serde_json::json!({ "kind": "sideways" });
690        assert!(serde_json::from_value::<DataHeader>(value).is_err());
691    }
692
693    #[test]
694    fn a_data_ack_carries_its_reason_when_it_fails() {
695        let ack = DataAck {
696            ok: false,
697            error: Some("no such workspace".into()),
698        };
699        assert_eq!(round_trip(&ack).error.as_deref(), Some("no such workspace"));
700    }
701
702    #[test]
703    fn method_names_are_namespaced() {
704        for name in [
705            REGISTER, UNREGISTER, PEERS, STATUS, INCOMING, INVITE, JOIN, WORKSPACES,
706        ] {
707            assert!(name.starts_with("bridge."), "{name}");
708        }
709    }
710
711    #[test]
712    fn config_method_names_are_namespaced() {
713        for name in [
714            CONFIG_SCHEMA,
715            CONFIG_LIST,
716            CONFIG_GET,
717            CONFIG_SET,
718            CONFIG_UNSET,
719        ] {
720            assert!(name.starts_with("config."), "{name}");
721        }
722        assert!(RESTART.starts_with("bridge."));
723    }
724
725    #[test]
726    fn every_method_is_relayed_answered_or_not() {
727        let all: std::collections::BTreeSet<&str> = [
728            REGISTER,
729            UNREGISTER,
730            PEERS,
731            STATUS,
732            INCOMING,
733            INVITE,
734            JOIN,
735            WORKSPACES,
736            WORKGROUP_CREATE,
737            DEVICE_RETIRE,
738            EMBED_INFO,
739            EMBED,
740            EMBED_IMAGES,
741            EMBED_SETTINGS,
742            EMBED_MODEL_SET,
743            EMBED_DEVICE_SET,
744            EMBED_KEY_SET,
745            EMBED_KEY_CLEAR,
746            CONFIG_SCHEMA,
747            CONFIG_LIST,
748            CONFIG_GET,
749            CONFIG_SET,
750            CONFIG_UNSET,
751            RESTART,
752            DEVICE_PRIORITY_SET,
753        ]
754        .into_iter()
755        .collect();
756        let relayed: std::collections::BTreeSet<&str> = RELAYED.iter().copied().collect();
757        let not_relayed: std::collections::BTreeSet<&str> = NOT_RELAYED.iter().copied().collect();
758        let answered: std::collections::BTreeSet<&str> =
759            ANSWERED_BY_APP_SERVER.iter().copied().collect();
760        assert_eq!(
761            answered.len(),
762            ANSWERED_BY_APP_SERVER.len(),
763            "ANSWERED_BY_APP_SERVER repeats a method"
764        );
765        assert!(relayed.is_disjoint(&answered));
766        assert!(not_relayed.is_disjoint(&answered));
767        assert_eq!(relayed.len(), RELAYED.len(), "RELAYED repeats a method");
768        assert_eq!(
769            not_relayed.len(),
770            NOT_RELAYED.len(),
771            "NOT_RELAYED repeats a method"
772        );
773        assert!(relayed.is_disjoint(&not_relayed));
774        let union: std::collections::BTreeSet<&str> = relayed
775            .union(&not_relayed)
776            .chain(answered.iter())
777            .copied()
778            .collect();
779        assert_eq!(union, all);
780    }
781
782    #[test]
783    fn the_crate_stays_free_of_the_workspace_and_network_stacks() {
784        let manifest = include_str!("../Cargo.toml");
785        for forbidden in [
786            "iroh",
787            "sapphire-framework-workspace",
788            "sapphire-framework-retrieve",
789            "sapphire-framework-backend",
790        ] {
791            assert!(
792                !manifest.contains(forbidden),
793                "sapphire-framework-bridge-api must not depend on {forbidden}"
794            );
795        }
796    }
797
798    #[test]
799    fn the_api_version_is_the_crate_major() {
800        let major: u32 = env!("CARGO_PKG_VERSION_MAJOR").parse().unwrap();
801        assert_eq!(API_VERSION, major);
802        assert_eq!(API_VERSION, 4);
803    }
804
805    #[test]
806    fn workgroup_create_and_device_retire_wire_shapes() {
807        let p = WorkgroupCreateParams {
808            name: "home".into(),
809            device_name: "desk".into(),
810        };
811        assert_eq!(
812            serde_json::to_value(&p).unwrap(),
813            serde_json::json!({ "name": "home", "device_name": "desk" })
814        );
815        let p = DeviceRetireParams {
816            selector: "laptop".into(),
817        };
818        assert_eq!(
819            serde_json::to_value(&p).unwrap(),
820            serde_json::json!({ "selector": "laptop" })
821        );
822        let id = GrainId::random();
823        let r = WorkgroupCreateResult {
824            workgroup_id: id,
825            name: "home".into(),
826            device_id: id,
827        };
828        assert_eq!(round_trip(&r).name, "home");
829        assert_eq!(WORKGROUP_CREATE, "bridge.workgroup_create");
830        assert_eq!(DEVICE_RETIRE, "bridge.device_retire");
831    }
832
833    #[test]
834    fn a_2_0_peers_answer_reads_with_no_roles_and_default_priority() {
835        let id = GrainId::random();
836        let old = serde_json::json!({
837            "peers": [{ "device_id": id, "name": "desk", "node_id": "", "connected": true }]
838        });
839
840        let read: PeersResult = serde_json::from_value(old).unwrap();
841
842        assert!(read.roles.is_empty());
843        assert_eq!(read.peers[0].priority, DEFAULT_PRIORITY);
844        assert_eq!(read.peers[0].availability, None);
845        assert!(read.roles_for(id).is_none());
846    }
847
848    #[test]
849    fn roles_for_finds_the_workspace() {
850        let ws = GrainId::random();
851        let d = GrainId::random();
852        let result = PeersResult {
853            peers: Vec::new(),
854            roles: vec![WorkspaceRoles {
855                workspace_id: ws,
856                primary: Some(d),
857                secondary: None,
858            }],
859        };
860
861        assert_eq!(result.roles_for(ws).unwrap().primary, Some(d));
862    }
863
864    #[test]
865    fn device_priority_set_params_are_selector_and_priority() {
866        let p = DevicePrioritySetParams {
867            selector: "desk".into(),
868            priority: 0,
869        };
870        assert_eq!(
871            serde_json::to_value(&p).unwrap(),
872            serde_json::json!({ "selector": "desk", "priority": 0 })
873        );
874    }
875}