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 Undo {
123 entry: u64,
124 },
125 ListChats {
128 after: Option<ChatCursor>,
129 limit: u32,
130 },
131 NewChat {
135 #[serde(default, skip_serializing_if = "Option::is_none")]
136 workspace: Option<String>,
137 },
138 OpenChat {
140 id: String,
141 },
142 RenameChat {
143 id: String,
144 title: String,
145 },
146 DeleteChat {
148 id: String,
149 },
150 PinChat {
151 id: String,
152 pinned: bool,
153 },
154 Upload {
159 upload: u64,
160 name: String,
161 size: u64,
162 offset: u64,
163 data: String,
164 done: bool,
165 },
166 GetMedia {
168 path: String,
169 },
170 GetArtifact {
173 id: String,
174 version: u32,
175 },
176 Compact {
179 #[serde(default, skip_serializing_if = "Option::is_none")]
180 focus: Option<String>,
181 },
182 WorkspaceEnv {
185 #[serde(default, skip_serializing_if = "Option::is_none")]
186 action: Option<EnvAction>,
187 #[serde(default, skip_serializing_if = "Option::is_none")]
188 workspace: Option<String>,
189 },
190 CreateWorkspace {
194 name: String,
195 folder: NewFolder,
196 #[serde(default)]
197 config: workspace::Layer,
198 },
199 RenameWorkspace {
200 id: String,
201 name: String,
202 },
203 RemoveWorkspace {
206 id: String,
207 #[serde(default)]
208 clean: bool,
209 },
210 GetConfig {
212 scope: ConfigScope,
213 },
214 SetConfig {
218 scope: ConfigScope,
219 layer: workspace::Layer,
220 #[serde(default, skip_serializing_if = "Option::is_none")]
221 api_key: Option<String>,
222 },
223 ListFolders {
226 #[serde(default, skip_serializing_if = "Option::is_none")]
227 path: Option<String>,
228 },
229 CheckContainers,
231 GetExtensions,
233 SetPluginEnabled {
237 scope: ConfigScope,
238 plugin: String,
239 enabled: Option<bool>,
240 },
241 SetPluginSetting {
245 plugin: String,
246 key: String,
247 value: Option<String>,
248 },
249 KeepPlugin {
253 plugin: String,
254 scope: PluginScope,
255 #[serde(default, skip_serializing_if = "Option::is_none")]
256 new_id: Option<String>,
257 },
258 RemovePlugin {
261 plugin: String,
262 scope: PluginScope,
263 },
264 ReloadPlugins,
266 TrustPlugins {
270 workspace: String,
271 #[serde(default)]
272 plugins: Vec<String>,
273 trust: bool,
274 },
275 Plugin {
278 plugin: String,
279 msg: serde_json::Value,
280 },
281 OpenView {
285 view: ViewRef,
286 },
287 CloseView {
289 view: ViewRef,
290 },
291 ViewEvent {
294 view: ViewRef,
295 event: tree::Event,
296 },
297 WebCall {
302 call: u64,
303 owner: web::WebOwner,
304 method: String,
305 #[serde(default)]
306 params: serde_json::Value,
307 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
308 approved: bool,
309 },
310 #[serde(other)]
312 Unknown,
313}
314
315#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
317#[serde(tag = "type", rename_all = "snake_case")]
318pub enum ServerMsg {
319 Welcome(Welcome),
321 State(EngineState),
323 Notice { level: NoticeLevel, text: String },
325 Transcript { entries: Vec<Entry> },
327 EntryAdded(Entry),
329 EntryDelta { id: u64, content: String, reasoning: String },
331 EntryFinished { id: u64, error: Option<String>, stats: Option<TurnStats> },
333 StepUpdated { entry: u64, step: Step },
335 EntryUndo { id: u64, undoable: bool, undone: bool },
337 Chats { pinned: Vec<ChatSummary>, recent: Vec<ChatSummary>, after: Option<ChatCursor>, next: Option<ChatCursor> },
340 ChatUpdated(ChatSummary),
342 ChatDeleted { id: String },
344 ChatOpened {
348 chat: Option<ChatSummary>,
349 #[serde(default)]
350 workspace: Option<String>,
351 },
352 Uploaded { upload: u64, attachment: Option<MediaRef>, error: Option<String> },
354 Media { path: String, content: MediaContent },
356 Artifacts { chat: Option<String>, artifacts: Vec<Artifact> },
359 ArtifactUpdated(Artifact),
361 ArtifactFile { id: String, version: u32, data: Option<String>, error: Option<String> },
363 Usage(ChatUsage),
365 Compactions { chat: Option<String>, items: Vec<Compaction> },
368 Compacted(Compaction),
370 Delegation { entry: u64, step: u64, update: DelegationUpdate },
372 InferenceTested(InferenceTest),
374 WorkspaceEnv(WorkspaceEnv),
376 Workspaces { items: Vec<WorkspaceSummary>, current: Option<String>, root: String, support: EnvSupport },
380 Config(Box<ConfigView>),
382 Folders(FolderList),
384 ContainersChecked { ok: bool, message: String },
386 WorkspaceCreated { id: Option<String>, error: Option<String> },
388 Queue(ChatQueue),
391 Extensions(Box<Extensions>),
394 Plugin { plugin: String, msg: serde_json::Value },
397 LiveView(LiveView),
400 WebReply {
403 call: u64,
404 #[serde(default, deserialize_with = "present_even_if_null", skip_serializing_if = "Option::is_none")]
406 result: Option<serde_json::Value>,
407 #[serde(default, skip_serializing_if = "Option::is_none")]
408 error: Option<web::WebError>,
409 },
410 WebPush { owner: web::WebOwner, msg: serde_json::Value },
413 #[serde(other)]
415 Unknown,
416}
417
418#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
420pub struct ChatSummary {
421 pub id: String,
422 pub title: String,
423 pub updated_at: i64,
425 pub pinned_at: Option<i64>,
427 #[serde(default)]
429 pub busy: bool,
430 #[serde(default, skip_serializing_if = "Option::is_none")]
432 pub workspace: Option<String>,
433}
434
435impl ChatSummary {
436 pub fn cursor(&self) -> ChatCursor {
437 ChatCursor { updated_at: self.updated_at, id: self.id.clone() }
438 }
439}
440
441#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
443pub struct ChatCursor {
444 pub updated_at: i64,
445 pub id: String,
446}
447
448#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
449#[serde(rename_all = "snake_case")]
450pub enum EntryRole {
451 User,
452 Assistant,
453}
454
455#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
457pub struct Entry {
458 pub id: u64,
459 pub role: EntryRole,
460 pub content: String,
461 pub reasoning: String,
462 pub done: bool,
464 pub error: Option<String>,
465 pub stats: Option<TurnStats>,
466 #[serde(default)]
469 pub steps: Vec<Step>,
470 #[serde(default)]
472 pub undoable: bool,
473 #[serde(default)]
475 pub undone: bool,
476 #[serde(default, skip_serializing_if = "Vec::is_empty")]
478 pub attachments: Vec<MediaRef>,
479}
480
481impl Entry {
482 pub fn append(&mut self, content: &str, reasoning: &str) {
484 self.content.push_str(content);
485 self.reasoning.push_str(reasoning);
486 }
487
488 pub fn upsert_step(&mut self, step: Step) {
490 match self.steps.iter_mut().find(|s| s.id == step.id) {
491 Some(existing) => *existing = step,
492 None => self.steps.push(step),
493 }
494 }
495
496 pub fn pending_approvals(&self) -> impl Iterator<Item = &Step> {
498 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)
499 }
500
501 pub fn apply_delegation(&mut self, step: u64, update: &DelegationUpdate) {
503 if let Some(d) = self.steps.iter_mut().find(|s| s.id == step).and_then(|s| s.delegation.as_deref_mut()) {
504 d.apply(update);
505 }
506 }
507}
508
509#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
511#[serde(rename_all = "snake_case")]
512pub enum ToolAccess {
513 Read,
514 Write,
515 Network,
516 Execute,
517}
518
519impl ToolAccess {
520 pub fn label(self) -> &'static str {
521 match self {
522 Self::Read => "read",
523 Self::Write => "write",
524 Self::Network => "network",
525 Self::Execute => "execute",
526 }
527 }
528}
529
530#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
531#[serde(rename_all = "snake_case")]
532pub enum StepStatus {
533 Running,
534 Waiting,
536 Done,
537 Failed,
539 Denied,
541}
542
543impl StepStatus {
544 pub fn finished(self) -> bool {
545 matches!(self, Self::Done | Self::Failed | Self::Denied)
546 }
547}
548
549#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
551#[serde(rename_all = "snake_case")]
552pub enum ApprovalAnswer {
553 Allow,
554 Always,
556 Deny,
557 AlwaysEverywhere,
559 #[serde(other)]
561 Unknown,
562}
563
564#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
566#[serde(tag = "kind", rename_all = "snake_case")]
567pub enum FileChange {
568 Created {
569 path: String,
570 },
571 Modified {
572 path: String,
573 },
574 Deleted {
575 path: String,
576 },
577 Moved {
578 from: String,
579 to: String,
580 },
581 #[serde(other)]
583 Other,
584}
585
586#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
588pub struct Step {
589 pub id: u64,
591 pub tool: String,
593 pub title: String,
595 pub access: ToolAccess,
596 pub status: StepStatus,
597 pub detail: String,
599 #[serde(default)]
600 pub changes: Vec<FileChange>,
601 #[serde(default)]
603 pub at: usize,
604 #[serde(default, skip_serializing_if = "Vec::is_empty")]
606 pub media: Vec<MediaRef>,
607 #[serde(default, skip_serializing_if = "Option::is_none")]
609 pub preview: Option<Preview>,
610 #[serde(default, skip_serializing_if = "Vec::is_empty")]
612 pub artifacts: Vec<ArtifactRef>,
613 #[serde(default, skip_serializing_if = "Option::is_none")]
615 pub delegation: Option<Box<Delegation>>,
616 #[serde(default, skip_serializing_if = "Option::is_none")]
620 pub ask: Option<Box<Ask>>,
621 #[serde(default, skip_serializing_if = "Vec::is_empty")]
625 pub views: Vec<View>,
626}
627
628impl Step {
629 pub fn view<T: ViewData>(&self) -> Option<T> {
631 self.views.iter().find_map(View::get)
632 }
633}
634
635#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
637pub struct Ask {
638 #[serde(default)]
640 pub text: String,
641 #[serde(default, skip_serializing_if = "Option::is_none")]
643 pub warning: Option<String>,
644 #[serde(default)]
646 pub always: bool,
647}
648
649pub const MAX_PREVIEW_LINES: usize = 40;
651pub const MAX_PREVIEW_LINE_CHARS: usize = 300;
653
654#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
656#[serde(tag = "kind", rename_all = "snake_case")]
657pub enum Preview {
658 Write {
661 path: String,
662 bytes: u64,
663 replaces: bool,
665 lines: Vec<DiffLine>,
666 #[serde(default)]
668 more: usize,
669 },
670 Move {
672 moves: Vec<(String, String)>,
673 #[serde(default)]
674 more: usize,
675 },
676 Delete { path: String, what: String },
678 Args {
680 fields: Vec<(String, String)>,
681 #[serde(default, skip_serializing_if = "Option::is_none")]
682 code: Option<String>,
683 #[serde(default)]
684 more: usize,
685 },
686 #[serde(other)]
688 Other,
689}
690
691#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
693pub struct DiffLine {
694 pub kind: LineKind,
695 pub text: String,
696}
697
698#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
699#[serde(rename_all = "snake_case")]
700pub enum LineKind {
701 Same,
703 Added,
704 Removed,
705 Skipped,
707}
708
709#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
710pub struct TurnStats {
711 pub prompt_tokens: u64,
712 pub completion_tokens: u64,
713 pub elapsed_ms: u64,
714 #[serde(default)]
716 pub model_calls: u64,
717}
718
719#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
720#[serde(rename_all = "snake_case")]
721pub enum NoticeLevel {
722 Error,
723 #[serde(other)]
725 Info,
726}
727
728#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
730pub struct EngineState {
731 pub version: String,
732 pub inference_base_url: String,
733 pub inference_model: String,
734 pub has_api_key: bool,
735 pub endpoint: Option<String>,
737 pub busy: bool,
739 #[serde(default)]
741 pub endpoint_info: Option<EndpointInfo>,
742 #[serde(default)]
744 pub link: Link,
745 #[serde(default)]
748 pub onboarded: bool,
749 #[serde(default)]
751 pub detected: Vec<Detected>,
752 #[serde(default)]
754 pub detecting: bool,
755 #[serde(default, skip_serializing_if = "Option::is_none")]
758 pub chat_endpoint: Option<ChatEndpoint>,
759}
760
761#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
763#[serde(rename_all = "snake_case")]
764pub enum ToolsMode {
765 Native,
767 Prompt,
769 #[default]
771 Unknown,
772}
773
774#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
776pub struct EndpointInfo {
777 #[serde(default)]
779 pub probing: bool,
780 #[serde(default)]
782 pub server: String,
783 #[serde(default)]
785 pub context_tokens: Option<u64>,
786 #[serde(default)]
787 pub tools: ToolsMode,
788 #[serde(default)]
790 pub vision: Option<bool>,
791}
792
793impl EndpointInfo {
794 pub fn summary(&self) -> String {
796 if self.probing {
797 return "checking endpoint…".into();
798 }
799 let mut parts = Vec::new();
800 if !self.server.is_empty() {
801 parts.push(self.server.clone());
802 }
803 if let Some(n) = self.context_tokens {
804 parts.push(if n >= 1000 { format!("{}k ctx", n / 1000) } else { format!("{n} ctx") });
805 }
806 parts.push(
807 match self.tools {
808 ToolsMode::Native => "native tools",
809 ToolsMode::Prompt => "prompt tools",
810 ToolsMode::Unknown => "tools untested",
811 }
812 .into(),
813 );
814 if self.vision == Some(true) {
815 parts.push("vision".into());
816 }
817 parts.join(" · ")
818 }
819}
820
821impl ClientMsg {
822 pub fn hello(client: &str) -> Self {
824 Self::Hello { protocol: PROTOCOL_MAJOR, minor: PROTOCOL_MINOR, client: client.to_owned(), caps: version::client_caps() }
825 }
826
827 pub fn to_json(&self) -> String {
828 serde_json::to_string(self).unwrap_or_default()
829 }
830
831 pub fn from_json(text: &str) -> Result<Self, String> {
833 if text.len() > MAX_FRAME_BYTES {
834 return Err(format!("frame too large ({} bytes)", text.len()));
835 }
836 serde_json::from_str(text).map_err(|e| e.to_string())
837 }
838}
839
840impl ServerMsg {
841 pub fn to_json(&self) -> String {
842 serde_json::to_string(self).unwrap_or_default()
843 }
844
845 pub fn to_frame(&self) -> String {
851 let json = self.to_json();
852 if json.len() <= MAX_FRAME_BYTES {
853 return json;
854 }
855 let why = format!("it is too large to send over this connection ({} KB, at most {} KB)", json.len() / 1024, MAX_FRAME_BYTES / 1024);
856 let instead = match self {
857 Self::LiveView(lv) if lv.tree.is_none() => Self::LiveView(LiveView { view: lv.view.clone(), reset: true, ..Default::default() }),
858 Self::LiveView(lv) => {
859 Self::LiveView(LiveView { view: lv.view.clone(), error: Some(format!("This view can't be shown here: {why}.")), ..Default::default() })
860 }
861 Self::WebReply { call, .. } => {
862 Self::WebReply { call: *call, result: None, error: Some(web::WebError::new(-32000, format!("byob couldn't send the answer: {why}"))) }
863 }
864 _ => Self::Notice { level: NoticeLevel::Error, text: format!("byob couldn't send an update: {why}.") },
865 };
866 instead.to_json()
867 }
868
869 pub fn from_json(text: &str) -> Result<Self, String> {
871 if text.len() > MAX_FRAME_BYTES {
872 return Err(format!("frame too large ({} bytes)", text.len()));
873 }
874 serde_json::from_str(text).map_err(|e| e.to_string())
875 }
876}
877
878pub trait Connection {
880 fn send(&mut self, msg: ClientMsg);
881 fn try_recv(&mut self) -> Option<ServerMsg>;
883}
884
885fn present_even_if_null<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<serde_json::Value>, D::Error> {
888 serde_json::Value::deserialize(d).map(Some)
889}
890
891#[cfg(test)]
892mod tests {
893 use super::*;
894
895 #[test]
898 fn web_reply_keeps_a_null_result() {
899 let null = ServerMsg::WebReply { call: 3, result: Some(serde_json::Value::Null), error: None };
900 assert_eq!(null.to_json(), r#"{"type":"web_reply","call":3,"result":null}"#);
901 assert_eq!(ServerMsg::from_json(&null.to_json()).unwrap(), null);
902 let none = ServerMsg::WebReply { call: 3, result: None, error: None };
903 assert_eq!(none.to_json(), r#"{"type":"web_reply","call":3}"#);
904 assert_eq!(ServerMsg::from_json(&none.to_json()).unwrap(), none);
905 let value = ServerMsg::WebReply { call: 3, result: Some(serde_json::json!({"a": [1]})), error: None };
906 assert_eq!(ServerMsg::from_json(&value.to_json()).unwrap(), value);
907 }
908
909 #[test]
910 fn client_msg_round_trips() {
911 let m = ClientMsg::hello("test");
912 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
913 }
914
915 #[test]
916 fn wire_format_is_tagged() {
917 let json = ServerMsg::Notice { level: NoticeLevel::Info, text: "hi".into() }.to_json();
918 assert_eq!(json, r#"{"type":"notice","level":"info","text":"hi"}"#);
919 }
920
921 #[test]
922 fn a_message_too_large_for_a_frame_is_sent_as_something_the_client_acts_on() {
923 let big = "x".repeat(MAX_FRAME_BYTES);
924 let r = ViewRef::new("p", "v", "k");
925 let small = ServerMsg::Notice { level: NoticeLevel::Info, text: "hi".into() };
926 assert_eq!(small.to_frame(), small.to_json());
927 let frame = |m: ServerMsg| {
928 let f = m.to_frame();
929 assert!(f.len() < 1024, "{} bytes", f.len());
930 ServerMsg::from_json(&f).unwrap()
931 };
932 let mut values = serde_json::Map::new();
933 values.insert("f".into(), serde_json::json!(big));
934 let change = LiveView { view: r.clone(), values, ..Default::default() };
935 assert_eq!(frame(ServerMsg::LiveView(change)), ServerMsg::LiveView(LiveView { view: r.clone(), reset: true, ..Default::default() }));
936 let texts: Vec<_> = (0..100).map(|_| serde_json::json!({"type": "text", "text": "y".repeat(60_000)})).collect();
938 let (tree, faults) = tree::decode(serde_json::json!({"type": "column", "children": texts}));
939 assert!(faults.is_empty(), "{faults:?}");
940 match frame(ServerMsg::LiveView(LiveView { view: r.clone(), tree: Some(tree), ..Default::default() })) {
941 ServerMsg::LiveView(lv) => assert!(lv.view == r && lv.tree.is_none() && lv.error.is_some_and(|e| e.contains("too large"))),
942 other => panic!("{other:?}"),
943 }
944 match frame(ServerMsg::WebReply { call: 9, result: Some(serde_json::json!(big)), error: None }) {
945 ServerMsg::WebReply { call: 9, result: None, error: Some(e) } => assert!(e.message.contains("too large")),
946 other => panic!("{other:?}"),
947 }
948 let plugin = ServerMsg::Plugin { plugin: "p".into(), msg: serde_json::json!(big) };
949 assert!(matches!(frame(plugin), ServerMsg::Notice { level: NoticeLevel::Error, .. }));
950 }
951
952 #[test]
953 fn rejects_garbage_and_oversized_frames() {
954 assert!(ClientMsg::from_json("{not json").is_err());
955 assert!(ClientMsg::from_json(&" ".repeat(MAX_FRAME_BYTES + 1)).is_err());
956 }
957
958 #[test]
959 fn approve_wire_format() {
960 let m = ClientMsg::Approve { step: 7, answer: ApprovalAnswer::Always };
961 assert_eq!(m.to_json(), r#"{"type":"approve","step":7,"answer":"always"}"#);
962 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
963 }
964
965 fn step(id: u64, status: StepStatus) -> Step {
966 Step {
967 id,
968 tool: "t".into(),
969 title: "T".into(),
970 access: ToolAccess::Write,
971 status,
972 detail: String::new(),
973 changes: vec![],
974 at: 0,
975 preview: None,
976 media: vec![],
977 artifacts: vec![],
978 delegation: None,
979 ask: None,
980 views: vec![],
981 }
982 }
983
984 #[test]
985 fn delegations_stream_into_their_step_and_round_trip() {
986 let mut parent = step(1, StepStatus::Running);
987 parent.delegation = Some(Box::new(Delegation { agent: "explorer".into(), task: "count lines".into(), ..Default::default() }));
988 let mut e = Entry {
989 id: 9,
990 role: EntryRole::Assistant,
991 content: String::new(),
992 reasoning: String::new(),
993 done: false,
994 error: None,
995 stats: None,
996 steps: vec![parent],
997 undoable: false,
998 undone: false,
999 attachments: vec![],
1000 };
1001 let updates = [
1002 DelegationUpdate::Status { state: DelegationState::Running, prompt_tokens: 0, completion_tokens: 0, error: None },
1003 DelegationUpdate::Delta { content: "Reading".into(), reasoning: "hm".into() },
1004 DelegationUpdate::Step(Box::new(step(2, StepStatus::Waiting))),
1005 DelegationUpdate::Delta { content: " a.txt".into(), reasoning: String::new() },
1006 ];
1007 for u in &updates {
1008 let msg = ServerMsg::Delegation { entry: 9, step: 1, update: u.clone() };
1009 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1010 e.apply_delegation(1, u);
1011 }
1012 e.apply_delegation(77, &updates[1]);
1014 let d = e.steps[0].delegation.as_deref().unwrap();
1015 assert_eq!((d.content.as_str(), d.reasoning.as_str(), d.state), ("Reading a.txt", "hm", DelegationState::Running));
1016 assert_eq!(d.status_line(), "explorer · 1 tool · waiting for approval");
1017 assert_eq!(e.pending_approvals().map(|s| s.id).collect::<Vec<_>>(), vec![2]);
1019 e.apply_delegation(1, &DelegationUpdate::Step(Box::new(step(2, StepStatus::Done))));
1020 e.apply_delegation(1, &DelegationUpdate::Status { state: DelegationState::Done, prompt_tokens: 50, completion_tokens: 5, error: None });
1021 assert_eq!(e.steps[0].delegation.as_deref().unwrap().status_line(), "explorer · 1 tool · done");
1022 assert_eq!(e.pending_approvals().count(), 0);
1023 let msg = ServerMsg::StepUpdated { entry: 9, step: e.steps[0].clone() };
1024 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1025 let json = r#"{"id":1,"tool":"t","title":"T","access":"read","status":"done","detail":""}"#;
1027 assert!(serde_json::from_str::<Step>(json).unwrap().delegation.is_none());
1028 }
1029
1030 #[test]
1031 fn steps_upsert_and_round_trip() {
1032 let mut e = Entry {
1033 id: 1,
1034 role: EntryRole::Assistant,
1035 content: String::new(),
1036 reasoning: String::new(),
1037 done: false,
1038 error: None,
1039 stats: None,
1040 steps: vec![],
1041 undoable: false,
1042 undone: false,
1043 attachments: vec![],
1044 };
1045 e.upsert_step(step(3, StepStatus::Running));
1046 e.upsert_step(step(4, StepStatus::Waiting));
1047 e.upsert_step(step(3, StepStatus::Done));
1048 assert_eq!(e.steps.len(), 2);
1049 assert_eq!(e.steps[0].status, StepStatus::Done);
1050 assert_eq!(e.pending_approvals().map(|s| s.id).collect::<Vec<_>>(), vec![4]);
1051 let mut s = step(5, StepStatus::Done);
1052 s.changes = vec![FileChange::Moved { from: "a".into(), to: "b".into() }];
1053 let msg = ServerMsg::StepUpdated { entry: 1, step: s };
1054 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1055 }
1056
1057 #[test]
1058 fn entry_without_steps_still_parses() {
1059 let json = r#"{"id":1,"role":"user","content":"hi","reasoning":"","done":true,"error":null,"stats":null}"#;
1060 let e: Entry = serde_json::from_str(json).unwrap();
1061 assert!(e.steps.is_empty());
1062 }
1063
1064 #[test]
1065 fn undo_and_preview_wire_format() {
1066 let m = ClientMsg::Undo { entry: 4 };
1067 assert_eq!(m.to_json(), r#"{"type":"undo","entry":4}"#);
1068 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1069 let mut s = step(1, StepStatus::Waiting);
1070 s.preview =
1071 Some(Preview::Write { path: "a.md".into(), bytes: 3, replaces: true, lines: vec![DiffLine { kind: LineKind::Added, text: "hi".into() }], more: 0 });
1072 let msg = ServerMsg::StepUpdated { entry: 1, step: s };
1073 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1074 let msg = ServerMsg::EntryUndo { id: 1, undoable: false, undone: true };
1075 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1076 }
1077
1078 #[test]
1079 fn chat_messages_round_trip() {
1080 let summary = ChatSummary { id: "c1".into(), title: "Plans".into(), updated_at: 5, pinned_at: None, busy: true, workspace: Some("w1".into()) };
1081 for m in [
1082 ServerMsg::Chats { pinned: vec![], recent: vec![summary.clone()], after: None, next: Some(summary.cursor()) },
1083 ServerMsg::ChatUpdated(summary.clone()),
1084 ServerMsg::ChatOpened { chat: Some(summary), workspace: None },
1085 ServerMsg::ChatDeleted { id: "c1".into() },
1086 ] {
1087 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1088 }
1089 let m = ClientMsg::ListChats { after: Some(ChatCursor { updated_at: 1, id: "x".into() }), limit: 50 };
1090 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1091 assert_eq!(ClientMsg::NewChat { workspace: None }.to_json(), r#"{"type":"new_chat"}"#);
1092 }
1093
1094 #[test]
1095 fn endpoint_info_is_optional_and_summarised() {
1096 let old = r#"{"version":"0","inference_base_url":"u","inference_model":"m","has_api_key":false,"endpoint":null,"busy":false}"#;
1097 assert_eq!(serde_json::from_str::<EngineState>(old).unwrap().endpoint_info, None);
1098 let info = EndpointInfo { probing: false, server: "llama.cpp".into(), context_tokens: Some(262_144), tools: ToolsMode::Native, vision: Some(true) };
1099 assert_eq!(info.summary(), "llama.cpp · 262k ctx · native tools · vision");
1100 assert_eq!(EndpointInfo { probing: true, ..info }.summary(), "checking endpoint…");
1101 assert_eq!(EndpointInfo::default().summary(), "tools untested");
1102 }
1103
1104 #[test]
1105 fn media_messages_round_trip() {
1106 let msgs = vec![
1107 ClientMsg::SendMessage { text: "chart it".into(), attachments: vec!["uploads/sales.csv".into()] },
1108 ClientMsg::Upload { upload: 1, name: "a.csv".into(), size: 3, offset: 0, data: media::encode(b"a,b"), done: true },
1109 ClientMsg::GetMedia { path: "charts/x.chart.json".into() },
1110 ];
1111 for m in msgs {
1112 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1113 }
1114 let spec = byob_types::chart::validate(&serde_json::json!({"type": "bar", "x": "m", "series": ["v"], "data": [{"m": "a", "v": 1}]})).unwrap();
1115 let msgs = vec![
1116 ServerMsg::Uploaded { upload: 1, attachment: Some(MediaRef::new("uploads/a.csv", 3)), error: None },
1117 ServerMsg::Media { path: "c.chart.json".into(), content: MediaContent::Chart { spec } },
1118 ServerMsg::Media { path: "p.png".into(), content: MediaContent::Image { mime: "image/png".into(), data: "AA==".into() } },
1119 ServerMsg::Media { path: "p.png".into(), content: MediaContent::Error { message: "gone".into() } },
1120 ];
1121 for m in msgs {
1122 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1123 }
1124 let mut s = step(1, StepStatus::Done);
1125 s.media = vec![MediaRef::new("charts/x.chart.json", 10)];
1126 let m = ServerMsg::StepUpdated { entry: 1, step: s };
1127 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1128 }
1129
1130 #[test]
1131 fn artifact_messages_round_trip() {
1132 let v = ArtifactVersion { n: 2, path: ".byob/artifacts/calc/v2.html".into(), created_at: 1, note: "blue button".into(), size: 10 };
1133 let a = Artifact {
1134 id: "calc".into(),
1135 kind: ArtifactKind::Html,
1136 content_type: artifact::TYPE_HTML.into(),
1137 title: "Calc".into(),
1138 filename: "calc.html".into(),
1139 versions: vec![v],
1140 };
1141 let msgs = vec![
1142 ServerMsg::Artifacts { chat: Some("c1".into()), artifacts: vec![a.clone()] },
1143 ServerMsg::Artifacts { chat: None, artifacts: vec![] },
1144 ServerMsg::ArtifactUpdated(a),
1145 ServerMsg::ArtifactFile { id: "calc".into(), version: 2, data: Some(media::encode(b"<p>")), error: None },
1146 ServerMsg::ArtifactFile { id: "calc".into(), version: 9, data: None, error: Some("no such version".into()) },
1147 ];
1148 for m in msgs {
1149 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1150 }
1151 let m = ClientMsg::GetArtifact { id: "calc".into(), version: 2 };
1152 assert_eq!(m.to_json(), r#"{"type":"get_artifact","id":"calc","version":2}"#);
1153 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1154 let mut s = step(1, StepStatus::Done);
1155 s.artifacts = vec![ArtifactRef { id: "calc".into(), version: 2 }];
1156 let m = ServerMsg::StepUpdated { entry: 1, step: s };
1157 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1158 let json = r#"{"id":1,"tool":"t","title":"T","access":"read","status":"done","detail":""}"#;
1160 assert!(serde_json::from_str::<Step>(json).unwrap().artifacts.is_empty());
1161 }
1162
1163 #[test]
1164 fn older_send_message_without_attachments_parses() {
1165 let m = ClientMsg::from_json(r#"{"type":"send_message","text":"hi"}"#).unwrap();
1166 assert_eq!(m, ClientMsg::SendMessage { text: "hi".into(), attachments: vec![] });
1167 assert_eq!(m.to_json(), r#"{"type":"send_message","text":"hi"}"#);
1168 }
1169
1170 #[test]
1171 fn compaction_messages_round_trip() {
1172 let c = Compaction {
1173 id: 1,
1174 after_entry: 7,
1175 tokens_before: 182_000,
1176 tokens_after: 9_000,
1177 summary: "## Goals".into(),
1178 manual: true,
1179 focus: Some("CSV".into()),
1180 created_at: 5,
1181 };
1182 let u = ChatUsage { chat: "c1".into(), context_used: 34_000, context_window: 262_144, compact_at: 209_715, model_calls: 3, ..Default::default() };
1183 for m in [ServerMsg::Usage(u), ServerMsg::Compactions { chat: Some("c1".into()), items: vec![c.clone()] }, ServerMsg::Compacted(c)] {
1184 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1185 }
1186 assert_eq!(ClientMsg::Compact { focus: None }.to_json(), r#"{"type":"compact"}"#);
1187 let m = ClientMsg::from_json(r#"{"type":"compact","focus":"keep the CSV"}"#).unwrap();
1188 assert_eq!(m, ClientMsg::Compact { focus: Some("keep the CSV".into()) });
1189 let s: TurnStats = serde_json::from_str(r#"{"prompt_tokens":1,"completion_tokens":2,"elapsed_ms":3}"#).unwrap();
1191 assert_eq!(s.model_calls, 0);
1192 }
1193
1194 #[test]
1195 fn connection_messages_round_trip() {
1196 for m in [
1197 ClientMsg::TestInference { base_url: "http://127.0.0.1:11434/v1".into(), model: "qwen3".into(), api_key: None },
1198 ClientMsg::TestInference { base_url: "https://api.openai.com/v1".into(), model: "m".into(), api_key: Some("sk".into()) },
1199 ClientMsg::DetectEndpoints,
1200 ClientMsg::Retry,
1201 ] {
1202 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1203 }
1204 assert_eq!(ClientMsg::Retry.to_json(), r#"{"type":"retry"}"#);
1205 let t = InferenceTest { base_url: "u".into(), model: "m".into(), ok: false, problem: Some(Problem::Unauthorized), detail: "x".into(), models: vec![] };
1206 let m = ServerMsg::InferenceTested(t);
1207 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1208 let state = EngineState {
1209 link: Link::failed("could not reach u: refused"),
1210 onboarded: true,
1211 detected: vec![Detected { preset: "ollama".into(), base_url: "http://127.0.0.1:11434/v1".into(), models: vec!["qwen3".into()] }],
1212 ..Default::default()
1213 };
1214 let m = ServerMsg::State(state);
1215 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1216 let old = r#"{"version":"0","inference_base_url":"u","inference_model":"m","has_api_key":false,"endpoint":null,"busy":false}"#;
1218 let s = serde_json::from_str::<EngineState>(old).unwrap();
1219 assert_eq!((s.link, s.onboarded, s.detected.len()), (Link::Unknown, false, 0));
1220 }
1221
1222 #[test]
1223 fn hello_negotiates_and_old_hellos_still_parse() {
1224 let m = ClientMsg::hello("desktop");
1225 let ClientMsg::Hello { protocol, minor, caps, .. } = &m else { panic!() };
1226 assert_eq!((*protocol, *minor), (PROTOCOL_MAJOR, PROTOCOL_MINOR));
1227 assert!(caps.iter().any(|c| c == version::CAP_PLUGIN_CHANNEL));
1228 assert!(m.check_sizes().is_ok());
1229 let old = ClientMsg::from_json(r#"{"type":"hello","protocol":12,"client":"old tab"}"#).unwrap();
1231 assert_eq!(old, ClientMsg::Hello { protocol: 12, minor: 0, client: "old tab".into(), caps: vec![] });
1232 let bad = ClientMsg::Hello { protocol: PROTOCOL_MAJOR, minor: 0, client: "x".into(), caps: vec!["NOT A CAP".into()] };
1233 assert!(bad.check_sizes().is_err());
1234 let w = ServerMsg::Welcome(Welcome::current());
1235 assert_eq!(ServerMsg::from_json(&w.to_json()).unwrap(), w);
1236 assert!(w.to_json().starts_with(r#"{"type":"welcome","protocol":13"#), "{}", w.to_json());
1237 }
1238
1239 #[test]
1240 fn plugin_channel_round_trips_and_is_capped() {
1241 let c = ClientMsg::Plugin { plugin: "sheets".into(), msg: serde_json::json!({"op": "get", "cell": "A1"}) };
1242 assert_eq!(c.to_json(), r#"{"type":"plugin","plugin":"sheets","msg":{"cell":"A1","op":"get"}}"#);
1243 assert_eq!(ClientMsg::from_json(&c.to_json()).unwrap(), c);
1244 assert!(c.check_sizes().is_ok());
1245 let s = ServerMsg::Plugin { plugin: "sheets".into(), msg: serde_json::json!([1, 2]) };
1246 assert_eq!(ServerMsg::from_json(&s.to_json()).unwrap(), s);
1247 for bad in [
1248 ClientMsg::Plugin { plugin: "Not/an id".into(), msg: serde_json::Value::Null },
1249 ClientMsg::Plugin { plugin: "sheets".into(), msg: serde_json::Value::String("x".repeat(version::MAX_PLUGIN_MSG_BYTES)) },
1250 ] {
1251 assert!(bad.check_sizes().is_err());
1252 }
1253 }
1254
1255 #[test]
1257 fn unknown_messages_and_enum_values_decode_to_fallbacks() {
1258 assert_eq!(ServerMsg::from_json(r#"{"type":"hologram","x":1,"y":{"z":[]}}"#).unwrap(), ServerMsg::Unknown);
1259 assert_eq!(ClientMsg::from_json(r#"{"type":"teleport","to":"mars"}"#).unwrap(), ClientMsg::Unknown);
1260 assert!(ServerMsg::from_json(r#"{"type":"notice","level":"info"}"#).is_err());
1262 let n = ServerMsg::from_json(r#"{"type":"notice","level":"debug","text":"t"}"#).unwrap();
1263 assert_eq!(n, ServerMsg::Notice { level: NoticeLevel::Info, text: "t".into() });
1264 let a = ClientMsg::from_json(r#"{"type":"approve","step":1,"answer":"maybe_later"}"#).unwrap();
1265 assert_eq!(a, ClientMsg::Approve { step: 1, answer: ApprovalAnswer::Unknown });
1266 let json = r#"{"id":1,"tool":"t","title":"T","access":"read","status":"done","detail":"",
1268 "changes":[{"kind":"chmod","path":"a","mode":"755"}],
1269 "preview":{"kind":"hexdump","bytes":"00"},
1270 "media":[{"kind":"video","path":"a.mp4"}],
1271 "views":[{"kind":"sheets.grid","v":4,"data":{"rows":[]},"fallback":"a *grid*"}]}"#;
1272 let s: Step = serde_json::from_str(json).unwrap();
1273 assert_eq!((s.changes.clone(), s.preview.clone()), (vec![FileChange::Other], Some(Preview::Other)));
1274 assert_eq!(s.media[0].kind, MediaKind::File);
1275 assert_eq!((s.views[0].kind.as_str(), s.views[0].fallback.as_str()), ("sheets.grid", "a *grid*"));
1276 assert!(s.view::<PluginCard>().is_none());
1277 let art: Artifact = serde_json::from_str(r#"{"id":"a","kind":"spreadsheet","title":"A","filename":"a.xlsx","versions":[]}"#).unwrap();
1278 assert_eq!(art.kind, ArtifactKind::Text);
1279 assert_eq!(serde_json::from_str::<SlashKind>(r#""macro""#).unwrap(), SlashKind::Other);
1280 assert_eq!(serde_json::from_str::<PluginAction>(r#""forked""#).unwrap(), PluginAction::Other);
1281 let env = ClientMsg::from_json(r#"{"type":"workspace_env","action":{"kind":"rebuild","fast":true}}"#).unwrap();
1282 assert_eq!(env, ClientMsg::WorkspaceEnv { action: Some(EnvAction::Unsupported), workspace: None });
1283 let d = ServerMsg::from_json(r#"{"type":"delegation","entry":1,"step":2,"update":{"kind":"progress","pct":5}}"#).unwrap();
1284 assert_eq!(d, ServerMsg::Delegation { entry: 1, step: 2, update: DelegationUpdate::Other });
1285 }
1286
1287 #[test]
1288 fn plugin_cards_travel_as_views() {
1289 let card = PluginCard {
1290 plugin: "scratch".into(),
1291 scope: PluginScope::Chat,
1292 action: PluginAction::Made,
1293 tools: vec!["shout".into()],
1294 added: vec!["shout".into()],
1295 removed: vec![],
1296 test: Some(plugins::PluginTest { ok: true, output: "HI".into() }),
1297 problems: vec![],
1298 missing_settings: vec![],
1299 };
1300 let mut s = step(1, StepStatus::Done);
1301 s.views.push(View::of(&card));
1302 let json = ServerMsg::StepUpdated { entry: 1, step: s }.to_json();
1303 assert!(json.contains(r#""views":[{"kind":"byob.plugin_card","v":1,"data":{"action":"made""#), "{json}");
1304 let ServerMsg::StepUpdated { step: back, .. } = ServerMsg::from_json(&json).unwrap() else { panic!() };
1305 assert_eq!(back.view::<PluginCard>(), Some(card));
1306 assert!(back.views[0].fallback.contains("**Plugin scratch** (this chat) · tool made") && back.views[0].fallback.contains("shout"));
1307 assert!(!ServerMsg::StepUpdated { entry: 1, step: step(2, StepStatus::Done) }.to_json().contains("views"));
1309 }
1310
1311 #[test]
1312 fn state_never_carries_api_key() {
1313 let json = serde_json::to_string(&EngineState::default()).unwrap();
1314 assert!(!json.contains("\"api_key\""));
1315 }
1316}