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 profiles;
15pub mod queue;
16pub mod sites;
17pub mod tree;
18pub mod usage;
19pub mod version;
20pub mod view;
21pub mod web;
22pub mod workspace;
23
24use serde::{Deserialize, Serialize};
25
26pub use artifact::{Artifact, ArtifactKind, ArtifactRef, ArtifactVersion};
27pub use connect::{Detected, InferenceTest, Link, PRESETS, Preset, Problem};
28pub use delegation::{Delegation, DelegationState, DelegationUpdate};
29pub use env::{ContainerEnv, EnvAction, EnvSupport, WorkspaceEnv};
30pub use media::{MediaContent, MediaKind, MediaRef};
31pub use plugins::{
32 BackendInfo, Extensions, PluginAction, PluginCard, PluginInfo, PluginLoadError, PluginOrigin, PluginScope, PluginSetting, PluginTest, RendererDecl,
33 ServerInfo, ServerState, SlashItem, SlashKind, StarterDecl,
34};
35pub use profiles::{CAP_PROFILES, Profile, ProfileList, ProfileTest, ProfileView};
36pub use queue::{ChatQueue, QueuePause, QueuedMessage};
37pub use sites::{LiveView, Site, ViewDecl, ViewRef};
38pub use usage::{ChatUsage, Compaction};
39pub use version::{PROTOCOL_MAJOR, PROTOCOL_MINOR, Welcome};
40pub use view::{View, ViewData};
41pub use workspace::{ChatEndpoint, ConfigScope, ConfigView, FolderList, NewFolder, WorkspaceSummary};
42
43pub const MAX_FRAME_BYTES: usize = 4 * 1024 * 1024;
45
46#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
48#[serde(tag = "type", rename_all = "snake_case")]
49pub enum ClientMsg {
50 Hello {
54 protocol: u32,
55 #[serde(default)]
56 minor: u32,
57 client: String,
58 #[serde(default)]
59 caps: Vec<String>,
60 },
61 SetInference {
65 base_url: String,
66 model: String,
67 api_key: Option<String>,
68 },
69 TestInference {
72 base_url: String,
73 model: String,
74 #[serde(default, skip_serializing_if = "Option::is_none")]
75 api_key: Option<String>,
76 },
77 DetectEndpoints,
80 Retry,
83 SendMessage {
87 text: String,
88 #[serde(default, skip_serializing_if = "Vec::is_empty")]
89 attachments: Vec<String>,
90 },
91 Cancel,
93 Unqueue {
95 id: u64,
96 },
97 EditQueued {
100 id: u64,
101 text: String,
102 #[serde(default, skip_serializing_if = "Vec::is_empty")]
103 attachments: Vec<String>,
104 },
105 MoveQueued {
107 id: u64,
108 to: u32,
109 },
110 SendQueuedNow {
112 id: u64,
113 },
114 ResumeQueue,
116 Approve {
119 step: u64,
120 answer: ApprovalAnswer,
121 },
122 AnswerQuestion {
126 step: u64,
127 text: String,
128 },
129 Undo {
132 entry: u64,
133 },
134 ListChats {
137 after: Option<ChatCursor>,
138 limit: u32,
139 },
140 NewChat {
144 #[serde(default, skip_serializing_if = "Option::is_none")]
145 workspace: Option<String>,
146 },
147 OpenChat {
149 id: String,
150 },
151 RenameChat {
152 id: String,
153 title: String,
154 },
155 DeleteChat {
157 id: String,
158 },
159 PinChat {
160 id: String,
161 pinned: bool,
162 },
163 Upload {
168 upload: u64,
169 name: String,
170 size: u64,
171 offset: u64,
172 data: String,
173 done: bool,
174 },
175 GetMedia {
177 path: String,
178 },
179 GetArtifact {
182 id: String,
183 version: u32,
184 },
185 Compact {
188 #[serde(default, skip_serializing_if = "Option::is_none")]
189 focus: Option<String>,
190 },
191 WorkspaceEnv {
194 #[serde(default, skip_serializing_if = "Option::is_none")]
195 action: Option<EnvAction>,
196 #[serde(default, skip_serializing_if = "Option::is_none")]
197 workspace: Option<String>,
198 },
199 CreateWorkspace {
203 name: String,
204 folder: NewFolder,
205 #[serde(default)]
206 config: workspace::Layer,
207 },
208 RenameWorkspace {
209 id: String,
210 name: String,
211 },
212 RemoveWorkspace {
215 id: String,
216 #[serde(default)]
217 clean: bool,
218 },
219 GetConfig {
221 scope: ConfigScope,
222 },
223 SetConfig {
227 scope: ConfigScope,
228 layer: workspace::Layer,
229 #[serde(default, skip_serializing_if = "Option::is_none")]
230 api_key: Option<String>,
231 },
232 ListFolders {
235 #[serde(default, skip_serializing_if = "Option::is_none")]
236 path: Option<String>,
237 },
238 CheckContainers,
240 GetExtensions,
242 SetPluginEnabled {
246 scope: ConfigScope,
247 plugin: String,
248 enabled: Option<bool>,
249 },
250 SetPluginSetting {
254 plugin: String,
255 key: String,
256 value: Option<String>,
257 },
258 KeepPlugin {
262 plugin: String,
263 scope: PluginScope,
264 #[serde(default, skip_serializing_if = "Option::is_none")]
265 new_id: Option<String>,
266 },
267 RemovePlugin {
270 plugin: String,
271 scope: PluginScope,
272 },
273 ReloadPlugins,
275 TrustPlugins {
279 workspace: String,
280 #[serde(default)]
281 plugins: Vec<String>,
282 trust: bool,
283 },
284 Plugin {
287 plugin: String,
288 msg: serde_json::Value,
289 },
290 OpenView {
294 view: ViewRef,
295 },
296 CloseView {
298 view: ViewRef,
299 },
300 ViewEvent {
303 view: ViewRef,
304 event: tree::Event,
305 },
306 WebCall {
311 call: u64,
312 owner: web::WebOwner,
313 method: String,
314 #[serde(default)]
315 params: serde_json::Value,
316 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
317 approved: bool,
318 },
319 GetProfiles,
322 CreateProfile {
325 profile: Profile,
326 #[serde(default, skip_serializing_if = "Option::is_none")]
327 api_key: Option<String>,
328 #[serde(default, skip_serializing_if = "Option::is_none")]
329 assign: Option<ConfigScope>,
330 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
331 make_main: bool,
332 },
333 UpdateProfile {
336 profile: Profile,
337 #[serde(default, skip_serializing_if = "Option::is_none")]
338 api_key: Option<String>,
339 },
340 DeleteProfile {
343 id: String,
344 },
345 DuplicateProfile {
347 id: String,
348 },
349 SetRole {
352 role: String,
353 profile: Option<String>,
354 },
355 TestProfile {
357 id: String,
358 },
359 SetLevelProfile {
362 scope: ConfigScope,
363 profile: Option<String>,
364 },
365 #[serde(other)]
367 Unknown,
368}
369
370#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
372#[serde(tag = "type", rename_all = "snake_case")]
373pub enum ServerMsg {
374 Welcome(Welcome),
376 State(EngineState),
378 Notice { level: NoticeLevel, text: String },
380 Transcript { entries: Vec<Entry> },
382 EntryAdded(Entry),
384 EntryDelta { id: u64, content: String, reasoning: String },
386 EntryFinished { id: u64, error: Option<String>, stats: Option<TurnStats> },
388 StepUpdated { entry: u64, step: Step },
390 EntryUndo { id: u64, undoable: bool, undone: bool },
392 Chats { pinned: Vec<ChatSummary>, recent: Vec<ChatSummary>, after: Option<ChatCursor>, next: Option<ChatCursor> },
395 ChatUpdated(ChatSummary),
397 ChatDeleted { id: String },
399 ChatOpened {
403 chat: Option<ChatSummary>,
404 #[serde(default)]
405 workspace: Option<String>,
406 },
407 Uploaded { upload: u64, attachment: Option<MediaRef>, error: Option<String> },
409 Media { path: String, content: MediaContent },
411 Artifacts { chat: Option<String>, artifacts: Vec<Artifact> },
414 ArtifactUpdated(Artifact),
416 ArtifactFile { id: String, version: u32, data: Option<String>, error: Option<String> },
418 Usage(ChatUsage),
420 Compactions { chat: Option<String>, items: Vec<Compaction> },
423 Compacted(Compaction),
425 Delegation { entry: u64, step: u64, update: DelegationUpdate },
427 InferenceTested(InferenceTest),
429 WorkspaceEnv(WorkspaceEnv),
431 Workspaces { items: Vec<WorkspaceSummary>, current: Option<String>, root: String, support: EnvSupport },
435 Config(Box<ConfigView>),
437 Folders(FolderList),
439 ContainersChecked { ok: bool, message: String },
441 WorkspaceCreated { id: Option<String>, error: Option<String> },
443 Queue(ChatQueue),
446 Extensions(Box<Extensions>),
449 Plugin { plugin: String, msg: serde_json::Value },
452 LiveView(LiveView),
455 WebReply {
458 call: u64,
459 #[serde(default, deserialize_with = "present_even_if_null", skip_serializing_if = "Option::is_none")]
461 result: Option<serde_json::Value>,
462 #[serde(default, skip_serializing_if = "Option::is_none")]
463 error: Option<web::WebError>,
464 },
465 WebPush { owner: web::WebOwner, msg: serde_json::Value },
468 Profiles(Box<ProfileList>),
471 ProfileTested(ProfileTest),
473 #[serde(other)]
475 Unknown,
476}
477
478#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
480pub struct ChatSummary {
481 pub id: String,
482 pub title: String,
483 pub updated_at: i64,
485 pub pinned_at: Option<i64>,
487 #[serde(default)]
489 pub busy: bool,
490 #[serde(default, skip_serializing_if = "Option::is_none")]
492 pub workspace: Option<String>,
493}
494
495impl ChatSummary {
496 pub fn cursor(&self) -> ChatCursor {
497 ChatCursor { updated_at: self.updated_at, id: self.id.clone() }
498 }
499}
500
501#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
503pub struct ChatCursor {
504 pub updated_at: i64,
505 pub id: String,
506}
507
508#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
509#[serde(rename_all = "snake_case")]
510pub enum EntryRole {
511 User,
512 Assistant,
513}
514
515#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
517pub struct Entry {
518 pub id: u64,
519 pub role: EntryRole,
520 pub content: String,
521 pub reasoning: String,
522 pub done: bool,
524 pub error: Option<String>,
525 pub stats: Option<TurnStats>,
526 #[serde(default)]
529 pub steps: Vec<Step>,
530 #[serde(default)]
532 pub undoable: bool,
533 #[serde(default)]
535 pub undone: bool,
536 #[serde(default, skip_serializing_if = "Vec::is_empty")]
538 pub attachments: Vec<MediaRef>,
539}
540
541impl Entry {
542 pub fn append(&mut self, content: &str, reasoning: &str) {
544 self.content.push_str(content);
545 self.reasoning.push_str(reasoning);
546 }
547
548 pub fn upsert_step(&mut self, step: Step) {
550 match self.steps.iter_mut().find(|s| s.id == step.id) {
551 Some(existing) => *existing = step,
552 None => self.steps.push(step),
553 }
554 }
555
556 pub fn pending_approvals(&self) -> impl Iterator<Item = &Step> {
558 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)
559 }
560
561 pub fn apply_delegation(&mut self, step: u64, update: &DelegationUpdate) {
563 if let Some(d) = self.steps.iter_mut().find(|s| s.id == step).and_then(|s| s.delegation.as_deref_mut()) {
564 d.apply(update);
565 }
566 }
567}
568
569#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
571#[serde(rename_all = "snake_case")]
572pub enum ToolAccess {
573 Read,
574 Write,
575 Network,
576 Execute,
577}
578
579impl ToolAccess {
580 pub fn label(self) -> &'static str {
581 match self {
582 Self::Read => "read",
583 Self::Write => "write",
584 Self::Network => "network",
585 Self::Execute => "execute",
586 }
587 }
588}
589
590#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
591#[serde(rename_all = "snake_case")]
592pub enum StepStatus {
593 Running,
594 Waiting,
596 Done,
597 Failed,
599 Denied,
601}
602
603impl StepStatus {
604 pub fn finished(self) -> bool {
605 matches!(self, Self::Done | Self::Failed | Self::Denied)
606 }
607}
608
609#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
611#[serde(rename_all = "snake_case")]
612pub enum ApprovalAnswer {
613 Allow,
614 Always,
616 Deny,
617 AlwaysEverywhere,
619 #[serde(other)]
621 Unknown,
622}
623
624#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
626#[serde(tag = "kind", rename_all = "snake_case")]
627pub enum FileChange {
628 Created {
629 path: String,
630 },
631 Modified {
632 path: String,
633 },
634 Deleted {
635 path: String,
636 },
637 Moved {
638 from: String,
639 to: String,
640 },
641 #[serde(other)]
643 Other,
644}
645
646#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
648pub struct Step {
649 pub id: u64,
651 pub tool: String,
653 pub title: String,
655 pub access: ToolAccess,
656 pub status: StepStatus,
657 pub detail: String,
659 #[serde(default)]
660 pub changes: Vec<FileChange>,
661 #[serde(default)]
663 pub at: usize,
664 #[serde(default, skip_serializing_if = "Vec::is_empty")]
666 pub media: Vec<MediaRef>,
667 #[serde(default, skip_serializing_if = "Option::is_none")]
669 pub preview: Option<Preview>,
670 #[serde(default, skip_serializing_if = "Vec::is_empty")]
672 pub artifacts: Vec<ArtifactRef>,
673 #[serde(default, skip_serializing_if = "Option::is_none")]
675 pub delegation: Option<Box<Delegation>>,
676 #[serde(default, skip_serializing_if = "Option::is_none")]
680 pub ask: Option<Box<Ask>>,
681 #[serde(default, skip_serializing_if = "Vec::is_empty")]
685 pub views: Vec<View>,
686}
687
688impl Step {
689 pub fn view<T: ViewData>(&self) -> Option<T> {
691 self.views.iter().find_map(View::get)
692 }
693}
694
695#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
697pub struct Ask {
698 #[serde(default)]
700 pub text: String,
701 #[serde(default, skip_serializing_if = "Option::is_none")]
703 pub warning: Option<String>,
704 #[serde(default)]
706 pub always: bool,
707 #[serde(default, skip_serializing_if = "Option::is_none")]
711 pub choice: Option<Choice>,
712}
713
714pub const MAX_CHOICE_OPTIONS: usize = 8;
716pub const MAX_ANSWER_CHARS: usize = 2000;
718
719#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
721pub struct Choice {
722 #[serde(default, skip_serializing_if = "Vec::is_empty")]
724 pub options: Vec<String>,
725 #[serde(default)]
727 pub free_text: bool,
728 #[serde(default, skip_serializing_if = "Option::is_none")]
730 pub answer: Option<String>,
731}
732
733pub const MAX_PREVIEW_LINES: usize = 40;
735pub const MAX_PREVIEW_LINE_CHARS: usize = 300;
737
738#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
740#[serde(tag = "kind", rename_all = "snake_case")]
741pub enum Preview {
742 Write {
745 path: String,
746 bytes: u64,
747 replaces: bool,
749 lines: Vec<DiffLine>,
750 #[serde(default)]
752 more: usize,
753 },
754 Move {
756 moves: Vec<(String, String)>,
757 #[serde(default)]
758 more: usize,
759 },
760 Delete { path: String, what: String },
762 Args {
764 fields: Vec<(String, String)>,
765 #[serde(default, skip_serializing_if = "Option::is_none")]
766 code: Option<String>,
767 #[serde(default)]
768 more: usize,
769 },
770 #[serde(other)]
772 Other,
773}
774
775#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
777pub struct DiffLine {
778 pub kind: LineKind,
779 pub text: String,
780}
781
782#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
783#[serde(rename_all = "snake_case")]
784pub enum LineKind {
785 Same,
787 Added,
788 Removed,
789 Skipped,
791}
792
793#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
794pub struct TurnStats {
795 pub prompt_tokens: u64,
796 pub completion_tokens: u64,
797 pub elapsed_ms: u64,
798 #[serde(default)]
800 pub model_calls: u64,
801}
802
803#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
804#[serde(rename_all = "snake_case")]
805pub enum NoticeLevel {
806 Error,
807 #[serde(other)]
809 Info,
810}
811
812#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
814pub struct EngineState {
815 pub version: String,
816 pub inference_base_url: String,
817 pub inference_model: String,
818 pub has_api_key: bool,
819 pub endpoint: Option<String>,
821 pub busy: bool,
823 #[serde(default)]
825 pub endpoint_info: Option<EndpointInfo>,
826 #[serde(default)]
828 pub link: Link,
829 #[serde(default)]
832 pub onboarded: bool,
833 #[serde(default)]
835 pub detected: Vec<Detected>,
836 #[serde(default)]
838 pub detecting: bool,
839 #[serde(default, skip_serializing_if = "Option::is_none")]
842 pub chat_endpoint: Option<ChatEndpoint>,
843}
844
845#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
847#[serde(rename_all = "snake_case")]
848pub enum ToolsMode {
849 Native,
851 Prompt,
853 #[default]
855 Unknown,
856}
857
858#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
860pub struct EndpointInfo {
861 #[serde(default)]
863 pub probing: bool,
864 #[serde(default)]
866 pub server: String,
867 #[serde(default)]
869 pub context_tokens: Option<u64>,
870 #[serde(default)]
871 pub tools: ToolsMode,
872 #[serde(default)]
874 pub vision: Option<bool>,
875 #[serde(default, skip_serializing_if = "Option::is_none")]
877 pub slots: Option<u64>,
878}
879
880impl EndpointInfo {
881 pub fn summary(&self) -> String {
883 if self.probing {
884 return "checking endpoint…".into();
885 }
886 let mut parts = Vec::new();
887 if !self.server.is_empty() {
888 parts.push(self.server.clone());
889 }
890 if let Some(n) = self.context_tokens {
891 parts.push(if n >= 1000 { format!("{}k ctx", n / 1000) } else { format!("{n} ctx") });
892 }
893 parts.push(
894 match self.tools {
895 ToolsMode::Native => "native tools",
896 ToolsMode::Prompt => "prompt tools",
897 ToolsMode::Unknown => "tools untested",
898 }
899 .into(),
900 );
901 if self.vision == Some(true) {
902 parts.push("vision".into());
903 }
904 if let Some(n) = self.slots.filter(|n| *n > 1) {
905 parts.push(format!("{n} slots"));
906 }
907 parts.join(" · ")
908 }
909}
910
911impl ClientMsg {
912 pub fn hello(client: &str) -> Self {
914 Self::Hello { protocol: PROTOCOL_MAJOR, minor: PROTOCOL_MINOR, client: client.to_owned(), caps: version::client_caps() }
915 }
916
917 pub fn to_json(&self) -> String {
918 serde_json::to_string(self).unwrap_or_default()
919 }
920
921 pub fn from_json(text: &str) -> Result<Self, String> {
923 if text.len() > MAX_FRAME_BYTES {
924 return Err(format!("frame too large ({} bytes)", text.len()));
925 }
926 serde_json::from_str(text).map_err(|e| e.to_string())
927 }
928}
929
930impl ServerMsg {
931 pub fn to_json(&self) -> String {
932 serde_json::to_string(self).unwrap_or_default()
933 }
934
935 pub fn to_frame(&self) -> String {
941 let json = self.to_json();
942 if json.len() <= MAX_FRAME_BYTES {
943 return json;
944 }
945 let why = format!("it is too large to send over this connection ({} KB, at most {} KB)", json.len() / 1024, MAX_FRAME_BYTES / 1024);
946 let instead = match self {
947 Self::LiveView(lv) if lv.tree.is_none() => Self::LiveView(LiveView { view: lv.view.clone(), reset: true, ..Default::default() }),
948 Self::LiveView(lv) => {
949 Self::LiveView(LiveView { view: lv.view.clone(), error: Some(format!("This view can't be shown here: {why}.")), ..Default::default() })
950 }
951 Self::WebReply { call, .. } => {
952 Self::WebReply { call: *call, result: None, error: Some(web::WebError::new(-32000, format!("byob couldn't send the answer: {why}"))) }
953 }
954 _ => Self::Notice { level: NoticeLevel::Error, text: format!("byob couldn't send an update: {why}.") },
955 };
956 instead.to_json()
957 }
958
959 pub fn from_json(text: &str) -> Result<Self, String> {
961 if text.len() > MAX_FRAME_BYTES {
962 return Err(format!("frame too large ({} bytes)", text.len()));
963 }
964 serde_json::from_str(text).map_err(|e| e.to_string())
965 }
966}
967
968pub trait Connection {
970 fn send(&mut self, msg: ClientMsg);
971 fn try_recv(&mut self) -> Option<ServerMsg>;
973}
974
975fn present_even_if_null<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<serde_json::Value>, D::Error> {
978 serde_json::Value::deserialize(d).map(Some)
979}
980
981#[cfg(test)]
982mod tests {
983 use super::*;
984
985 #[test]
988 fn web_reply_keeps_a_null_result() {
989 let null = ServerMsg::WebReply { call: 3, result: Some(serde_json::Value::Null), error: None };
990 assert_eq!(null.to_json(), r#"{"type":"web_reply","call":3,"result":null}"#);
991 assert_eq!(ServerMsg::from_json(&null.to_json()).unwrap(), null);
992 let none = ServerMsg::WebReply { call: 3, result: None, error: None };
993 assert_eq!(none.to_json(), r#"{"type":"web_reply","call":3}"#);
994 assert_eq!(ServerMsg::from_json(&none.to_json()).unwrap(), none);
995 let value = ServerMsg::WebReply { call: 3, result: Some(serde_json::json!({"a": [1]})), error: None };
996 assert_eq!(ServerMsg::from_json(&value.to_json()).unwrap(), value);
997 }
998
999 #[test]
1000 fn client_msg_round_trips() {
1001 let m = ClientMsg::hello("test");
1002 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1003 }
1004
1005 #[test]
1006 fn wire_format_is_tagged() {
1007 let json = ServerMsg::Notice { level: NoticeLevel::Info, text: "hi".into() }.to_json();
1008 assert_eq!(json, r#"{"type":"notice","level":"info","text":"hi"}"#);
1009 }
1010
1011 #[test]
1012 fn a_message_too_large_for_a_frame_is_sent_as_something_the_client_acts_on() {
1013 let big = "x".repeat(MAX_FRAME_BYTES);
1014 let r = ViewRef::new("p", "v", "k");
1015 let small = ServerMsg::Notice { level: NoticeLevel::Info, text: "hi".into() };
1016 assert_eq!(small.to_frame(), small.to_json());
1017 let frame = |m: ServerMsg| {
1018 let f = m.to_frame();
1019 assert!(f.len() < 1024, "{} bytes", f.len());
1020 ServerMsg::from_json(&f).unwrap()
1021 };
1022 let mut values = serde_json::Map::new();
1023 values.insert("f".into(), serde_json::json!(big));
1024 let change = LiveView { view: r.clone(), values, ..Default::default() };
1025 assert_eq!(frame(ServerMsg::LiveView(change)), ServerMsg::LiveView(LiveView { view: r.clone(), reset: true, ..Default::default() }));
1026 let texts: Vec<_> = (0..100).map(|_| serde_json::json!({"type": "text", "text": "y".repeat(60_000)})).collect();
1028 let (tree, faults) = tree::decode(serde_json::json!({"type": "column", "children": texts}));
1029 assert!(faults.is_empty(), "{faults:?}");
1030 match frame(ServerMsg::LiveView(LiveView { view: r.clone(), tree: Some(tree), ..Default::default() })) {
1031 ServerMsg::LiveView(lv) => assert!(lv.view == r && lv.tree.is_none() && lv.error.is_some_and(|e| e.contains("too large"))),
1032 other => panic!("{other:?}"),
1033 }
1034 match frame(ServerMsg::WebReply { call: 9, result: Some(serde_json::json!(big)), error: None }) {
1035 ServerMsg::WebReply { call: 9, result: None, error: Some(e) } => assert!(e.message.contains("too large")),
1036 other => panic!("{other:?}"),
1037 }
1038 let plugin = ServerMsg::Plugin { plugin: "p".into(), msg: serde_json::json!(big) };
1039 assert!(matches!(frame(plugin), ServerMsg::Notice { level: NoticeLevel::Error, .. }));
1040 }
1041
1042 #[test]
1043 fn rejects_garbage_and_oversized_frames() {
1044 assert!(ClientMsg::from_json("{not json").is_err());
1045 assert!(ClientMsg::from_json(&" ".repeat(MAX_FRAME_BYTES + 1)).is_err());
1046 }
1047
1048 #[test]
1049 fn approve_wire_format() {
1050 let m = ClientMsg::Approve { step: 7, answer: ApprovalAnswer::Always };
1051 assert_eq!(m.to_json(), r#"{"type":"approve","step":7,"answer":"always"}"#);
1052 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1053 }
1054
1055 fn step(id: u64, status: StepStatus) -> Step {
1056 Step {
1057 id,
1058 tool: "t".into(),
1059 title: "T".into(),
1060 access: ToolAccess::Write,
1061 status,
1062 detail: String::new(),
1063 changes: vec![],
1064 at: 0,
1065 preview: None,
1066 media: vec![],
1067 artifacts: vec![],
1068 delegation: None,
1069 ask: None,
1070 views: vec![],
1071 }
1072 }
1073
1074 #[test]
1075 fn delegations_stream_into_their_step_and_round_trip() {
1076 let mut parent = step(1, StepStatus::Running);
1077 parent.delegation = Some(Box::new(Delegation { agent: "explorer".into(), task: "count lines".into(), ..Default::default() }));
1078 let mut e = Entry {
1079 id: 9,
1080 role: EntryRole::Assistant,
1081 content: String::new(),
1082 reasoning: String::new(),
1083 done: false,
1084 error: None,
1085 stats: None,
1086 steps: vec![parent],
1087 undoable: false,
1088 undone: false,
1089 attachments: vec![],
1090 };
1091 let updates = [
1092 DelegationUpdate::Status { state: DelegationState::Running, prompt_tokens: 0, completion_tokens: 0, error: None },
1093 DelegationUpdate::Delta { content: "Reading".into(), reasoning: "hm".into() },
1094 DelegationUpdate::Step(Box::new(step(2, StepStatus::Waiting))),
1095 DelegationUpdate::Delta { content: " a.txt".into(), reasoning: String::new() },
1096 ];
1097 for u in &updates {
1098 let msg = ServerMsg::Delegation { entry: 9, step: 1, update: u.clone() };
1099 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1100 e.apply_delegation(1, u);
1101 }
1102 e.apply_delegation(77, &updates[1]);
1104 let d = e.steps[0].delegation.as_deref().unwrap();
1105 assert_eq!((d.content.as_str(), d.reasoning.as_str(), d.state), ("Reading a.txt", "hm", DelegationState::Running));
1106 assert_eq!(d.status_line(), "explorer · 1 tool · waiting for approval");
1107 assert_eq!(e.pending_approvals().map(|s| s.id).collect::<Vec<_>>(), vec![2]);
1109 e.apply_delegation(1, &DelegationUpdate::Step(Box::new(step(2, StepStatus::Done))));
1110 e.apply_delegation(1, &DelegationUpdate::Status { state: DelegationState::Done, prompt_tokens: 50, completion_tokens: 5, error: None });
1111 assert_eq!(e.steps[0].delegation.as_deref().unwrap().status_line(), "explorer · 1 tool · done");
1112 assert_eq!(e.pending_approvals().count(), 0);
1113 let msg = ServerMsg::StepUpdated { entry: 9, step: e.steps[0].clone() };
1114 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1115 let json = r#"{"id":1,"tool":"t","title":"T","access":"read","status":"done","detail":""}"#;
1117 assert!(serde_json::from_str::<Step>(json).unwrap().delegation.is_none());
1118 }
1119
1120 #[test]
1121 fn steps_upsert_and_round_trip() {
1122 let mut e = Entry {
1123 id: 1,
1124 role: EntryRole::Assistant,
1125 content: String::new(),
1126 reasoning: String::new(),
1127 done: false,
1128 error: None,
1129 stats: None,
1130 steps: vec![],
1131 undoable: false,
1132 undone: false,
1133 attachments: vec![],
1134 };
1135 e.upsert_step(step(3, StepStatus::Running));
1136 e.upsert_step(step(4, StepStatus::Waiting));
1137 e.upsert_step(step(3, StepStatus::Done));
1138 assert_eq!(e.steps.len(), 2);
1139 assert_eq!(e.steps[0].status, StepStatus::Done);
1140 assert_eq!(e.pending_approvals().map(|s| s.id).collect::<Vec<_>>(), vec![4]);
1141 let mut s = step(5, StepStatus::Done);
1142 s.changes = vec![FileChange::Moved { from: "a".into(), to: "b".into() }];
1143 let msg = ServerMsg::StepUpdated { entry: 1, step: s };
1144 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1145 }
1146
1147 #[test]
1148 fn entry_without_steps_still_parses() {
1149 let json = r#"{"id":1,"role":"user","content":"hi","reasoning":"","done":true,"error":null,"stats":null}"#;
1150 let e: Entry = serde_json::from_str(json).unwrap();
1151 assert!(e.steps.is_empty());
1152 }
1153
1154 #[test]
1155 fn undo_and_preview_wire_format() {
1156 let m = ClientMsg::Undo { entry: 4 };
1157 assert_eq!(m.to_json(), r#"{"type":"undo","entry":4}"#);
1158 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1159 let mut s = step(1, StepStatus::Waiting);
1160 s.preview =
1161 Some(Preview::Write { path: "a.md".into(), bytes: 3, replaces: true, lines: vec![DiffLine { kind: LineKind::Added, text: "hi".into() }], more: 0 });
1162 let msg = ServerMsg::StepUpdated { entry: 1, step: s };
1163 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1164 let msg = ServerMsg::EntryUndo { id: 1, undoable: false, undone: true };
1165 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1166 }
1167
1168 #[test]
1169 fn chat_messages_round_trip() {
1170 let summary = ChatSummary { id: "c1".into(), title: "Plans".into(), updated_at: 5, pinned_at: None, busy: true, workspace: Some("w1".into()) };
1171 for m in [
1172 ServerMsg::Chats { pinned: vec![], recent: vec![summary.clone()], after: None, next: Some(summary.cursor()) },
1173 ServerMsg::ChatUpdated(summary.clone()),
1174 ServerMsg::ChatOpened { chat: Some(summary), workspace: None },
1175 ServerMsg::ChatDeleted { id: "c1".into() },
1176 ] {
1177 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1178 }
1179 let m = ClientMsg::ListChats { after: Some(ChatCursor { updated_at: 1, id: "x".into() }), limit: 50 };
1180 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1181 assert_eq!(ClientMsg::NewChat { workspace: None }.to_json(), r#"{"type":"new_chat"}"#);
1182 }
1183
1184 #[test]
1185 fn endpoint_info_is_optional_and_summarised() {
1186 let old = r#"{"version":"0","inference_base_url":"u","inference_model":"m","has_api_key":false,"endpoint":null,"busy":false}"#;
1187 assert_eq!(serde_json::from_str::<EngineState>(old).unwrap().endpoint_info, None);
1188 let info = EndpointInfo {
1189 probing: false,
1190 server: "llama.cpp".into(),
1191 context_tokens: Some(262_144),
1192 tools: ToolsMode::Native,
1193 vision: Some(true),
1194 slots: None,
1195 };
1196 assert_eq!(info.summary(), "llama.cpp · 262k ctx · native tools · vision");
1197 assert_eq!(EndpointInfo { slots: Some(4), ..info.clone() }.summary(), "llama.cpp · 262k ctx · native tools · vision · 4 slots");
1198 assert_eq!(EndpointInfo { probing: true, ..info }.summary(), "checking endpoint…");
1199 assert_eq!(EndpointInfo::default().summary(), "tools untested");
1200 }
1201
1202 #[test]
1203 fn media_messages_round_trip() {
1204 let msgs = vec![
1205 ClientMsg::SendMessage { text: "chart it".into(), attachments: vec!["uploads/sales.csv".into()] },
1206 ClientMsg::Upload { upload: 1, name: "a.csv".into(), size: 3, offset: 0, data: media::encode(b"a,b"), done: true },
1207 ClientMsg::GetMedia { path: "charts/x.chart.json".into() },
1208 ];
1209 for m in msgs {
1210 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1211 }
1212 let spec = byob_types::chart::validate(&serde_json::json!({"type": "bar", "x": "m", "series": ["v"], "data": [{"m": "a", "v": 1}]})).unwrap();
1213 let msgs = vec![
1214 ServerMsg::Uploaded { upload: 1, attachment: Some(MediaRef::new("uploads/a.csv", 3)), error: None },
1215 ServerMsg::Media { path: "c.chart.json".into(), content: MediaContent::Chart { spec } },
1216 ServerMsg::Media { path: "p.png".into(), content: MediaContent::Image { mime: "image/png".into(), data: "AA==".into() } },
1217 ServerMsg::Media { path: "p.png".into(), content: MediaContent::Error { message: "gone".into() } },
1218 ];
1219 for m in msgs {
1220 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1221 }
1222 let mut s = step(1, StepStatus::Done);
1223 s.media = vec![MediaRef::new("charts/x.chart.json", 10)];
1224 let m = ServerMsg::StepUpdated { entry: 1, step: s };
1225 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1226 }
1227
1228 #[test]
1229 fn artifact_messages_round_trip() {
1230 let v = ArtifactVersion { n: 2, path: ".byob/artifacts/calc/v2.html".into(), created_at: 1, note: "blue button".into(), size: 10 };
1231 let a = Artifact {
1232 id: "calc".into(),
1233 kind: ArtifactKind::Html,
1234 content_type: artifact::TYPE_HTML.into(),
1235 title: "Calc".into(),
1236 filename: "calc.html".into(),
1237 versions: vec![v],
1238 };
1239 let msgs = vec![
1240 ServerMsg::Artifacts { chat: Some("c1".into()), artifacts: vec![a.clone()] },
1241 ServerMsg::Artifacts { chat: None, artifacts: vec![] },
1242 ServerMsg::ArtifactUpdated(a),
1243 ServerMsg::ArtifactFile { id: "calc".into(), version: 2, data: Some(media::encode(b"<p>")), error: None },
1244 ServerMsg::ArtifactFile { id: "calc".into(), version: 9, data: None, error: Some("no such version".into()) },
1245 ];
1246 for m in msgs {
1247 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1248 }
1249 let m = ClientMsg::GetArtifact { id: "calc".into(), version: 2 };
1250 assert_eq!(m.to_json(), r#"{"type":"get_artifact","id":"calc","version":2}"#);
1251 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1252 let mut s = step(1, StepStatus::Done);
1253 s.artifacts = vec![ArtifactRef { id: "calc".into(), version: 2 }];
1254 let m = ServerMsg::StepUpdated { entry: 1, step: s };
1255 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1256 let json = r#"{"id":1,"tool":"t","title":"T","access":"read","status":"done","detail":""}"#;
1258 assert!(serde_json::from_str::<Step>(json).unwrap().artifacts.is_empty());
1259 }
1260
1261 #[test]
1262 fn older_send_message_without_attachments_parses() {
1263 let m = ClientMsg::from_json(r#"{"type":"send_message","text":"hi"}"#).unwrap();
1264 assert_eq!(m, ClientMsg::SendMessage { text: "hi".into(), attachments: vec![] });
1265 assert_eq!(m.to_json(), r#"{"type":"send_message","text":"hi"}"#);
1266 }
1267
1268 #[test]
1269 fn compaction_messages_round_trip() {
1270 let c = Compaction {
1271 id: 1,
1272 after_entry: 7,
1273 tokens_before: 182_000,
1274 tokens_after: 9_000,
1275 summary: "## Goals".into(),
1276 manual: true,
1277 focus: Some("CSV".into()),
1278 created_at: 5,
1279 };
1280 let u = ChatUsage { chat: "c1".into(), context_used: 34_000, context_window: 262_144, compact_at: 209_715, model_calls: 3, ..Default::default() };
1281 for m in [ServerMsg::Usage(u), ServerMsg::Compactions { chat: Some("c1".into()), items: vec![c.clone()] }, ServerMsg::Compacted(c)] {
1282 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1283 }
1284 assert_eq!(ClientMsg::Compact { focus: None }.to_json(), r#"{"type":"compact"}"#);
1285 let m = ClientMsg::from_json(r#"{"type":"compact","focus":"keep the CSV"}"#).unwrap();
1286 assert_eq!(m, ClientMsg::Compact { focus: Some("keep the CSV".into()) });
1287 let s: TurnStats = serde_json::from_str(r#"{"prompt_tokens":1,"completion_tokens":2,"elapsed_ms":3}"#).unwrap();
1289 assert_eq!(s.model_calls, 0);
1290 }
1291
1292 #[test]
1293 fn connection_messages_round_trip() {
1294 for m in [
1295 ClientMsg::TestInference { base_url: "http://127.0.0.1:11434/v1".into(), model: "qwen3".into(), api_key: None },
1296 ClientMsg::TestInference { base_url: "https://api.openai.com/v1".into(), model: "m".into(), api_key: Some("sk".into()) },
1297 ClientMsg::DetectEndpoints,
1298 ClientMsg::Retry,
1299 ] {
1300 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1301 }
1302 assert_eq!(ClientMsg::Retry.to_json(), r#"{"type":"retry"}"#);
1303 let t = InferenceTest { base_url: "u".into(), model: "m".into(), ok: false, problem: Some(Problem::Unauthorized), detail: "x".into(), models: vec![] };
1304 let m = ServerMsg::InferenceTested(t);
1305 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1306 let state = EngineState {
1307 link: Link::failed("could not reach u: refused"),
1308 onboarded: true,
1309 detected: vec![Detected { preset: "ollama".into(), base_url: "http://127.0.0.1:11434/v1".into(), models: vec!["qwen3".into()] }],
1310 ..Default::default()
1311 };
1312 let m = ServerMsg::State(state);
1313 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1314 let old = r#"{"version":"0","inference_base_url":"u","inference_model":"m","has_api_key":false,"endpoint":null,"busy":false}"#;
1316 let s = serde_json::from_str::<EngineState>(old).unwrap();
1317 assert_eq!((s.link, s.onboarded, s.detected.len()), (Link::Unknown, false, 0));
1318 }
1319
1320 #[test]
1321 fn hello_negotiates_and_old_hellos_still_parse() {
1322 let m = ClientMsg::hello("desktop");
1323 let ClientMsg::Hello { protocol, minor, caps, .. } = &m else { panic!() };
1324 assert_eq!((*protocol, *minor), (PROTOCOL_MAJOR, PROTOCOL_MINOR));
1325 assert!(caps.iter().any(|c| c == version::CAP_PLUGIN_CHANNEL));
1326 assert!(m.check_sizes().is_ok());
1327 let old = ClientMsg::from_json(r#"{"type":"hello","protocol":12,"client":"old tab"}"#).unwrap();
1329 assert_eq!(old, ClientMsg::Hello { protocol: 12, minor: 0, client: "old tab".into(), caps: vec![] });
1330 let bad = ClientMsg::Hello { protocol: PROTOCOL_MAJOR, minor: 0, client: "x".into(), caps: vec!["NOT A CAP".into()] };
1331 assert!(bad.check_sizes().is_err());
1332 let w = ServerMsg::Welcome(Welcome::current());
1333 assert_eq!(ServerMsg::from_json(&w.to_json()).unwrap(), w);
1334 assert!(w.to_json().starts_with(r#"{"type":"welcome","protocol":13"#), "{}", w.to_json());
1335 }
1336
1337 #[test]
1338 fn plugin_channel_round_trips_and_is_capped() {
1339 let c = ClientMsg::Plugin { plugin: "sheets".into(), msg: serde_json::json!({"op": "get", "cell": "A1"}) };
1340 assert_eq!(c.to_json(), r#"{"type":"plugin","plugin":"sheets","msg":{"cell":"A1","op":"get"}}"#);
1341 assert_eq!(ClientMsg::from_json(&c.to_json()).unwrap(), c);
1342 assert!(c.check_sizes().is_ok());
1343 let s = ServerMsg::Plugin { plugin: "sheets".into(), msg: serde_json::json!([1, 2]) };
1344 assert_eq!(ServerMsg::from_json(&s.to_json()).unwrap(), s);
1345 for bad in [
1346 ClientMsg::Plugin { plugin: "Not/an id".into(), msg: serde_json::Value::Null },
1347 ClientMsg::Plugin { plugin: "sheets".into(), msg: serde_json::Value::String("x".repeat(version::MAX_PLUGIN_MSG_BYTES)) },
1348 ] {
1349 assert!(bad.check_sizes().is_err());
1350 }
1351 }
1352
1353 #[test]
1354 fn question_cards_round_trip_and_older_asks_still_parse() {
1355 let c = ClientMsg::AnswerQuestion { step: 4, text: "Metric".into() };
1356 assert_eq!(c.to_json(), r#"{"type":"answer_question","step":4,"text":"Metric"}"#);
1357 assert_eq!(ClientMsg::from_json(&c.to_json()).unwrap(), c);
1358 assert!(c.check_sizes().is_ok());
1359 assert!(ClientMsg::AnswerQuestion { step: 4, text: "x".repeat(MAX_ANSWER_CHARS + 1) }.check_sizes().is_err());
1360 let ask = Ask {
1361 text: "Which units?".into(),
1362 warning: None,
1363 always: true,
1364 choice: Some(Choice { options: vec!["Metric".into(), "Imperial".into()], free_text: true, answer: None }),
1365 };
1366 let json = serde_json::to_string(&ask).unwrap();
1367 assert_eq!(serde_json::from_str::<Ask>(&json).unwrap(), ask);
1368 let old: Ask = serde_json::from_str(r#"{"text":"t","always":true}"#).unwrap();
1370 assert!(old.choice.is_none());
1371 assert!(!serde_json::to_string(&old).unwrap().contains("choice"));
1372 }
1373
1374 #[test]
1376 fn unknown_messages_and_enum_values_decode_to_fallbacks() {
1377 assert_eq!(ServerMsg::from_json(r#"{"type":"hologram","x":1,"y":{"z":[]}}"#).unwrap(), ServerMsg::Unknown);
1378 assert_eq!(ClientMsg::from_json(r#"{"type":"teleport","to":"mars"}"#).unwrap(), ClientMsg::Unknown);
1379 assert!(ServerMsg::from_json(r#"{"type":"notice","level":"info"}"#).is_err());
1381 let n = ServerMsg::from_json(r#"{"type":"notice","level":"debug","text":"t"}"#).unwrap();
1382 assert_eq!(n, ServerMsg::Notice { level: NoticeLevel::Info, text: "t".into() });
1383 let a = ClientMsg::from_json(r#"{"type":"approve","step":1,"answer":"maybe_later"}"#).unwrap();
1384 assert_eq!(a, ClientMsg::Approve { step: 1, answer: ApprovalAnswer::Unknown });
1385 let json = r#"{"id":1,"tool":"t","title":"T","access":"read","status":"done","detail":"",
1387 "changes":[{"kind":"chmod","path":"a","mode":"755"}],
1388 "preview":{"kind":"hexdump","bytes":"00"},
1389 "media":[{"kind":"video","path":"a.mp4"}],
1390 "views":[{"kind":"sheets.grid","v":4,"data":{"rows":[]},"fallback":"a *grid*"}]}"#;
1391 let s: Step = serde_json::from_str(json).unwrap();
1392 assert_eq!((s.changes.clone(), s.preview.clone()), (vec![FileChange::Other], Some(Preview::Other)));
1393 assert_eq!(s.media[0].kind, MediaKind::File);
1394 assert_eq!((s.views[0].kind.as_str(), s.views[0].fallback.as_str()), ("sheets.grid", "a *grid*"));
1395 assert!(s.view::<PluginCard>().is_none());
1396 let art: Artifact = serde_json::from_str(r#"{"id":"a","kind":"spreadsheet","title":"A","filename":"a.xlsx","versions":[]}"#).unwrap();
1397 assert_eq!(art.kind, ArtifactKind::Text);
1398 assert_eq!(serde_json::from_str::<SlashKind>(r#""macro""#).unwrap(), SlashKind::Other);
1399 assert_eq!(serde_json::from_str::<PluginAction>(r#""forked""#).unwrap(), PluginAction::Other);
1400 let env = ClientMsg::from_json(r#"{"type":"workspace_env","action":{"kind":"rebuild","fast":true}}"#).unwrap();
1401 assert_eq!(env, ClientMsg::WorkspaceEnv { action: Some(EnvAction::Unsupported), workspace: None });
1402 let d = ServerMsg::from_json(r#"{"type":"delegation","entry":1,"step":2,"update":{"kind":"progress","pct":5}}"#).unwrap();
1403 assert_eq!(d, ServerMsg::Delegation { entry: 1, step: 2, update: DelegationUpdate::Other });
1404 }
1405
1406 #[test]
1407 fn plugin_cards_travel_as_views() {
1408 let card = PluginCard {
1409 plugin: "scratch".into(),
1410 scope: PluginScope::Chat,
1411 action: PluginAction::Made,
1412 tools: vec!["shout".into()],
1413 added: vec!["shout".into()],
1414 removed: vec![],
1415 test: Some(plugins::PluginTest { ok: true, output: "HI".into() }),
1416 problems: vec![],
1417 missing_settings: vec![],
1418 };
1419 let mut s = step(1, StepStatus::Done);
1420 s.views.push(View::of(&card));
1421 let json = ServerMsg::StepUpdated { entry: 1, step: s }.to_json();
1422 assert!(json.contains(r#""views":[{"kind":"byob.plugin_card","v":1,"data":{"action":"made""#), "{json}");
1423 let ServerMsg::StepUpdated { step: back, .. } = ServerMsg::from_json(&json).unwrap() else { panic!() };
1424 assert_eq!(back.view::<PluginCard>(), Some(card));
1425 assert!(back.views[0].fallback.contains("**Plugin scratch** (this chat) · tool made") && back.views[0].fallback.contains("shout"));
1426 assert!(!ServerMsg::StepUpdated { entry: 1, step: step(2, StepStatus::Done) }.to_json().contains("views"));
1428 }
1429
1430 #[test]
1431 fn state_never_carries_api_key() {
1432 let json = serde_json::to_string(&EngineState::default()).unwrap();
1433 assert!(!json.contains("\"api_key\""));
1434 }
1435}