Skip to main content

weirdnet_agent/
model.rs

1//! The model backend trait and chat messages. Inference lives elsewhere
2//! (`weirdnet-model`, remote nodes); this crate only drives it.
3
4use async_trait::async_trait;
5use serde::{Deserialize, Serialize};
6use serde_json::Value;
7use tokio::sync::mpsc::UnboundedSender;
8
9use crate::cancel::CancelToken;
10use crate::session::AgentEvent;
11use crate::tool::ToolSpec;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
14#[serde(rename_all = "snake_case")]
15#[non_exhaustive]
16pub enum Role {
17    System,
18    User,
19    Assistant,
20    Tool,
21}
22
23/// A tool call the model asked for.
24#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
25pub struct ToolCall {
26    pub id: String,
27    pub name: String,
28    #[serde(default)]
29    pub arguments: Value,
30}
31
32/// What a message says: plain text, or OpenAI-style parts (text, images, audio, video).
33///
34/// Text serializes as a plain string, exactly as `content` did before 0.5, so text-only messages
35/// stay readable by older peers. Parts serialize as a list of `{"type": ...}` objects; peers older
36/// than 0.5 can't read them.
37#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
38#[serde(untagged)]
39pub enum Content {
40    Text(String),
41    Parts(Vec<ContentPart>),
42}
43
44impl Default for Content {
45    fn default() -> Self {
46        Content::Text(String::new())
47    }
48}
49
50/// One part of a [`Content::Parts`] message, in the OpenAI chat shape.
51#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
52#[serde(tag = "type", rename_all = "snake_case")]
53#[non_exhaustive]
54pub enum ContentPart {
55    Text {
56        text: String,
57    },
58    /// An image as a `data:` URL (`data:image/png;base64,...`).
59    ImageUrl {
60        image_url: ImageUrl,
61    },
62    /// Base64 audio and its format (`wav`, `mp3`).
63    InputAudio {
64        input_audio: InputAudio,
65    },
66    /// A whole video clip as a `data:` URL (`data:video/mp4;base64,...`), for models that read
67    /// video natively ([`Modalities::video`]); `{"type": "video_url", "video_url": {"url": ...}}`
68    /// on the wire, the part vLLM and mistral.rs take. Since 0.5.10: peers before it can't read a
69    /// message carrying one, and [`Catalog::route`](crate::remote::catalog::Catalog::route) only
70    /// sends it to models whose catalog entry says `inputs.video`, which older nodes never do.
71    VideoUrl {
72        video_url: VideoUrl,
73    },
74}
75
76#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
77#[non_exhaustive]
78pub struct ImageUrl {
79    pub url: String,
80    /// OpenAI's `detail` hint (`auto`, `low`, `high`), passed on as is.
81    #[serde(default, skip_serializing_if = "Option::is_none")]
82    pub detail: Option<String>,
83}
84
85/// A video clip, inline. Small clips only for now: the whole request must fit in one stream
86/// message (32 MiB on Weirdnet, less behind a bridge's `max_request_bytes`). A reference to a
87/// clip the node fetches over the link (a `weirdnet-net` content root) may be added later as
88/// another optional field, so this stays the place to look.
89#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
90#[non_exhaustive]
91pub struct VideoUrl {
92    /// A `data:video/...;base64,` URL (see [`Content::check`]); remote URLs are never fetched.
93    pub url: String,
94}
95
96impl VideoUrl {
97    /// The clip's MIME type (`video/mp4`) when the URL is a `data:` URL.
98    pub fn mime_type(&self) -> Option<&str> {
99        let rest = self.url.strip_prefix("data:")?;
100        let end = rest.find([';', ','])?;
101        Some(&rest[..end]).filter(|m| !m.is_empty())
102    }
103
104    /// The clip's size in bytes once decoded, from the base64 length of a `data:...;base64,` URL
105    /// (nothing is decoded), to compare with
106    /// [`MediaLimits::video_max_bytes`](crate::MediaLimits::video_max_bytes). `None` for any
107    /// other URL.
108    pub fn data_len(&self) -> Option<u64> {
109        let (head, data) = self.url.strip_prefix("data:")?.split_once(',')?;
110        if !head.ends_with(";base64") {
111            return None;
112        }
113        let data = data.trim_end();
114        let pad = data.bytes().rev().take_while(|b| *b == b'=').count().min(2);
115        Some((data.len() as u64 * 3 / 4).saturating_sub(pad as u64))
116    }
117}
118
119#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
120#[non_exhaustive]
121pub struct InputAudio {
122    /// Base64, no `data:` prefix.
123    pub data: String,
124    pub format: String,
125}
126
127impl ContentPart {
128    pub fn text(text: impl Into<String>) -> Self {
129        ContentPart::Text { text: text.into() }
130    }
131
132    /// An image part; `url` should be a `data:image/...;base64,` URL (see [`Content::check`]).
133    pub fn image(url: impl Into<String>) -> Self {
134        ContentPart::ImageUrl { image_url: ImageUrl { url: url.into(), detail: None } }
135    }
136
137    pub fn audio(data: impl Into<String>, format: impl Into<String>) -> Self {
138        ContentPart::InputAudio { input_audio: InputAudio { data: data.into(), format: format.into() } }
139    }
140
141    /// A video part; `url` should be a `data:video/...;base64,` URL (see [`Content::check`]).
142    /// Since 0.5.10.
143    pub fn video(url: impl Into<String>) -> Self {
144        ContentPart::VideoUrl { video_url: VideoUrl { url: url.into() } }
145    }
146
147    /// A video part from the clip's bytes and MIME type (`video/mp4`, `video/webm`), as a
148    /// `data:` URL. Since 0.5.10.
149    pub fn video_bytes(bytes: &[u8], mime_type: &str) -> Self {
150        use base64::Engine as _;
151        Self::video(format!("data:{mime_type};base64,{}", base64::engine::general_purpose::STANDARD.encode(bytes)))
152    }
153
154    /// What a model needs to read this part.
155    pub fn needs(&self) -> Modalities {
156        match self {
157            ContentPart::Text { .. } => Modalities::TEXT,
158            ContentPart::ImageUrl { .. } => Modalities::VISION,
159            ContentPart::InputAudio { .. } => Modalities::AUDIO,
160            ContentPart::VideoUrl { .. } => Modalities::VIDEO,
161        }
162    }
163}
164
165impl Content {
166    /// The text: the string, or the text parts joined (images, audio and video left out).
167    pub fn text(&self) -> std::borrow::Cow<'_, str> {
168        match self {
169            Content::Text(t) => std::borrow::Cow::Borrowed(t),
170            Content::Parts(parts) => parts
171                .iter()
172                .filter_map(|p| match p {
173                    ContentPart::Text { text } => Some(text.as_str()),
174                    _ => None,
175                })
176                .collect::<String>()
177                .into(),
178        }
179    }
180
181    /// The string, if this is plain text.
182    pub fn as_text(&self) -> Option<&str> {
183        match self {
184            Content::Text(t) => Some(t),
185            Content::Parts(_) => None,
186        }
187    }
188
189    /// The text, consuming the content (see [`text`](Self::text)).
190    pub fn into_text(self) -> String {
191        match self {
192            Content::Text(t) => t,
193            other => other.text().into_owned(),
194        }
195    }
196
197    /// The parts; plain text is one text part.
198    pub fn parts(&self) -> Vec<ContentPart> {
199        match self {
200            Content::Text(t) => vec![ContentPart::text(t.clone())],
201            Content::Parts(p) => p.clone(),
202        }
203    }
204
205    pub fn is_empty(&self) -> bool {
206        match self {
207            Content::Text(t) => t.is_empty(),
208            Content::Parts(p) => p.is_empty(),
209        }
210    }
211
212    /// What a model needs to read this content.
213    pub fn needs(&self) -> Modalities {
214        match self {
215            Content::Text(_) => Modalities::TEXT,
216            Content::Parts(p) => p.iter().fold(Modalities::TEXT, |m, part| m.union(part.needs())),
217        }
218    }
219
220    /// Text-only parts become plain text, the form older peers read. Content with images, audio
221    /// or video is unchanged.
222    pub fn normalized(self) -> Self {
223        match self {
224            Content::Parts(p) if p.iter().all(|x| matches!(x, ContentPart::Text { .. })) => Content::Parts(p).into_text().into(),
225            other => other,
226        }
227    }
228
229    /// Images must be `data:image/...` URLs and videos `data:video/...` URLs (nodes never fetch
230    /// remote URLs), and audio needs a format. `Err` says what is wrong, for a 400.
231    pub fn check(&self) -> Result<(), String> {
232        let Content::Parts(parts) = self else { return Ok(()) };
233        for p in parts {
234            match p {
235                ContentPart::ImageUrl { image_url } if !image_url.url.starts_with("data:image/") => {
236                    return Err("image_url must be a data:image/... URL; remote image URLs are not fetched".into());
237                }
238                ContentPart::InputAudio { input_audio } if input_audio.format.is_empty() || input_audio.data.is_empty() => {
239                    return Err("input_audio needs data and a format".into());
240                }
241                ContentPart::VideoUrl { video_url } if !video_url.url.starts_with("data:video/") => {
242                    return Err("video_url must be a data:video/... URL; remote video URLs are not fetched".into());
243                }
244                _ => {}
245            }
246        }
247        Ok(())
248    }
249}
250
251impl From<String> for Content {
252    fn from(s: String) -> Self {
253        Content::Text(s)
254    }
255}
256
257impl From<&str> for Content {
258    fn from(s: &str) -> Self {
259        Content::Text(s.to_string())
260    }
261}
262
263impl From<&String> for Content {
264    fn from(s: &String) -> Self {
265        Content::Text(s.clone())
266    }
267}
268
269impl From<Vec<ContentPart>> for Content {
270    fn from(p: Vec<ContentPart>) -> Self {
271        Content::Parts(p)
272    }
273}
274
275impl PartialEq<str> for Content {
276    fn eq(&self, other: &str) -> bool {
277        self.as_text() == Some(other)
278    }
279}
280
281impl PartialEq<&str> for Content {
282    fn eq(&self, other: &&str) -> bool {
283        self.as_text() == Some(*other)
284    }
285}
286
287impl std::fmt::Display for Content {
288    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
289        f.write_str(&self.text())
290    }
291}
292
293/// Input kinds beyond text: what a request needs, or what a model accepts.
294#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
295#[non_exhaustive]
296pub struct Modalities {
297    /// Images (`image_url` parts).
298    #[serde(default, skip_serializing_if = "is_false")]
299    pub vision: bool,
300    /// Audio (`input_audio` parts).
301    #[serde(default, skip_serializing_if = "is_false")]
302    pub audio: bool,
303    /// Whole video clips (`video_url` parts), read natively rather than as frames. Since 0.5.10;
304    /// absent (`false`) from older peers, so their models count as not reading video.
305    #[serde(default, skip_serializing_if = "is_false")]
306    pub video: bool,
307}
308
309fn is_false(b: &bool) -> bool {
310    !*b
311}
312
313impl Modalities {
314    /// Text only.
315    pub const TEXT: Self = Self { vision: false, audio: false, video: false };
316    pub const VISION: Self = Self { vision: true, audio: false, video: false };
317    pub const AUDIO: Self = Self { vision: false, audio: true, video: false };
318    /// Whole video clips (`video_url` parts). Since 0.5.10.
319    pub const VIDEO: Self = Self { vision: false, audio: false, video: true };
320
321    /// Images and audio; add video with [`with_video`](Self::with_video).
322    pub fn new(vision: bool, audio: bool) -> Self {
323        Self { vision, audio, video: false }
324    }
325
326    /// The same with video set to `video`. Since 0.5.10.
327    pub fn with_video(mut self, video: bool) -> Self {
328        self.video = video;
329        self
330    }
331
332    pub fn is_text(&self) -> bool {
333        !self.vision && !self.audio && !self.video
334    }
335
336    pub fn union(self, other: Self) -> Self {
337        Self { vision: self.vision || other.vision, audio: self.audio || other.audio, video: self.video || other.video }
338    }
339
340    /// A model accepting `self` can read input that needs `needed`.
341    pub fn covers(&self, needed: Modalities) -> bool {
342        (self.vision || !needed.vision) && (self.audio || !needed.audio) && (self.video || !needed.video)
343    }
344
345    /// What `self` lacks of `needed`, for errors: `"images"`, `"audio"`, `"video"`,
346    /// `"images and audio"`, `"images and video"`, `"audio and video"` or
347    /// `"images, audio and video"`.
348    pub fn lacking(&self, needed: Modalities) -> Option<&'static str> {
349        match (needed.vision && !self.vision, needed.audio && !self.audio, needed.video && !self.video) {
350            (true, true, true) => Some("images, audio and video"),
351            (true, true, false) => Some("images and audio"),
352            (true, false, true) => Some("images and video"),
353            (false, true, true) => Some("audio and video"),
354            (true, false, false) => Some("images"),
355            (false, true, false) => Some("audio"),
356            (false, false, true) => Some("video"),
357            (false, false, false) => None,
358        }
359    }
360}
361
362#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
363pub struct Message {
364    pub role: Role,
365    pub content: Content,
366    #[serde(default, skip_serializing_if = "Vec::is_empty")]
367    pub tool_calls: Vec<ToolCall>,
368    #[serde(default, skip_serializing_if = "Option::is_none")]
369    pub tool_call_id: Option<String>,
370}
371
372impl Message {
373    pub fn system(content: impl Into<Content>) -> Self {
374        Self { role: Role::System, content: content.into(), tool_calls: Vec::new(), tool_call_id: None }
375    }
376
377    /// A user message: text (`Message::user("hi")`) or parts
378    /// (`Message::user(vec![ContentPart::text("what is this?"), ContentPart::image(url)])`).
379    pub fn user(content: impl Into<Content>) -> Self {
380        Self { role: Role::User, content: content.into(), tool_calls: Vec::new(), tool_call_id: None }
381    }
382
383    pub fn assistant(content: impl Into<Content>, tool_calls: Vec<ToolCall>) -> Self {
384        Self { role: Role::Assistant, content: content.into(), tool_calls, tool_call_id: None }
385    }
386
387    pub fn tool(call_id: impl Into<String>, content: impl Into<Content>) -> Self {
388        Self { role: Role::Tool, content: content.into(), tool_calls: Vec::new(), tool_call_id: Some(call_id.into()) }
389    }
390
391    /// The text of the message (text parts joined; see [`Content::text`]).
392    pub fn text(&self) -> std::borrow::Cow<'_, str> {
393        self.content.text()
394    }
395
396    /// What a model needs to read this message.
397    pub fn needs(&self) -> Modalities {
398        self.content.needs()
399    }
400}
401
402/// What a model needs to read all of `messages`.
403pub fn needs(messages: &[Message]) -> Modalities {
404    messages.iter().fold(Modalities::TEXT, |m, msg| m.union(msg.needs()))
405}
406
407/// One model turn: final text and any tool calls.
408#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
409pub struct ModelTurn {
410    pub text: String,
411    #[serde(default)]
412    pub tool_calls: Vec<ToolCall>,
413}
414
415#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
416#[non_exhaustive]
417pub enum ModelError {
418    #[error("model unavailable: {0}")]
419    Unavailable(String),
420    #[error("model failed: {0}")]
421    Failed(String),
422    #[error("cancelled")]
423    Cancelled,
424    /// No inference node of a model pool could be reached (none found, or every one was
425    /// unreachable, timed out or closed before answering). Apps usually fall back to a local
426    /// model on it; [`remote::pool_model::PoolModel`](crate::remote::pool_model::PoolModel) can do that itself.
427    #[error("model pool unreachable: {0}")]
428    PoolUnreachable(String),
429}
430
431/// Where a turn's model runs, when that changes during the turn: shown to the user as a short
432/// note ([`AgentEvent::ModelNotice`]), never part of the turn's text.
433#[derive(Debug, Clone, PartialEq, Eq)]
434#[non_exhaustive]
435pub enum ModelNotice {
436    /// A node failed mid-answer and the answer continues on `node` from `offset` characters,
437    /// with no text repeated.
438    Continued { node: String, offset: u64 },
439    /// The pool could not take the turn before any text streamed (`reason`), so `to` (usually
440    /// the local model) runs it instead.
441    FellBack { reason: String, to: String },
442    /// The chosen model `from` can't read this turn's `needs` (for example "images"), so the
443    /// pool picks a model that can.
444    Rerouted { from: String, needs: String },
445}
446
447/// Where a backend streams text as it is sampled.
448#[derive(Debug, Clone)]
449pub struct DeltaSink {
450    tx: Option<UnboundedSender<AgentEvent>>,
451}
452
453impl DeltaSink {
454    pub fn new(tx: Option<UnboundedSender<AgentEvent>>) -> Self {
455        Self { tx }
456    }
457
458    /// A sink that drops everything.
459    pub fn discard() -> Self {
460        Self { tx: None }
461    }
462
463    pub fn text(&self, delta: impl Into<String>) {
464        if let Some(tx) = &self.tx {
465            let _ = tx.send(AgentEvent::TextDelta(delta.into()));
466        }
467    }
468
469    /// Reasoning ("thinking") text, streamed apart from the answer. It is shown but never part
470    /// of the turn's text.
471    pub fn reasoning(&self, delta: impl Into<String>) {
472        if let Some(tx) = &self.tx {
473            let _ = tx.send(AgentEvent::ReasoningDelta(delta.into()));
474        }
475    }
476
477    /// A note about where the model runs ([`ModelNotice`]).
478    pub fn notice(&self, notice: ModelNotice) {
479        if let Some(tx) = &self.tx {
480            let _ = tx.send(AgentEvent::ModelNotice(notice));
481        }
482    }
483}
484
485/// A chat model with tool calling. Implementations should poll `cancel` while
486/// sampling and stream text through `deltas`.
487#[async_trait]
488pub trait ModelBackend: Send + Sync {
489    /// Shown in traces, for example `gemma-4-e4b@node-a`.
490    fn name(&self) -> String;
491
492    async fn complete(&self, messages: &[Message], tools: &[ToolSpec], deltas: &DeltaSink, cancel: &CancelToken) -> Result<ModelTurn, ModelError>;
493}
494
495#[cfg(test)]
496mod tests {
497    use super::*;
498
499    const PNG: &str = "data:image/png;base64,iVBORw0KGgo=";
500
501    #[test]
502    fn text_content_keeps_the_plain_string_wire_form() {
503        let m = Message::user("hi");
504        assert_eq!(serde_json::to_value(&m).unwrap(), serde_json::json!({"role": "user", "content": "hi"}));
505        let cbor = crate::remote::to_cbor(&m).unwrap();
506        #[derive(Deserialize)]
507        struct Old {
508            content: String,
509        }
510        assert_eq!(crate::remote::from_cbor::<Old>(&cbor).unwrap().content, "hi", "a 0.4 peer reads it");
511        let old = serde_json::json!({"role": "user", "content": "from 0.4"});
512        assert_eq!(serde_json::from_value::<Message>(old).unwrap().content, "from 0.4");
513    }
514
515    #[test]
516    fn parts_round_trip_in_json_and_cbor() {
517        let m = Message::user(vec![ContentPart::text("what is it?"), ContentPart::image(PNG), ContentPart::audio("UklGRg==", "wav")]);
518        let j = serde_json::to_value(&m).unwrap();
519        assert_eq!(
520            j["content"],
521            serde_json::json!([
522                {"type": "text", "text": "what is it?"},
523                {"type": "image_url", "image_url": {"url": PNG}},
524                {"type": "input_audio", "input_audio": {"data": "UklGRg==", "format": "wav"}}
525            ])
526        );
527        assert_eq!(serde_json::from_value::<Message>(j).unwrap(), m);
528        let back: Message = crate::remote::from_cbor(&crate::remote::to_cbor(&m).unwrap()).unwrap();
529        assert_eq!(back, m);
530        assert_eq!(m.needs(), Modalities::new(true, true));
531        assert_eq!(m.text(), "what is it?");
532    }
533
534    #[test]
535    fn needs_covers_and_lacking() {
536        let msgs = [Message::system("s"), Message::user(vec![ContentPart::image(PNG)])];
537        let n = needs(&msgs);
538        assert_eq!(n, Modalities::VISION);
539        assert!(Modalities::VISION.covers(n) && !Modalities::TEXT.covers(n) && !Modalities::AUDIO.covers(n));
540        assert_eq!(Modalities::TEXT.lacking(Modalities::new(true, true)), Some("images and audio"));
541        assert_eq!(Modalities::VISION.lacking(n), None);
542        assert!(needs(&[Message::user("x")]).is_text());
543    }
544
545    #[test]
546    fn check_refuses_remote_images_and_empty_audio() {
547        assert!(Content::from(vec![ContentPart::image(PNG)]).check().is_ok());
548        assert!(Content::from(vec![ContentPart::image("https://example.com/a.png")]).check().is_err());
549        assert!(Content::from(vec![ContentPart::audio("", "wav")]).check().is_err());
550        assert!(Content::from("text").check().is_ok());
551    }
552
553    const MP4: &str = "data:video/mp4;base64,AAAAIGZ0eXBpc29t";
554
555    #[test]
556    fn video_parts_round_trip_in_json_and_cbor() {
557        let m = Message::user(vec![ContentPart::text("what happens?"), ContentPart::video(MP4)]);
558        let j = serde_json::to_value(&m).unwrap();
559        assert_eq!(j["content"], serde_json::json!([{"type": "text", "text": "what happens?"}, {"type": "video_url", "video_url": {"url": MP4}}]));
560        assert_eq!(serde_json::from_value::<Message>(j).unwrap(), m);
561        let cbor = crate::remote::to_cbor(&m).unwrap();
562        assert_eq!(crate::remote::from_cbor::<Message>(&cbor).unwrap(), m);
563        assert_eq!(m.needs(), Modalities::VIDEO);
564        assert_eq!(m.text(), "what happens?");
565        let mixed = Message::user(vec![ContentPart::image(PNG), ContentPart::video(MP4), ContentPart::audio("UklGRg==", "wav")]);
566        assert_eq!(mixed.needs(), Modalities::new(true, true).with_video(true));
567        // A part this version doesn't know (a newer one) fails the message, as a video part does
568        // for peers before 0.5.10; routing keeps it away from them.
569        let newer = serde_json::json!({"role": "user", "content": [{"type": "hologram_url", "hologram_url": {"url": "x"}}]});
570        assert!(serde_json::from_value::<Message>(newer).is_err());
571    }
572
573    #[test]
574    fn video_bytes_mime_and_size() {
575        let clip = b"\x00\x00\x00\x20ftypisom-a-tiny-clip";
576        let ContentPart::VideoUrl { video_url } = ContentPart::video_bytes(clip, "video/mp4") else { panic!("a video part") };
577        assert!(video_url.url.starts_with("data:video/mp4;base64,"));
578        assert_eq!(video_url.mime_type(), Some("video/mp4"));
579        assert_eq!(video_url.data_len(), Some(clip.len() as u64));
580        for n in 0..8usize {
581            let ContentPart::VideoUrl { video_url } = ContentPart::video_bytes(&vec![7u8; n], "video/webm") else { unreachable!() };
582            assert_eq!(video_url.data_len(), Some(n as u64), "{n} bytes");
583        }
584        let remote = VideoUrl { url: "https://example.com/a.mp4".into() };
585        assert_eq!((remote.mime_type(), remote.data_len()), (None, None));
586        assert_eq!(VideoUrl { url: "data:video/mp4,raw".into() }.data_len(), None, "not base64");
587        assert!(Content::from(vec![ContentPart::video(MP4)]).check().is_ok());
588        assert!(Content::from(vec![ContentPart::video("https://example.com/a.mp4")]).check().is_err());
589        assert!(Content::from(vec![ContentPart::video("data:image/png;base64,iVBORw0KGgo=")]).check().is_err());
590        let v = Content::from(vec![ContentPart::video(MP4)]);
591        assert_eq!(v.clone().normalized(), v, "video stays parts");
592    }
593
594    #[test]
595    fn video_modality() {
596        let v = Modalities::VIDEO;
597        assert!(!v.is_text() && v.video && !v.vision && !v.audio);
598        assert_eq!(Modalities::new(true, false).with_video(true), Modalities::VISION.union(Modalities::VIDEO));
599        assert!(Modalities::VIDEO.covers(Modalities::VIDEO) && !Modalities::new(true, true).covers(Modalities::VIDEO));
600        assert!(Modalities::VIDEO.covers(Modalities::TEXT) && !Modalities::VIDEO.covers(Modalities::VISION));
601        let all = Modalities::new(true, true).with_video(true);
602        assert_eq!(Modalities::TEXT.lacking(all), Some("images, audio and video"));
603        assert_eq!(Modalities::AUDIO.lacking(all), Some("images and video"));
604        assert_eq!(Modalities::VISION.lacking(all), Some("audio and video"));
605        assert_eq!(Modalities::VIDEO.lacking(all), Some("images and audio"));
606        assert_eq!(Modalities::new(true, true).lacking(all), Some("video"));
607        assert_eq!(all.lacking(all), None);
608        // On the wire: absent unless set, and older peers' records read as no video.
609        assert_eq!(serde_json::to_value(Modalities::new(true, true)).unwrap(), serde_json::json!({"vision": true, "audio": true}));
610        assert_eq!(serde_json::to_value(Modalities::VIDEO).unwrap(), serde_json::json!({"video": true}));
611        assert_eq!(serde_json::from_str::<Modalities>(r#"{"vision":true}"#).unwrap(), Modalities::VISION);
612        let back: Modalities = crate::remote::from_cbor(&crate::remote::to_cbor(&all).unwrap()).unwrap();
613        assert_eq!(back, all);
614        #[derive(Deserialize, PartialEq, Debug)]
615        struct Old {
616            #[serde(default)]
617            vision: bool,
618            #[serde(default)]
619            audio: bool,
620        }
621        let old: Old = crate::remote::from_cbor(&crate::remote::to_cbor(&all).unwrap()).unwrap();
622        assert_eq!(old, Old { vision: true, audio: true }, "a 0.5.9 peer reads the rest and ignores video");
623    }
624
625    #[test]
626    fn text_parts_normalize_to_a_string() {
627        let c = Content::from(vec![ContentPart::text("a"), ContentPart::text("b")]).normalized();
628        assert_eq!(c, Content::Text("ab".into()));
629        let img = Content::from(vec![ContentPart::image(PNG)]);
630        assert_eq!(img.clone().normalized(), img);
631    }
632}