1#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]
7
8pub mod artifact;
9pub mod connect;
10pub mod delegation;
11pub mod env;
12pub mod media;
13pub mod plugins;
14pub mod queue;
15pub mod sites;
16pub mod tree;
17pub mod usage;
18pub mod version;
19pub mod view;
20pub mod web;
21pub mod workspace;
22
23use serde::{Deserialize, Serialize};
24
25pub use artifact::{Artifact, ArtifactKind, ArtifactRef, ArtifactVersion};
26pub use connect::{Detected, InferenceTest, Link, PRESETS, Preset, Problem};
27pub use delegation::{Delegation, DelegationState, DelegationUpdate};
28pub use env::{ContainerEnv, EnvAction, EnvSupport, WorkspaceEnv};
29pub use media::{MediaContent, MediaKind, MediaRef};
30pub use plugins::{
31 BackendInfo, Extensions, PluginAction, PluginCard, PluginInfo, PluginLoadError, PluginOrigin, PluginScope, PluginSetting, PluginTest, RendererDecl,
32 ServerInfo, ServerState, SlashItem, SlashKind, StarterDecl,
33};
34pub use queue::{ChatQueue, QueuePause, QueuedMessage};
35pub use sites::{LiveView, Site, ViewDecl, ViewRef};
36pub use usage::{ChatUsage, Compaction};
37pub use version::{PROTOCOL_MAJOR, PROTOCOL_MINOR, Welcome};
38pub use view::{View, ViewData};
39pub use workspace::{ChatEndpoint, ConfigScope, ConfigView, FolderList, NewFolder, WorkspaceSummary};
40
41pub const MAX_FRAME_BYTES: usize = 4 * 1024 * 1024;
43
44#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
46#[serde(tag = "type", rename_all = "snake_case")]
47pub enum ClientMsg {
48 Hello {
52 protocol: u32,
53 #[serde(default)]
54 minor: u32,
55 client: String,
56 #[serde(default)]
57 caps: Vec<String>,
58 },
59 SetInference {
63 base_url: String,
64 model: String,
65 api_key: Option<String>,
66 },
67 TestInference {
70 base_url: String,
71 model: String,
72 #[serde(default, skip_serializing_if = "Option::is_none")]
73 api_key: Option<String>,
74 },
75 DetectEndpoints,
78 Retry,
81 SendMessage {
85 text: String,
86 #[serde(default, skip_serializing_if = "Vec::is_empty")]
87 attachments: Vec<String>,
88 },
89 Cancel,
91 Unqueue {
93 id: u64,
94 },
95 EditQueued {
98 id: u64,
99 text: String,
100 #[serde(default, skip_serializing_if = "Vec::is_empty")]
101 attachments: Vec<String>,
102 },
103 MoveQueued {
105 id: u64,
106 to: u32,
107 },
108 SendQueuedNow {
110 id: u64,
111 },
112 ResumeQueue,
114 Approve {
117 step: u64,
118 answer: ApprovalAnswer,
119 },
120 AnswerQuestion {
124 step: u64,
125 text: String,
126 },
127 Undo {
130 entry: u64,
131 },
132 ListChats {
135 after: Option<ChatCursor>,
136 limit: u32,
137 },
138 NewChat {
142 #[serde(default, skip_serializing_if = "Option::is_none")]
143 workspace: Option<String>,
144 },
145 OpenChat {
147 id: String,
148 },
149 RenameChat {
150 id: String,
151 title: String,
152 },
153 DeleteChat {
155 id: String,
156 },
157 PinChat {
158 id: String,
159 pinned: bool,
160 },
161 Upload {
166 upload: u64,
167 name: String,
168 size: u64,
169 offset: u64,
170 data: String,
171 done: bool,
172 },
173 GetMedia {
175 path: String,
176 },
177 GetArtifact {
180 id: String,
181 version: u32,
182 },
183 Compact {
186 #[serde(default, skip_serializing_if = "Option::is_none")]
187 focus: Option<String>,
188 },
189 WorkspaceEnv {
192 #[serde(default, skip_serializing_if = "Option::is_none")]
193 action: Option<EnvAction>,
194 #[serde(default, skip_serializing_if = "Option::is_none")]
195 workspace: Option<String>,
196 },
197 CreateWorkspace {
201 name: String,
202 folder: NewFolder,
203 #[serde(default)]
204 config: workspace::Layer,
205 },
206 RenameWorkspace {
207 id: String,
208 name: String,
209 },
210 RemoveWorkspace {
213 id: String,
214 #[serde(default)]
215 clean: bool,
216 },
217 GetConfig {
219 scope: ConfigScope,
220 },
221 SetConfig {
225 scope: ConfigScope,
226 layer: workspace::Layer,
227 #[serde(default, skip_serializing_if = "Option::is_none")]
228 api_key: Option<String>,
229 },
230 ListFolders {
233 #[serde(default, skip_serializing_if = "Option::is_none")]
234 path: Option<String>,
235 },
236 CheckContainers,
238 GetExtensions,
240 SetPluginEnabled {
244 scope: ConfigScope,
245 plugin: String,
246 enabled: Option<bool>,
247 },
248 SetPluginSetting {
252 plugin: String,
253 key: String,
254 value: Option<String>,
255 },
256 KeepPlugin {
260 plugin: String,
261 scope: PluginScope,
262 #[serde(default, skip_serializing_if = "Option::is_none")]
263 new_id: Option<String>,
264 },
265 RemovePlugin {
268 plugin: String,
269 scope: PluginScope,
270 },
271 ReloadPlugins,
273 TrustPlugins {
277 workspace: String,
278 #[serde(default)]
279 plugins: Vec<String>,
280 trust: bool,
281 },
282 Plugin {
285 plugin: String,
286 msg: serde_json::Value,
287 },
288 OpenView {
292 view: ViewRef,
293 },
294 CloseView {
296 view: ViewRef,
297 },
298 ViewEvent {
301 view: ViewRef,
302 event: tree::Event,
303 },
304 WebCall {
309 call: u64,
310 owner: web::WebOwner,
311 method: String,
312 #[serde(default)]
313 params: serde_json::Value,
314 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
315 approved: bool,
316 },
317 #[serde(other)]
319 Unknown,
320}
321
322#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
324#[serde(tag = "type", rename_all = "snake_case")]
325pub enum ServerMsg {
326 Welcome(Welcome),
328 State(EngineState),
330 Notice { level: NoticeLevel, text: String },
332 Transcript { entries: Vec<Entry> },
334 EntryAdded(Entry),
336 EntryDelta { id: u64, content: String, reasoning: String },
338 EntryFinished { id: u64, error: Option<String>, stats: Option<TurnStats> },
340 StepUpdated { entry: u64, step: Step },
342 EntryUndo { id: u64, undoable: bool, undone: bool },
344 Chats { pinned: Vec<ChatSummary>, recent: Vec<ChatSummary>, after: Option<ChatCursor>, next: Option<ChatCursor> },
347 ChatUpdated(ChatSummary),
349 ChatDeleted { id: String },
351 ChatOpened {
355 chat: Option<ChatSummary>,
356 #[serde(default)]
357 workspace: Option<String>,
358 },
359 Uploaded { upload: u64, attachment: Option<MediaRef>, error: Option<String> },
361 Media { path: String, content: MediaContent },
363 Artifacts { chat: Option<String>, artifacts: Vec<Artifact> },
366 ArtifactUpdated(Artifact),
368 ArtifactFile { id: String, version: u32, data: Option<String>, error: Option<String> },
370 Usage(ChatUsage),
372 Compactions { chat: Option<String>, items: Vec<Compaction> },
375 Compacted(Compaction),
377 Delegation { entry: u64, step: u64, update: DelegationUpdate },
379 InferenceTested(InferenceTest),
381 WorkspaceEnv(WorkspaceEnv),
383 Workspaces { items: Vec<WorkspaceSummary>, current: Option<String>, root: String, support: EnvSupport },
387 Config(Box<ConfigView>),
389 Folders(FolderList),
391 ContainersChecked { ok: bool, message: String },
393 WorkspaceCreated { id: Option<String>, error: Option<String> },
395 Queue(ChatQueue),
398 Extensions(Box<Extensions>),
401 Plugin { plugin: String, msg: serde_json::Value },
404 LiveView(LiveView),
407 WebReply {
410 call: u64,
411 #[serde(default, deserialize_with = "present_even_if_null", skip_serializing_if = "Option::is_none")]
413 result: Option<serde_json::Value>,
414 #[serde(default, skip_serializing_if = "Option::is_none")]
415 error: Option<web::WebError>,
416 },
417 WebPush { owner: web::WebOwner, msg: serde_json::Value },
420 #[serde(other)]
422 Unknown,
423}
424
425#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
427pub struct ChatSummary {
428 pub id: String,
429 pub title: String,
430 pub updated_at: i64,
432 pub pinned_at: Option<i64>,
434 #[serde(default)]
436 pub busy: bool,
437 #[serde(default, skip_serializing_if = "Option::is_none")]
439 pub workspace: Option<String>,
440}
441
442impl ChatSummary {
443 pub fn cursor(&self) -> ChatCursor {
444 ChatCursor { updated_at: self.updated_at, id: self.id.clone() }
445 }
446}
447
448#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
450pub struct ChatCursor {
451 pub updated_at: i64,
452 pub id: String,
453}
454
455#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
456#[serde(rename_all = "snake_case")]
457pub enum EntryRole {
458 User,
459 Assistant,
460}
461
462#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
464pub struct Entry {
465 pub id: u64,
466 pub role: EntryRole,
467 pub content: String,
468 pub reasoning: String,
469 pub done: bool,
471 pub error: Option<String>,
472 pub stats: Option<TurnStats>,
473 #[serde(default)]
476 pub steps: Vec<Step>,
477 #[serde(default)]
479 pub undoable: bool,
480 #[serde(default)]
482 pub undone: bool,
483 #[serde(default, skip_serializing_if = "Vec::is_empty")]
485 pub attachments: Vec<MediaRef>,
486}
487
488impl Entry {
489 pub fn append(&mut self, content: &str, reasoning: &str) {
491 self.content.push_str(content);
492 self.reasoning.push_str(reasoning);
493 }
494
495 pub fn upsert_step(&mut self, step: Step) {
497 match self.steps.iter_mut().find(|s| s.id == step.id) {
498 Some(existing) => *existing = step,
499 None => self.steps.push(step),
500 }
501 }
502
503 pub fn pending_approvals(&self) -> impl Iterator<Item = &Step> {
505 self.steps.iter().flat_map(|s| std::iter::once(s).chain(s.delegation.iter().flat_map(|d| d.steps.iter()))).filter(|s| s.status == StepStatus::Waiting)
506 }
507
508 pub fn apply_delegation(&mut self, step: u64, update: &DelegationUpdate) {
510 if let Some(d) = self.steps.iter_mut().find(|s| s.id == step).and_then(|s| s.delegation.as_deref_mut()) {
511 d.apply(update);
512 }
513 }
514}
515
516#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
518#[serde(rename_all = "snake_case")]
519pub enum ToolAccess {
520 Read,
521 Write,
522 Network,
523 Execute,
524}
525
526impl ToolAccess {
527 pub fn label(self) -> &'static str {
528 match self {
529 Self::Read => "read",
530 Self::Write => "write",
531 Self::Network => "network",
532 Self::Execute => "execute",
533 }
534 }
535}
536
537#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
538#[serde(rename_all = "snake_case")]
539pub enum StepStatus {
540 Running,
541 Waiting,
543 Done,
544 Failed,
546 Denied,
548}
549
550impl StepStatus {
551 pub fn finished(self) -> bool {
552 matches!(self, Self::Done | Self::Failed | Self::Denied)
553 }
554}
555
556#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
558#[serde(rename_all = "snake_case")]
559pub enum ApprovalAnswer {
560 Allow,
561 Always,
563 Deny,
564 AlwaysEverywhere,
566 #[serde(other)]
568 Unknown,
569}
570
571#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
573#[serde(tag = "kind", rename_all = "snake_case")]
574pub enum FileChange {
575 Created {
576 path: String,
577 },
578 Modified {
579 path: String,
580 },
581 Deleted {
582 path: String,
583 },
584 Moved {
585 from: String,
586 to: String,
587 },
588 #[serde(other)]
590 Other,
591}
592
593#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
595pub struct Step {
596 pub id: u64,
598 pub tool: String,
600 pub title: String,
602 pub access: ToolAccess,
603 pub status: StepStatus,
604 pub detail: String,
606 #[serde(default)]
607 pub changes: Vec<FileChange>,
608 #[serde(default)]
610 pub at: usize,
611 #[serde(default, skip_serializing_if = "Vec::is_empty")]
613 pub media: Vec<MediaRef>,
614 #[serde(default, skip_serializing_if = "Option::is_none")]
616 pub preview: Option<Preview>,
617 #[serde(default, skip_serializing_if = "Vec::is_empty")]
619 pub artifacts: Vec<ArtifactRef>,
620 #[serde(default, skip_serializing_if = "Option::is_none")]
622 pub delegation: Option<Box<Delegation>>,
623 #[serde(default, skip_serializing_if = "Option::is_none")]
627 pub ask: Option<Box<Ask>>,
628 #[serde(default, skip_serializing_if = "Vec::is_empty")]
632 pub views: Vec<View>,
633}
634
635impl Step {
636 pub fn view<T: ViewData>(&self) -> Option<T> {
638 self.views.iter().find_map(View::get)
639 }
640}
641
642#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
644pub struct Ask {
645 #[serde(default)]
647 pub text: String,
648 #[serde(default, skip_serializing_if = "Option::is_none")]
650 pub warning: Option<String>,
651 #[serde(default)]
653 pub always: bool,
654 #[serde(default, skip_serializing_if = "Option::is_none")]
658 pub choice: Option<Choice>,
659}
660
661pub const MAX_CHOICE_OPTIONS: usize = 8;
663pub const MAX_ANSWER_CHARS: usize = 2000;
665
666#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
668pub struct Choice {
669 #[serde(default, skip_serializing_if = "Vec::is_empty")]
671 pub options: Vec<String>,
672 #[serde(default)]
674 pub free_text: bool,
675 #[serde(default, skip_serializing_if = "Option::is_none")]
677 pub answer: Option<String>,
678}
679
680pub const MAX_PREVIEW_LINES: usize = 40;
682pub const MAX_PREVIEW_LINE_CHARS: usize = 300;
684
685#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
687#[serde(tag = "kind", rename_all = "snake_case")]
688pub enum Preview {
689 Write {
692 path: String,
693 bytes: u64,
694 replaces: bool,
696 lines: Vec<DiffLine>,
697 #[serde(default)]
699 more: usize,
700 },
701 Move {
703 moves: Vec<(String, String)>,
704 #[serde(default)]
705 more: usize,
706 },
707 Delete { path: String, what: String },
709 Args {
711 fields: Vec<(String, String)>,
712 #[serde(default, skip_serializing_if = "Option::is_none")]
713 code: Option<String>,
714 #[serde(default)]
715 more: usize,
716 },
717 #[serde(other)]
719 Other,
720}
721
722#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
724pub struct DiffLine {
725 pub kind: LineKind,
726 pub text: String,
727}
728
729#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
730#[serde(rename_all = "snake_case")]
731pub enum LineKind {
732 Same,
734 Added,
735 Removed,
736 Skipped,
738}
739
740#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
741pub struct TurnStats {
742 pub prompt_tokens: u64,
743 pub completion_tokens: u64,
744 pub elapsed_ms: u64,
745 #[serde(default)]
747 pub model_calls: u64,
748}
749
750#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
751#[serde(rename_all = "snake_case")]
752pub enum NoticeLevel {
753 Error,
754 #[serde(other)]
756 Info,
757}
758
759#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
761pub struct EngineState {
762 pub version: String,
763 pub inference_base_url: String,
764 pub inference_model: String,
765 pub has_api_key: bool,
766 pub endpoint: Option<String>,
768 pub busy: bool,
770 #[serde(default)]
772 pub endpoint_info: Option<EndpointInfo>,
773 #[serde(default)]
775 pub link: Link,
776 #[serde(default)]
779 pub onboarded: bool,
780 #[serde(default)]
782 pub detected: Vec<Detected>,
783 #[serde(default)]
785 pub detecting: bool,
786 #[serde(default, skip_serializing_if = "Option::is_none")]
789 pub chat_endpoint: Option<ChatEndpoint>,
790}
791
792#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
794#[serde(rename_all = "snake_case")]
795pub enum ToolsMode {
796 Native,
798 Prompt,
800 #[default]
802 Unknown,
803}
804
805#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
807pub struct EndpointInfo {
808 #[serde(default)]
810 pub probing: bool,
811 #[serde(default)]
813 pub server: String,
814 #[serde(default)]
816 pub context_tokens: Option<u64>,
817 #[serde(default)]
818 pub tools: ToolsMode,
819 #[serde(default)]
821 pub vision: Option<bool>,
822}
823
824impl EndpointInfo {
825 pub fn summary(&self) -> String {
827 if self.probing {
828 return "checking endpoint…".into();
829 }
830 let mut parts = Vec::new();
831 if !self.server.is_empty() {
832 parts.push(self.server.clone());
833 }
834 if let Some(n) = self.context_tokens {
835 parts.push(if n >= 1000 { format!("{}k ctx", n / 1000) } else { format!("{n} ctx") });
836 }
837 parts.push(
838 match self.tools {
839 ToolsMode::Native => "native tools",
840 ToolsMode::Prompt => "prompt tools",
841 ToolsMode::Unknown => "tools untested",
842 }
843 .into(),
844 );
845 if self.vision == Some(true) {
846 parts.push("vision".into());
847 }
848 parts.join(" · ")
849 }
850}
851
852impl ClientMsg {
853 pub fn hello(client: &str) -> Self {
855 Self::Hello { protocol: PROTOCOL_MAJOR, minor: PROTOCOL_MINOR, client: client.to_owned(), caps: version::client_caps() }
856 }
857
858 pub fn to_json(&self) -> String {
859 serde_json::to_string(self).unwrap_or_default()
860 }
861
862 pub fn from_json(text: &str) -> Result<Self, String> {
864 if text.len() > MAX_FRAME_BYTES {
865 return Err(format!("frame too large ({} bytes)", text.len()));
866 }
867 serde_json::from_str(text).map_err(|e| e.to_string())
868 }
869}
870
871impl ServerMsg {
872 pub fn to_json(&self) -> String {
873 serde_json::to_string(self).unwrap_or_default()
874 }
875
876 pub fn to_frame(&self) -> String {
882 let json = self.to_json();
883 if json.len() <= MAX_FRAME_BYTES {
884 return json;
885 }
886 let why = format!("it is too large to send over this connection ({} KB, at most {} KB)", json.len() / 1024, MAX_FRAME_BYTES / 1024);
887 let instead = match self {
888 Self::LiveView(lv) if lv.tree.is_none() => Self::LiveView(LiveView { view: lv.view.clone(), reset: true, ..Default::default() }),
889 Self::LiveView(lv) => {
890 Self::LiveView(LiveView { view: lv.view.clone(), error: Some(format!("This view can't be shown here: {why}.")), ..Default::default() })
891 }
892 Self::WebReply { call, .. } => {
893 Self::WebReply { call: *call, result: None, error: Some(web::WebError::new(-32000, format!("byob couldn't send the answer: {why}"))) }
894 }
895 _ => Self::Notice { level: NoticeLevel::Error, text: format!("byob couldn't send an update: {why}.") },
896 };
897 instead.to_json()
898 }
899
900 pub fn from_json(text: &str) -> Result<Self, String> {
902 if text.len() > MAX_FRAME_BYTES {
903 return Err(format!("frame too large ({} bytes)", text.len()));
904 }
905 serde_json::from_str(text).map_err(|e| e.to_string())
906 }
907}
908
909pub trait Connection {
911 fn send(&mut self, msg: ClientMsg);
912 fn try_recv(&mut self) -> Option<ServerMsg>;
914}
915
916fn present_even_if_null<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<serde_json::Value>, D::Error> {
919 serde_json::Value::deserialize(d).map(Some)
920}
921
922#[cfg(test)]
923mod tests {
924 use super::*;
925
926 #[test]
929 fn web_reply_keeps_a_null_result() {
930 let null = ServerMsg::WebReply { call: 3, result: Some(serde_json::Value::Null), error: None };
931 assert_eq!(null.to_json(), r#"{"type":"web_reply","call":3,"result":null}"#);
932 assert_eq!(ServerMsg::from_json(&null.to_json()).unwrap(), null);
933 let none = ServerMsg::WebReply { call: 3, result: None, error: None };
934 assert_eq!(none.to_json(), r#"{"type":"web_reply","call":3}"#);
935 assert_eq!(ServerMsg::from_json(&none.to_json()).unwrap(), none);
936 let value = ServerMsg::WebReply { call: 3, result: Some(serde_json::json!({"a": [1]})), error: None };
937 assert_eq!(ServerMsg::from_json(&value.to_json()).unwrap(), value);
938 }
939
940 #[test]
941 fn client_msg_round_trips() {
942 let m = ClientMsg::hello("test");
943 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
944 }
945
946 #[test]
947 fn wire_format_is_tagged() {
948 let json = ServerMsg::Notice { level: NoticeLevel::Info, text: "hi".into() }.to_json();
949 assert_eq!(json, r#"{"type":"notice","level":"info","text":"hi"}"#);
950 }
951
952 #[test]
953 fn a_message_too_large_for_a_frame_is_sent_as_something_the_client_acts_on() {
954 let big = "x".repeat(MAX_FRAME_BYTES);
955 let r = ViewRef::new("p", "v", "k");
956 let small = ServerMsg::Notice { level: NoticeLevel::Info, text: "hi".into() };
957 assert_eq!(small.to_frame(), small.to_json());
958 let frame = |m: ServerMsg| {
959 let f = m.to_frame();
960 assert!(f.len() < 1024, "{} bytes", f.len());
961 ServerMsg::from_json(&f).unwrap()
962 };
963 let mut values = serde_json::Map::new();
964 values.insert("f".into(), serde_json::json!(big));
965 let change = LiveView { view: r.clone(), values, ..Default::default() };
966 assert_eq!(frame(ServerMsg::LiveView(change)), ServerMsg::LiveView(LiveView { view: r.clone(), reset: true, ..Default::default() }));
967 let texts: Vec<_> = (0..100).map(|_| serde_json::json!({"type": "text", "text": "y".repeat(60_000)})).collect();
969 let (tree, faults) = tree::decode(serde_json::json!({"type": "column", "children": texts}));
970 assert!(faults.is_empty(), "{faults:?}");
971 match frame(ServerMsg::LiveView(LiveView { view: r.clone(), tree: Some(tree), ..Default::default() })) {
972 ServerMsg::LiveView(lv) => assert!(lv.view == r && lv.tree.is_none() && lv.error.is_some_and(|e| e.contains("too large"))),
973 other => panic!("{other:?}"),
974 }
975 match frame(ServerMsg::WebReply { call: 9, result: Some(serde_json::json!(big)), error: None }) {
976 ServerMsg::WebReply { call: 9, result: None, error: Some(e) } => assert!(e.message.contains("too large")),
977 other => panic!("{other:?}"),
978 }
979 let plugin = ServerMsg::Plugin { plugin: "p".into(), msg: serde_json::json!(big) };
980 assert!(matches!(frame(plugin), ServerMsg::Notice { level: NoticeLevel::Error, .. }));
981 }
982
983 #[test]
984 fn rejects_garbage_and_oversized_frames() {
985 assert!(ClientMsg::from_json("{not json").is_err());
986 assert!(ClientMsg::from_json(&" ".repeat(MAX_FRAME_BYTES + 1)).is_err());
987 }
988
989 #[test]
990 fn approve_wire_format() {
991 let m = ClientMsg::Approve { step: 7, answer: ApprovalAnswer::Always };
992 assert_eq!(m.to_json(), r#"{"type":"approve","step":7,"answer":"always"}"#);
993 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
994 }
995
996 fn step(id: u64, status: StepStatus) -> Step {
997 Step {
998 id,
999 tool: "t".into(),
1000 title: "T".into(),
1001 access: ToolAccess::Write,
1002 status,
1003 detail: String::new(),
1004 changes: vec![],
1005 at: 0,
1006 preview: None,
1007 media: vec![],
1008 artifacts: vec![],
1009 delegation: None,
1010 ask: None,
1011 views: vec![],
1012 }
1013 }
1014
1015 #[test]
1016 fn delegations_stream_into_their_step_and_round_trip() {
1017 let mut parent = step(1, StepStatus::Running);
1018 parent.delegation = Some(Box::new(Delegation { agent: "explorer".into(), task: "count lines".into(), ..Default::default() }));
1019 let mut e = Entry {
1020 id: 9,
1021 role: EntryRole::Assistant,
1022 content: String::new(),
1023 reasoning: String::new(),
1024 done: false,
1025 error: None,
1026 stats: None,
1027 steps: vec![parent],
1028 undoable: false,
1029 undone: false,
1030 attachments: vec![],
1031 };
1032 let updates = [
1033 DelegationUpdate::Status { state: DelegationState::Running, prompt_tokens: 0, completion_tokens: 0, error: None },
1034 DelegationUpdate::Delta { content: "Reading".into(), reasoning: "hm".into() },
1035 DelegationUpdate::Step(Box::new(step(2, StepStatus::Waiting))),
1036 DelegationUpdate::Delta { content: " a.txt".into(), reasoning: String::new() },
1037 ];
1038 for u in &updates {
1039 let msg = ServerMsg::Delegation { entry: 9, step: 1, update: u.clone() };
1040 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1041 e.apply_delegation(1, u);
1042 }
1043 e.apply_delegation(77, &updates[1]);
1045 let d = e.steps[0].delegation.as_deref().unwrap();
1046 assert_eq!((d.content.as_str(), d.reasoning.as_str(), d.state), ("Reading a.txt", "hm", DelegationState::Running));
1047 assert_eq!(d.status_line(), "explorer · 1 tool · waiting for approval");
1048 assert_eq!(e.pending_approvals().map(|s| s.id).collect::<Vec<_>>(), vec![2]);
1050 e.apply_delegation(1, &DelegationUpdate::Step(Box::new(step(2, StepStatus::Done))));
1051 e.apply_delegation(1, &DelegationUpdate::Status { state: DelegationState::Done, prompt_tokens: 50, completion_tokens: 5, error: None });
1052 assert_eq!(e.steps[0].delegation.as_deref().unwrap().status_line(), "explorer · 1 tool · done");
1053 assert_eq!(e.pending_approvals().count(), 0);
1054 let msg = ServerMsg::StepUpdated { entry: 9, step: e.steps[0].clone() };
1055 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1056 let json = r#"{"id":1,"tool":"t","title":"T","access":"read","status":"done","detail":""}"#;
1058 assert!(serde_json::from_str::<Step>(json).unwrap().delegation.is_none());
1059 }
1060
1061 #[test]
1062 fn steps_upsert_and_round_trip() {
1063 let mut e = Entry {
1064 id: 1,
1065 role: EntryRole::Assistant,
1066 content: String::new(),
1067 reasoning: String::new(),
1068 done: false,
1069 error: None,
1070 stats: None,
1071 steps: vec![],
1072 undoable: false,
1073 undone: false,
1074 attachments: vec![],
1075 };
1076 e.upsert_step(step(3, StepStatus::Running));
1077 e.upsert_step(step(4, StepStatus::Waiting));
1078 e.upsert_step(step(3, StepStatus::Done));
1079 assert_eq!(e.steps.len(), 2);
1080 assert_eq!(e.steps[0].status, StepStatus::Done);
1081 assert_eq!(e.pending_approvals().map(|s| s.id).collect::<Vec<_>>(), vec![4]);
1082 let mut s = step(5, StepStatus::Done);
1083 s.changes = vec![FileChange::Moved { from: "a".into(), to: "b".into() }];
1084 let msg = ServerMsg::StepUpdated { entry: 1, step: s };
1085 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1086 }
1087
1088 #[test]
1089 fn entry_without_steps_still_parses() {
1090 let json = r#"{"id":1,"role":"user","content":"hi","reasoning":"","done":true,"error":null,"stats":null}"#;
1091 let e: Entry = serde_json::from_str(json).unwrap();
1092 assert!(e.steps.is_empty());
1093 }
1094
1095 #[test]
1096 fn undo_and_preview_wire_format() {
1097 let m = ClientMsg::Undo { entry: 4 };
1098 assert_eq!(m.to_json(), r#"{"type":"undo","entry":4}"#);
1099 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1100 let mut s = step(1, StepStatus::Waiting);
1101 s.preview =
1102 Some(Preview::Write { path: "a.md".into(), bytes: 3, replaces: true, lines: vec![DiffLine { kind: LineKind::Added, text: "hi".into() }], more: 0 });
1103 let msg = ServerMsg::StepUpdated { entry: 1, step: s };
1104 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1105 let msg = ServerMsg::EntryUndo { id: 1, undoable: false, undone: true };
1106 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1107 }
1108
1109 #[test]
1110 fn chat_messages_round_trip() {
1111 let summary = ChatSummary { id: "c1".into(), title: "Plans".into(), updated_at: 5, pinned_at: None, busy: true, workspace: Some("w1".into()) };
1112 for m in [
1113 ServerMsg::Chats { pinned: vec![], recent: vec![summary.clone()], after: None, next: Some(summary.cursor()) },
1114 ServerMsg::ChatUpdated(summary.clone()),
1115 ServerMsg::ChatOpened { chat: Some(summary), workspace: None },
1116 ServerMsg::ChatDeleted { id: "c1".into() },
1117 ] {
1118 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1119 }
1120 let m = ClientMsg::ListChats { after: Some(ChatCursor { updated_at: 1, id: "x".into() }), limit: 50 };
1121 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1122 assert_eq!(ClientMsg::NewChat { workspace: None }.to_json(), r#"{"type":"new_chat"}"#);
1123 }
1124
1125 #[test]
1126 fn endpoint_info_is_optional_and_summarised() {
1127 let old = r#"{"version":"0","inference_base_url":"u","inference_model":"m","has_api_key":false,"endpoint":null,"busy":false}"#;
1128 assert_eq!(serde_json::from_str::<EngineState>(old).unwrap().endpoint_info, None);
1129 let info = EndpointInfo { probing: false, server: "llama.cpp".into(), context_tokens: Some(262_144), tools: ToolsMode::Native, vision: Some(true) };
1130 assert_eq!(info.summary(), "llama.cpp · 262k ctx · native tools · vision");
1131 assert_eq!(EndpointInfo { probing: true, ..info }.summary(), "checking endpoint…");
1132 assert_eq!(EndpointInfo::default().summary(), "tools untested");
1133 }
1134
1135 #[test]
1136 fn media_messages_round_trip() {
1137 let msgs = vec![
1138 ClientMsg::SendMessage { text: "chart it".into(), attachments: vec!["uploads/sales.csv".into()] },
1139 ClientMsg::Upload { upload: 1, name: "a.csv".into(), size: 3, offset: 0, data: media::encode(b"a,b"), done: true },
1140 ClientMsg::GetMedia { path: "charts/x.chart.json".into() },
1141 ];
1142 for m in msgs {
1143 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1144 }
1145 let spec = byob_types::chart::validate(&serde_json::json!({"type": "bar", "x": "m", "series": ["v"], "data": [{"m": "a", "v": 1}]})).unwrap();
1146 let msgs = vec![
1147 ServerMsg::Uploaded { upload: 1, attachment: Some(MediaRef::new("uploads/a.csv", 3)), error: None },
1148 ServerMsg::Media { path: "c.chart.json".into(), content: MediaContent::Chart { spec } },
1149 ServerMsg::Media { path: "p.png".into(), content: MediaContent::Image { mime: "image/png".into(), data: "AA==".into() } },
1150 ServerMsg::Media { path: "p.png".into(), content: MediaContent::Error { message: "gone".into() } },
1151 ];
1152 for m in msgs {
1153 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1154 }
1155 let mut s = step(1, StepStatus::Done);
1156 s.media = vec![MediaRef::new("charts/x.chart.json", 10)];
1157 let m = ServerMsg::StepUpdated { entry: 1, step: s };
1158 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1159 }
1160
1161 #[test]
1162 fn artifact_messages_round_trip() {
1163 let v = ArtifactVersion { n: 2, path: ".byob/artifacts/calc/v2.html".into(), created_at: 1, note: "blue button".into(), size: 10 };
1164 let a = Artifact {
1165 id: "calc".into(),
1166 kind: ArtifactKind::Html,
1167 content_type: artifact::TYPE_HTML.into(),
1168 title: "Calc".into(),
1169 filename: "calc.html".into(),
1170 versions: vec![v],
1171 };
1172 let msgs = vec![
1173 ServerMsg::Artifacts { chat: Some("c1".into()), artifacts: vec![a.clone()] },
1174 ServerMsg::Artifacts { chat: None, artifacts: vec![] },
1175 ServerMsg::ArtifactUpdated(a),
1176 ServerMsg::ArtifactFile { id: "calc".into(), version: 2, data: Some(media::encode(b"<p>")), error: None },
1177 ServerMsg::ArtifactFile { id: "calc".into(), version: 9, data: None, error: Some("no such version".into()) },
1178 ];
1179 for m in msgs {
1180 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1181 }
1182 let m = ClientMsg::GetArtifact { id: "calc".into(), version: 2 };
1183 assert_eq!(m.to_json(), r#"{"type":"get_artifact","id":"calc","version":2}"#);
1184 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1185 let mut s = step(1, StepStatus::Done);
1186 s.artifacts = vec![ArtifactRef { id: "calc".into(), version: 2 }];
1187 let m = ServerMsg::StepUpdated { entry: 1, step: s };
1188 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1189 let json = r#"{"id":1,"tool":"t","title":"T","access":"read","status":"done","detail":""}"#;
1191 assert!(serde_json::from_str::<Step>(json).unwrap().artifacts.is_empty());
1192 }
1193
1194 #[test]
1195 fn older_send_message_without_attachments_parses() {
1196 let m = ClientMsg::from_json(r#"{"type":"send_message","text":"hi"}"#).unwrap();
1197 assert_eq!(m, ClientMsg::SendMessage { text: "hi".into(), attachments: vec![] });
1198 assert_eq!(m.to_json(), r#"{"type":"send_message","text":"hi"}"#);
1199 }
1200
1201 #[test]
1202 fn compaction_messages_round_trip() {
1203 let c = Compaction {
1204 id: 1,
1205 after_entry: 7,
1206 tokens_before: 182_000,
1207 tokens_after: 9_000,
1208 summary: "## Goals".into(),
1209 manual: true,
1210 focus: Some("CSV".into()),
1211 created_at: 5,
1212 };
1213 let u = ChatUsage { chat: "c1".into(), context_used: 34_000, context_window: 262_144, compact_at: 209_715, model_calls: 3, ..Default::default() };
1214 for m in [ServerMsg::Usage(u), ServerMsg::Compactions { chat: Some("c1".into()), items: vec![c.clone()] }, ServerMsg::Compacted(c)] {
1215 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1216 }
1217 assert_eq!(ClientMsg::Compact { focus: None }.to_json(), r#"{"type":"compact"}"#);
1218 let m = ClientMsg::from_json(r#"{"type":"compact","focus":"keep the CSV"}"#).unwrap();
1219 assert_eq!(m, ClientMsg::Compact { focus: Some("keep the CSV".into()) });
1220 let s: TurnStats = serde_json::from_str(r#"{"prompt_tokens":1,"completion_tokens":2,"elapsed_ms":3}"#).unwrap();
1222 assert_eq!(s.model_calls, 0);
1223 }
1224
1225 #[test]
1226 fn connection_messages_round_trip() {
1227 for m in [
1228 ClientMsg::TestInference { base_url: "http://127.0.0.1:11434/v1".into(), model: "qwen3".into(), api_key: None },
1229 ClientMsg::TestInference { base_url: "https://api.openai.com/v1".into(), model: "m".into(), api_key: Some("sk".into()) },
1230 ClientMsg::DetectEndpoints,
1231 ClientMsg::Retry,
1232 ] {
1233 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1234 }
1235 assert_eq!(ClientMsg::Retry.to_json(), r#"{"type":"retry"}"#);
1236 let t = InferenceTest { base_url: "u".into(), model: "m".into(), ok: false, problem: Some(Problem::Unauthorized), detail: "x".into(), models: vec![] };
1237 let m = ServerMsg::InferenceTested(t);
1238 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1239 let state = EngineState {
1240 link: Link::failed("could not reach u: refused"),
1241 onboarded: true,
1242 detected: vec![Detected { preset: "ollama".into(), base_url: "http://127.0.0.1:11434/v1".into(), models: vec!["qwen3".into()] }],
1243 ..Default::default()
1244 };
1245 let m = ServerMsg::State(state);
1246 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1247 let old = r#"{"version":"0","inference_base_url":"u","inference_model":"m","has_api_key":false,"endpoint":null,"busy":false}"#;
1249 let s = serde_json::from_str::<EngineState>(old).unwrap();
1250 assert_eq!((s.link, s.onboarded, s.detected.len()), (Link::Unknown, false, 0));
1251 }
1252
1253 #[test]
1254 fn hello_negotiates_and_old_hellos_still_parse() {
1255 let m = ClientMsg::hello("desktop");
1256 let ClientMsg::Hello { protocol, minor, caps, .. } = &m else { panic!() };
1257 assert_eq!((*protocol, *minor), (PROTOCOL_MAJOR, PROTOCOL_MINOR));
1258 assert!(caps.iter().any(|c| c == version::CAP_PLUGIN_CHANNEL));
1259 assert!(m.check_sizes().is_ok());
1260 let old = ClientMsg::from_json(r#"{"type":"hello","protocol":12,"client":"old tab"}"#).unwrap();
1262 assert_eq!(old, ClientMsg::Hello { protocol: 12, minor: 0, client: "old tab".into(), caps: vec![] });
1263 let bad = ClientMsg::Hello { protocol: PROTOCOL_MAJOR, minor: 0, client: "x".into(), caps: vec!["NOT A CAP".into()] };
1264 assert!(bad.check_sizes().is_err());
1265 let w = ServerMsg::Welcome(Welcome::current());
1266 assert_eq!(ServerMsg::from_json(&w.to_json()).unwrap(), w);
1267 assert!(w.to_json().starts_with(r#"{"type":"welcome","protocol":13"#), "{}", w.to_json());
1268 }
1269
1270 #[test]
1271 fn plugin_channel_round_trips_and_is_capped() {
1272 let c = ClientMsg::Plugin { plugin: "sheets".into(), msg: serde_json::json!({"op": "get", "cell": "A1"}) };
1273 assert_eq!(c.to_json(), r#"{"type":"plugin","plugin":"sheets","msg":{"cell":"A1","op":"get"}}"#);
1274 assert_eq!(ClientMsg::from_json(&c.to_json()).unwrap(), c);
1275 assert!(c.check_sizes().is_ok());
1276 let s = ServerMsg::Plugin { plugin: "sheets".into(), msg: serde_json::json!([1, 2]) };
1277 assert_eq!(ServerMsg::from_json(&s.to_json()).unwrap(), s);
1278 for bad in [
1279 ClientMsg::Plugin { plugin: "Not/an id".into(), msg: serde_json::Value::Null },
1280 ClientMsg::Plugin { plugin: "sheets".into(), msg: serde_json::Value::String("x".repeat(version::MAX_PLUGIN_MSG_BYTES)) },
1281 ] {
1282 assert!(bad.check_sizes().is_err());
1283 }
1284 }
1285
1286 #[test]
1287 fn question_cards_round_trip_and_older_asks_still_parse() {
1288 let c = ClientMsg::AnswerQuestion { step: 4, text: "Metric".into() };
1289 assert_eq!(c.to_json(), r#"{"type":"answer_question","step":4,"text":"Metric"}"#);
1290 assert_eq!(ClientMsg::from_json(&c.to_json()).unwrap(), c);
1291 assert!(c.check_sizes().is_ok());
1292 assert!(ClientMsg::AnswerQuestion { step: 4, text: "x".repeat(MAX_ANSWER_CHARS + 1) }.check_sizes().is_err());
1293 let ask = Ask {
1294 text: "Which units?".into(),
1295 warning: None,
1296 always: true,
1297 choice: Some(Choice { options: vec!["Metric".into(), "Imperial".into()], free_text: true, answer: None }),
1298 };
1299 let json = serde_json::to_string(&ask).unwrap();
1300 assert_eq!(serde_json::from_str::<Ask>(&json).unwrap(), ask);
1301 let old: Ask = serde_json::from_str(r#"{"text":"t","always":true}"#).unwrap();
1303 assert!(old.choice.is_none());
1304 assert!(!serde_json::to_string(&old).unwrap().contains("choice"));
1305 }
1306
1307 #[test]
1309 fn unknown_messages_and_enum_values_decode_to_fallbacks() {
1310 assert_eq!(ServerMsg::from_json(r#"{"type":"hologram","x":1,"y":{"z":[]}}"#).unwrap(), ServerMsg::Unknown);
1311 assert_eq!(ClientMsg::from_json(r#"{"type":"teleport","to":"mars"}"#).unwrap(), ClientMsg::Unknown);
1312 assert!(ServerMsg::from_json(r#"{"type":"notice","level":"info"}"#).is_err());
1314 let n = ServerMsg::from_json(r#"{"type":"notice","level":"debug","text":"t"}"#).unwrap();
1315 assert_eq!(n, ServerMsg::Notice { level: NoticeLevel::Info, text: "t".into() });
1316 let a = ClientMsg::from_json(r#"{"type":"approve","step":1,"answer":"maybe_later"}"#).unwrap();
1317 assert_eq!(a, ClientMsg::Approve { step: 1, answer: ApprovalAnswer::Unknown });
1318 let json = r#"{"id":1,"tool":"t","title":"T","access":"read","status":"done","detail":"",
1320 "changes":[{"kind":"chmod","path":"a","mode":"755"}],
1321 "preview":{"kind":"hexdump","bytes":"00"},
1322 "media":[{"kind":"video","path":"a.mp4"}],
1323 "views":[{"kind":"sheets.grid","v":4,"data":{"rows":[]},"fallback":"a *grid*"}]}"#;
1324 let s: Step = serde_json::from_str(json).unwrap();
1325 assert_eq!((s.changes.clone(), s.preview.clone()), (vec![FileChange::Other], Some(Preview::Other)));
1326 assert_eq!(s.media[0].kind, MediaKind::File);
1327 assert_eq!((s.views[0].kind.as_str(), s.views[0].fallback.as_str()), ("sheets.grid", "a *grid*"));
1328 assert!(s.view::<PluginCard>().is_none());
1329 let art: Artifact = serde_json::from_str(r#"{"id":"a","kind":"spreadsheet","title":"A","filename":"a.xlsx","versions":[]}"#).unwrap();
1330 assert_eq!(art.kind, ArtifactKind::Text);
1331 assert_eq!(serde_json::from_str::<SlashKind>(r#""macro""#).unwrap(), SlashKind::Other);
1332 assert_eq!(serde_json::from_str::<PluginAction>(r#""forked""#).unwrap(), PluginAction::Other);
1333 let env = ClientMsg::from_json(r#"{"type":"workspace_env","action":{"kind":"rebuild","fast":true}}"#).unwrap();
1334 assert_eq!(env, ClientMsg::WorkspaceEnv { action: Some(EnvAction::Unsupported), workspace: None });
1335 let d = ServerMsg::from_json(r#"{"type":"delegation","entry":1,"step":2,"update":{"kind":"progress","pct":5}}"#).unwrap();
1336 assert_eq!(d, ServerMsg::Delegation { entry: 1, step: 2, update: DelegationUpdate::Other });
1337 }
1338
1339 #[test]
1340 fn plugin_cards_travel_as_views() {
1341 let card = PluginCard {
1342 plugin: "scratch".into(),
1343 scope: PluginScope::Chat,
1344 action: PluginAction::Made,
1345 tools: vec!["shout".into()],
1346 added: vec!["shout".into()],
1347 removed: vec![],
1348 test: Some(plugins::PluginTest { ok: true, output: "HI".into() }),
1349 problems: vec![],
1350 missing_settings: vec![],
1351 };
1352 let mut s = step(1, StepStatus::Done);
1353 s.views.push(View::of(&card));
1354 let json = ServerMsg::StepUpdated { entry: 1, step: s }.to_json();
1355 assert!(json.contains(r#""views":[{"kind":"byob.plugin_card","v":1,"data":{"action":"made""#), "{json}");
1356 let ServerMsg::StepUpdated { step: back, .. } = ServerMsg::from_json(&json).unwrap() else { panic!() };
1357 assert_eq!(back.view::<PluginCard>(), Some(card));
1358 assert!(back.views[0].fallback.contains("**Plugin scratch** (this chat) · tool made") && back.views[0].fallback.contains("shout"));
1359 assert!(!ServerMsg::StepUpdated { entry: 1, step: step(2, StepStatus::Done) }.to_json().contains("views"));
1361 }
1362
1363 #[test]
1364 fn state_never_carries_api_key() {
1365 let json = serde_json::to_string(&EngineState::default()).unwrap();
1366 assert!(!json.contains("\"api_key\""));
1367 }
1368}