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 layout;
13pub mod look;
14pub mod media;
15pub mod plugins;
16pub mod profiles;
17pub mod queue;
18pub mod sites;
19pub mod tree;
20pub mod usage;
21pub mod version;
22pub mod view;
23pub mod web;
24pub mod workspace;
25
26use serde::{Deserialize, Serialize};
27
28pub use artifact::{Artifact, ArtifactKind, ArtifactRef, ArtifactVersion};
29pub use connect::{Detected, InferenceTest, Link, PRESETS, Preset, Problem};
30pub use delegation::{Delegation, DelegationState, DelegationUpdate};
31pub use env::{ContainerEnv, EnvAction, EnvSupport, WorkspaceEnv};
32pub use media::{MediaContent, MediaKind, MediaRef};
33pub use plugins::{
34 BackendInfo, Extensions, PluginAction, PluginCard, PluginInfo, PluginLoadError, PluginOrigin, PluginScope, PluginSetting, PluginTest, RendererDecl,
35 ServerInfo, ServerState, SlashItem, SlashKind, StarterDecl,
36};
37pub use profiles::{CAP_PROFILES, Profile, ProfileList, ProfileTest, ProfileView};
38pub use queue::{ChatQueue, QueuePause, QueuedMessage};
39pub use sites::{LiveView, Site, ViewDecl, ViewRef};
40pub use usage::{ChatUsage, Compaction};
41pub use version::{PROTOCOL_MAJOR, PROTOCOL_MINOR, Welcome};
42pub use view::{View, ViewData};
43pub use workspace::{ChatEndpoint, ConfigScope, ConfigView, FolderList, NewFolder, WorkspaceSummary};
44
45pub const MAX_FRAME_BYTES: usize = 4 * 1024 * 1024;
47
48#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
50#[serde(tag = "type", rename_all = "snake_case")]
51pub enum ClientMsg {
52 Hello {
56 protocol: u32,
57 #[serde(default)]
58 minor: u32,
59 client: String,
60 #[serde(default)]
61 caps: Vec<String>,
62 },
63 SetInference {
67 base_url: String,
68 model: String,
69 api_key: Option<String>,
70 },
71 TestInference {
74 base_url: String,
75 model: String,
76 #[serde(default, skip_serializing_if = "Option::is_none")]
77 api_key: Option<String>,
78 },
79 DetectEndpoints,
82 Retry,
85 Rewind {
91 entry: u64,
92 text: String,
93 },
94 SendMessage {
98 text: String,
99 #[serde(default, skip_serializing_if = "Vec::is_empty")]
100 attachments: Vec<String>,
101 },
102 Cancel,
104 Unqueue {
106 id: u64,
107 },
108 EditQueued {
111 id: u64,
112 text: String,
113 #[serde(default, skip_serializing_if = "Vec::is_empty")]
114 attachments: Vec<String>,
115 },
116 MoveQueued {
118 id: u64,
119 to: u32,
120 },
121 SendQueuedNow {
123 id: u64,
124 },
125 ResumeQueue,
127 Approve {
130 step: u64,
131 answer: ApprovalAnswer,
132 },
133 AnswerQuestion {
137 step: u64,
138 text: String,
139 },
140 Undo {
143 entry: u64,
144 },
145 ListChats {
148 after: Option<ChatCursor>,
149 limit: u32,
150 },
151 NewChat {
155 #[serde(default, skip_serializing_if = "Option::is_none")]
156 workspace: Option<String>,
157 },
158 OpenChat {
160 id: String,
161 },
162 RenameChat {
163 id: String,
164 title: String,
165 },
166 DeleteChat {
168 id: String,
169 },
170 PinChat {
171 id: String,
172 pinned: bool,
173 },
174 Upload {
179 upload: u64,
180 name: String,
181 size: u64,
182 offset: u64,
183 data: String,
184 done: bool,
185 },
186 GetMedia {
188 path: String,
189 },
190 GetArtifact {
193 id: String,
194 version: u32,
195 },
196 SetArtifactNetwork {
200 id: String,
201 on: bool,
202 },
203 Compact {
206 #[serde(default, skip_serializing_if = "Option::is_none")]
207 focus: Option<String>,
208 },
209 WorkspaceEnv {
212 #[serde(default, skip_serializing_if = "Option::is_none")]
213 action: Option<EnvAction>,
214 #[serde(default, skip_serializing_if = "Option::is_none")]
215 workspace: Option<String>,
216 },
217 CreateWorkspace {
221 name: String,
222 folder: NewFolder,
223 #[serde(default)]
224 config: workspace::Layer,
225 },
226 RenameWorkspace {
227 id: String,
228 name: String,
229 },
230 RemoveWorkspace {
233 id: String,
234 #[serde(default)]
235 clean: bool,
236 },
237 GetConfig {
239 scope: ConfigScope,
240 },
241 SetConfig {
245 scope: ConfigScope,
246 layer: workspace::Layer,
247 #[serde(default, skip_serializing_if = "Option::is_none")]
248 api_key: Option<String>,
249 },
250 ListFolders {
253 #[serde(default, skip_serializing_if = "Option::is_none")]
254 path: Option<String>,
255 },
256 CheckContainers,
258 GetExtensions,
260 SetPluginEnabled {
264 scope: ConfigScope,
265 plugin: String,
266 enabled: Option<bool>,
267 },
268 SetPluginSetting {
272 plugin: String,
273 key: String,
274 value: Option<String>,
275 },
276 KeepPlugin {
280 plugin: String,
281 scope: PluginScope,
282 #[serde(default, skip_serializing_if = "Option::is_none")]
283 new_id: Option<String>,
284 },
285 RemovePlugin {
288 plugin: String,
289 scope: PluginScope,
290 },
291 ReloadPlugins,
293 TrustPlugins {
297 workspace: String,
298 #[serde(default)]
299 plugins: Vec<String>,
300 trust: bool,
301 },
302 Plugin {
305 plugin: String,
306 msg: serde_json::Value,
307 },
308 OpenView {
312 view: ViewRef,
313 },
314 CloseView {
316 view: ViewRef,
317 },
318 ViewEvent {
321 view: ViewRef,
322 event: tree::Event,
323 },
324 WebCall {
329 call: u64,
330 owner: web::WebOwner,
331 method: String,
332 #[serde(default)]
333 params: serde_json::Value,
334 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
335 approved: bool,
336 },
337 GetProfiles,
340 CreateProfile {
343 profile: Profile,
344 #[serde(default, skip_serializing_if = "Option::is_none")]
345 api_key: Option<String>,
346 #[serde(default, skip_serializing_if = "Option::is_none")]
347 assign: Option<ConfigScope>,
348 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
349 make_main: bool,
350 },
351 UpdateProfile {
354 profile: Profile,
355 #[serde(default, skip_serializing_if = "Option::is_none")]
356 api_key: Option<String>,
357 },
358 DeleteProfile {
361 id: String,
362 },
363 DuplicateProfile {
365 id: String,
366 },
367 SetRole {
370 role: String,
371 profile: Option<String>,
372 },
373 TestProfile {
375 id: String,
376 },
377 SetLevelProfile {
380 scope: ConfigScope,
381 profile: Option<String>,
382 },
383 SetLayout {
386 layout: layout::Layout,
387 },
388 ReportLook(look::LookReport),
391 #[serde(other)]
393 Unknown,
394}
395
396#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
398#[serde(tag = "type", rename_all = "snake_case")]
399pub enum ServerMsg {
400 Welcome(Welcome),
402 State(EngineState),
404 Notice { level: NoticeLevel, text: String },
406 Transcript { entries: Vec<Entry> },
408 EntryAdded(Entry),
410 EntryDelta { id: u64, content: String, reasoning: String },
412 EntryFinished { id: u64, error: Option<String>, stats: Option<TurnStats> },
414 StepUpdated { entry: u64, step: Step },
416 EntryUndo { id: u64, undoable: bool, undone: bool },
418 Chats { pinned: Vec<ChatSummary>, recent: Vec<ChatSummary>, after: Option<ChatCursor>, next: Option<ChatCursor> },
421 ChatUpdated(ChatSummary),
423 ChatDeleted { id: String },
425 ChatOpened {
429 chat: Option<ChatSummary>,
430 #[serde(default)]
431 workspace: Option<String>,
432 },
433 Uploaded { upload: u64, attachment: Option<MediaRef>, error: Option<String> },
435 Media { path: String, content: MediaContent },
437 Artifacts { chat: Option<String>, artifacts: Vec<Artifact> },
440 ArtifactUpdated(Artifact),
442 ArtifactFile { id: String, version: u32, data: Option<String>, error: Option<String> },
444 Usage(ChatUsage),
446 Compactions { chat: Option<String>, items: Vec<Compaction> },
449 Compacted(Compaction),
451 Delegation { entry: u64, step: u64, update: DelegationUpdate },
453 InferenceTested(InferenceTest),
455 WorkspaceEnv(WorkspaceEnv),
457 Workspaces { items: Vec<WorkspaceSummary>, current: Option<String>, root: String, support: EnvSupport },
461 Config(Box<ConfigView>),
463 Folders(FolderList),
465 ContainersChecked { ok: bool, message: String },
467 WorkspaceCreated { id: Option<String>, error: Option<String> },
469 Queue(ChatQueue),
472 Extensions(Box<Extensions>),
475 Plugin { plugin: String, msg: serde_json::Value },
478 LiveView(LiveView),
481 WebReply {
484 call: u64,
485 #[serde(default, deserialize_with = "present_even_if_null", skip_serializing_if = "Option::is_none")]
487 result: Option<serde_json::Value>,
488 #[serde(default, skip_serializing_if = "Option::is_none")]
489 error: Option<web::WebError>,
490 },
491 WebPush { owner: web::WebOwner, msg: serde_json::Value },
494 Profiles(Box<ProfileList>),
497 ProfileTested(ProfileTest),
499 Layout(layout::Layout),
502 SetLook { request: u64, changes: look::LookChanges },
506 #[serde(other)]
508 Unknown,
509}
510
511#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
513pub struct ChatSummary {
514 pub id: String,
515 pub title: String,
516 pub updated_at: i64,
518 pub pinned_at: Option<i64>,
520 #[serde(default)]
522 pub busy: bool,
523 #[serde(default, skip_serializing_if = "Option::is_none")]
525 pub workspace: Option<String>,
526}
527
528impl ChatSummary {
529 pub fn cursor(&self) -> ChatCursor {
530 ChatCursor { updated_at: self.updated_at, id: self.id.clone() }
531 }
532}
533
534#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
536pub struct ChatCursor {
537 pub updated_at: i64,
538 pub id: String,
539}
540
541#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
542#[serde(rename_all = "snake_case")]
543pub enum EntryRole {
544 User,
545 Assistant,
546}
547
548#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
550pub struct Entry {
551 pub id: u64,
552 pub role: EntryRole,
553 pub content: String,
554 pub reasoning: String,
555 pub done: bool,
557 pub error: Option<String>,
558 pub stats: Option<TurnStats>,
559 #[serde(default)]
562 pub steps: Vec<Step>,
563 #[serde(default)]
565 pub undoable: bool,
566 #[serde(default)]
568 pub undone: bool,
569 #[serde(default, skip_serializing_if = "Vec::is_empty")]
571 pub attachments: Vec<MediaRef>,
572}
573
574impl Entry {
575 pub fn append(&mut self, content: &str, reasoning: &str) {
577 self.content.push_str(content);
578 self.reasoning.push_str(reasoning);
579 }
580
581 pub fn upsert_step(&mut self, step: Step) {
583 match self.steps.iter_mut().find(|s| s.id == step.id) {
584 Some(existing) => *existing = step,
585 None => self.steps.push(step),
586 }
587 }
588
589 pub fn pending_approvals(&self) -> impl Iterator<Item = &Step> {
591 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)
592 }
593
594 pub fn apply_delegation(&mut self, step: u64, update: &DelegationUpdate) {
596 if let Some(d) = self.steps.iter_mut().find(|s| s.id == step).and_then(|s| s.delegation.as_deref_mut()) {
597 d.apply(update);
598 }
599 }
600}
601
602#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
604#[serde(rename_all = "snake_case")]
605pub enum ToolAccess {
606 Read,
607 Write,
608 Network,
609 Execute,
610}
611
612impl ToolAccess {
613 pub fn label(self) -> &'static str {
614 match self {
615 Self::Read => "read",
616 Self::Write => "write",
617 Self::Network => "network",
618 Self::Execute => "execute",
619 }
620 }
621}
622
623#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
624#[serde(rename_all = "snake_case")]
625pub enum StepStatus {
626 Running,
627 Waiting,
629 Done,
630 Failed,
632 Denied,
634}
635
636impl StepStatus {
637 pub fn finished(self) -> bool {
638 matches!(self, Self::Done | Self::Failed | Self::Denied)
639 }
640}
641
642#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
644#[serde(rename_all = "snake_case")]
645pub enum ApprovalAnswer {
646 Allow,
647 Always,
649 Deny,
650 AlwaysEverywhere,
652 #[serde(other)]
654 Unknown,
655}
656
657#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
659#[serde(tag = "kind", rename_all = "snake_case")]
660pub enum FileChange {
661 Created {
662 path: String,
663 },
664 Modified {
665 path: String,
666 },
667 Deleted {
668 path: String,
669 },
670 Moved {
671 from: String,
672 to: String,
673 },
674 #[serde(other)]
676 Other,
677}
678
679#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
681pub struct Step {
682 pub id: u64,
684 pub tool: String,
686 pub title: String,
688 pub access: ToolAccess,
689 pub status: StepStatus,
690 pub detail: String,
692 #[serde(default)]
693 pub changes: Vec<FileChange>,
694 #[serde(default)]
696 pub at: usize,
697 #[serde(default, skip_serializing_if = "Vec::is_empty")]
699 pub media: Vec<MediaRef>,
700 #[serde(default, skip_serializing_if = "Option::is_none")]
702 pub preview: Option<Preview>,
703 #[serde(default, skip_serializing_if = "Vec::is_empty")]
705 pub artifacts: Vec<ArtifactRef>,
706 #[serde(default, skip_serializing_if = "Option::is_none")]
708 pub delegation: Option<Box<Delegation>>,
709 #[serde(default, skip_serializing_if = "Option::is_none")]
713 pub ask: Option<Box<Ask>>,
714 #[serde(default, skip_serializing_if = "Vec::is_empty")]
718 pub views: Vec<View>,
719}
720
721impl Step {
722 pub fn view<T: ViewData>(&self) -> Option<T> {
724 self.views.iter().find_map(View::get)
725 }
726}
727
728#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
730pub struct Ask {
731 #[serde(default)]
733 pub text: String,
734 #[serde(default, skip_serializing_if = "Option::is_none")]
736 pub warning: Option<String>,
737 #[serde(default)]
739 pub always: bool,
740 #[serde(default, skip_serializing_if = "Option::is_none")]
744 pub choice: Option<Choice>,
745}
746
747pub const MAX_CHOICE_OPTIONS: usize = 8;
749pub const MAX_ANSWER_CHARS: usize = 2000;
751
752#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
754pub struct Choice {
755 #[serde(default, skip_serializing_if = "Vec::is_empty")]
757 pub options: Vec<String>,
758 #[serde(default)]
760 pub free_text: bool,
761 #[serde(default, skip_serializing_if = "Option::is_none")]
763 pub answer: Option<String>,
764}
765
766pub const MAX_PREVIEW_LINES: usize = 40;
768pub const MAX_PREVIEW_LINE_CHARS: usize = 300;
770
771#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
773#[serde(tag = "kind", rename_all = "snake_case")]
774pub enum Preview {
775 Write {
778 path: String,
779 bytes: u64,
780 replaces: bool,
782 lines: Vec<DiffLine>,
783 #[serde(default)]
785 more: usize,
786 },
787 Move {
789 moves: Vec<(String, String)>,
790 #[serde(default)]
791 more: usize,
792 },
793 Delete { path: String, what: String },
795 Args {
797 fields: Vec<(String, String)>,
798 #[serde(default, skip_serializing_if = "Option::is_none")]
799 code: Option<String>,
800 #[serde(default)]
801 more: usize,
802 },
803 #[serde(other)]
805 Other,
806}
807
808#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
810pub struct DiffLine {
811 pub kind: LineKind,
812 pub text: String,
813}
814
815#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
816#[serde(rename_all = "snake_case")]
817pub enum LineKind {
818 Same,
820 Added,
821 Removed,
822 Skipped,
824}
825
826#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
827pub struct TurnStats {
828 pub prompt_tokens: u64,
829 pub completion_tokens: u64,
830 pub elapsed_ms: u64,
831 #[serde(default)]
833 pub model_calls: u64,
834 #[serde(default, skip_serializing_if = "is_zero")]
838 pub context_tokens: u64,
839}
840
841fn is_zero(n: &u64) -> bool {
842 *n == 0
843}
844
845#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
846#[serde(rename_all = "snake_case")]
847pub enum NoticeLevel {
848 Error,
849 #[serde(other)]
851 Info,
852}
853
854#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
856pub struct EngineState {
857 pub version: String,
858 pub inference_base_url: String,
859 pub inference_model: String,
860 pub has_api_key: bool,
861 pub endpoint: Option<String>,
863 pub busy: bool,
865 #[serde(default)]
867 pub endpoint_info: Option<EndpointInfo>,
868 #[serde(default)]
870 pub link: Link,
871 #[serde(default)]
874 pub onboarded: bool,
875 #[serde(default)]
877 pub detected: Vec<Detected>,
878 #[serde(default)]
880 pub detecting: bool,
881 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
883 pub yolo: bool,
884 #[serde(default, skip_serializing_if = "Option::is_none")]
887 pub chat_endpoint: Option<ChatEndpoint>,
888}
889
890#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
892#[serde(rename_all = "snake_case")]
893pub enum ToolsMode {
894 Native,
896 Prompt,
898 #[default]
900 Unknown,
901}
902
903#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
905pub struct EndpointInfo {
906 #[serde(default)]
908 pub probing: bool,
909 #[serde(default)]
911 pub server: String,
912 #[serde(default)]
914 pub context_tokens: Option<u64>,
915 #[serde(default)]
916 pub tools: ToolsMode,
917 #[serde(default)]
919 pub vision: Option<bool>,
920 #[serde(default, skip_serializing_if = "Option::is_none")]
922 pub slots: Option<u64>,
923}
924
925impl EndpointInfo {
926 pub fn summary(&self) -> String {
928 if self.probing {
929 return "checking endpoint…".into();
930 }
931 let mut parts = Vec::new();
932 if !self.server.is_empty() {
933 parts.push(self.server.clone());
934 }
935 if let Some(n) = self.context_tokens {
936 parts.push(if n >= 1000 { format!("{}k ctx", n / 1000) } else { format!("{n} ctx") });
937 }
938 parts.push(
939 match self.tools {
940 ToolsMode::Native => "native tools",
941 ToolsMode::Prompt => "prompt tools",
942 ToolsMode::Unknown => "tools untested",
943 }
944 .into(),
945 );
946 if self.vision == Some(true) {
947 parts.push("vision".into());
948 }
949 if let Some(n) = self.slots.filter(|n| *n > 1) {
950 parts.push(format!("{n} slots"));
951 }
952 parts.join(" · ")
953 }
954}
955
956impl ClientMsg {
957 pub fn hello(client: &str) -> Self {
959 Self::Hello { protocol: PROTOCOL_MAJOR, minor: PROTOCOL_MINOR, client: client.to_owned(), caps: version::client_caps() }
960 }
961
962 pub fn to_json(&self) -> String {
963 serde_json::to_string(self).unwrap_or_default()
964 }
965
966 pub fn from_json(text: &str) -> Result<Self, String> {
968 if text.len() > MAX_FRAME_BYTES {
969 return Err(format!("frame too large ({} bytes)", text.len()));
970 }
971 serde_json::from_str(text).map_err(|e| e.to_string())
972 }
973}
974
975impl ServerMsg {
976 pub fn to_json(&self) -> String {
977 serde_json::to_string(self).unwrap_or_default()
978 }
979
980 pub fn to_frame(&self) -> String {
986 let json = self.to_json();
987 if json.len() <= MAX_FRAME_BYTES {
988 return json;
989 }
990 let why = format!("it is too large to send over this connection ({} KB, at most {} KB)", json.len() / 1024, MAX_FRAME_BYTES / 1024);
991 let instead = match self {
992 Self::LiveView(lv) if lv.tree.is_none() => Self::LiveView(LiveView { view: lv.view.clone(), reset: true, ..Default::default() }),
993 Self::LiveView(lv) => {
994 Self::LiveView(LiveView { view: lv.view.clone(), error: Some(format!("This view can't be shown here: {why}.")), ..Default::default() })
995 }
996 Self::WebReply { call, .. } => {
997 Self::WebReply { call: *call, result: None, error: Some(web::WebError::new(-32000, format!("byob couldn't send the answer: {why}"))) }
998 }
999 _ => Self::Notice { level: NoticeLevel::Error, text: format!("byob couldn't send an update: {why}.") },
1000 };
1001 instead.to_json()
1002 }
1003
1004 pub fn from_json(text: &str) -> Result<Self, String> {
1006 if text.len() > MAX_FRAME_BYTES {
1007 return Err(format!("frame too large ({} bytes)", text.len()));
1008 }
1009 serde_json::from_str(text).map_err(|e| e.to_string())
1010 }
1011}
1012
1013pub trait Connection {
1015 fn send(&mut self, msg: ClientMsg);
1016 fn try_recv(&mut self) -> Option<ServerMsg>;
1018}
1019
1020fn present_even_if_null<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<serde_json::Value>, D::Error> {
1023 serde_json::Value::deserialize(d).map(Some)
1024}
1025
1026#[cfg(test)]
1027mod tests {
1028 use super::*;
1029
1030 #[test]
1033 fn web_reply_keeps_a_null_result() {
1034 let null = ServerMsg::WebReply { call: 3, result: Some(serde_json::Value::Null), error: None };
1035 assert_eq!(null.to_json(), r#"{"type":"web_reply","call":3,"result":null}"#);
1036 assert_eq!(ServerMsg::from_json(&null.to_json()).unwrap(), null);
1037 let none = ServerMsg::WebReply { call: 3, result: None, error: None };
1038 assert_eq!(none.to_json(), r#"{"type":"web_reply","call":3}"#);
1039 assert_eq!(ServerMsg::from_json(&none.to_json()).unwrap(), none);
1040 let value = ServerMsg::WebReply { call: 3, result: Some(serde_json::json!({"a": [1]})), error: None };
1041 assert_eq!(ServerMsg::from_json(&value.to_json()).unwrap(), value);
1042 }
1043
1044 #[test]
1045 fn client_msg_round_trips() {
1046 let m = ClientMsg::hello("test");
1047 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1048 }
1049
1050 #[test]
1051 fn wire_format_is_tagged() {
1052 let json = ServerMsg::Notice { level: NoticeLevel::Info, text: "hi".into() }.to_json();
1053 assert_eq!(json, r#"{"type":"notice","level":"info","text":"hi"}"#);
1054 }
1055
1056 #[test]
1057 fn a_message_too_large_for_a_frame_is_sent_as_something_the_client_acts_on() {
1058 let big = "x".repeat(MAX_FRAME_BYTES);
1059 let r = ViewRef::new("p", "v", "k");
1060 let small = ServerMsg::Notice { level: NoticeLevel::Info, text: "hi".into() };
1061 assert_eq!(small.to_frame(), small.to_json());
1062 let frame = |m: ServerMsg| {
1063 let f = m.to_frame();
1064 assert!(f.len() < 1024, "{} bytes", f.len());
1065 ServerMsg::from_json(&f).unwrap()
1066 };
1067 let mut values = serde_json::Map::new();
1068 values.insert("f".into(), serde_json::json!(big));
1069 let change = LiveView { view: r.clone(), values, ..Default::default() };
1070 assert_eq!(frame(ServerMsg::LiveView(change)), ServerMsg::LiveView(LiveView { view: r.clone(), reset: true, ..Default::default() }));
1071 let texts: Vec<_> = (0..100).map(|_| serde_json::json!({"type": "text", "text": "y".repeat(60_000)})).collect();
1073 let (tree, faults) = tree::decode(serde_json::json!({"type": "column", "children": texts}));
1074 assert!(faults.is_empty(), "{faults:?}");
1075 match frame(ServerMsg::LiveView(LiveView { view: r.clone(), tree: Some(tree), ..Default::default() })) {
1076 ServerMsg::LiveView(lv) => assert!(lv.view == r && lv.tree.is_none() && lv.error.is_some_and(|e| e.contains("too large"))),
1077 other => panic!("{other:?}"),
1078 }
1079 match frame(ServerMsg::WebReply { call: 9, result: Some(serde_json::json!(big)), error: None }) {
1080 ServerMsg::WebReply { call: 9, result: None, error: Some(e) } => assert!(e.message.contains("too large")),
1081 other => panic!("{other:?}"),
1082 }
1083 let plugin = ServerMsg::Plugin { plugin: "p".into(), msg: serde_json::json!(big) };
1084 assert!(matches!(frame(plugin), ServerMsg::Notice { level: NoticeLevel::Error, .. }));
1085 }
1086
1087 #[test]
1088 fn rejects_garbage_and_oversized_frames() {
1089 assert!(ClientMsg::from_json("{not json").is_err());
1090 assert!(ClientMsg::from_json(&" ".repeat(MAX_FRAME_BYTES + 1)).is_err());
1091 }
1092
1093 #[test]
1094 fn approve_wire_format() {
1095 let m = ClientMsg::Approve { step: 7, answer: ApprovalAnswer::Always };
1096 assert_eq!(m.to_json(), r#"{"type":"approve","step":7,"answer":"always"}"#);
1097 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1098 }
1099
1100 fn step(id: u64, status: StepStatus) -> Step {
1101 Step {
1102 id,
1103 tool: "t".into(),
1104 title: "T".into(),
1105 access: ToolAccess::Write,
1106 status,
1107 detail: String::new(),
1108 changes: vec![],
1109 at: 0,
1110 preview: None,
1111 media: vec![],
1112 artifacts: vec![],
1113 delegation: None,
1114 ask: None,
1115 views: vec![],
1116 }
1117 }
1118
1119 #[test]
1120 fn delegations_stream_into_their_step_and_round_trip() {
1121 let mut parent = step(1, StepStatus::Running);
1122 parent.delegation = Some(Box::new(Delegation { agent: "explorer".into(), task: "count lines".into(), ..Default::default() }));
1123 let mut e = Entry {
1124 id: 9,
1125 role: EntryRole::Assistant,
1126 content: String::new(),
1127 reasoning: String::new(),
1128 done: false,
1129 error: None,
1130 stats: None,
1131 steps: vec![parent],
1132 undoable: false,
1133 undone: false,
1134 attachments: vec![],
1135 };
1136 let updates = [
1137 DelegationUpdate::Status { state: DelegationState::Running, prompt_tokens: 0, completion_tokens: 0, error: None },
1138 DelegationUpdate::Delta { content: "Reading".into(), reasoning: "hm".into() },
1139 DelegationUpdate::Step(Box::new(step(2, StepStatus::Waiting))),
1140 DelegationUpdate::Delta { content: " a.txt".into(), reasoning: String::new() },
1141 ];
1142 for u in &updates {
1143 let msg = ServerMsg::Delegation { entry: 9, step: 1, update: u.clone() };
1144 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1145 e.apply_delegation(1, u);
1146 }
1147 e.apply_delegation(77, &updates[1]);
1149 let d = e.steps[0].delegation.as_deref().unwrap();
1150 assert_eq!((d.content.as_str(), d.reasoning.as_str(), d.state), ("Reading a.txt", "hm", DelegationState::Running));
1151 assert_eq!(d.status_line(), "explorer · 1 tool · waiting for approval");
1152 assert_eq!(e.pending_approvals().map(|s| s.id).collect::<Vec<_>>(), vec![2]);
1154 e.apply_delegation(1, &DelegationUpdate::Step(Box::new(step(2, StepStatus::Done))));
1155 e.apply_delegation(1, &DelegationUpdate::Status { state: DelegationState::Done, prompt_tokens: 50, completion_tokens: 5, error: None });
1156 assert_eq!(e.steps[0].delegation.as_deref().unwrap().status_line(), "explorer · 1 tool · done");
1157 assert_eq!(e.pending_approvals().count(), 0);
1158 let msg = ServerMsg::StepUpdated { entry: 9, step: e.steps[0].clone() };
1159 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1160 let json = r#"{"id":1,"tool":"t","title":"T","access":"read","status":"done","detail":""}"#;
1162 assert!(serde_json::from_str::<Step>(json).unwrap().delegation.is_none());
1163 }
1164
1165 #[test]
1166 fn steps_upsert_and_round_trip() {
1167 let mut e = Entry {
1168 id: 1,
1169 role: EntryRole::Assistant,
1170 content: String::new(),
1171 reasoning: String::new(),
1172 done: false,
1173 error: None,
1174 stats: None,
1175 steps: vec![],
1176 undoable: false,
1177 undone: false,
1178 attachments: vec![],
1179 };
1180 e.upsert_step(step(3, StepStatus::Running));
1181 e.upsert_step(step(4, StepStatus::Waiting));
1182 e.upsert_step(step(3, StepStatus::Done));
1183 assert_eq!(e.steps.len(), 2);
1184 assert_eq!(e.steps[0].status, StepStatus::Done);
1185 assert_eq!(e.pending_approvals().map(|s| s.id).collect::<Vec<_>>(), vec![4]);
1186 let mut s = step(5, StepStatus::Done);
1187 s.changes = vec![FileChange::Moved { from: "a".into(), to: "b".into() }];
1188 let msg = ServerMsg::StepUpdated { entry: 1, step: s };
1189 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1190 }
1191
1192 #[test]
1193 fn entry_without_steps_still_parses() {
1194 let json = r#"{"id":1,"role":"user","content":"hi","reasoning":"","done":true,"error":null,"stats":null}"#;
1195 let e: Entry = serde_json::from_str(json).unwrap();
1196 assert!(e.steps.is_empty());
1197 }
1198
1199 #[test]
1200 fn undo_and_preview_wire_format() {
1201 let m = ClientMsg::Undo { entry: 4 };
1202 assert_eq!(m.to_json(), r#"{"type":"undo","entry":4}"#);
1203 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1204 let mut s = step(1, StepStatus::Waiting);
1205 s.preview =
1206 Some(Preview::Write { path: "a.md".into(), bytes: 3, replaces: true, lines: vec![DiffLine { kind: LineKind::Added, text: "hi".into() }], more: 0 });
1207 let msg = ServerMsg::StepUpdated { entry: 1, step: s };
1208 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1209 let msg = ServerMsg::EntryUndo { id: 1, undoable: false, undone: true };
1210 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1211 }
1212
1213 #[test]
1214 fn chat_messages_round_trip() {
1215 let summary = ChatSummary { id: "c1".into(), title: "Plans".into(), updated_at: 5, pinned_at: None, busy: true, workspace: Some("w1".into()) };
1216 for m in [
1217 ServerMsg::Chats { pinned: vec![], recent: vec![summary.clone()], after: None, next: Some(summary.cursor()) },
1218 ServerMsg::ChatUpdated(summary.clone()),
1219 ServerMsg::ChatOpened { chat: Some(summary), workspace: None },
1220 ServerMsg::ChatDeleted { id: "c1".into() },
1221 ] {
1222 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1223 }
1224 let m = ClientMsg::ListChats { after: Some(ChatCursor { updated_at: 1, id: "x".into() }), limit: 50 };
1225 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1226 assert_eq!(ClientMsg::NewChat { workspace: None }.to_json(), r#"{"type":"new_chat"}"#);
1227 }
1228
1229 #[test]
1230 fn endpoint_info_is_optional_and_summarised() {
1231 let old = r#"{"version":"0","inference_base_url":"u","inference_model":"m","has_api_key":false,"endpoint":null,"busy":false}"#;
1232 assert_eq!(serde_json::from_str::<EngineState>(old).unwrap().endpoint_info, None);
1233 let info = EndpointInfo {
1234 probing: false,
1235 server: "llama.cpp".into(),
1236 context_tokens: Some(262_144),
1237 tools: ToolsMode::Native,
1238 vision: Some(true),
1239 slots: None,
1240 };
1241 assert_eq!(info.summary(), "llama.cpp · 262k ctx · native tools · vision");
1242 assert_eq!(EndpointInfo { slots: Some(4), ..info.clone() }.summary(), "llama.cpp · 262k ctx · native tools · vision · 4 slots");
1243 assert_eq!(EndpointInfo { probing: true, ..info }.summary(), "checking endpoint…");
1244 assert_eq!(EndpointInfo::default().summary(), "tools untested");
1245 }
1246
1247 #[test]
1248 fn media_messages_round_trip() {
1249 let msgs = vec![
1250 ClientMsg::SendMessage { text: "chart it".into(), attachments: vec!["uploads/sales.csv".into()] },
1251 ClientMsg::Upload { upload: 1, name: "a.csv".into(), size: 3, offset: 0, data: media::encode(b"a,b"), done: true },
1252 ClientMsg::GetMedia { path: "charts/x.chart.json".into() },
1253 ];
1254 for m in msgs {
1255 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1256 }
1257 let spec = byob_types::chart::validate(&serde_json::json!({"type": "bar", "x": "m", "series": ["v"], "data": [{"m": "a", "v": 1}]})).unwrap();
1258 let msgs = vec![
1259 ServerMsg::Uploaded { upload: 1, attachment: Some(MediaRef::new("uploads/a.csv", 3)), error: None },
1260 ServerMsg::Media { path: "c.chart.json".into(), content: MediaContent::Chart { spec } },
1261 ServerMsg::Media { path: "p.png".into(), content: MediaContent::Image { mime: "image/png".into(), data: "AA==".into() } },
1262 ServerMsg::Media { path: "p.png".into(), content: MediaContent::Error { message: "gone".into() } },
1263 ];
1264 for m in msgs {
1265 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1266 }
1267 let mut s = step(1, StepStatus::Done);
1268 s.media = vec![MediaRef::new("charts/x.chart.json", 10)];
1269 let m = ServerMsg::StepUpdated { entry: 1, step: s };
1270 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1271 }
1272
1273 #[test]
1274 fn artifact_messages_round_trip() {
1275 let v = ArtifactVersion { n: 2, path: ".byob/artifacts/calc/v2.html".into(), created_at: 1, note: "blue button".into(), size: 10, turn: String::new() };
1276 let a = Artifact {
1277 id: "calc".into(),
1278 kind: ArtifactKind::Html,
1279 content_type: artifact::TYPE_HTML.into(),
1280 title: "Calc".into(),
1281 filename: "calc.html".into(),
1282 versions: vec![v],
1283 network: false,
1284 };
1285 let msgs = vec![
1286 ServerMsg::Artifacts { chat: Some("c1".into()), artifacts: vec![a.clone()] },
1287 ServerMsg::Artifacts { chat: None, artifacts: vec![] },
1288 ServerMsg::ArtifactUpdated(a),
1289 ServerMsg::ArtifactFile { id: "calc".into(), version: 2, data: Some(media::encode(b"<p>")), error: None },
1290 ServerMsg::ArtifactFile { id: "calc".into(), version: 9, data: None, error: Some("no such version".into()) },
1291 ];
1292 for m in msgs {
1293 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1294 }
1295 let m = ClientMsg::GetArtifact { id: "calc".into(), version: 2 };
1296 assert_eq!(m.to_json(), r#"{"type":"get_artifact","id":"calc","version":2}"#);
1297 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1298 let mut s = step(1, StepStatus::Done);
1299 s.artifacts = vec![ArtifactRef { id: "calc".into(), version: 2 }];
1300 let m = ServerMsg::StepUpdated { entry: 1, step: s };
1301 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1302 let json = r#"{"id":1,"tool":"t","title":"T","access":"read","status":"done","detail":""}"#;
1304 assert!(serde_json::from_str::<Step>(json).unwrap().artifacts.is_empty());
1305 }
1306
1307 #[test]
1308 fn older_send_message_without_attachments_parses() {
1309 let m = ClientMsg::from_json(r#"{"type":"send_message","text":"hi"}"#).unwrap();
1310 assert_eq!(m, ClientMsg::SendMessage { text: "hi".into(), attachments: vec![] });
1311 assert_eq!(m.to_json(), r#"{"type":"send_message","text":"hi"}"#);
1312 }
1313
1314 #[test]
1315 fn compaction_messages_round_trip() {
1316 let c = Compaction {
1317 id: 1,
1318 after_entry: 7,
1319 tokens_before: 182_000,
1320 tokens_after: 9_000,
1321 summary: "## Goals".into(),
1322 manual: true,
1323 focus: Some("CSV".into()),
1324 created_at: 5,
1325 };
1326 let u = ChatUsage { chat: "c1".into(), context_used: 34_000, context_window: 262_144, compact_at: 209_715, model_calls: 3, ..Default::default() };
1327 for m in [ServerMsg::Usage(u), ServerMsg::Compactions { chat: Some("c1".into()), items: vec![c.clone()] }, ServerMsg::Compacted(c)] {
1328 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1329 }
1330 assert_eq!(ClientMsg::Compact { focus: None }.to_json(), r#"{"type":"compact"}"#);
1331 let m = ClientMsg::from_json(r#"{"type":"compact","focus":"keep the CSV"}"#).unwrap();
1332 assert_eq!(m, ClientMsg::Compact { focus: Some("keep the CSV".into()) });
1333 let s: TurnStats = serde_json::from_str(r#"{"prompt_tokens":1,"completion_tokens":2,"elapsed_ms":3}"#).unwrap();
1335 assert_eq!(s.model_calls, 0);
1336 }
1337
1338 #[test]
1339 fn connection_messages_round_trip() {
1340 for m in [
1341 ClientMsg::TestInference { base_url: "http://127.0.0.1:11434/v1".into(), model: "qwen3".into(), api_key: None },
1342 ClientMsg::TestInference { base_url: "https://api.openai.com/v1".into(), model: "m".into(), api_key: Some("sk".into()) },
1343 ClientMsg::DetectEndpoints,
1344 ClientMsg::Retry,
1345 ClientMsg::Rewind { entry: 7, text: "again, differently".into() },
1346 ] {
1347 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1348 }
1349 assert_eq!(ClientMsg::Retry.to_json(), r#"{"type":"retry"}"#);
1350 let t = InferenceTest { base_url: "u".into(), model: "m".into(), ok: false, problem: Some(Problem::Unauthorized), detail: "x".into(), models: vec![] };
1351 let m = ServerMsg::InferenceTested(t);
1352 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1353 let state = EngineState {
1354 link: Link::failed("could not reach u: refused"),
1355 onboarded: true,
1356 detected: vec![Detected { preset: "ollama".into(), base_url: "http://127.0.0.1:11434/v1".into(), models: vec!["qwen3".into()] }],
1357 ..Default::default()
1358 };
1359 let m = ServerMsg::State(state);
1360 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1361 let old = r#"{"version":"0","inference_base_url":"u","inference_model":"m","has_api_key":false,"endpoint":null,"busy":false}"#;
1363 let s = serde_json::from_str::<EngineState>(old).unwrap();
1364 assert_eq!((s.link, s.onboarded, s.detected.len()), (Link::Unknown, false, 0));
1365 }
1366
1367 #[test]
1368 fn hello_negotiates_and_old_hellos_still_parse() {
1369 let m = ClientMsg::hello("desktop");
1370 let ClientMsg::Hello { protocol, minor, caps, .. } = &m else { panic!() };
1371 assert_eq!((*protocol, *minor), (PROTOCOL_MAJOR, PROTOCOL_MINOR));
1372 assert!(caps.iter().any(|c| c == version::CAP_PLUGIN_CHANNEL));
1373 assert!(m.check_sizes().is_ok());
1374 let old = ClientMsg::from_json(r#"{"type":"hello","protocol":12,"client":"old tab"}"#).unwrap();
1376 assert_eq!(old, ClientMsg::Hello { protocol: 12, minor: 0, client: "old tab".into(), caps: vec![] });
1377 let bad = ClientMsg::Hello { protocol: PROTOCOL_MAJOR, minor: 0, client: "x".into(), caps: vec!["NOT A CAP".into()] };
1378 assert!(bad.check_sizes().is_err());
1379 let w = ServerMsg::Welcome(Welcome::current());
1380 assert_eq!(ServerMsg::from_json(&w.to_json()).unwrap(), w);
1381 assert!(w.to_json().starts_with(r#"{"type":"welcome","protocol":13"#), "{}", w.to_json());
1382 }
1383
1384 #[test]
1385 fn plugin_channel_round_trips_and_is_capped() {
1386 let c = ClientMsg::Plugin { plugin: "sheets".into(), msg: serde_json::json!({"op": "get", "cell": "A1"}) };
1387 assert_eq!(c.to_json(), r#"{"type":"plugin","plugin":"sheets","msg":{"cell":"A1","op":"get"}}"#);
1388 assert_eq!(ClientMsg::from_json(&c.to_json()).unwrap(), c);
1389 assert!(c.check_sizes().is_ok());
1390 let s = ServerMsg::Plugin { plugin: "sheets".into(), msg: serde_json::json!([1, 2]) };
1391 assert_eq!(ServerMsg::from_json(&s.to_json()).unwrap(), s);
1392 for bad in [
1393 ClientMsg::Plugin { plugin: "Not/an id".into(), msg: serde_json::Value::Null },
1394 ClientMsg::Plugin { plugin: "sheets".into(), msg: serde_json::Value::String("x".repeat(version::MAX_PLUGIN_MSG_BYTES)) },
1395 ] {
1396 assert!(bad.check_sizes().is_err());
1397 }
1398 }
1399
1400 #[test]
1401 fn question_cards_round_trip_and_older_asks_still_parse() {
1402 let c = ClientMsg::AnswerQuestion { step: 4, text: "Metric".into() };
1403 assert_eq!(c.to_json(), r#"{"type":"answer_question","step":4,"text":"Metric"}"#);
1404 assert_eq!(ClientMsg::from_json(&c.to_json()).unwrap(), c);
1405 assert!(c.check_sizes().is_ok());
1406 assert!(ClientMsg::AnswerQuestion { step: 4, text: "x".repeat(MAX_ANSWER_CHARS + 1) }.check_sizes().is_err());
1407 let ask = Ask {
1408 text: "Which units?".into(),
1409 warning: None,
1410 always: true,
1411 choice: Some(Choice { options: vec!["Metric".into(), "Imperial".into()], free_text: true, answer: None }),
1412 };
1413 let json = serde_json::to_string(&ask).unwrap();
1414 assert_eq!(serde_json::from_str::<Ask>(&json).unwrap(), ask);
1415 let old: Ask = serde_json::from_str(r#"{"text":"t","always":true}"#).unwrap();
1417 assert!(old.choice.is_none());
1418 assert!(!serde_json::to_string(&old).unwrap().contains("choice"));
1419 }
1420
1421 #[test]
1423 fn unknown_messages_and_enum_values_decode_to_fallbacks() {
1424 assert_eq!(ServerMsg::from_json(r#"{"type":"hologram","x":1,"y":{"z":[]}}"#).unwrap(), ServerMsg::Unknown);
1425 assert_eq!(ClientMsg::from_json(r#"{"type":"teleport","to":"mars"}"#).unwrap(), ClientMsg::Unknown);
1426 assert!(ServerMsg::from_json(r#"{"type":"notice","level":"info"}"#).is_err());
1428 let n = ServerMsg::from_json(r#"{"type":"notice","level":"debug","text":"t"}"#).unwrap();
1429 assert_eq!(n, ServerMsg::Notice { level: NoticeLevel::Info, text: "t".into() });
1430 let a = ClientMsg::from_json(r#"{"type":"approve","step":1,"answer":"maybe_later"}"#).unwrap();
1431 assert_eq!(a, ClientMsg::Approve { step: 1, answer: ApprovalAnswer::Unknown });
1432 let json = r#"{"id":1,"tool":"t","title":"T","access":"read","status":"done","detail":"",
1434 "changes":[{"kind":"chmod","path":"a","mode":"755"}],
1435 "preview":{"kind":"hexdump","bytes":"00"},
1436 "media":[{"kind":"video","path":"a.mp4"}],
1437 "views":[{"kind":"sheets.grid","v":4,"data":{"rows":[]},"fallback":"a *grid*"}]}"#;
1438 let s: Step = serde_json::from_str(json).unwrap();
1439 assert_eq!((s.changes.clone(), s.preview.clone()), (vec![FileChange::Other], Some(Preview::Other)));
1440 assert_eq!(s.media[0].kind, MediaKind::File);
1441 assert_eq!((s.views[0].kind.as_str(), s.views[0].fallback.as_str()), ("sheets.grid", "a *grid*"));
1442 assert!(s.view::<PluginCard>().is_none());
1443 let art: Artifact = serde_json::from_str(r#"{"id":"a","kind":"spreadsheet","title":"A","filename":"a.xlsx","versions":[]}"#).unwrap();
1444 assert_eq!(art.kind, ArtifactKind::Text);
1445 assert_eq!(serde_json::from_str::<SlashKind>(r#""macro""#).unwrap(), SlashKind::Other);
1446 assert_eq!(serde_json::from_str::<PluginAction>(r#""forked""#).unwrap(), PluginAction::Other);
1447 let env = ClientMsg::from_json(r#"{"type":"workspace_env","action":{"kind":"rebuild","fast":true}}"#).unwrap();
1448 assert_eq!(env, ClientMsg::WorkspaceEnv { action: Some(EnvAction::Unsupported), workspace: None });
1449 let d = ServerMsg::from_json(r#"{"type":"delegation","entry":1,"step":2,"update":{"kind":"progress","pct":5}}"#).unwrap();
1450 assert_eq!(d, ServerMsg::Delegation { entry: 1, step: 2, update: DelegationUpdate::Other });
1451 }
1452
1453 #[test]
1454 fn plugin_cards_travel_as_views() {
1455 let card = PluginCard {
1456 plugin: "scratch".into(),
1457 scope: PluginScope::Chat,
1458 action: PluginAction::Made,
1459 tools: vec!["shout".into()],
1460 added: vec!["shout".into()],
1461 removed: vec![],
1462 test: Some(plugins::PluginTest { ok: true, output: "HI".into() }),
1463 problems: vec![],
1464 missing_settings: vec![],
1465 };
1466 let mut s = step(1, StepStatus::Done);
1467 s.views.push(View::of(&card));
1468 let json = ServerMsg::StepUpdated { entry: 1, step: s }.to_json();
1469 assert!(json.contains(r#""views":[{"kind":"byob.plugin_card","v":1,"data":{"action":"made""#), "{json}");
1470 let ServerMsg::StepUpdated { step: back, .. } = ServerMsg::from_json(&json).unwrap() else { panic!() };
1471 assert_eq!(back.view::<PluginCard>(), Some(card));
1472 assert!(back.views[0].fallback.contains("**Plugin scratch** (this chat) · tool made") && back.views[0].fallback.contains("shout"));
1473 assert!(!ServerMsg::StepUpdated { entry: 1, step: step(2, StepStatus::Done) }.to_json().contains("views"));
1475 }
1476
1477 #[test]
1478 fn state_never_carries_api_key() {
1479 let json = serde_json::to_string(&EngineState::default()).unwrap();
1480 assert!(!json.contains("\"api_key\""));
1481 }
1482}