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 Compact {
199 #[serde(default, skip_serializing_if = "Option::is_none")]
200 focus: Option<String>,
201 },
202 WorkspaceEnv {
205 #[serde(default, skip_serializing_if = "Option::is_none")]
206 action: Option<EnvAction>,
207 #[serde(default, skip_serializing_if = "Option::is_none")]
208 workspace: Option<String>,
209 },
210 CreateWorkspace {
214 name: String,
215 folder: NewFolder,
216 #[serde(default)]
217 config: workspace::Layer,
218 },
219 RenameWorkspace {
220 id: String,
221 name: String,
222 },
223 RemoveWorkspace {
226 id: String,
227 #[serde(default)]
228 clean: bool,
229 },
230 GetConfig {
232 scope: ConfigScope,
233 },
234 SetConfig {
238 scope: ConfigScope,
239 layer: workspace::Layer,
240 #[serde(default, skip_serializing_if = "Option::is_none")]
241 api_key: Option<String>,
242 },
243 ListFolders {
246 #[serde(default, skip_serializing_if = "Option::is_none")]
247 path: Option<String>,
248 },
249 CheckContainers,
251 GetExtensions,
253 SetPluginEnabled {
257 scope: ConfigScope,
258 plugin: String,
259 enabled: Option<bool>,
260 },
261 SetPluginSetting {
265 plugin: String,
266 key: String,
267 value: Option<String>,
268 },
269 KeepPlugin {
273 plugin: String,
274 scope: PluginScope,
275 #[serde(default, skip_serializing_if = "Option::is_none")]
276 new_id: Option<String>,
277 },
278 RemovePlugin {
281 plugin: String,
282 scope: PluginScope,
283 },
284 ReloadPlugins,
286 TrustPlugins {
290 workspace: String,
291 #[serde(default)]
292 plugins: Vec<String>,
293 trust: bool,
294 },
295 Plugin {
298 plugin: String,
299 msg: serde_json::Value,
300 },
301 OpenView {
305 view: ViewRef,
306 },
307 CloseView {
309 view: ViewRef,
310 },
311 ViewEvent {
314 view: ViewRef,
315 event: tree::Event,
316 },
317 WebCall {
322 call: u64,
323 owner: web::WebOwner,
324 method: String,
325 #[serde(default)]
326 params: serde_json::Value,
327 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
328 approved: bool,
329 },
330 GetProfiles,
333 CreateProfile {
336 profile: Profile,
337 #[serde(default, skip_serializing_if = "Option::is_none")]
338 api_key: Option<String>,
339 #[serde(default, skip_serializing_if = "Option::is_none")]
340 assign: Option<ConfigScope>,
341 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
342 make_main: bool,
343 },
344 UpdateProfile {
347 profile: Profile,
348 #[serde(default, skip_serializing_if = "Option::is_none")]
349 api_key: Option<String>,
350 },
351 DeleteProfile {
354 id: String,
355 },
356 DuplicateProfile {
358 id: String,
359 },
360 SetRole {
363 role: String,
364 profile: Option<String>,
365 },
366 TestProfile {
368 id: String,
369 },
370 SetLevelProfile {
373 scope: ConfigScope,
374 profile: Option<String>,
375 },
376 SetLayout {
379 layout: layout::Layout,
380 },
381 ReportLook(look::LookReport),
384 #[serde(other)]
386 Unknown,
387}
388
389#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
391#[serde(tag = "type", rename_all = "snake_case")]
392pub enum ServerMsg {
393 Welcome(Welcome),
395 State(EngineState),
397 Notice { level: NoticeLevel, text: String },
399 Transcript { entries: Vec<Entry> },
401 EntryAdded(Entry),
403 EntryDelta { id: u64, content: String, reasoning: String },
405 EntryFinished { id: u64, error: Option<String>, stats: Option<TurnStats> },
407 StepUpdated { entry: u64, step: Step },
409 EntryUndo { id: u64, undoable: bool, undone: bool },
411 Chats { pinned: Vec<ChatSummary>, recent: Vec<ChatSummary>, after: Option<ChatCursor>, next: Option<ChatCursor> },
414 ChatUpdated(ChatSummary),
416 ChatDeleted { id: String },
418 ChatOpened {
422 chat: Option<ChatSummary>,
423 #[serde(default)]
424 workspace: Option<String>,
425 },
426 Uploaded { upload: u64, attachment: Option<MediaRef>, error: Option<String> },
428 Media { path: String, content: MediaContent },
430 Artifacts { chat: Option<String>, artifacts: Vec<Artifact> },
433 ArtifactUpdated(Artifact),
435 ArtifactFile { id: String, version: u32, data: Option<String>, error: Option<String> },
437 Usage(ChatUsage),
439 Compactions { chat: Option<String>, items: Vec<Compaction> },
442 Compacted(Compaction),
444 Delegation { entry: u64, step: u64, update: DelegationUpdate },
446 InferenceTested(InferenceTest),
448 WorkspaceEnv(WorkspaceEnv),
450 Workspaces { items: Vec<WorkspaceSummary>, current: Option<String>, root: String, support: EnvSupport },
454 Config(Box<ConfigView>),
456 Folders(FolderList),
458 ContainersChecked { ok: bool, message: String },
460 WorkspaceCreated { id: Option<String>, error: Option<String> },
462 Queue(ChatQueue),
465 Extensions(Box<Extensions>),
468 Plugin { plugin: String, msg: serde_json::Value },
471 LiveView(LiveView),
474 WebReply {
477 call: u64,
478 #[serde(default, deserialize_with = "present_even_if_null", skip_serializing_if = "Option::is_none")]
480 result: Option<serde_json::Value>,
481 #[serde(default, skip_serializing_if = "Option::is_none")]
482 error: Option<web::WebError>,
483 },
484 WebPush { owner: web::WebOwner, msg: serde_json::Value },
487 Profiles(Box<ProfileList>),
490 ProfileTested(ProfileTest),
492 Layout(layout::Layout),
495 SetLook { request: u64, changes: look::LookChanges },
499 #[serde(other)]
501 Unknown,
502}
503
504#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
506pub struct ChatSummary {
507 pub id: String,
508 pub title: String,
509 pub updated_at: i64,
511 pub pinned_at: Option<i64>,
513 #[serde(default)]
515 pub busy: bool,
516 #[serde(default, skip_serializing_if = "Option::is_none")]
518 pub workspace: Option<String>,
519}
520
521impl ChatSummary {
522 pub fn cursor(&self) -> ChatCursor {
523 ChatCursor { updated_at: self.updated_at, id: self.id.clone() }
524 }
525}
526
527#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
529pub struct ChatCursor {
530 pub updated_at: i64,
531 pub id: String,
532}
533
534#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
535#[serde(rename_all = "snake_case")]
536pub enum EntryRole {
537 User,
538 Assistant,
539}
540
541#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
543pub struct Entry {
544 pub id: u64,
545 pub role: EntryRole,
546 pub content: String,
547 pub reasoning: String,
548 pub done: bool,
550 pub error: Option<String>,
551 pub stats: Option<TurnStats>,
552 #[serde(default)]
555 pub steps: Vec<Step>,
556 #[serde(default)]
558 pub undoable: bool,
559 #[serde(default)]
561 pub undone: bool,
562 #[serde(default, skip_serializing_if = "Vec::is_empty")]
564 pub attachments: Vec<MediaRef>,
565}
566
567impl Entry {
568 pub fn append(&mut self, content: &str, reasoning: &str) {
570 self.content.push_str(content);
571 self.reasoning.push_str(reasoning);
572 }
573
574 pub fn upsert_step(&mut self, step: Step) {
576 match self.steps.iter_mut().find(|s| s.id == step.id) {
577 Some(existing) => *existing = step,
578 None => self.steps.push(step),
579 }
580 }
581
582 pub fn pending_approvals(&self) -> impl Iterator<Item = &Step> {
584 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)
585 }
586
587 pub fn apply_delegation(&mut self, step: u64, update: &DelegationUpdate) {
589 if let Some(d) = self.steps.iter_mut().find(|s| s.id == step).and_then(|s| s.delegation.as_deref_mut()) {
590 d.apply(update);
591 }
592 }
593}
594
595#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
597#[serde(rename_all = "snake_case")]
598pub enum ToolAccess {
599 Read,
600 Write,
601 Network,
602 Execute,
603}
604
605impl ToolAccess {
606 pub fn label(self) -> &'static str {
607 match self {
608 Self::Read => "read",
609 Self::Write => "write",
610 Self::Network => "network",
611 Self::Execute => "execute",
612 }
613 }
614}
615
616#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
617#[serde(rename_all = "snake_case")]
618pub enum StepStatus {
619 Running,
620 Waiting,
622 Done,
623 Failed,
625 Denied,
627}
628
629impl StepStatus {
630 pub fn finished(self) -> bool {
631 matches!(self, Self::Done | Self::Failed | Self::Denied)
632 }
633}
634
635#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
637#[serde(rename_all = "snake_case")]
638pub enum ApprovalAnswer {
639 Allow,
640 Always,
642 Deny,
643 AlwaysEverywhere,
645 #[serde(other)]
647 Unknown,
648}
649
650#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
652#[serde(tag = "kind", rename_all = "snake_case")]
653pub enum FileChange {
654 Created {
655 path: String,
656 },
657 Modified {
658 path: String,
659 },
660 Deleted {
661 path: String,
662 },
663 Moved {
664 from: String,
665 to: String,
666 },
667 #[serde(other)]
669 Other,
670}
671
672#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
674pub struct Step {
675 pub id: u64,
677 pub tool: String,
679 pub title: String,
681 pub access: ToolAccess,
682 pub status: StepStatus,
683 pub detail: String,
685 #[serde(default)]
686 pub changes: Vec<FileChange>,
687 #[serde(default)]
689 pub at: usize,
690 #[serde(default, skip_serializing_if = "Vec::is_empty")]
692 pub media: Vec<MediaRef>,
693 #[serde(default, skip_serializing_if = "Option::is_none")]
695 pub preview: Option<Preview>,
696 #[serde(default, skip_serializing_if = "Vec::is_empty")]
698 pub artifacts: Vec<ArtifactRef>,
699 #[serde(default, skip_serializing_if = "Option::is_none")]
701 pub delegation: Option<Box<Delegation>>,
702 #[serde(default, skip_serializing_if = "Option::is_none")]
706 pub ask: Option<Box<Ask>>,
707 #[serde(default, skip_serializing_if = "Vec::is_empty")]
711 pub views: Vec<View>,
712}
713
714impl Step {
715 pub fn view<T: ViewData>(&self) -> Option<T> {
717 self.views.iter().find_map(View::get)
718 }
719}
720
721#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
723pub struct Ask {
724 #[serde(default)]
726 pub text: String,
727 #[serde(default, skip_serializing_if = "Option::is_none")]
729 pub warning: Option<String>,
730 #[serde(default)]
732 pub always: bool,
733 #[serde(default, skip_serializing_if = "Option::is_none")]
737 pub choice: Option<Choice>,
738}
739
740pub const MAX_CHOICE_OPTIONS: usize = 8;
742pub const MAX_ANSWER_CHARS: usize = 2000;
744
745#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
747pub struct Choice {
748 #[serde(default, skip_serializing_if = "Vec::is_empty")]
750 pub options: Vec<String>,
751 #[serde(default)]
753 pub free_text: bool,
754 #[serde(default, skip_serializing_if = "Option::is_none")]
756 pub answer: Option<String>,
757}
758
759pub const MAX_PREVIEW_LINES: usize = 40;
761pub const MAX_PREVIEW_LINE_CHARS: usize = 300;
763
764#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
766#[serde(tag = "kind", rename_all = "snake_case")]
767pub enum Preview {
768 Write {
771 path: String,
772 bytes: u64,
773 replaces: bool,
775 lines: Vec<DiffLine>,
776 #[serde(default)]
778 more: usize,
779 },
780 Move {
782 moves: Vec<(String, String)>,
783 #[serde(default)]
784 more: usize,
785 },
786 Delete { path: String, what: String },
788 Args {
790 fields: Vec<(String, String)>,
791 #[serde(default, skip_serializing_if = "Option::is_none")]
792 code: Option<String>,
793 #[serde(default)]
794 more: usize,
795 },
796 #[serde(other)]
798 Other,
799}
800
801#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
803pub struct DiffLine {
804 pub kind: LineKind,
805 pub text: String,
806}
807
808#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
809#[serde(rename_all = "snake_case")]
810pub enum LineKind {
811 Same,
813 Added,
814 Removed,
815 Skipped,
817}
818
819#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
820pub struct TurnStats {
821 pub prompt_tokens: u64,
822 pub completion_tokens: u64,
823 pub elapsed_ms: u64,
824 #[serde(default)]
826 pub model_calls: u64,
827}
828
829#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
830#[serde(rename_all = "snake_case")]
831pub enum NoticeLevel {
832 Error,
833 #[serde(other)]
835 Info,
836}
837
838#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
840pub struct EngineState {
841 pub version: String,
842 pub inference_base_url: String,
843 pub inference_model: String,
844 pub has_api_key: bool,
845 pub endpoint: Option<String>,
847 pub busy: bool,
849 #[serde(default)]
851 pub endpoint_info: Option<EndpointInfo>,
852 #[serde(default)]
854 pub link: Link,
855 #[serde(default)]
858 pub onboarded: bool,
859 #[serde(default)]
861 pub detected: Vec<Detected>,
862 #[serde(default)]
864 pub detecting: bool,
865 #[serde(default, skip_serializing_if = "Option::is_none")]
868 pub chat_endpoint: Option<ChatEndpoint>,
869}
870
871#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
873#[serde(rename_all = "snake_case")]
874pub enum ToolsMode {
875 Native,
877 Prompt,
879 #[default]
881 Unknown,
882}
883
884#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
886pub struct EndpointInfo {
887 #[serde(default)]
889 pub probing: bool,
890 #[serde(default)]
892 pub server: String,
893 #[serde(default)]
895 pub context_tokens: Option<u64>,
896 #[serde(default)]
897 pub tools: ToolsMode,
898 #[serde(default)]
900 pub vision: Option<bool>,
901 #[serde(default, skip_serializing_if = "Option::is_none")]
903 pub slots: Option<u64>,
904}
905
906impl EndpointInfo {
907 pub fn summary(&self) -> String {
909 if self.probing {
910 return "checking endpoint…".into();
911 }
912 let mut parts = Vec::new();
913 if !self.server.is_empty() {
914 parts.push(self.server.clone());
915 }
916 if let Some(n) = self.context_tokens {
917 parts.push(if n >= 1000 { format!("{}k ctx", n / 1000) } else { format!("{n} ctx") });
918 }
919 parts.push(
920 match self.tools {
921 ToolsMode::Native => "native tools",
922 ToolsMode::Prompt => "prompt tools",
923 ToolsMode::Unknown => "tools untested",
924 }
925 .into(),
926 );
927 if self.vision == Some(true) {
928 parts.push("vision".into());
929 }
930 if let Some(n) = self.slots.filter(|n| *n > 1) {
931 parts.push(format!("{n} slots"));
932 }
933 parts.join(" · ")
934 }
935}
936
937impl ClientMsg {
938 pub fn hello(client: &str) -> Self {
940 Self::Hello { protocol: PROTOCOL_MAJOR, minor: PROTOCOL_MINOR, client: client.to_owned(), caps: version::client_caps() }
941 }
942
943 pub fn to_json(&self) -> String {
944 serde_json::to_string(self).unwrap_or_default()
945 }
946
947 pub fn from_json(text: &str) -> Result<Self, String> {
949 if text.len() > MAX_FRAME_BYTES {
950 return Err(format!("frame too large ({} bytes)", text.len()));
951 }
952 serde_json::from_str(text).map_err(|e| e.to_string())
953 }
954}
955
956impl ServerMsg {
957 pub fn to_json(&self) -> String {
958 serde_json::to_string(self).unwrap_or_default()
959 }
960
961 pub fn to_frame(&self) -> String {
967 let json = self.to_json();
968 if json.len() <= MAX_FRAME_BYTES {
969 return json;
970 }
971 let why = format!("it is too large to send over this connection ({} KB, at most {} KB)", json.len() / 1024, MAX_FRAME_BYTES / 1024);
972 let instead = match self {
973 Self::LiveView(lv) if lv.tree.is_none() => Self::LiveView(LiveView { view: lv.view.clone(), reset: true, ..Default::default() }),
974 Self::LiveView(lv) => {
975 Self::LiveView(LiveView { view: lv.view.clone(), error: Some(format!("This view can't be shown here: {why}.")), ..Default::default() })
976 }
977 Self::WebReply { call, .. } => {
978 Self::WebReply { call: *call, result: None, error: Some(web::WebError::new(-32000, format!("byob couldn't send the answer: {why}"))) }
979 }
980 _ => Self::Notice { level: NoticeLevel::Error, text: format!("byob couldn't send an update: {why}.") },
981 };
982 instead.to_json()
983 }
984
985 pub fn from_json(text: &str) -> Result<Self, String> {
987 if text.len() > MAX_FRAME_BYTES {
988 return Err(format!("frame too large ({} bytes)", text.len()));
989 }
990 serde_json::from_str(text).map_err(|e| e.to_string())
991 }
992}
993
994pub trait Connection {
996 fn send(&mut self, msg: ClientMsg);
997 fn try_recv(&mut self) -> Option<ServerMsg>;
999}
1000
1001fn present_even_if_null<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<serde_json::Value>, D::Error> {
1004 serde_json::Value::deserialize(d).map(Some)
1005}
1006
1007#[cfg(test)]
1008mod tests {
1009 use super::*;
1010
1011 #[test]
1014 fn web_reply_keeps_a_null_result() {
1015 let null = ServerMsg::WebReply { call: 3, result: Some(serde_json::Value::Null), error: None };
1016 assert_eq!(null.to_json(), r#"{"type":"web_reply","call":3,"result":null}"#);
1017 assert_eq!(ServerMsg::from_json(&null.to_json()).unwrap(), null);
1018 let none = ServerMsg::WebReply { call: 3, result: None, error: None };
1019 assert_eq!(none.to_json(), r#"{"type":"web_reply","call":3}"#);
1020 assert_eq!(ServerMsg::from_json(&none.to_json()).unwrap(), none);
1021 let value = ServerMsg::WebReply { call: 3, result: Some(serde_json::json!({"a": [1]})), error: None };
1022 assert_eq!(ServerMsg::from_json(&value.to_json()).unwrap(), value);
1023 }
1024
1025 #[test]
1026 fn client_msg_round_trips() {
1027 let m = ClientMsg::hello("test");
1028 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1029 }
1030
1031 #[test]
1032 fn wire_format_is_tagged() {
1033 let json = ServerMsg::Notice { level: NoticeLevel::Info, text: "hi".into() }.to_json();
1034 assert_eq!(json, r#"{"type":"notice","level":"info","text":"hi"}"#);
1035 }
1036
1037 #[test]
1038 fn a_message_too_large_for_a_frame_is_sent_as_something_the_client_acts_on() {
1039 let big = "x".repeat(MAX_FRAME_BYTES);
1040 let r = ViewRef::new("p", "v", "k");
1041 let small = ServerMsg::Notice { level: NoticeLevel::Info, text: "hi".into() };
1042 assert_eq!(small.to_frame(), small.to_json());
1043 let frame = |m: ServerMsg| {
1044 let f = m.to_frame();
1045 assert!(f.len() < 1024, "{} bytes", f.len());
1046 ServerMsg::from_json(&f).unwrap()
1047 };
1048 let mut values = serde_json::Map::new();
1049 values.insert("f".into(), serde_json::json!(big));
1050 let change = LiveView { view: r.clone(), values, ..Default::default() };
1051 assert_eq!(frame(ServerMsg::LiveView(change)), ServerMsg::LiveView(LiveView { view: r.clone(), reset: true, ..Default::default() }));
1052 let texts: Vec<_> = (0..100).map(|_| serde_json::json!({"type": "text", "text": "y".repeat(60_000)})).collect();
1054 let (tree, faults) = tree::decode(serde_json::json!({"type": "column", "children": texts}));
1055 assert!(faults.is_empty(), "{faults:?}");
1056 match frame(ServerMsg::LiveView(LiveView { view: r.clone(), tree: Some(tree), ..Default::default() })) {
1057 ServerMsg::LiveView(lv) => assert!(lv.view == r && lv.tree.is_none() && lv.error.is_some_and(|e| e.contains("too large"))),
1058 other => panic!("{other:?}"),
1059 }
1060 match frame(ServerMsg::WebReply { call: 9, result: Some(serde_json::json!(big)), error: None }) {
1061 ServerMsg::WebReply { call: 9, result: None, error: Some(e) } => assert!(e.message.contains("too large")),
1062 other => panic!("{other:?}"),
1063 }
1064 let plugin = ServerMsg::Plugin { plugin: "p".into(), msg: serde_json::json!(big) };
1065 assert!(matches!(frame(plugin), ServerMsg::Notice { level: NoticeLevel::Error, .. }));
1066 }
1067
1068 #[test]
1069 fn rejects_garbage_and_oversized_frames() {
1070 assert!(ClientMsg::from_json("{not json").is_err());
1071 assert!(ClientMsg::from_json(&" ".repeat(MAX_FRAME_BYTES + 1)).is_err());
1072 }
1073
1074 #[test]
1075 fn approve_wire_format() {
1076 let m = ClientMsg::Approve { step: 7, answer: ApprovalAnswer::Always };
1077 assert_eq!(m.to_json(), r#"{"type":"approve","step":7,"answer":"always"}"#);
1078 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1079 }
1080
1081 fn step(id: u64, status: StepStatus) -> Step {
1082 Step {
1083 id,
1084 tool: "t".into(),
1085 title: "T".into(),
1086 access: ToolAccess::Write,
1087 status,
1088 detail: String::new(),
1089 changes: vec![],
1090 at: 0,
1091 preview: None,
1092 media: vec![],
1093 artifacts: vec![],
1094 delegation: None,
1095 ask: None,
1096 views: vec![],
1097 }
1098 }
1099
1100 #[test]
1101 fn delegations_stream_into_their_step_and_round_trip() {
1102 let mut parent = step(1, StepStatus::Running);
1103 parent.delegation = Some(Box::new(Delegation { agent: "explorer".into(), task: "count lines".into(), ..Default::default() }));
1104 let mut e = Entry {
1105 id: 9,
1106 role: EntryRole::Assistant,
1107 content: String::new(),
1108 reasoning: String::new(),
1109 done: false,
1110 error: None,
1111 stats: None,
1112 steps: vec![parent],
1113 undoable: false,
1114 undone: false,
1115 attachments: vec![],
1116 };
1117 let updates = [
1118 DelegationUpdate::Status { state: DelegationState::Running, prompt_tokens: 0, completion_tokens: 0, error: None },
1119 DelegationUpdate::Delta { content: "Reading".into(), reasoning: "hm".into() },
1120 DelegationUpdate::Step(Box::new(step(2, StepStatus::Waiting))),
1121 DelegationUpdate::Delta { content: " a.txt".into(), reasoning: String::new() },
1122 ];
1123 for u in &updates {
1124 let msg = ServerMsg::Delegation { entry: 9, step: 1, update: u.clone() };
1125 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1126 e.apply_delegation(1, u);
1127 }
1128 e.apply_delegation(77, &updates[1]);
1130 let d = e.steps[0].delegation.as_deref().unwrap();
1131 assert_eq!((d.content.as_str(), d.reasoning.as_str(), d.state), ("Reading a.txt", "hm", DelegationState::Running));
1132 assert_eq!(d.status_line(), "explorer · 1 tool · waiting for approval");
1133 assert_eq!(e.pending_approvals().map(|s| s.id).collect::<Vec<_>>(), vec![2]);
1135 e.apply_delegation(1, &DelegationUpdate::Step(Box::new(step(2, StepStatus::Done))));
1136 e.apply_delegation(1, &DelegationUpdate::Status { state: DelegationState::Done, prompt_tokens: 50, completion_tokens: 5, error: None });
1137 assert_eq!(e.steps[0].delegation.as_deref().unwrap().status_line(), "explorer · 1 tool · done");
1138 assert_eq!(e.pending_approvals().count(), 0);
1139 let msg = ServerMsg::StepUpdated { entry: 9, step: e.steps[0].clone() };
1140 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1141 let json = r#"{"id":1,"tool":"t","title":"T","access":"read","status":"done","detail":""}"#;
1143 assert!(serde_json::from_str::<Step>(json).unwrap().delegation.is_none());
1144 }
1145
1146 #[test]
1147 fn steps_upsert_and_round_trip() {
1148 let mut e = Entry {
1149 id: 1,
1150 role: EntryRole::Assistant,
1151 content: String::new(),
1152 reasoning: String::new(),
1153 done: false,
1154 error: None,
1155 stats: None,
1156 steps: vec![],
1157 undoable: false,
1158 undone: false,
1159 attachments: vec![],
1160 };
1161 e.upsert_step(step(3, StepStatus::Running));
1162 e.upsert_step(step(4, StepStatus::Waiting));
1163 e.upsert_step(step(3, StepStatus::Done));
1164 assert_eq!(e.steps.len(), 2);
1165 assert_eq!(e.steps[0].status, StepStatus::Done);
1166 assert_eq!(e.pending_approvals().map(|s| s.id).collect::<Vec<_>>(), vec![4]);
1167 let mut s = step(5, StepStatus::Done);
1168 s.changes = vec![FileChange::Moved { from: "a".into(), to: "b".into() }];
1169 let msg = ServerMsg::StepUpdated { entry: 1, step: s };
1170 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1171 }
1172
1173 #[test]
1174 fn entry_without_steps_still_parses() {
1175 let json = r#"{"id":1,"role":"user","content":"hi","reasoning":"","done":true,"error":null,"stats":null}"#;
1176 let e: Entry = serde_json::from_str(json).unwrap();
1177 assert!(e.steps.is_empty());
1178 }
1179
1180 #[test]
1181 fn undo_and_preview_wire_format() {
1182 let m = ClientMsg::Undo { entry: 4 };
1183 assert_eq!(m.to_json(), r#"{"type":"undo","entry":4}"#);
1184 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1185 let mut s = step(1, StepStatus::Waiting);
1186 s.preview =
1187 Some(Preview::Write { path: "a.md".into(), bytes: 3, replaces: true, lines: vec![DiffLine { kind: LineKind::Added, text: "hi".into() }], more: 0 });
1188 let msg = ServerMsg::StepUpdated { entry: 1, step: s };
1189 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1190 let msg = ServerMsg::EntryUndo { id: 1, undoable: false, undone: true };
1191 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1192 }
1193
1194 #[test]
1195 fn chat_messages_round_trip() {
1196 let summary = ChatSummary { id: "c1".into(), title: "Plans".into(), updated_at: 5, pinned_at: None, busy: true, workspace: Some("w1".into()) };
1197 for m in [
1198 ServerMsg::Chats { pinned: vec![], recent: vec![summary.clone()], after: None, next: Some(summary.cursor()) },
1199 ServerMsg::ChatUpdated(summary.clone()),
1200 ServerMsg::ChatOpened { chat: Some(summary), workspace: None },
1201 ServerMsg::ChatDeleted { id: "c1".into() },
1202 ] {
1203 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1204 }
1205 let m = ClientMsg::ListChats { after: Some(ChatCursor { updated_at: 1, id: "x".into() }), limit: 50 };
1206 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1207 assert_eq!(ClientMsg::NewChat { workspace: None }.to_json(), r#"{"type":"new_chat"}"#);
1208 }
1209
1210 #[test]
1211 fn endpoint_info_is_optional_and_summarised() {
1212 let old = r#"{"version":"0","inference_base_url":"u","inference_model":"m","has_api_key":false,"endpoint":null,"busy":false}"#;
1213 assert_eq!(serde_json::from_str::<EngineState>(old).unwrap().endpoint_info, None);
1214 let info = EndpointInfo {
1215 probing: false,
1216 server: "llama.cpp".into(),
1217 context_tokens: Some(262_144),
1218 tools: ToolsMode::Native,
1219 vision: Some(true),
1220 slots: None,
1221 };
1222 assert_eq!(info.summary(), "llama.cpp · 262k ctx · native tools · vision");
1223 assert_eq!(EndpointInfo { slots: Some(4), ..info.clone() }.summary(), "llama.cpp · 262k ctx · native tools · vision · 4 slots");
1224 assert_eq!(EndpointInfo { probing: true, ..info }.summary(), "checking endpoint…");
1225 assert_eq!(EndpointInfo::default().summary(), "tools untested");
1226 }
1227
1228 #[test]
1229 fn media_messages_round_trip() {
1230 let msgs = vec![
1231 ClientMsg::SendMessage { text: "chart it".into(), attachments: vec!["uploads/sales.csv".into()] },
1232 ClientMsg::Upload { upload: 1, name: "a.csv".into(), size: 3, offset: 0, data: media::encode(b"a,b"), done: true },
1233 ClientMsg::GetMedia { path: "charts/x.chart.json".into() },
1234 ];
1235 for m in msgs {
1236 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1237 }
1238 let spec = byob_types::chart::validate(&serde_json::json!({"type": "bar", "x": "m", "series": ["v"], "data": [{"m": "a", "v": 1}]})).unwrap();
1239 let msgs = vec![
1240 ServerMsg::Uploaded { upload: 1, attachment: Some(MediaRef::new("uploads/a.csv", 3)), error: None },
1241 ServerMsg::Media { path: "c.chart.json".into(), content: MediaContent::Chart { spec } },
1242 ServerMsg::Media { path: "p.png".into(), content: MediaContent::Image { mime: "image/png".into(), data: "AA==".into() } },
1243 ServerMsg::Media { path: "p.png".into(), content: MediaContent::Error { message: "gone".into() } },
1244 ];
1245 for m in msgs {
1246 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1247 }
1248 let mut s = step(1, StepStatus::Done);
1249 s.media = vec![MediaRef::new("charts/x.chart.json", 10)];
1250 let m = ServerMsg::StepUpdated { entry: 1, step: s };
1251 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1252 }
1253
1254 #[test]
1255 fn artifact_messages_round_trip() {
1256 let v = ArtifactVersion { n: 2, path: ".byob/artifacts/calc/v2.html".into(), created_at: 1, note: "blue button".into(), size: 10 };
1257 let a = Artifact {
1258 id: "calc".into(),
1259 kind: ArtifactKind::Html,
1260 content_type: artifact::TYPE_HTML.into(),
1261 title: "Calc".into(),
1262 filename: "calc.html".into(),
1263 versions: vec![v],
1264 };
1265 let msgs = vec![
1266 ServerMsg::Artifacts { chat: Some("c1".into()), artifacts: vec![a.clone()] },
1267 ServerMsg::Artifacts { chat: None, artifacts: vec![] },
1268 ServerMsg::ArtifactUpdated(a),
1269 ServerMsg::ArtifactFile { id: "calc".into(), version: 2, data: Some(media::encode(b"<p>")), error: None },
1270 ServerMsg::ArtifactFile { id: "calc".into(), version: 9, data: None, error: Some("no such version".into()) },
1271 ];
1272 for m in msgs {
1273 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1274 }
1275 let m = ClientMsg::GetArtifact { id: "calc".into(), version: 2 };
1276 assert_eq!(m.to_json(), r#"{"type":"get_artifact","id":"calc","version":2}"#);
1277 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1278 let mut s = step(1, StepStatus::Done);
1279 s.artifacts = vec![ArtifactRef { id: "calc".into(), version: 2 }];
1280 let m = ServerMsg::StepUpdated { entry: 1, step: s };
1281 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1282 let json = r#"{"id":1,"tool":"t","title":"T","access":"read","status":"done","detail":""}"#;
1284 assert!(serde_json::from_str::<Step>(json).unwrap().artifacts.is_empty());
1285 }
1286
1287 #[test]
1288 fn older_send_message_without_attachments_parses() {
1289 let m = ClientMsg::from_json(r#"{"type":"send_message","text":"hi"}"#).unwrap();
1290 assert_eq!(m, ClientMsg::SendMessage { text: "hi".into(), attachments: vec![] });
1291 assert_eq!(m.to_json(), r#"{"type":"send_message","text":"hi"}"#);
1292 }
1293
1294 #[test]
1295 fn compaction_messages_round_trip() {
1296 let c = Compaction {
1297 id: 1,
1298 after_entry: 7,
1299 tokens_before: 182_000,
1300 tokens_after: 9_000,
1301 summary: "## Goals".into(),
1302 manual: true,
1303 focus: Some("CSV".into()),
1304 created_at: 5,
1305 };
1306 let u = ChatUsage { chat: "c1".into(), context_used: 34_000, context_window: 262_144, compact_at: 209_715, model_calls: 3, ..Default::default() };
1307 for m in [ServerMsg::Usage(u), ServerMsg::Compactions { chat: Some("c1".into()), items: vec![c.clone()] }, ServerMsg::Compacted(c)] {
1308 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1309 }
1310 assert_eq!(ClientMsg::Compact { focus: None }.to_json(), r#"{"type":"compact"}"#);
1311 let m = ClientMsg::from_json(r#"{"type":"compact","focus":"keep the CSV"}"#).unwrap();
1312 assert_eq!(m, ClientMsg::Compact { focus: Some("keep the CSV".into()) });
1313 let s: TurnStats = serde_json::from_str(r#"{"prompt_tokens":1,"completion_tokens":2,"elapsed_ms":3}"#).unwrap();
1315 assert_eq!(s.model_calls, 0);
1316 }
1317
1318 #[test]
1319 fn connection_messages_round_trip() {
1320 for m in [
1321 ClientMsg::TestInference { base_url: "http://127.0.0.1:11434/v1".into(), model: "qwen3".into(), api_key: None },
1322 ClientMsg::TestInference { base_url: "https://api.openai.com/v1".into(), model: "m".into(), api_key: Some("sk".into()) },
1323 ClientMsg::DetectEndpoints,
1324 ClientMsg::Retry,
1325 ClientMsg::Rewind { entry: 7, text: "again, differently".into() },
1326 ] {
1327 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1328 }
1329 assert_eq!(ClientMsg::Retry.to_json(), r#"{"type":"retry"}"#);
1330 let t = InferenceTest { base_url: "u".into(), model: "m".into(), ok: false, problem: Some(Problem::Unauthorized), detail: "x".into(), models: vec![] };
1331 let m = ServerMsg::InferenceTested(t);
1332 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1333 let state = EngineState {
1334 link: Link::failed("could not reach u: refused"),
1335 onboarded: true,
1336 detected: vec![Detected { preset: "ollama".into(), base_url: "http://127.0.0.1:11434/v1".into(), models: vec!["qwen3".into()] }],
1337 ..Default::default()
1338 };
1339 let m = ServerMsg::State(state);
1340 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1341 let old = r#"{"version":"0","inference_base_url":"u","inference_model":"m","has_api_key":false,"endpoint":null,"busy":false}"#;
1343 let s = serde_json::from_str::<EngineState>(old).unwrap();
1344 assert_eq!((s.link, s.onboarded, s.detected.len()), (Link::Unknown, false, 0));
1345 }
1346
1347 #[test]
1348 fn hello_negotiates_and_old_hellos_still_parse() {
1349 let m = ClientMsg::hello("desktop");
1350 let ClientMsg::Hello { protocol, minor, caps, .. } = &m else { panic!() };
1351 assert_eq!((*protocol, *minor), (PROTOCOL_MAJOR, PROTOCOL_MINOR));
1352 assert!(caps.iter().any(|c| c == version::CAP_PLUGIN_CHANNEL));
1353 assert!(m.check_sizes().is_ok());
1354 let old = ClientMsg::from_json(r#"{"type":"hello","protocol":12,"client":"old tab"}"#).unwrap();
1356 assert_eq!(old, ClientMsg::Hello { protocol: 12, minor: 0, client: "old tab".into(), caps: vec![] });
1357 let bad = ClientMsg::Hello { protocol: PROTOCOL_MAJOR, minor: 0, client: "x".into(), caps: vec!["NOT A CAP".into()] };
1358 assert!(bad.check_sizes().is_err());
1359 let w = ServerMsg::Welcome(Welcome::current());
1360 assert_eq!(ServerMsg::from_json(&w.to_json()).unwrap(), w);
1361 assert!(w.to_json().starts_with(r#"{"type":"welcome","protocol":13"#), "{}", w.to_json());
1362 }
1363
1364 #[test]
1365 fn plugin_channel_round_trips_and_is_capped() {
1366 let c = ClientMsg::Plugin { plugin: "sheets".into(), msg: serde_json::json!({"op": "get", "cell": "A1"}) };
1367 assert_eq!(c.to_json(), r#"{"type":"plugin","plugin":"sheets","msg":{"cell":"A1","op":"get"}}"#);
1368 assert_eq!(ClientMsg::from_json(&c.to_json()).unwrap(), c);
1369 assert!(c.check_sizes().is_ok());
1370 let s = ServerMsg::Plugin { plugin: "sheets".into(), msg: serde_json::json!([1, 2]) };
1371 assert_eq!(ServerMsg::from_json(&s.to_json()).unwrap(), s);
1372 for bad in [
1373 ClientMsg::Plugin { plugin: "Not/an id".into(), msg: serde_json::Value::Null },
1374 ClientMsg::Plugin { plugin: "sheets".into(), msg: serde_json::Value::String("x".repeat(version::MAX_PLUGIN_MSG_BYTES)) },
1375 ] {
1376 assert!(bad.check_sizes().is_err());
1377 }
1378 }
1379
1380 #[test]
1381 fn question_cards_round_trip_and_older_asks_still_parse() {
1382 let c = ClientMsg::AnswerQuestion { step: 4, text: "Metric".into() };
1383 assert_eq!(c.to_json(), r#"{"type":"answer_question","step":4,"text":"Metric"}"#);
1384 assert_eq!(ClientMsg::from_json(&c.to_json()).unwrap(), c);
1385 assert!(c.check_sizes().is_ok());
1386 assert!(ClientMsg::AnswerQuestion { step: 4, text: "x".repeat(MAX_ANSWER_CHARS + 1) }.check_sizes().is_err());
1387 let ask = Ask {
1388 text: "Which units?".into(),
1389 warning: None,
1390 always: true,
1391 choice: Some(Choice { options: vec!["Metric".into(), "Imperial".into()], free_text: true, answer: None }),
1392 };
1393 let json = serde_json::to_string(&ask).unwrap();
1394 assert_eq!(serde_json::from_str::<Ask>(&json).unwrap(), ask);
1395 let old: Ask = serde_json::from_str(r#"{"text":"t","always":true}"#).unwrap();
1397 assert!(old.choice.is_none());
1398 assert!(!serde_json::to_string(&old).unwrap().contains("choice"));
1399 }
1400
1401 #[test]
1403 fn unknown_messages_and_enum_values_decode_to_fallbacks() {
1404 assert_eq!(ServerMsg::from_json(r#"{"type":"hologram","x":1,"y":{"z":[]}}"#).unwrap(), ServerMsg::Unknown);
1405 assert_eq!(ClientMsg::from_json(r#"{"type":"teleport","to":"mars"}"#).unwrap(), ClientMsg::Unknown);
1406 assert!(ServerMsg::from_json(r#"{"type":"notice","level":"info"}"#).is_err());
1408 let n = ServerMsg::from_json(r#"{"type":"notice","level":"debug","text":"t"}"#).unwrap();
1409 assert_eq!(n, ServerMsg::Notice { level: NoticeLevel::Info, text: "t".into() });
1410 let a = ClientMsg::from_json(r#"{"type":"approve","step":1,"answer":"maybe_later"}"#).unwrap();
1411 assert_eq!(a, ClientMsg::Approve { step: 1, answer: ApprovalAnswer::Unknown });
1412 let json = r#"{"id":1,"tool":"t","title":"T","access":"read","status":"done","detail":"",
1414 "changes":[{"kind":"chmod","path":"a","mode":"755"}],
1415 "preview":{"kind":"hexdump","bytes":"00"},
1416 "media":[{"kind":"video","path":"a.mp4"}],
1417 "views":[{"kind":"sheets.grid","v":4,"data":{"rows":[]},"fallback":"a *grid*"}]}"#;
1418 let s: Step = serde_json::from_str(json).unwrap();
1419 assert_eq!((s.changes.clone(), s.preview.clone()), (vec![FileChange::Other], Some(Preview::Other)));
1420 assert_eq!(s.media[0].kind, MediaKind::File);
1421 assert_eq!((s.views[0].kind.as_str(), s.views[0].fallback.as_str()), ("sheets.grid", "a *grid*"));
1422 assert!(s.view::<PluginCard>().is_none());
1423 let art: Artifact = serde_json::from_str(r#"{"id":"a","kind":"spreadsheet","title":"A","filename":"a.xlsx","versions":[]}"#).unwrap();
1424 assert_eq!(art.kind, ArtifactKind::Text);
1425 assert_eq!(serde_json::from_str::<SlashKind>(r#""macro""#).unwrap(), SlashKind::Other);
1426 assert_eq!(serde_json::from_str::<PluginAction>(r#""forked""#).unwrap(), PluginAction::Other);
1427 let env = ClientMsg::from_json(r#"{"type":"workspace_env","action":{"kind":"rebuild","fast":true}}"#).unwrap();
1428 assert_eq!(env, ClientMsg::WorkspaceEnv { action: Some(EnvAction::Unsupported), workspace: None });
1429 let d = ServerMsg::from_json(r#"{"type":"delegation","entry":1,"step":2,"update":{"kind":"progress","pct":5}}"#).unwrap();
1430 assert_eq!(d, ServerMsg::Delegation { entry: 1, step: 2, update: DelegationUpdate::Other });
1431 }
1432
1433 #[test]
1434 fn plugin_cards_travel_as_views() {
1435 let card = PluginCard {
1436 plugin: "scratch".into(),
1437 scope: PluginScope::Chat,
1438 action: PluginAction::Made,
1439 tools: vec!["shout".into()],
1440 added: vec!["shout".into()],
1441 removed: vec![],
1442 test: Some(plugins::PluginTest { ok: true, output: "HI".into() }),
1443 problems: vec![],
1444 missing_settings: vec![],
1445 };
1446 let mut s = step(1, StepStatus::Done);
1447 s.views.push(View::of(&card));
1448 let json = ServerMsg::StepUpdated { entry: 1, step: s }.to_json();
1449 assert!(json.contains(r#""views":[{"kind":"byob.plugin_card","v":1,"data":{"action":"made""#), "{json}");
1450 let ServerMsg::StepUpdated { step: back, .. } = ServerMsg::from_json(&json).unwrap() else { panic!() };
1451 assert_eq!(back.view::<PluginCard>(), Some(card));
1452 assert!(back.views[0].fallback.contains("**Plugin scratch** (this chat) · tool made") && back.views[0].fallback.contains("shout"));
1453 assert!(!ServerMsg::StepUpdated { entry: 1, step: step(2, StepStatus::Done) }.to_json().contains("views"));
1455 }
1456
1457 #[test]
1458 fn state_never_carries_api_key() {
1459 let json = serde_json::to_string(&EngineState::default()).unwrap();
1460 assert!(!json.contains("\"api_key\""));
1461 }
1462}