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//!
14//! Steering ([`crate::ClientMsg::Steer`], engine cap [`CAP_STEER`]): a message meant for the
15//! reply that is running waits in the same queue, marked [`QueuedMessage::steer`], ahead of
16//! the ones sent with [`crate::ClientMsg::SendMessage`]. At the reply's next step (its tool
17//! calls have finished, the next model request hasn't gone yet) the engine takes every
18//! steering item out of the queue and the reply goes on with them in view: the transcript
19//! shows the reply up to there, the user's message (one entry, the items joined), and the
20//! rest of the reply as a new assistant entry, so later requests (and a reload) see the same
21//! order. A reply that ends without another step leaves them in the queue as ordinary items
22//! (the first one starts the next turn); a stop pauses them with the rest.
23
24use serde::{Deserialize, Serialize};
25
26use crate::{ClientMsg, MediaRef};
27
28/// Engine cap: it takes [`crate::ClientMsg::Steer`] (send it only to an engine that lists it).
29pub const CAP_STEER: &str = "steer";
30
31/// Most messages queued in one chat.
32pub const MAX_QUEUED: usize = 20;
33/// Most bytes of text in one queued message.
34pub const MAX_QUEUED_TEXT_BYTES: usize = 256 * 1024;
35/// Most bytes of text in one chat's whole queue.
36pub const MAX_QUEUE_BYTES: usize = 1024 * 1024;
37
38/// A message waiting to be sent.
39#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40pub struct QueuedMessage {
41    /// Unique within the engine run.
42    pub id: u64,
43    /// The whole text (clients show a preview and edit the whole).
44    pub text: String,
45    /// Files it carries, uploaded before it was queued.
46    #[serde(default, skip_serializing_if = "Vec::is_empty")]
47    pub attachments: Vec<MediaRef>,
48    /// For the reply running now: it reaches the model at the reply's next step instead of
49    /// waiting for the reply to end.
50    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
51    pub steer: bool,
52}
53
54impl QueuedMessage {
55    /// The text on one line (whitespace runs, newlines included, become one space),
56    /// shortened to `max` characters, for a compact row.
57    pub fn preview(&self, max: usize) -> String {
58        let mut out = String::new();
59        for (i, word) in self.text.split_whitespace().enumerate() {
60            if i > 0 {
61                out.push(' ');
62            }
63            out.push_str(word);
64            if out.chars().count() > max {
65                break;
66            }
67        }
68        if out.chars().count() > max {
69            out = out.chars().take(max).collect();
70            out.push('…');
71        }
72        out
73    }
74}
75
76/// Why a queue stopped moving on.
77#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
78#[serde(rename_all = "snake_case")]
79pub enum QueuePause {
80    /// The user stopped the reply.
81    Stopped,
82    /// The reply failed (or the next one couldn't start).
83    Failed,
84}
85
86/// The queue of the chat a client looks at (`chat: None` for a new chat: always empty).
87/// Sent after [`crate::ServerMsg::Transcript`] and whenever it changes; replaces the
88/// client's copy.
89#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
90pub struct ChatQueue {
91    pub chat: Option<String>,
92    /// In the order they will be sent.
93    pub items: Vec<QueuedMessage>,
94    /// The queue waits for the user instead of sending the next message when the chat is free.
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub paused: Option<QueuePause>,
97}
98
99/// Size checks of the queue messages (see [`ClientMsg::check_sizes`]).
100pub(crate) fn check_sizes(msg: &ClientMsg) -> Result<(), String> {
101    match msg {
102        ClientMsg::EditQueued { text, attachments, .. } => {
103            if text.len() > MAX_QUEUED_TEXT_BYTES {
104                return Err(format!("a queued message can be at most {} KB", MAX_QUEUED_TEXT_BYTES / 1024));
105            }
106            if attachments.len() > crate::media::MAX_ATTACHMENTS {
107                return Err(format!("at most {} files per message", crate::media::MAX_ATTACHMENTS));
108            }
109            Ok(())
110        }
111        _ => Ok(()),
112    }
113}
114
115#[cfg(test)]
116mod tests {
117    use super::*;
118    use crate::ServerMsg;
119
120    #[test]
121    fn queue_messages_round_trip() {
122        let q = ChatQueue {
123            chat: Some("c1".into()),
124            items: vec![
125                QueuedMessage { id: 4, text: "not that file".into(), attachments: vec![], steer: true },
126                QueuedMessage { id: 3, text: "and then?".into(), attachments: vec![MediaRef::new("uploads/a.csv", 3)], steer: false },
127            ],
128            paused: Some(QueuePause::Stopped),
129        };
130        let m = ServerMsg::Queue(q);
131        assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
132        for m in [
133            ClientMsg::Unqueue { id: 3 },
134            ClientMsg::EditQueued { id: 3, text: "x".into(), attachments: vec!["uploads/a.csv".into()] },
135            ClientMsg::MoveQueued { id: 3, to: 0 },
136            ClientMsg::SendQueuedNow { id: 3 },
137            ClientMsg::ResumeQueue,
138            ClientMsg::Steer { text: "use the other file".into(), attachments: vec!["uploads/b.png".into()] },
139        ] {
140            assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
141        }
142        assert_eq!(ClientMsg::Steer { text: "x".into(), attachments: vec![] }.to_json(), r#"{"type":"steer","text":"x"}"#);
143        // Older peers: an ordinary item has no `steer` key, and one without it is ordinary.
144        let json =
145            ServerMsg::Queue(ChatQueue { chat: None, items: vec![QueuedMessage { id: 1, text: "x".into(), attachments: vec![], steer: false }], paused: None })
146                .to_json();
147        assert!(!json.contains("steer"), "{json}");
148        let old: QueuedMessage = serde_json::from_str(r#"{"id":1,"text":"x"}"#).unwrap();
149        assert!(!old.steer);
150        assert_eq!(ClientMsg::ResumeQueue.to_json(), r#"{"type":"resume_queue"}"#);
151        let empty = ServerMsg::Queue(ChatQueue::default()).to_json();
152        assert_eq!(empty, r#"{"type":"queue","chat":null,"items":[]}"#);
153    }
154
155    #[test]
156    fn edits_are_size_checked_and_previews_are_short() {
157        let big = ClientMsg::EditQueued { id: 1, text: "x".repeat(MAX_QUEUED_TEXT_BYTES + 1), attachments: vec![] };
158        assert!(big.check_sizes().is_err());
159        let many = ClientMsg::EditQueued { id: 1, text: "x".into(), attachments: vec!["a".into(); crate::media::MAX_ATTACHMENTS + 1] };
160        assert!(many.check_sizes().is_err());
161        let q = |t: &str| QueuedMessage { id: 1, text: t.into(), attachments: vec![], steer: false };
162        assert_eq!(q("\n  first line  \nsecond").preview(40), "first line second");
163        assert_eq!(q("abcdef").preview(3), "abc…");
164        assert_eq!(q("abc").preview(3), "abc");
165    }
166}