Skip to main content

byob_protocol/
queue.rs

1//! Message queueing: follow-ups typed while a reply runs.
2//!
3//! While a chat is busy, [`crate::ClientMsg::SendMessage`] appends to that chat's queue in the
4//! engine instead of being refused. When the running turn ends normally the engine starts the
5//! first queued message as the next turn, and so on. A turn that is stopped or fails pauses the
6//! queue ([`ChatQueue::paused`]); it stays, untouched, until a client resumes it
7//! ([`crate::ClientMsg::ResumeQueue`]), sends one item now ([`crate::ClientMsg::SendQueuedNow`])
8//! or retries the failed reply. A turn waiting for an approval simply keeps the queue waiting.
9//!
10//! The queue lives in the engine (so every client of the chat sees the same one, and it
11//! survives a closed window or tab) but only in memory: it is gone after an engine restart.
12//! Queued messages are not part of the transcript until they are sent.
13
14use serde::{Deserialize, Serialize};
15
16use crate::{ClientMsg, MediaRef};
17
18/// Most messages queued in one chat.
19pub const MAX_QUEUED: usize = 20;
20/// Most bytes of text in one queued message.
21pub const MAX_QUEUED_TEXT_BYTES: usize = 256 * 1024;
22/// Most bytes of text in one chat's whole queue.
23pub const MAX_QUEUE_BYTES: usize = 1024 * 1024;
24
25/// A message waiting to be sent.
26#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
27pub struct QueuedMessage {
28    /// Unique within the engine run.
29    pub id: u64,
30    /// The whole text (clients show a preview and edit the whole).
31    pub text: String,
32    /// Files it carries, uploaded before it was queued.
33    #[serde(default, skip_serializing_if = "Vec::is_empty")]
34    pub attachments: Vec<MediaRef>,
35}
36
37impl QueuedMessage {
38    /// The text on one line (whitespace runs, newlines included, become one space),
39    /// shortened to `max` characters, for a compact row.
40    pub fn preview(&self, max: usize) -> String {
41        let mut out = String::new();
42        for (i, word) in self.text.split_whitespace().enumerate() {
43            if i > 0 {
44                out.push(' ');
45            }
46            out.push_str(word);
47            if out.chars().count() > max {
48                break;
49            }
50        }
51        if out.chars().count() > max {
52            out = out.chars().take(max).collect();
53            out.push('…');
54        }
55        out
56    }
57}
58
59/// Why a queue stopped moving on.
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
61#[serde(rename_all = "snake_case")]
62pub enum QueuePause {
63    /// The user stopped the reply.
64    Stopped,
65    /// The reply failed (or the next one couldn't start).
66    Failed,
67}
68
69/// The queue of the chat a client looks at (`chat: None` for a new chat: always empty).
70/// Sent after [`crate::ServerMsg::Transcript`] and whenever it changes; replaces the
71/// client's copy.
72#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
73pub struct ChatQueue {
74    pub chat: Option<String>,
75    /// In the order they will be sent.
76    pub items: Vec<QueuedMessage>,
77    /// The queue waits for the user instead of sending the next message when the chat is free.
78    #[serde(default, skip_serializing_if = "Option::is_none")]
79    pub paused: Option<QueuePause>,
80}
81
82/// Size checks of the queue messages (see [`ClientMsg::check_sizes`]).
83pub(crate) fn check_sizes(msg: &ClientMsg) -> Result<(), String> {
84    match msg {
85        ClientMsg::EditQueued { text, attachments, .. } => {
86            if text.len() > MAX_QUEUED_TEXT_BYTES {
87                return Err(format!("a queued message can be at most {} KB", MAX_QUEUED_TEXT_BYTES / 1024));
88            }
89            if attachments.len() > crate::media::MAX_ATTACHMENTS {
90                return Err(format!("at most {} files per message", crate::media::MAX_ATTACHMENTS));
91            }
92            Ok(())
93        }
94        _ => Ok(()),
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101    use crate::ServerMsg;
102
103    #[test]
104    fn queue_messages_round_trip() {
105        let q = ChatQueue {
106            chat: Some("c1".into()),
107            items: vec![QueuedMessage { id: 3, text: "and then?".into(), attachments: vec![MediaRef::new("uploads/a.csv", 3)] }],
108            paused: Some(QueuePause::Stopped),
109        };
110        let m = ServerMsg::Queue(q);
111        assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
112        for m in [
113            ClientMsg::Unqueue { id: 3 },
114            ClientMsg::EditQueued { id: 3, text: "x".into(), attachments: vec!["uploads/a.csv".into()] },
115            ClientMsg::MoveQueued { id: 3, to: 0 },
116            ClientMsg::SendQueuedNow { id: 3 },
117            ClientMsg::ResumeQueue,
118        ] {
119            assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
120        }
121        assert_eq!(ClientMsg::ResumeQueue.to_json(), r#"{"type":"resume_queue"}"#);
122        let empty = ServerMsg::Queue(ChatQueue::default()).to_json();
123        assert_eq!(empty, r#"{"type":"queue","chat":null,"items":[]}"#);
124    }
125
126    #[test]
127    fn edits_are_size_checked_and_previews_are_short() {
128        let big = ClientMsg::EditQueued { id: 1, text: "x".repeat(MAX_QUEUED_TEXT_BYTES + 1), attachments: vec![] };
129        assert!(big.check_sizes().is_err());
130        let many = ClientMsg::EditQueued { id: 1, text: "x".into(), attachments: vec!["a".into(); crate::media::MAX_ATTACHMENTS + 1] };
131        assert!(many.check_sizes().is_err());
132        let q = |t: &str| QueuedMessage { id: 1, text: t.into(), attachments: vec![] };
133        assert_eq!(q("\n  first line  \nsecond").preview(40), "first line second");
134        assert_eq!(q("abcdef").preview(3), "abc…");
135        assert_eq!(q("abc").preview(3), "abc");
136    }
137}