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 phone;
16pub mod plugins;
17pub mod profiles;
18pub mod queue;
19pub mod routines;
20pub mod sites;
21pub mod tree;
22pub mod usage;
23pub mod version;
24pub mod view;
25pub mod web;
26pub mod workspace;
27
28use serde::{Deserialize, Serialize};
29
30pub use artifact::{Artifact, ArtifactKind, ArtifactRef, ArtifactVersion, LibraryItem};
31pub use connect::{Detected, InferenceTest, Link, PRESETS, Preset, Problem};
32pub use delegation::{Delegation, DelegationState, DelegationUpdate};
33pub use env::{ContainerEnv, EnvAction, EnvSupport, WorkspaceEnv};
34pub use media::{MediaContent, MediaKind, MediaRef};
35pub use phone::{CAP_PHONE, PhoneState};
36pub use plugins::{
37 BackendInfo, Extensions, PluginAction, PluginCard, PluginInfo, PluginLoadError, PluginOrigin, PluginScope, PluginSetting, PluginTest, RendererDecl,
38 ServerInfo, ServerState, SlashItem, SlashKind, StarterDecl,
39};
40pub use profiles::{CAP_PROFILES, Profile, ProfileList, ProfileTest, ProfileView};
41pub use queue::{ChatQueue, QueuePause, QueuedMessage};
42pub use routines::{CAP_ROUTINES, RoutineEventKind, RoutineView};
43pub use sites::{LiveView, Site, ViewDecl, ViewRef};
44pub use usage::{ChatUsage, Compaction};
45pub use version::{PROTOCOL_MAJOR, PROTOCOL_MINOR, Welcome};
46pub use view::{View, ViewData};
47pub use workspace::{ChatEndpoint, ConfigScope, ConfigView, FolderList, NewFolder, WorkspaceSummary};
48
49pub const MAX_FRAME_BYTES: usize = 4 * 1024 * 1024;
51
52#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
54#[serde(tag = "type", rename_all = "snake_case")]
55pub enum ClientMsg {
56 Hello {
60 protocol: u32,
61 #[serde(default)]
62 minor: u32,
63 client: String,
64 #[serde(default)]
65 caps: Vec<String>,
66 },
67 SetInference {
71 base_url: String,
72 model: String,
73 api_key: Option<String>,
74 },
75 TestInference {
78 base_url: String,
79 model: String,
80 #[serde(default, skip_serializing_if = "Option::is_none")]
81 api_key: Option<String>,
82 },
83 DetectEndpoints,
86 Retry,
89 Rewind {
95 entry: u64,
96 text: String,
97 },
98 SendMessage {
102 text: String,
103 #[serde(default, skip_serializing_if = "Vec::is_empty")]
104 attachments: Vec<String>,
105 },
106 Steer {
113 text: String,
114 #[serde(default, skip_serializing_if = "Vec::is_empty")]
115 attachments: Vec<String>,
116 },
117 Cancel,
119 Unqueue {
121 id: u64,
122 },
123 EditQueued {
126 id: u64,
127 text: String,
128 #[serde(default, skip_serializing_if = "Vec::is_empty")]
129 attachments: Vec<String>,
130 },
131 MoveQueued {
133 id: u64,
134 to: u32,
135 },
136 SendQueuedNow {
138 id: u64,
139 },
140 ResumeQueue,
142 Approve {
145 step: u64,
146 answer: ApprovalAnswer,
147 },
148 AnswerQuestion {
152 step: u64,
153 text: String,
154 },
155 Undo {
158 entry: u64,
159 },
160 ListChats {
163 after: Option<ChatCursor>,
164 limit: u32,
165 },
166 NewChat {
170 #[serde(default, skip_serializing_if = "Option::is_none")]
171 workspace: Option<String>,
172 },
173 NewUnattachedChat,
178 ChatToProject {
182 chat: String,
183 },
184 OpenChat {
186 id: String,
187 },
188 RenameChat {
189 id: String,
190 title: String,
191 },
192 DeleteChat {
194 id: String,
195 },
196 PinChat {
198 id: String,
199 pinned: bool,
200 },
201 ArchiveChat {
204 id: String,
205 archived: bool,
206 },
207 ListLibrary,
210 GetPluginLogo {
213 plugin: String,
214 },
215 GetLibraryFile {
218 chat: String,
219 id: String,
220 version: u32,
221 },
222 DeleteArtifact {
225 chat: String,
226 id: String,
227 },
228 RevealArtifact {
231 chat: String,
232 id: String,
233 },
234 RevealChatFolder {
237 chat: String,
238 },
239 AddLiveFile {
243 path: String,
244 },
245 Upload {
250 upload: u64,
251 name: String,
252 size: u64,
253 offset: u64,
254 data: String,
255 done: bool,
256 },
257 GetMedia {
259 path: String,
260 },
261 GetArtifact {
264 id: String,
265 version: u32,
266 },
267 SetArtifactNetwork {
271 id: String,
272 on: bool,
273 },
274 Compact {
277 #[serde(default, skip_serializing_if = "Option::is_none")]
278 focus: Option<String>,
279 },
280 WorkspaceEnv {
283 #[serde(default, skip_serializing_if = "Option::is_none")]
284 action: Option<EnvAction>,
285 #[serde(default, skip_serializing_if = "Option::is_none")]
286 workspace: Option<String>,
287 },
288 CreateWorkspace {
292 name: String,
293 folder: NewFolder,
294 #[serde(default)]
295 config: workspace::Layer,
296 #[serde(default, skip_serializing_if = "Vec::is_empty")]
298 folders: Vec<String>,
299 },
300 SetWorkspaceFolders {
304 id: String,
305 folders: Vec<String>,
306 },
307 RenameWorkspace {
308 id: String,
309 name: String,
310 },
311 RemoveWorkspace {
314 id: String,
315 #[serde(default)]
316 clean: bool,
317 },
318 GetConfig {
320 scope: ConfigScope,
321 },
322 SetConfig {
326 scope: ConfigScope,
327 layer: workspace::Layer,
328 #[serde(default, skip_serializing_if = "Option::is_none")]
329 api_key: Option<String>,
330 },
331 ListFolders {
334 #[serde(default, skip_serializing_if = "Option::is_none")]
335 path: Option<String>,
336 },
337 CheckContainers,
339 GetExtensions,
341 SetPluginEnabled {
345 scope: ConfigScope,
346 plugin: String,
347 enabled: Option<bool>,
348 },
349 SetPluginSetting {
353 plugin: String,
354 key: String,
355 value: Option<String>,
356 },
357 KeepPlugin {
361 plugin: String,
362 scope: PluginScope,
363 #[serde(default, skip_serializing_if = "Option::is_none")]
364 new_id: Option<String>,
365 },
366 RemovePlugin {
369 plugin: String,
370 scope: PluginScope,
371 },
372 ReloadPlugins,
374 TrustPlugins {
378 workspace: String,
379 #[serde(default)]
380 plugins: Vec<String>,
381 trust: bool,
382 },
383 Plugin {
386 plugin: String,
387 msg: serde_json::Value,
388 },
389 OpenView {
393 view: ViewRef,
394 },
395 CloseView {
397 view: ViewRef,
398 },
399 ViewEvent {
402 view: ViewRef,
403 event: tree::Event,
404 },
405 WebCall {
410 call: u64,
411 owner: web::WebOwner,
412 method: String,
413 #[serde(default)]
414 params: serde_json::Value,
415 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
416 approved: bool,
417 },
418 GetProfiles,
421 CreateProfile {
424 profile: Profile,
425 #[serde(default, skip_serializing_if = "Option::is_none")]
426 api_key: Option<String>,
427 #[serde(default, skip_serializing_if = "Option::is_none")]
428 assign: Option<ConfigScope>,
429 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
430 make_main: bool,
431 },
432 UpdateProfile {
435 profile: Profile,
436 #[serde(default, skip_serializing_if = "Option::is_none")]
437 api_key: Option<String>,
438 },
439 DeleteProfile {
442 id: String,
443 },
444 DuplicateProfile {
446 id: String,
447 },
448 SetRole {
451 role: String,
452 profile: Option<String>,
453 },
454 TestProfile {
456 id: String,
457 },
458 SetLevelProfile {
461 scope: ConfigScope,
462 profile: Option<String>,
463 },
464 SetKeepRunning {
468 value: byob_types::desktop::KeepRunning,
469 },
470 SetLayout {
473 layout: layout::Layout,
474 },
475 ReportLook(look::LookReport),
478 Captured {
482 request: u64,
483 #[serde(default, skip_serializing_if = "Option::is_none")]
484 image: Option<String>,
485 #[serde(default, skip_serializing_if = "Option::is_none")]
486 error: Option<String>,
487 },
488 SaveRoutine {
491 routine: routines::Routine,
492 },
493 DeleteRoutine {
495 id: String,
496 },
497 RunRoutine {
499 id: String,
500 },
501 SetRoutineEnabled {
503 id: String,
504 enabled: bool,
505 },
506 ListRoutineRuns {
508 id: String,
509 },
510 PauseRoutines {
515 paused: bool,
516 },
517 PairPhone {
521 channel: String,
522 },
523 CancelPairing,
525 UnpairPhone,
527 TestPhone,
529 #[serde(other)]
531 Unknown,
532}
533
534#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
536#[serde(tag = "type", rename_all = "snake_case")]
537pub enum ServerMsg {
538 Welcome(Welcome),
540 State(EngineState),
542 Notice { level: NoticeLevel, text: String },
544 Transcript { entries: Vec<Entry> },
546 EntryAdded(Entry),
548 EntryDelta { id: u64, content: String, reasoning: String },
550 EntryFinished { id: u64, error: Option<String>, stats: Option<TurnStats> },
552 StepUpdated { entry: u64, step: Step },
554 EntryUndo { id: u64, undoable: bool, undone: bool },
556 Chats { pinned: Vec<ChatSummary>, recent: Vec<ChatSummary>, after: Option<ChatCursor>, next: Option<ChatCursor> },
559 ChatUpdated(ChatSummary),
561 ChatDeleted { id: String },
563 ChatOpened {
567 chat: Option<ChatSummary>,
568 #[serde(default)]
569 workspace: Option<String>,
570 },
571 Uploaded { upload: u64, attachment: Option<MediaRef>, error: Option<String> },
573 Media { path: String, content: MediaContent },
575 Artifacts { chat: Option<String>, artifacts: Vec<Artifact> },
578 Library { items: Vec<LibraryItem> },
581 PluginLogo { plugin: String, data: Option<String> },
583 LibraryFile { chat: String, id: String, version: u32, data: Option<String>, error: Option<String> },
585 ArtifactUpdated(Artifact),
587 ArtifactFile { id: String, version: u32, data: Option<String>, error: Option<String> },
589 Usage(ChatUsage),
591 Compactions { chat: Option<String>, items: Vec<Compaction> },
594 Compacted(Compaction),
596 Delegation { entry: u64, step: u64, update: DelegationUpdate },
598 InferenceTested(InferenceTest),
600 WorkspaceEnv(WorkspaceEnv),
602 Workspaces { items: Vec<WorkspaceSummary>, current: Option<String>, root: String, support: EnvSupport },
606 Config(Box<ConfigView>),
608 Folders(FolderList),
610 ContainersChecked { ok: bool, message: String },
612 WorkspaceCreated { id: Option<String>, error: Option<String> },
614 Queue(ChatQueue),
617 Extensions(Box<Extensions>),
620 Plugin { plugin: String, msg: serde_json::Value },
623 LiveView(LiveView),
626 WebReply {
629 call: u64,
630 #[serde(default, deserialize_with = "present_even_if_null", skip_serializing_if = "Option::is_none")]
632 result: Option<serde_json::Value>,
633 #[serde(default, skip_serializing_if = "Option::is_none")]
634 error: Option<web::WebError>,
635 },
636 WebPush { owner: web::WebOwner, msg: serde_json::Value },
639 Profiles(Box<ProfileList>),
642 ProfileTested(ProfileTest),
644 Layout(layout::Layout),
647 SetLook { request: u64, changes: look::LookChanges },
651 Capture { request: u64 },
654 Routines { items: Vec<RoutineView> },
657 RoutineRuns { routine: String, runs: Vec<routines::RunRecord> },
659 RoutineEvent {
662 routine: String,
663 #[serde(default)]
665 name: String,
666 #[serde(default, skip_serializing_if = "Option::is_none")]
668 chat: Option<String>,
669 kind: RoutineEventKind,
670 title: String,
671 #[serde(default)]
672 body: String,
673 },
674 Phone(phone::PhoneState),
677 #[serde(other)]
679 Unknown,
680}
681
682#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
684pub struct ChatSummary {
685 pub id: String,
686 pub title: String,
687 pub updated_at: i64,
689 pub pinned_at: Option<i64>,
691 #[serde(default)]
693 pub busy: bool,
694 #[serde(default, skip_serializing_if = "Option::is_none")]
696 pub workspace: Option<String>,
697 #[serde(default, skip_serializing_if = "Option::is_none")]
699 pub archived_at: Option<i64>,
700 #[serde(default, skip_serializing_if = "Option::is_none")]
702 pub origin: Option<String>,
703}
704
705impl ChatSummary {
706 pub fn cursor(&self) -> ChatCursor {
707 ChatCursor { updated_at: self.updated_at, id: self.id.clone() }
708 }
709}
710
711#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
713pub struct ChatCursor {
714 pub updated_at: i64,
715 pub id: String,
716}
717
718#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
719#[serde(rename_all = "snake_case")]
720pub enum EntryRole {
721 User,
722 Assistant,
723}
724
725#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
727pub struct Entry {
728 pub id: u64,
729 pub role: EntryRole,
730 pub content: String,
731 pub reasoning: String,
732 pub done: bool,
734 pub error: Option<String>,
735 pub stats: Option<TurnStats>,
736 #[serde(default)]
739 pub steps: Vec<Step>,
740 #[serde(default)]
742 pub undoable: bool,
743 #[serde(default)]
745 pub undone: bool,
746 #[serde(default, skip_serializing_if = "Vec::is_empty")]
748 pub attachments: Vec<MediaRef>,
749}
750
751impl Entry {
752 pub fn append(&mut self, content: &str, reasoning: &str) {
754 self.content.push_str(content);
755 self.reasoning.push_str(reasoning);
756 }
757
758 pub fn upsert_step(&mut self, step: Step) {
760 match self.steps.iter_mut().find(|s| s.id == step.id) {
761 Some(existing) => *existing = step,
762 None => self.steps.push(step),
763 }
764 }
765
766 pub fn pending_approvals(&self) -> impl Iterator<Item = &Step> {
768 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)
769 }
770
771 pub fn apply_delegation(&mut self, step: u64, update: &DelegationUpdate) {
773 if let Some(d) = self.steps.iter_mut().find(|s| s.id == step).and_then(|s| s.delegation.as_deref_mut()) {
774 d.apply(update);
775 }
776 }
777}
778
779#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
781#[serde(rename_all = "snake_case")]
782pub enum ToolAccess {
783 Read,
784 Write,
785 Network,
786 Execute,
787}
788
789impl ToolAccess {
790 pub fn label(self) -> &'static str {
791 match self {
792 Self::Read => "read",
793 Self::Write => "write",
794 Self::Network => "network",
795 Self::Execute => "execute",
796 }
797 }
798}
799
800#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
801#[serde(rename_all = "snake_case")]
802pub enum StepStatus {
803 Running,
804 Waiting,
806 Done,
807 Failed,
809 Denied,
811}
812
813impl StepStatus {
814 pub fn finished(self) -> bool {
815 matches!(self, Self::Done | Self::Failed | Self::Denied)
816 }
817}
818
819#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
821#[serde(rename_all = "snake_case")]
822pub enum ApprovalAnswer {
823 Allow,
824 Always,
826 Deny,
827 AlwaysEverywhere,
829 #[serde(other)]
831 Unknown,
832}
833
834#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
836#[serde(tag = "kind", rename_all = "snake_case")]
837pub enum FileChange {
838 Created {
839 path: String,
840 },
841 Modified {
842 path: String,
843 },
844 Deleted {
845 path: String,
846 },
847 Moved {
848 from: String,
849 to: String,
850 },
851 #[serde(other)]
853 Other,
854}
855
856#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
858pub struct Step {
859 pub id: u64,
861 pub tool: String,
863 pub title: String,
865 pub access: ToolAccess,
866 pub status: StepStatus,
867 pub detail: String,
869 #[serde(default)]
870 pub changes: Vec<FileChange>,
871 #[serde(default)]
873 pub at: usize,
874 #[serde(default, skip_serializing_if = "Vec::is_empty")]
876 pub media: Vec<MediaRef>,
877 #[serde(default, skip_serializing_if = "Option::is_none")]
879 pub preview: Option<Preview>,
880 #[serde(default, skip_serializing_if = "Vec::is_empty")]
882 pub artifacts: Vec<ArtifactRef>,
883 #[serde(default, skip_serializing_if = "Option::is_none")]
885 pub delegation: Option<Box<Delegation>>,
886 #[serde(default, skip_serializing_if = "Option::is_none")]
890 pub ask: Option<Box<Ask>>,
891 #[serde(default, skip_serializing_if = "Vec::is_empty")]
895 pub views: Vec<View>,
896}
897
898impl Step {
899 pub fn view<T: ViewData>(&self) -> Option<T> {
901 self.views.iter().find_map(View::get)
902 }
903}
904
905#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
907pub struct Ask {
908 #[serde(default)]
910 pub text: String,
911 #[serde(default, skip_serializing_if = "Option::is_none")]
913 pub warning: Option<String>,
914 #[serde(default)]
916 pub always: bool,
917 #[serde(default, skip_serializing_if = "Option::is_none")]
921 pub choice: Option<Choice>,
922 #[serde(default, skip_serializing_if = "Option::is_none")]
925 pub card: Option<CardWords>,
926}
927
928#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
930pub struct CardWords {
931 #[serde(default)]
933 pub access: String,
934 #[serde(default, skip_serializing_if = "Option::is_none")]
936 pub allow: Option<String>,
937 #[serde(default, skip_serializing_if = "Option::is_none")]
939 pub deny: Option<String>,
940}
941
942pub const MAX_CHOICE_OPTIONS: usize = 8;
944pub const MAX_ANSWER_CHARS: usize = 2000;
946
947#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
949pub struct Choice {
950 #[serde(default, skip_serializing_if = "Vec::is_empty")]
952 pub options: Vec<String>,
953 #[serde(default)]
955 pub free_text: bool,
956 #[serde(default, skip_serializing_if = "Option::is_none")]
958 pub answer: Option<String>,
959}
960
961pub const MAX_PREVIEW_LINES: usize = 40;
963pub const MAX_PREVIEW_LINE_CHARS: usize = 300;
965
966#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
968#[serde(tag = "kind", rename_all = "snake_case")]
969pub enum Preview {
970 Write {
973 path: String,
974 bytes: u64,
975 replaces: bool,
977 lines: Vec<DiffLine>,
978 #[serde(default)]
980 more: usize,
981 },
982 Move {
984 moves: Vec<(String, String)>,
985 #[serde(default)]
986 more: usize,
987 },
988 Delete { path: String, what: String },
990 Args {
992 fields: Vec<(String, String)>,
993 #[serde(default, skip_serializing_if = "Option::is_none")]
994 code: Option<String>,
995 #[serde(default)]
996 more: usize,
997 },
998 #[serde(other)]
1000 Other,
1001}
1002
1003#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1005pub struct DiffLine {
1006 pub kind: LineKind,
1007 pub text: String,
1008}
1009
1010#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1011#[serde(rename_all = "snake_case")]
1012pub enum LineKind {
1013 Same,
1015 Added,
1016 Removed,
1017 Skipped,
1019}
1020
1021#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
1022pub struct TurnStats {
1023 pub prompt_tokens: u64,
1024 pub completion_tokens: u64,
1025 pub elapsed_ms: u64,
1026 #[serde(default)]
1028 pub model_calls: u64,
1029 #[serde(default, skip_serializing_if = "is_zero")]
1033 pub context_tokens: u64,
1034}
1035
1036fn is_zero(n: &u64) -> bool {
1037 *n == 0
1038}
1039
1040#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1041#[serde(rename_all = "snake_case")]
1042pub enum NoticeLevel {
1043 Error,
1044 #[serde(other)]
1046 Info,
1047}
1048
1049#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1051pub struct EngineState {
1052 pub version: String,
1053 pub inference_base_url: String,
1054 pub inference_model: String,
1055 pub has_api_key: bool,
1056 pub endpoint: Option<String>,
1058 pub busy: bool,
1060 #[serde(default)]
1062 pub endpoint_info: Option<EndpointInfo>,
1063 #[serde(default)]
1065 pub link: Link,
1066 #[serde(default)]
1069 pub onboarded: bool,
1070 #[serde(default)]
1072 pub detected: Vec<Detected>,
1073 #[serde(default)]
1075 pub detecting: bool,
1076 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1078 pub yolo: bool,
1079 #[serde(default, skip_serializing_if = "Option::is_none")]
1082 pub chat_endpoint: Option<ChatEndpoint>,
1083 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1085 pub routines_active: bool,
1086 #[serde(default, skip_serializing_if = "Option::is_none")]
1089 pub keep_running: Option<byob_types::desktop::KeepRunning>,
1090 #[serde(default, skip_serializing_if = "Option::is_none")]
1093 pub routines_paused: Option<bool>,
1094}
1095
1096#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1098#[serde(rename_all = "snake_case")]
1099pub enum ToolsMode {
1100 Native,
1102 Prompt,
1104 #[default]
1106 Unknown,
1107}
1108
1109#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1111pub struct EndpointInfo {
1112 #[serde(default)]
1114 pub probing: bool,
1115 #[serde(default)]
1117 pub server: String,
1118 #[serde(default)]
1120 pub context_tokens: Option<u64>,
1121 #[serde(default)]
1122 pub tools: ToolsMode,
1123 #[serde(default)]
1125 pub vision: Option<bool>,
1126 #[serde(default, skip_serializing_if = "Option::is_none")]
1128 pub slots: Option<u64>,
1129}
1130
1131impl EndpointInfo {
1132 pub fn summary(&self) -> String {
1134 if self.probing {
1135 return "checking endpoint…".into();
1136 }
1137 let mut parts = Vec::new();
1138 if !self.server.is_empty() {
1139 parts.push(self.server.clone());
1140 }
1141 if let Some(n) = self.context_tokens {
1142 parts.push(if n >= 1000 { format!("{}k ctx", n / 1000) } else { format!("{n} ctx") });
1143 }
1144 parts.push(
1145 match self.tools {
1146 ToolsMode::Native => "native tools",
1147 ToolsMode::Prompt => "prompt tools",
1148 ToolsMode::Unknown => "tools untested",
1149 }
1150 .into(),
1151 );
1152 if self.vision == Some(true) {
1153 parts.push("vision".into());
1154 }
1155 if let Some(n) = self.slots.filter(|n| *n > 1) {
1156 parts.push(format!("{n} slots"));
1157 }
1158 parts.join(" · ")
1159 }
1160}
1161
1162impl ClientMsg {
1163 pub fn hello(client: &str) -> Self {
1165 Self::Hello { protocol: PROTOCOL_MAJOR, minor: PROTOCOL_MINOR, client: client.to_owned(), caps: version::client_caps() }
1166 }
1167
1168 pub fn to_json(&self) -> String {
1169 serde_json::to_string(self).unwrap_or_default()
1170 }
1171
1172 pub fn from_json(text: &str) -> Result<Self, String> {
1174 if text.len() > MAX_FRAME_BYTES {
1175 return Err(format!("frame too large ({} bytes)", text.len()));
1176 }
1177 serde_json::from_str(text).map_err(|e| e.to_string())
1178 }
1179}
1180
1181impl ServerMsg {
1182 pub fn to_json(&self) -> String {
1183 serde_json::to_string(self).unwrap_or_default()
1184 }
1185
1186 pub fn to_frame(&self) -> String {
1192 let json = self.to_json();
1193 if json.len() <= MAX_FRAME_BYTES {
1194 return json;
1195 }
1196 let why = format!("it is too large to send over this connection ({} KB, at most {} KB)", json.len() / 1024, MAX_FRAME_BYTES / 1024);
1197 let instead = match self {
1198 Self::LiveView(lv) if lv.tree.is_none() => Self::LiveView(LiveView { view: lv.view.clone(), reset: true, ..Default::default() }),
1199 Self::LiveView(lv) => {
1200 Self::LiveView(LiveView { view: lv.view.clone(), error: Some(format!("This view can't be shown here: {why}.")), ..Default::default() })
1201 }
1202 Self::WebReply { call, .. } => {
1203 Self::WebReply { call: *call, result: None, error: Some(web::WebError::new(-32000, format!("byob couldn't send the answer: {why}"))) }
1204 }
1205 _ => Self::Notice { level: NoticeLevel::Error, text: format!("byob couldn't send an update: {why}.") },
1206 };
1207 instead.to_json()
1208 }
1209
1210 pub fn from_json(text: &str) -> Result<Self, String> {
1212 if text.len() > MAX_FRAME_BYTES {
1213 return Err(format!("frame too large ({} bytes)", text.len()));
1214 }
1215 serde_json::from_str(text).map_err(|e| e.to_string())
1216 }
1217}
1218
1219pub trait Connection {
1221 fn send(&mut self, msg: ClientMsg);
1222 fn try_recv(&mut self) -> Option<ServerMsg>;
1224}
1225
1226fn present_even_if_null<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<serde_json::Value>, D::Error> {
1229 serde_json::Value::deserialize(d).map(Some)
1230}
1231
1232#[cfg(test)]
1233mod tests {
1234 use super::*;
1235
1236 #[test]
1239 fn web_reply_keeps_a_null_result() {
1240 let null = ServerMsg::WebReply { call: 3, result: Some(serde_json::Value::Null), error: None };
1241 assert_eq!(null.to_json(), r#"{"type":"web_reply","call":3,"result":null}"#);
1242 assert_eq!(ServerMsg::from_json(&null.to_json()).unwrap(), null);
1243 let none = ServerMsg::WebReply { call: 3, result: None, error: None };
1244 assert_eq!(none.to_json(), r#"{"type":"web_reply","call":3}"#);
1245 assert_eq!(ServerMsg::from_json(&none.to_json()).unwrap(), none);
1246 let value = ServerMsg::WebReply { call: 3, result: Some(serde_json::json!({"a": [1]})), error: None };
1247 assert_eq!(ServerMsg::from_json(&value.to_json()).unwrap(), value);
1248 }
1249
1250 #[test]
1251 fn client_msg_round_trips() {
1252 let m = ClientMsg::hello("test");
1253 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1254 }
1255
1256 #[test]
1257 fn wire_format_is_tagged() {
1258 let json = ServerMsg::Notice { level: NoticeLevel::Info, text: "hi".into() }.to_json();
1259 assert_eq!(json, r#"{"type":"notice","level":"info","text":"hi"}"#);
1260 }
1261
1262 #[test]
1263 fn a_message_too_large_for_a_frame_is_sent_as_something_the_client_acts_on() {
1264 let big = "x".repeat(MAX_FRAME_BYTES);
1265 let r = ViewRef::new("p", "v", "k");
1266 let small = ServerMsg::Notice { level: NoticeLevel::Info, text: "hi".into() };
1267 assert_eq!(small.to_frame(), small.to_json());
1268 let frame = |m: ServerMsg| {
1269 let f = m.to_frame();
1270 assert!(f.len() < 1024, "{} bytes", f.len());
1271 ServerMsg::from_json(&f).unwrap()
1272 };
1273 let mut values = serde_json::Map::new();
1274 values.insert("f".into(), serde_json::json!(big));
1275 let change = LiveView { view: r.clone(), values, ..Default::default() };
1276 assert_eq!(frame(ServerMsg::LiveView(change)), ServerMsg::LiveView(LiveView { view: r.clone(), reset: true, ..Default::default() }));
1277 let texts: Vec<_> = (0..100).map(|_| serde_json::json!({"type": "text", "text": "y".repeat(60_000)})).collect();
1279 let (tree, faults) = tree::decode(serde_json::json!({"type": "column", "children": texts}));
1280 assert!(faults.is_empty(), "{faults:?}");
1281 match frame(ServerMsg::LiveView(LiveView { view: r.clone(), tree: Some(tree), ..Default::default() })) {
1282 ServerMsg::LiveView(lv) => assert!(lv.view == r && lv.tree.is_none() && lv.error.is_some_and(|e| e.contains("too large"))),
1283 other => panic!("{other:?}"),
1284 }
1285 match frame(ServerMsg::WebReply { call: 9, result: Some(serde_json::json!(big)), error: None }) {
1286 ServerMsg::WebReply { call: 9, result: None, error: Some(e) } => assert!(e.message.contains("too large")),
1287 other => panic!("{other:?}"),
1288 }
1289 let plugin = ServerMsg::Plugin { plugin: "p".into(), msg: serde_json::json!(big) };
1290 assert!(matches!(frame(plugin), ServerMsg::Notice { level: NoticeLevel::Error, .. }));
1291 }
1292
1293 #[test]
1294 fn rejects_garbage_and_oversized_frames() {
1295 assert!(ClientMsg::from_json("{not json").is_err());
1296 assert!(ClientMsg::from_json(&" ".repeat(MAX_FRAME_BYTES + 1)).is_err());
1297 }
1298
1299 #[test]
1300 fn approve_wire_format() {
1301 let m = ClientMsg::Approve { step: 7, answer: ApprovalAnswer::Always };
1302 assert_eq!(m.to_json(), r#"{"type":"approve","step":7,"answer":"always"}"#);
1303 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1304 }
1305
1306 fn step(id: u64, status: StepStatus) -> Step {
1307 Step {
1308 id,
1309 tool: "t".into(),
1310 title: "T".into(),
1311 access: ToolAccess::Write,
1312 status,
1313 detail: String::new(),
1314 changes: vec![],
1315 at: 0,
1316 preview: None,
1317 media: vec![],
1318 artifacts: vec![],
1319 delegation: None,
1320 ask: None,
1321 views: vec![],
1322 }
1323 }
1324
1325 #[test]
1326 fn delegations_stream_into_their_step_and_round_trip() {
1327 let mut parent = step(1, StepStatus::Running);
1328 parent.delegation = Some(Box::new(Delegation { agent: "explorer".into(), task: "count lines".into(), ..Default::default() }));
1329 let mut e = Entry {
1330 id: 9,
1331 role: EntryRole::Assistant,
1332 content: String::new(),
1333 reasoning: String::new(),
1334 done: false,
1335 error: None,
1336 stats: None,
1337 steps: vec![parent],
1338 undoable: false,
1339 undone: false,
1340 attachments: vec![],
1341 };
1342 let updates = [
1343 DelegationUpdate::Status { state: DelegationState::Running, prompt_tokens: 0, completion_tokens: 0, error: None },
1344 DelegationUpdate::Delta { content: "Reading".into(), reasoning: "hm".into() },
1345 DelegationUpdate::Step(Box::new(step(2, StepStatus::Waiting))),
1346 DelegationUpdate::Delta { content: " a.txt".into(), reasoning: String::new() },
1347 ];
1348 for u in &updates {
1349 let msg = ServerMsg::Delegation { entry: 9, step: 1, update: u.clone() };
1350 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1351 e.apply_delegation(1, u);
1352 }
1353 e.apply_delegation(77, &updates[1]);
1355 let d = e.steps[0].delegation.as_deref().unwrap();
1356 assert_eq!((d.content.as_str(), d.reasoning.as_str(), d.state), ("Reading a.txt", "hm", DelegationState::Running));
1357 assert_eq!(d.status_line(), "explorer · 1 tool · waiting for approval");
1358 assert_eq!(e.pending_approvals().map(|s| s.id).collect::<Vec<_>>(), vec![2]);
1360 e.apply_delegation(1, &DelegationUpdate::Step(Box::new(step(2, StepStatus::Done))));
1361 e.apply_delegation(1, &DelegationUpdate::Status { state: DelegationState::Done, prompt_tokens: 50, completion_tokens: 5, error: None });
1362 assert_eq!(e.steps[0].delegation.as_deref().unwrap().status_line(), "explorer · 1 tool · done");
1363 assert_eq!(e.pending_approvals().count(), 0);
1364 let msg = ServerMsg::StepUpdated { entry: 9, step: e.steps[0].clone() };
1365 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1366 let json = r#"{"id":1,"tool":"t","title":"T","access":"read","status":"done","detail":""}"#;
1368 assert!(serde_json::from_str::<Step>(json).unwrap().delegation.is_none());
1369 }
1370
1371 #[test]
1372 fn steps_upsert_and_round_trip() {
1373 let mut e = Entry {
1374 id: 1,
1375 role: EntryRole::Assistant,
1376 content: String::new(),
1377 reasoning: String::new(),
1378 done: false,
1379 error: None,
1380 stats: None,
1381 steps: vec![],
1382 undoable: false,
1383 undone: false,
1384 attachments: vec![],
1385 };
1386 e.upsert_step(step(3, StepStatus::Running));
1387 e.upsert_step(step(4, StepStatus::Waiting));
1388 e.upsert_step(step(3, StepStatus::Done));
1389 assert_eq!(e.steps.len(), 2);
1390 assert_eq!(e.steps[0].status, StepStatus::Done);
1391 assert_eq!(e.pending_approvals().map(|s| s.id).collect::<Vec<_>>(), vec![4]);
1392 let mut s = step(5, StepStatus::Done);
1393 s.changes = vec![FileChange::Moved { from: "a".into(), to: "b".into() }];
1394 let msg = ServerMsg::StepUpdated { entry: 1, step: s };
1395 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1396 }
1397
1398 #[test]
1399 fn entry_without_steps_still_parses() {
1400 let json = r#"{"id":1,"role":"user","content":"hi","reasoning":"","done":true,"error":null,"stats":null}"#;
1401 let e: Entry = serde_json::from_str(json).unwrap();
1402 assert!(e.steps.is_empty());
1403 }
1404
1405 #[test]
1406 fn undo_and_preview_wire_format() {
1407 let m = ClientMsg::Undo { entry: 4 };
1408 assert_eq!(m.to_json(), r#"{"type":"undo","entry":4}"#);
1409 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1410 let mut s = step(1, StepStatus::Waiting);
1411 s.preview =
1412 Some(Preview::Write { path: "a.md".into(), bytes: 3, replaces: true, lines: vec![DiffLine { kind: LineKind::Added, text: "hi".into() }], more: 0 });
1413 let msg = ServerMsg::StepUpdated { entry: 1, step: s };
1414 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1415 let msg = ServerMsg::EntryUndo { id: 1, undoable: false, undone: true };
1416 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1417 }
1418
1419 #[test]
1420 fn chat_messages_round_trip() {
1421 let summary = ChatSummary {
1422 id: "c1".into(),
1423 title: "Plans".into(),
1424 updated_at: 5,
1425 pinned_at: None,
1426 busy: true,
1427 workspace: Some("w1".into()),
1428 archived_at: None,
1429 origin: None,
1430 };
1431 for m in [
1432 ServerMsg::Chats { pinned: vec![], recent: vec![summary.clone()], after: None, next: Some(summary.cursor()) },
1433 ServerMsg::ChatUpdated(summary.clone()),
1434 ServerMsg::ChatOpened { chat: Some(summary), workspace: None },
1435 ServerMsg::ChatDeleted { id: "c1".into() },
1436 ] {
1437 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1438 }
1439 let m = ClientMsg::ListChats { after: Some(ChatCursor { updated_at: 1, id: "x".into() }), limit: 50 };
1440 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1441 assert_eq!(ClientMsg::NewChat { workspace: None }.to_json(), r#"{"type":"new_chat"}"#);
1442 }
1443
1444 #[test]
1445 fn endpoint_info_is_optional_and_summarized() {
1446 let old = r#"{"version":"0","inference_base_url":"u","inference_model":"m","has_api_key":false,"endpoint":null,"busy":false}"#;
1447 assert_eq!(serde_json::from_str::<EngineState>(old).unwrap().endpoint_info, None);
1448 let info = EndpointInfo {
1449 probing: false,
1450 server: "llama.cpp".into(),
1451 context_tokens: Some(262_144),
1452 tools: ToolsMode::Native,
1453 vision: Some(true),
1454 slots: None,
1455 };
1456 assert_eq!(info.summary(), "llama.cpp · 262k ctx · native tools · vision");
1457 assert_eq!(EndpointInfo { slots: Some(4), ..info.clone() }.summary(), "llama.cpp · 262k ctx · native tools · vision · 4 slots");
1458 assert_eq!(EndpointInfo { probing: true, ..info }.summary(), "checking endpoint…");
1459 assert_eq!(EndpointInfo::default().summary(), "tools untested");
1460 }
1461
1462 #[test]
1463 fn media_messages_round_trip() {
1464 let msgs = vec![
1465 ClientMsg::SendMessage { text: "chart it".into(), attachments: vec!["uploads/sales.csv".into()] },
1466 ClientMsg::Upload { upload: 1, name: "a.csv".into(), size: 3, offset: 0, data: media::encode(b"a,b"), done: true },
1467 ClientMsg::GetMedia { path: "charts/x.chart.json".into() },
1468 ];
1469 for m in msgs {
1470 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1471 }
1472 let spec = byob_types::chart::validate(&serde_json::json!({"type": "bar", "x": "m", "series": ["v"], "data": [{"m": "a", "v": 1}]})).unwrap();
1473 let msgs = vec![
1474 ServerMsg::Uploaded { upload: 1, attachment: Some(MediaRef::new("uploads/a.csv", 3)), error: None },
1475 ServerMsg::Media { path: "c.chart.json".into(), content: MediaContent::Chart { spec } },
1476 ServerMsg::Media { path: "p.png".into(), content: MediaContent::Image { mime: "image/png".into(), data: "AA==".into() } },
1477 ServerMsg::Media { path: "p.png".into(), content: MediaContent::Error { message: "gone".into() } },
1478 ];
1479 for m in msgs {
1480 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1481 }
1482 let mut s = step(1, StepStatus::Done);
1483 s.media = vec![MediaRef::new("charts/x.chart.json", 10)];
1484 let m = ServerMsg::StepUpdated { entry: 1, step: s };
1485 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1486 }
1487
1488 #[test]
1489 fn artifact_messages_round_trip() {
1490 let v = ArtifactVersion { n: 2, path: ".byob/artifacts/calc/v2.html".into(), created_at: 1, note: "blue button".into(), size: 10, turn: String::new() };
1491 let a = Artifact {
1492 id: "calc".into(),
1493 kind: ArtifactKind::Html,
1494 content_type: artifact::TYPE_HTML.into(),
1495 title: "Calc".into(),
1496 filename: "calc.html".into(),
1497 versions: vec![v],
1498 network: false,
1499 };
1500 let msgs = vec![
1501 ServerMsg::Artifacts { chat: Some("c1".into()), artifacts: vec![a.clone()] },
1502 ServerMsg::Artifacts { chat: None, artifacts: vec![] },
1503 ServerMsg::ArtifactUpdated(a),
1504 ServerMsg::ArtifactFile { id: "calc".into(), version: 2, data: Some(media::encode(b"<p>")), error: None },
1505 ServerMsg::ArtifactFile { id: "calc".into(), version: 9, data: None, error: Some("no such version".into()) },
1506 ];
1507 for m in msgs {
1508 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1509 }
1510 let m = ClientMsg::GetArtifact { id: "calc".into(), version: 2 };
1511 assert_eq!(m.to_json(), r#"{"type":"get_artifact","id":"calc","version":2}"#);
1512 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1513 let mut s = step(1, StepStatus::Done);
1514 s.artifacts = vec![ArtifactRef { id: "calc".into(), version: 2 }];
1515 let m = ServerMsg::StepUpdated { entry: 1, step: s };
1516 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1517 let json = r#"{"id":1,"tool":"t","title":"T","access":"read","status":"done","detail":""}"#;
1519 assert!(serde_json::from_str::<Step>(json).unwrap().artifacts.is_empty());
1520 }
1521
1522 #[test]
1523 fn older_send_message_without_attachments_parses() {
1524 let m = ClientMsg::from_json(r#"{"type":"send_message","text":"hi"}"#).unwrap();
1525 assert_eq!(m, ClientMsg::SendMessage { text: "hi".into(), attachments: vec![] });
1526 assert_eq!(m.to_json(), r#"{"type":"send_message","text":"hi"}"#);
1527 }
1528
1529 #[test]
1530 fn compaction_messages_round_trip() {
1531 let c = Compaction {
1532 id: 1,
1533 after_entry: 7,
1534 tokens_before: 182_000,
1535 tokens_after: 9_000,
1536 summary: "## Goals".into(),
1537 manual: true,
1538 focus: Some("CSV".into()),
1539 created_at: 5,
1540 };
1541 let u = ChatUsage { chat: "c1".into(), context_used: 34_000, context_window: 262_144, compact_at: 209_715, model_calls: 3, ..Default::default() };
1542 for m in [ServerMsg::Usage(u), ServerMsg::Compactions { chat: Some("c1".into()), items: vec![c.clone()] }, ServerMsg::Compacted(c)] {
1543 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1544 }
1545 assert_eq!(ClientMsg::Compact { focus: None }.to_json(), r#"{"type":"compact"}"#);
1546 let m = ClientMsg::from_json(r#"{"type":"compact","focus":"keep the CSV"}"#).unwrap();
1547 assert_eq!(m, ClientMsg::Compact { focus: Some("keep the CSV".into()) });
1548 let s: TurnStats = serde_json::from_str(r#"{"prompt_tokens":1,"completion_tokens":2,"elapsed_ms":3}"#).unwrap();
1550 assert_eq!(s.model_calls, 0);
1551 }
1552
1553 #[test]
1554 fn connection_messages_round_trip() {
1555 for m in [
1556 ClientMsg::TestInference { base_url: "http://127.0.0.1:11434/v1".into(), model: "qwen3".into(), api_key: None },
1557 ClientMsg::TestInference { base_url: "https://api.openai.com/v1".into(), model: "m".into(), api_key: Some("sk".into()) },
1558 ClientMsg::DetectEndpoints,
1559 ClientMsg::Retry,
1560 ClientMsg::Rewind { entry: 7, text: "again, differently".into() },
1561 ClientMsg::NewUnattachedChat,
1562 ClientMsg::ChatToProject { chat: "c1".into() },
1563 ] {
1564 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1565 }
1566 assert_eq!(ClientMsg::Retry.to_json(), r#"{"type":"retry"}"#);
1567 let t = InferenceTest { base_url: "u".into(), model: "m".into(), ok: false, problem: Some(Problem::Unauthorized), detail: "x".into(), models: vec![] };
1568 let m = ServerMsg::InferenceTested(t);
1569 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1570 let state = EngineState {
1571 link: Link::failed("could not reach u: refused"),
1572 onboarded: true,
1573 detected: vec![Detected { preset: "ollama".into(), base_url: "http://127.0.0.1:11434/v1".into(), models: vec!["qwen3".into()] }],
1574 ..Default::default()
1575 };
1576 let m = ServerMsg::State(state);
1577 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1578 let old = r#"{"version":"0","inference_base_url":"u","inference_model":"m","has_api_key":false,"endpoint":null,"busy":false}"#;
1580 let s = serde_json::from_str::<EngineState>(old).unwrap();
1581 assert_eq!((s.link, s.onboarded, s.detected.len()), (Link::Unknown, false, 0));
1582 }
1583
1584 #[test]
1585 fn hello_negotiates_and_old_hellos_still_parse() {
1586 let m = ClientMsg::hello("desktop");
1587 let ClientMsg::Hello { protocol, minor, caps, .. } = &m else { panic!() };
1588 assert_eq!((*protocol, *minor), (PROTOCOL_MAJOR, PROTOCOL_MINOR));
1589 assert!(caps.iter().any(|c| c == version::CAP_PLUGIN_CHANNEL));
1590 assert!(m.check_sizes().is_ok());
1591 let old = ClientMsg::from_json(r#"{"type":"hello","protocol":12,"client":"old tab"}"#).unwrap();
1593 assert_eq!(old, ClientMsg::Hello { protocol: 12, minor: 0, client: "old tab".into(), caps: vec![] });
1594 let bad = ClientMsg::Hello { protocol: PROTOCOL_MAJOR, minor: 0, client: "x".into(), caps: vec!["NOT A CAP".into()] };
1595 assert!(bad.check_sizes().is_err());
1596 let w = ServerMsg::Welcome(Welcome::current());
1597 assert_eq!(ServerMsg::from_json(&w.to_json()).unwrap(), w);
1598 assert!(w.to_json().starts_with(r#"{"type":"welcome","protocol":13"#), "{}", w.to_json());
1599 }
1600
1601 #[test]
1602 fn plugin_channel_round_trips_and_is_capped() {
1603 let c = ClientMsg::Plugin { plugin: "sheets".into(), msg: serde_json::json!({"op": "get", "cell": "A1"}) };
1604 assert_eq!(c.to_json(), r#"{"type":"plugin","plugin":"sheets","msg":{"cell":"A1","op":"get"}}"#);
1605 assert_eq!(ClientMsg::from_json(&c.to_json()).unwrap(), c);
1606 assert!(c.check_sizes().is_ok());
1607 let s = ServerMsg::Plugin { plugin: "sheets".into(), msg: serde_json::json!([1, 2]) };
1608 assert_eq!(ServerMsg::from_json(&s.to_json()).unwrap(), s);
1609 for bad in [
1610 ClientMsg::Plugin { plugin: "Not/an id".into(), msg: serde_json::Value::Null },
1611 ClientMsg::Plugin { plugin: "sheets".into(), msg: serde_json::Value::String("x".repeat(version::MAX_PLUGIN_MSG_BYTES)) },
1612 ] {
1613 assert!(bad.check_sizes().is_err());
1614 }
1615 }
1616
1617 #[test]
1618 fn question_cards_round_trip_and_older_asks_still_parse() {
1619 let c = ClientMsg::AnswerQuestion { step: 4, text: "Metric".into() };
1620 assert_eq!(c.to_json(), r#"{"type":"answer_question","step":4,"text":"Metric"}"#);
1621 assert_eq!(ClientMsg::from_json(&c.to_json()).unwrap(), c);
1622 assert!(c.check_sizes().is_ok());
1623 assert!(ClientMsg::AnswerQuestion { step: 4, text: "x".repeat(MAX_ANSWER_CHARS + 1) }.check_sizes().is_err());
1624 let ask = Ask {
1625 text: "Which units?".into(),
1626 warning: None,
1627 always: true,
1628 choice: Some(Choice { options: vec!["Metric".into(), "Imperial".into()], free_text: true, answer: None }),
1629 card: None,
1630 };
1631 let json = serde_json::to_string(&ask).unwrap();
1632 assert_eq!(serde_json::from_str::<Ask>(&json).unwrap(), ask);
1633 let old: Ask = serde_json::from_str(r#"{"text":"t","always":true}"#).unwrap();
1635 assert!(old.choice.is_none());
1636 assert!(!serde_json::to_string(&old).unwrap().contains("choice"));
1637 }
1638
1639 #[test]
1641 fn unknown_messages_and_enum_values_decode_to_fallbacks() {
1642 assert_eq!(ServerMsg::from_json(r#"{"type":"hologram","x":1,"y":{"z":[]}}"#).unwrap(), ServerMsg::Unknown);
1643 assert_eq!(ClientMsg::from_json(r#"{"type":"teleport","to":"mars"}"#).unwrap(), ClientMsg::Unknown);
1644 assert!(ServerMsg::from_json(r#"{"type":"notice","level":"info"}"#).is_err());
1646 let n = ServerMsg::from_json(r#"{"type":"notice","level":"debug","text":"t"}"#).unwrap();
1647 assert_eq!(n, ServerMsg::Notice { level: NoticeLevel::Info, text: "t".into() });
1648 let a = ClientMsg::from_json(r#"{"type":"approve","step":1,"answer":"maybe_later"}"#).unwrap();
1649 assert_eq!(a, ClientMsg::Approve { step: 1, answer: ApprovalAnswer::Unknown });
1650 let json = r#"{"id":1,"tool":"t","title":"T","access":"read","status":"done","detail":"",
1652 "changes":[{"kind":"chmod","path":"a","mode":"755"}],
1653 "preview":{"kind":"hexdump","bytes":"00"},
1654 "media":[{"kind":"video","path":"a.mp4"}],
1655 "views":[{"kind":"sheets.grid","v":4,"data":{"rows":[]},"fallback":"a *grid*"}]}"#;
1656 let s: Step = serde_json::from_str(json).unwrap();
1657 assert_eq!((s.changes.clone(), s.preview.clone()), (vec![FileChange::Other], Some(Preview::Other)));
1658 assert_eq!(s.media[0].kind, MediaKind::File);
1659 assert_eq!((s.views[0].kind.as_str(), s.views[0].fallback.as_str()), ("sheets.grid", "a *grid*"));
1660 assert!(s.view::<PluginCard>().is_none());
1661 let art: Artifact = serde_json::from_str(r#"{"id":"a","kind":"spreadsheet","title":"A","filename":"a.xlsx","versions":[]}"#).unwrap();
1662 assert_eq!(art.kind, ArtifactKind::Text);
1663 assert_eq!(serde_json::from_str::<SlashKind>(r#""macro""#).unwrap(), SlashKind::Other);
1664 assert_eq!(serde_json::from_str::<PluginAction>(r#""forked""#).unwrap(), PluginAction::Other);
1665 let env = ClientMsg::from_json(r#"{"type":"workspace_env","action":{"kind":"rebuild","fast":true}}"#).unwrap();
1666 assert_eq!(env, ClientMsg::WorkspaceEnv { action: Some(EnvAction::Unsupported), workspace: None });
1667 let d = ServerMsg::from_json(r#"{"type":"delegation","entry":1,"step":2,"update":{"kind":"progress","pct":5}}"#).unwrap();
1668 assert_eq!(d, ServerMsg::Delegation { entry: 1, step: 2, update: DelegationUpdate::Other });
1669 }
1670
1671 #[test]
1672 fn plugin_cards_travel_as_views() {
1673 let card = PluginCard {
1674 plugin: "scratch".into(),
1675 scope: PluginScope::Chat,
1676 action: PluginAction::Made,
1677 tools: vec!["shout".into()],
1678 added: vec!["shout".into()],
1679 removed: vec![],
1680 test: Some(plugins::PluginTest { ok: true, output: "HI".into() }),
1681 problems: vec![],
1682 missing_settings: vec![],
1683 };
1684 let mut s = step(1, StepStatus::Done);
1685 s.views.push(View::of(&card));
1686 let json = ServerMsg::StepUpdated { entry: 1, step: s }.to_json();
1687 assert!(json.contains(r#""views":[{"kind":"byob.plugin_card","v":1,"data":{"action":"made""#), "{json}");
1688 let ServerMsg::StepUpdated { step: back, .. } = ServerMsg::from_json(&json).unwrap() else { panic!() };
1689 assert_eq!(back.view::<PluginCard>(), Some(card));
1690 assert!(back.views[0].fallback.contains("**Plugin scratch** (this chat) · tool made") && back.views[0].fallback.contains("shout"));
1691 assert!(!ServerMsg::StepUpdated { entry: 1, step: step(2, StepStatus::Done) }.to_json().contains("views"));
1693 }
1694
1695 #[test]
1696 fn state_never_carries_api_key() {
1697 let json = serde_json::to_string(&EngineState::default()).unwrap();
1698 assert!(!json.contains("\"api_key\""));
1699 }
1700}