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 Cancel,
108 Unqueue {
110 id: u64,
111 },
112 EditQueued {
115 id: u64,
116 text: String,
117 #[serde(default, skip_serializing_if = "Vec::is_empty")]
118 attachments: Vec<String>,
119 },
120 MoveQueued {
122 id: u64,
123 to: u32,
124 },
125 SendQueuedNow {
127 id: u64,
128 },
129 ResumeQueue,
131 Approve {
134 step: u64,
135 answer: ApprovalAnswer,
136 },
137 AnswerQuestion {
141 step: u64,
142 text: String,
143 },
144 Undo {
147 entry: u64,
148 },
149 ListChats {
152 after: Option<ChatCursor>,
153 limit: u32,
154 },
155 NewChat {
159 #[serde(default, skip_serializing_if = "Option::is_none")]
160 workspace: Option<String>,
161 },
162 NewUnattachedChat,
167 ChatToProject {
171 chat: String,
172 },
173 OpenChat {
175 id: String,
176 },
177 RenameChat {
178 id: String,
179 title: String,
180 },
181 DeleteChat {
183 id: String,
184 },
185 PinChat {
187 id: String,
188 pinned: bool,
189 },
190 ArchiveChat {
193 id: String,
194 archived: bool,
195 },
196 ListLibrary,
199 GetPluginLogo {
202 plugin: String,
203 },
204 GetLibraryFile {
207 chat: String,
208 id: String,
209 version: u32,
210 },
211 DeleteArtifact {
214 chat: String,
215 id: String,
216 },
217 RevealArtifact {
220 chat: String,
221 id: String,
222 },
223 RevealChatFolder {
226 chat: String,
227 },
228 AddLiveFile {
232 path: String,
233 },
234 Upload {
239 upload: u64,
240 name: String,
241 size: u64,
242 offset: u64,
243 data: String,
244 done: bool,
245 },
246 GetMedia {
248 path: String,
249 },
250 GetArtifact {
253 id: String,
254 version: u32,
255 },
256 SetArtifactNetwork {
260 id: String,
261 on: bool,
262 },
263 Compact {
266 #[serde(default, skip_serializing_if = "Option::is_none")]
267 focus: Option<String>,
268 },
269 WorkspaceEnv {
272 #[serde(default, skip_serializing_if = "Option::is_none")]
273 action: Option<EnvAction>,
274 #[serde(default, skip_serializing_if = "Option::is_none")]
275 workspace: Option<String>,
276 },
277 CreateWorkspace {
281 name: String,
282 folder: NewFolder,
283 #[serde(default)]
284 config: workspace::Layer,
285 #[serde(default, skip_serializing_if = "Vec::is_empty")]
287 folders: Vec<String>,
288 },
289 SetWorkspaceFolders {
293 id: String,
294 folders: Vec<String>,
295 },
296 RenameWorkspace {
297 id: String,
298 name: String,
299 },
300 RemoveWorkspace {
303 id: String,
304 #[serde(default)]
305 clean: bool,
306 },
307 GetConfig {
309 scope: ConfigScope,
310 },
311 SetConfig {
315 scope: ConfigScope,
316 layer: workspace::Layer,
317 #[serde(default, skip_serializing_if = "Option::is_none")]
318 api_key: Option<String>,
319 },
320 ListFolders {
323 #[serde(default, skip_serializing_if = "Option::is_none")]
324 path: Option<String>,
325 },
326 CheckContainers,
328 GetExtensions,
330 SetPluginEnabled {
334 scope: ConfigScope,
335 plugin: String,
336 enabled: Option<bool>,
337 },
338 SetPluginSetting {
342 plugin: String,
343 key: String,
344 value: Option<String>,
345 },
346 KeepPlugin {
350 plugin: String,
351 scope: PluginScope,
352 #[serde(default, skip_serializing_if = "Option::is_none")]
353 new_id: Option<String>,
354 },
355 RemovePlugin {
358 plugin: String,
359 scope: PluginScope,
360 },
361 ReloadPlugins,
363 TrustPlugins {
367 workspace: String,
368 #[serde(default)]
369 plugins: Vec<String>,
370 trust: bool,
371 },
372 Plugin {
375 plugin: String,
376 msg: serde_json::Value,
377 },
378 OpenView {
382 view: ViewRef,
383 },
384 CloseView {
386 view: ViewRef,
387 },
388 ViewEvent {
391 view: ViewRef,
392 event: tree::Event,
393 },
394 WebCall {
399 call: u64,
400 owner: web::WebOwner,
401 method: String,
402 #[serde(default)]
403 params: serde_json::Value,
404 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
405 approved: bool,
406 },
407 GetProfiles,
410 CreateProfile {
413 profile: Profile,
414 #[serde(default, skip_serializing_if = "Option::is_none")]
415 api_key: Option<String>,
416 #[serde(default, skip_serializing_if = "Option::is_none")]
417 assign: Option<ConfigScope>,
418 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
419 make_main: bool,
420 },
421 UpdateProfile {
424 profile: Profile,
425 #[serde(default, skip_serializing_if = "Option::is_none")]
426 api_key: Option<String>,
427 },
428 DeleteProfile {
431 id: String,
432 },
433 DuplicateProfile {
435 id: String,
436 },
437 SetRole {
440 role: String,
441 profile: Option<String>,
442 },
443 TestProfile {
445 id: String,
446 },
447 SetLevelProfile {
450 scope: ConfigScope,
451 profile: Option<String>,
452 },
453 SetKeepRunning {
457 value: byob_types::desktop::KeepRunning,
458 },
459 SetLayout {
462 layout: layout::Layout,
463 },
464 ReportLook(look::LookReport),
467 Captured {
471 request: u64,
472 #[serde(default, skip_serializing_if = "Option::is_none")]
473 image: Option<String>,
474 #[serde(default, skip_serializing_if = "Option::is_none")]
475 error: Option<String>,
476 },
477 SaveRoutine {
480 routine: routines::Routine,
481 },
482 DeleteRoutine {
484 id: String,
485 },
486 RunRoutine {
488 id: String,
489 },
490 SetRoutineEnabled {
492 id: String,
493 enabled: bool,
494 },
495 ListRoutineRuns {
497 id: String,
498 },
499 PauseRoutines {
504 paused: bool,
505 },
506 PairPhone {
510 channel: String,
511 },
512 CancelPairing,
514 UnpairPhone,
516 TestPhone,
518 #[serde(other)]
520 Unknown,
521}
522
523#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
525#[serde(tag = "type", rename_all = "snake_case")]
526pub enum ServerMsg {
527 Welcome(Welcome),
529 State(EngineState),
531 Notice { level: NoticeLevel, text: String },
533 Transcript { entries: Vec<Entry> },
535 EntryAdded(Entry),
537 EntryDelta { id: u64, content: String, reasoning: String },
539 EntryFinished { id: u64, error: Option<String>, stats: Option<TurnStats> },
541 StepUpdated { entry: u64, step: Step },
543 EntryUndo { id: u64, undoable: bool, undone: bool },
545 Chats { pinned: Vec<ChatSummary>, recent: Vec<ChatSummary>, after: Option<ChatCursor>, next: Option<ChatCursor> },
548 ChatUpdated(ChatSummary),
550 ChatDeleted { id: String },
552 ChatOpened {
556 chat: Option<ChatSummary>,
557 #[serde(default)]
558 workspace: Option<String>,
559 },
560 Uploaded { upload: u64, attachment: Option<MediaRef>, error: Option<String> },
562 Media { path: String, content: MediaContent },
564 Artifacts { chat: Option<String>, artifacts: Vec<Artifact> },
567 Library { items: Vec<LibraryItem> },
570 PluginLogo { plugin: String, data: Option<String> },
572 LibraryFile { chat: String, id: String, version: u32, data: Option<String>, error: Option<String> },
574 ArtifactUpdated(Artifact),
576 ArtifactFile { id: String, version: u32, data: Option<String>, error: Option<String> },
578 Usage(ChatUsage),
580 Compactions { chat: Option<String>, items: Vec<Compaction> },
583 Compacted(Compaction),
585 Delegation { entry: u64, step: u64, update: DelegationUpdate },
587 InferenceTested(InferenceTest),
589 WorkspaceEnv(WorkspaceEnv),
591 Workspaces { items: Vec<WorkspaceSummary>, current: Option<String>, root: String, support: EnvSupport },
595 Config(Box<ConfigView>),
597 Folders(FolderList),
599 ContainersChecked { ok: bool, message: String },
601 WorkspaceCreated { id: Option<String>, error: Option<String> },
603 Queue(ChatQueue),
606 Extensions(Box<Extensions>),
609 Plugin { plugin: String, msg: serde_json::Value },
612 LiveView(LiveView),
615 WebReply {
618 call: u64,
619 #[serde(default, deserialize_with = "present_even_if_null", skip_serializing_if = "Option::is_none")]
621 result: Option<serde_json::Value>,
622 #[serde(default, skip_serializing_if = "Option::is_none")]
623 error: Option<web::WebError>,
624 },
625 WebPush { owner: web::WebOwner, msg: serde_json::Value },
628 Profiles(Box<ProfileList>),
631 ProfileTested(ProfileTest),
633 Layout(layout::Layout),
636 SetLook { request: u64, changes: look::LookChanges },
640 Capture { request: u64 },
643 Routines { items: Vec<RoutineView> },
646 RoutineRuns { routine: String, runs: Vec<routines::RunRecord> },
648 RoutineEvent {
651 routine: String,
652 #[serde(default)]
654 name: String,
655 #[serde(default, skip_serializing_if = "Option::is_none")]
657 chat: Option<String>,
658 kind: RoutineEventKind,
659 title: String,
660 #[serde(default)]
661 body: String,
662 },
663 Phone(phone::PhoneState),
666 #[serde(other)]
668 Unknown,
669}
670
671#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
673pub struct ChatSummary {
674 pub id: String,
675 pub title: String,
676 pub updated_at: i64,
678 pub pinned_at: Option<i64>,
680 #[serde(default)]
682 pub busy: bool,
683 #[serde(default, skip_serializing_if = "Option::is_none")]
685 pub workspace: Option<String>,
686 #[serde(default, skip_serializing_if = "Option::is_none")]
688 pub archived_at: Option<i64>,
689 #[serde(default, skip_serializing_if = "Option::is_none")]
691 pub origin: Option<String>,
692}
693
694impl ChatSummary {
695 pub fn cursor(&self) -> ChatCursor {
696 ChatCursor { updated_at: self.updated_at, id: self.id.clone() }
697 }
698}
699
700#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
702pub struct ChatCursor {
703 pub updated_at: i64,
704 pub id: String,
705}
706
707#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
708#[serde(rename_all = "snake_case")]
709pub enum EntryRole {
710 User,
711 Assistant,
712}
713
714#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
716pub struct Entry {
717 pub id: u64,
718 pub role: EntryRole,
719 pub content: String,
720 pub reasoning: String,
721 pub done: bool,
723 pub error: Option<String>,
724 pub stats: Option<TurnStats>,
725 #[serde(default)]
728 pub steps: Vec<Step>,
729 #[serde(default)]
731 pub undoable: bool,
732 #[serde(default)]
734 pub undone: bool,
735 #[serde(default, skip_serializing_if = "Vec::is_empty")]
737 pub attachments: Vec<MediaRef>,
738}
739
740impl Entry {
741 pub fn append(&mut self, content: &str, reasoning: &str) {
743 self.content.push_str(content);
744 self.reasoning.push_str(reasoning);
745 }
746
747 pub fn upsert_step(&mut self, step: Step) {
749 match self.steps.iter_mut().find(|s| s.id == step.id) {
750 Some(existing) => *existing = step,
751 None => self.steps.push(step),
752 }
753 }
754
755 pub fn pending_approvals(&self) -> impl Iterator<Item = &Step> {
757 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)
758 }
759
760 pub fn apply_delegation(&mut self, step: u64, update: &DelegationUpdate) {
762 if let Some(d) = self.steps.iter_mut().find(|s| s.id == step).and_then(|s| s.delegation.as_deref_mut()) {
763 d.apply(update);
764 }
765 }
766}
767
768#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
770#[serde(rename_all = "snake_case")]
771pub enum ToolAccess {
772 Read,
773 Write,
774 Network,
775 Execute,
776}
777
778impl ToolAccess {
779 pub fn label(self) -> &'static str {
780 match self {
781 Self::Read => "read",
782 Self::Write => "write",
783 Self::Network => "network",
784 Self::Execute => "execute",
785 }
786 }
787}
788
789#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
790#[serde(rename_all = "snake_case")]
791pub enum StepStatus {
792 Running,
793 Waiting,
795 Done,
796 Failed,
798 Denied,
800}
801
802impl StepStatus {
803 pub fn finished(self) -> bool {
804 matches!(self, Self::Done | Self::Failed | Self::Denied)
805 }
806}
807
808#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
810#[serde(rename_all = "snake_case")]
811pub enum ApprovalAnswer {
812 Allow,
813 Always,
815 Deny,
816 AlwaysEverywhere,
818 #[serde(other)]
820 Unknown,
821}
822
823#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
825#[serde(tag = "kind", rename_all = "snake_case")]
826pub enum FileChange {
827 Created {
828 path: String,
829 },
830 Modified {
831 path: String,
832 },
833 Deleted {
834 path: String,
835 },
836 Moved {
837 from: String,
838 to: String,
839 },
840 #[serde(other)]
842 Other,
843}
844
845#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
847pub struct Step {
848 pub id: u64,
850 pub tool: String,
852 pub title: String,
854 pub access: ToolAccess,
855 pub status: StepStatus,
856 pub detail: String,
858 #[serde(default)]
859 pub changes: Vec<FileChange>,
860 #[serde(default)]
862 pub at: usize,
863 #[serde(default, skip_serializing_if = "Vec::is_empty")]
865 pub media: Vec<MediaRef>,
866 #[serde(default, skip_serializing_if = "Option::is_none")]
868 pub preview: Option<Preview>,
869 #[serde(default, skip_serializing_if = "Vec::is_empty")]
871 pub artifacts: Vec<ArtifactRef>,
872 #[serde(default, skip_serializing_if = "Option::is_none")]
874 pub delegation: Option<Box<Delegation>>,
875 #[serde(default, skip_serializing_if = "Option::is_none")]
879 pub ask: Option<Box<Ask>>,
880 #[serde(default, skip_serializing_if = "Vec::is_empty")]
884 pub views: Vec<View>,
885}
886
887impl Step {
888 pub fn view<T: ViewData>(&self) -> Option<T> {
890 self.views.iter().find_map(View::get)
891 }
892}
893
894#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
896pub struct Ask {
897 #[serde(default)]
899 pub text: String,
900 #[serde(default, skip_serializing_if = "Option::is_none")]
902 pub warning: Option<String>,
903 #[serde(default)]
905 pub always: bool,
906 #[serde(default, skip_serializing_if = "Option::is_none")]
910 pub choice: Option<Choice>,
911 #[serde(default, skip_serializing_if = "Option::is_none")]
914 pub card: Option<CardWords>,
915}
916
917#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
919pub struct CardWords {
920 #[serde(default)]
922 pub access: String,
923 #[serde(default, skip_serializing_if = "Option::is_none")]
925 pub allow: Option<String>,
926 #[serde(default, skip_serializing_if = "Option::is_none")]
928 pub deny: Option<String>,
929}
930
931pub const MAX_CHOICE_OPTIONS: usize = 8;
933pub const MAX_ANSWER_CHARS: usize = 2000;
935
936#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
938pub struct Choice {
939 #[serde(default, skip_serializing_if = "Vec::is_empty")]
941 pub options: Vec<String>,
942 #[serde(default)]
944 pub free_text: bool,
945 #[serde(default, skip_serializing_if = "Option::is_none")]
947 pub answer: Option<String>,
948}
949
950pub const MAX_PREVIEW_LINES: usize = 40;
952pub const MAX_PREVIEW_LINE_CHARS: usize = 300;
954
955#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
957#[serde(tag = "kind", rename_all = "snake_case")]
958pub enum Preview {
959 Write {
962 path: String,
963 bytes: u64,
964 replaces: bool,
966 lines: Vec<DiffLine>,
967 #[serde(default)]
969 more: usize,
970 },
971 Move {
973 moves: Vec<(String, String)>,
974 #[serde(default)]
975 more: usize,
976 },
977 Delete { path: String, what: String },
979 Args {
981 fields: Vec<(String, String)>,
982 #[serde(default, skip_serializing_if = "Option::is_none")]
983 code: Option<String>,
984 #[serde(default)]
985 more: usize,
986 },
987 #[serde(other)]
989 Other,
990}
991
992#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
994pub struct DiffLine {
995 pub kind: LineKind,
996 pub text: String,
997}
998
999#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1000#[serde(rename_all = "snake_case")]
1001pub enum LineKind {
1002 Same,
1004 Added,
1005 Removed,
1006 Skipped,
1008}
1009
1010#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
1011pub struct TurnStats {
1012 pub prompt_tokens: u64,
1013 pub completion_tokens: u64,
1014 pub elapsed_ms: u64,
1015 #[serde(default)]
1017 pub model_calls: u64,
1018 #[serde(default, skip_serializing_if = "is_zero")]
1022 pub context_tokens: u64,
1023}
1024
1025fn is_zero(n: &u64) -> bool {
1026 *n == 0
1027}
1028
1029#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1030#[serde(rename_all = "snake_case")]
1031pub enum NoticeLevel {
1032 Error,
1033 #[serde(other)]
1035 Info,
1036}
1037
1038#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1040pub struct EngineState {
1041 pub version: String,
1042 pub inference_base_url: String,
1043 pub inference_model: String,
1044 pub has_api_key: bool,
1045 pub endpoint: Option<String>,
1047 pub busy: bool,
1049 #[serde(default)]
1051 pub endpoint_info: Option<EndpointInfo>,
1052 #[serde(default)]
1054 pub link: Link,
1055 #[serde(default)]
1058 pub onboarded: bool,
1059 #[serde(default)]
1061 pub detected: Vec<Detected>,
1062 #[serde(default)]
1064 pub detecting: bool,
1065 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1067 pub yolo: bool,
1068 #[serde(default, skip_serializing_if = "Option::is_none")]
1071 pub chat_endpoint: Option<ChatEndpoint>,
1072 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1074 pub routines_active: bool,
1075 #[serde(default, skip_serializing_if = "Option::is_none")]
1078 pub keep_running: Option<byob_types::desktop::KeepRunning>,
1079 #[serde(default, skip_serializing_if = "Option::is_none")]
1082 pub routines_paused: Option<bool>,
1083}
1084
1085#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1087#[serde(rename_all = "snake_case")]
1088pub enum ToolsMode {
1089 Native,
1091 Prompt,
1093 #[default]
1095 Unknown,
1096}
1097
1098#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1100pub struct EndpointInfo {
1101 #[serde(default)]
1103 pub probing: bool,
1104 #[serde(default)]
1106 pub server: String,
1107 #[serde(default)]
1109 pub context_tokens: Option<u64>,
1110 #[serde(default)]
1111 pub tools: ToolsMode,
1112 #[serde(default)]
1114 pub vision: Option<bool>,
1115 #[serde(default, skip_serializing_if = "Option::is_none")]
1117 pub slots: Option<u64>,
1118}
1119
1120impl EndpointInfo {
1121 pub fn summary(&self) -> String {
1123 if self.probing {
1124 return "checking endpoint…".into();
1125 }
1126 let mut parts = Vec::new();
1127 if !self.server.is_empty() {
1128 parts.push(self.server.clone());
1129 }
1130 if let Some(n) = self.context_tokens {
1131 parts.push(if n >= 1000 { format!("{}k ctx", n / 1000) } else { format!("{n} ctx") });
1132 }
1133 parts.push(
1134 match self.tools {
1135 ToolsMode::Native => "native tools",
1136 ToolsMode::Prompt => "prompt tools",
1137 ToolsMode::Unknown => "tools untested",
1138 }
1139 .into(),
1140 );
1141 if self.vision == Some(true) {
1142 parts.push("vision".into());
1143 }
1144 if let Some(n) = self.slots.filter(|n| *n > 1) {
1145 parts.push(format!("{n} slots"));
1146 }
1147 parts.join(" · ")
1148 }
1149}
1150
1151impl ClientMsg {
1152 pub fn hello(client: &str) -> Self {
1154 Self::Hello { protocol: PROTOCOL_MAJOR, minor: PROTOCOL_MINOR, client: client.to_owned(), caps: version::client_caps() }
1155 }
1156
1157 pub fn to_json(&self) -> String {
1158 serde_json::to_string(self).unwrap_or_default()
1159 }
1160
1161 pub fn from_json(text: &str) -> Result<Self, String> {
1163 if text.len() > MAX_FRAME_BYTES {
1164 return Err(format!("frame too large ({} bytes)", text.len()));
1165 }
1166 serde_json::from_str(text).map_err(|e| e.to_string())
1167 }
1168}
1169
1170impl ServerMsg {
1171 pub fn to_json(&self) -> String {
1172 serde_json::to_string(self).unwrap_or_default()
1173 }
1174
1175 pub fn to_frame(&self) -> String {
1181 let json = self.to_json();
1182 if json.len() <= MAX_FRAME_BYTES {
1183 return json;
1184 }
1185 let why = format!("it is too large to send over this connection ({} KB, at most {} KB)", json.len() / 1024, MAX_FRAME_BYTES / 1024);
1186 let instead = match self {
1187 Self::LiveView(lv) if lv.tree.is_none() => Self::LiveView(LiveView { view: lv.view.clone(), reset: true, ..Default::default() }),
1188 Self::LiveView(lv) => {
1189 Self::LiveView(LiveView { view: lv.view.clone(), error: Some(format!("This view can't be shown here: {why}.")), ..Default::default() })
1190 }
1191 Self::WebReply { call, .. } => {
1192 Self::WebReply { call: *call, result: None, error: Some(web::WebError::new(-32000, format!("byob couldn't send the answer: {why}"))) }
1193 }
1194 _ => Self::Notice { level: NoticeLevel::Error, text: format!("byob couldn't send an update: {why}.") },
1195 };
1196 instead.to_json()
1197 }
1198
1199 pub fn from_json(text: &str) -> Result<Self, String> {
1201 if text.len() > MAX_FRAME_BYTES {
1202 return Err(format!("frame too large ({} bytes)", text.len()));
1203 }
1204 serde_json::from_str(text).map_err(|e| e.to_string())
1205 }
1206}
1207
1208pub trait Connection {
1210 fn send(&mut self, msg: ClientMsg);
1211 fn try_recv(&mut self) -> Option<ServerMsg>;
1213}
1214
1215fn present_even_if_null<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<serde_json::Value>, D::Error> {
1218 serde_json::Value::deserialize(d).map(Some)
1219}
1220
1221#[cfg(test)]
1222mod tests {
1223 use super::*;
1224
1225 #[test]
1228 fn web_reply_keeps_a_null_result() {
1229 let null = ServerMsg::WebReply { call: 3, result: Some(serde_json::Value::Null), error: None };
1230 assert_eq!(null.to_json(), r#"{"type":"web_reply","call":3,"result":null}"#);
1231 assert_eq!(ServerMsg::from_json(&null.to_json()).unwrap(), null);
1232 let none = ServerMsg::WebReply { call: 3, result: None, error: None };
1233 assert_eq!(none.to_json(), r#"{"type":"web_reply","call":3}"#);
1234 assert_eq!(ServerMsg::from_json(&none.to_json()).unwrap(), none);
1235 let value = ServerMsg::WebReply { call: 3, result: Some(serde_json::json!({"a": [1]})), error: None };
1236 assert_eq!(ServerMsg::from_json(&value.to_json()).unwrap(), value);
1237 }
1238
1239 #[test]
1240 fn client_msg_round_trips() {
1241 let m = ClientMsg::hello("test");
1242 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1243 }
1244
1245 #[test]
1246 fn wire_format_is_tagged() {
1247 let json = ServerMsg::Notice { level: NoticeLevel::Info, text: "hi".into() }.to_json();
1248 assert_eq!(json, r#"{"type":"notice","level":"info","text":"hi"}"#);
1249 }
1250
1251 #[test]
1252 fn a_message_too_large_for_a_frame_is_sent_as_something_the_client_acts_on() {
1253 let big = "x".repeat(MAX_FRAME_BYTES);
1254 let r = ViewRef::new("p", "v", "k");
1255 let small = ServerMsg::Notice { level: NoticeLevel::Info, text: "hi".into() };
1256 assert_eq!(small.to_frame(), small.to_json());
1257 let frame = |m: ServerMsg| {
1258 let f = m.to_frame();
1259 assert!(f.len() < 1024, "{} bytes", f.len());
1260 ServerMsg::from_json(&f).unwrap()
1261 };
1262 let mut values = serde_json::Map::new();
1263 values.insert("f".into(), serde_json::json!(big));
1264 let change = LiveView { view: r.clone(), values, ..Default::default() };
1265 assert_eq!(frame(ServerMsg::LiveView(change)), ServerMsg::LiveView(LiveView { view: r.clone(), reset: true, ..Default::default() }));
1266 let texts: Vec<_> = (0..100).map(|_| serde_json::json!({"type": "text", "text": "y".repeat(60_000)})).collect();
1268 let (tree, faults) = tree::decode(serde_json::json!({"type": "column", "children": texts}));
1269 assert!(faults.is_empty(), "{faults:?}");
1270 match frame(ServerMsg::LiveView(LiveView { view: r.clone(), tree: Some(tree), ..Default::default() })) {
1271 ServerMsg::LiveView(lv) => assert!(lv.view == r && lv.tree.is_none() && lv.error.is_some_and(|e| e.contains("too large"))),
1272 other => panic!("{other:?}"),
1273 }
1274 match frame(ServerMsg::WebReply { call: 9, result: Some(serde_json::json!(big)), error: None }) {
1275 ServerMsg::WebReply { call: 9, result: None, error: Some(e) } => assert!(e.message.contains("too large")),
1276 other => panic!("{other:?}"),
1277 }
1278 let plugin = ServerMsg::Plugin { plugin: "p".into(), msg: serde_json::json!(big) };
1279 assert!(matches!(frame(plugin), ServerMsg::Notice { level: NoticeLevel::Error, .. }));
1280 }
1281
1282 #[test]
1283 fn rejects_garbage_and_oversized_frames() {
1284 assert!(ClientMsg::from_json("{not json").is_err());
1285 assert!(ClientMsg::from_json(&" ".repeat(MAX_FRAME_BYTES + 1)).is_err());
1286 }
1287
1288 #[test]
1289 fn approve_wire_format() {
1290 let m = ClientMsg::Approve { step: 7, answer: ApprovalAnswer::Always };
1291 assert_eq!(m.to_json(), r#"{"type":"approve","step":7,"answer":"always"}"#);
1292 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1293 }
1294
1295 fn step(id: u64, status: StepStatus) -> Step {
1296 Step {
1297 id,
1298 tool: "t".into(),
1299 title: "T".into(),
1300 access: ToolAccess::Write,
1301 status,
1302 detail: String::new(),
1303 changes: vec![],
1304 at: 0,
1305 preview: None,
1306 media: vec![],
1307 artifacts: vec![],
1308 delegation: None,
1309 ask: None,
1310 views: vec![],
1311 }
1312 }
1313
1314 #[test]
1315 fn delegations_stream_into_their_step_and_round_trip() {
1316 let mut parent = step(1, StepStatus::Running);
1317 parent.delegation = Some(Box::new(Delegation { agent: "explorer".into(), task: "count lines".into(), ..Default::default() }));
1318 let mut e = Entry {
1319 id: 9,
1320 role: EntryRole::Assistant,
1321 content: String::new(),
1322 reasoning: String::new(),
1323 done: false,
1324 error: None,
1325 stats: None,
1326 steps: vec![parent],
1327 undoable: false,
1328 undone: false,
1329 attachments: vec![],
1330 };
1331 let updates = [
1332 DelegationUpdate::Status { state: DelegationState::Running, prompt_tokens: 0, completion_tokens: 0, error: None },
1333 DelegationUpdate::Delta { content: "Reading".into(), reasoning: "hm".into() },
1334 DelegationUpdate::Step(Box::new(step(2, StepStatus::Waiting))),
1335 DelegationUpdate::Delta { content: " a.txt".into(), reasoning: String::new() },
1336 ];
1337 for u in &updates {
1338 let msg = ServerMsg::Delegation { entry: 9, step: 1, update: u.clone() };
1339 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1340 e.apply_delegation(1, u);
1341 }
1342 e.apply_delegation(77, &updates[1]);
1344 let d = e.steps[0].delegation.as_deref().unwrap();
1345 assert_eq!((d.content.as_str(), d.reasoning.as_str(), d.state), ("Reading a.txt", "hm", DelegationState::Running));
1346 assert_eq!(d.status_line(), "explorer · 1 tool · waiting for approval");
1347 assert_eq!(e.pending_approvals().map(|s| s.id).collect::<Vec<_>>(), vec![2]);
1349 e.apply_delegation(1, &DelegationUpdate::Step(Box::new(step(2, StepStatus::Done))));
1350 e.apply_delegation(1, &DelegationUpdate::Status { state: DelegationState::Done, prompt_tokens: 50, completion_tokens: 5, error: None });
1351 assert_eq!(e.steps[0].delegation.as_deref().unwrap().status_line(), "explorer · 1 tool · done");
1352 assert_eq!(e.pending_approvals().count(), 0);
1353 let msg = ServerMsg::StepUpdated { entry: 9, step: e.steps[0].clone() };
1354 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1355 let json = r#"{"id":1,"tool":"t","title":"T","access":"read","status":"done","detail":""}"#;
1357 assert!(serde_json::from_str::<Step>(json).unwrap().delegation.is_none());
1358 }
1359
1360 #[test]
1361 fn steps_upsert_and_round_trip() {
1362 let mut e = Entry {
1363 id: 1,
1364 role: EntryRole::Assistant,
1365 content: String::new(),
1366 reasoning: String::new(),
1367 done: false,
1368 error: None,
1369 stats: None,
1370 steps: vec![],
1371 undoable: false,
1372 undone: false,
1373 attachments: vec![],
1374 };
1375 e.upsert_step(step(3, StepStatus::Running));
1376 e.upsert_step(step(4, StepStatus::Waiting));
1377 e.upsert_step(step(3, StepStatus::Done));
1378 assert_eq!(e.steps.len(), 2);
1379 assert_eq!(e.steps[0].status, StepStatus::Done);
1380 assert_eq!(e.pending_approvals().map(|s| s.id).collect::<Vec<_>>(), vec![4]);
1381 let mut s = step(5, StepStatus::Done);
1382 s.changes = vec![FileChange::Moved { from: "a".into(), to: "b".into() }];
1383 let msg = ServerMsg::StepUpdated { entry: 1, step: s };
1384 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1385 }
1386
1387 #[test]
1388 fn entry_without_steps_still_parses() {
1389 let json = r#"{"id":1,"role":"user","content":"hi","reasoning":"","done":true,"error":null,"stats":null}"#;
1390 let e: Entry = serde_json::from_str(json).unwrap();
1391 assert!(e.steps.is_empty());
1392 }
1393
1394 #[test]
1395 fn undo_and_preview_wire_format() {
1396 let m = ClientMsg::Undo { entry: 4 };
1397 assert_eq!(m.to_json(), r#"{"type":"undo","entry":4}"#);
1398 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1399 let mut s = step(1, StepStatus::Waiting);
1400 s.preview =
1401 Some(Preview::Write { path: "a.md".into(), bytes: 3, replaces: true, lines: vec![DiffLine { kind: LineKind::Added, text: "hi".into() }], more: 0 });
1402 let msg = ServerMsg::StepUpdated { entry: 1, step: s };
1403 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1404 let msg = ServerMsg::EntryUndo { id: 1, undoable: false, undone: true };
1405 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1406 }
1407
1408 #[test]
1409 fn chat_messages_round_trip() {
1410 let summary = ChatSummary {
1411 id: "c1".into(),
1412 title: "Plans".into(),
1413 updated_at: 5,
1414 pinned_at: None,
1415 busy: true,
1416 workspace: Some("w1".into()),
1417 archived_at: None,
1418 origin: None,
1419 };
1420 for m in [
1421 ServerMsg::Chats { pinned: vec![], recent: vec![summary.clone()], after: None, next: Some(summary.cursor()) },
1422 ServerMsg::ChatUpdated(summary.clone()),
1423 ServerMsg::ChatOpened { chat: Some(summary), workspace: None },
1424 ServerMsg::ChatDeleted { id: "c1".into() },
1425 ] {
1426 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1427 }
1428 let m = ClientMsg::ListChats { after: Some(ChatCursor { updated_at: 1, id: "x".into() }), limit: 50 };
1429 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1430 assert_eq!(ClientMsg::NewChat { workspace: None }.to_json(), r#"{"type":"new_chat"}"#);
1431 }
1432
1433 #[test]
1434 fn endpoint_info_is_optional_and_summarized() {
1435 let old = r#"{"version":"0","inference_base_url":"u","inference_model":"m","has_api_key":false,"endpoint":null,"busy":false}"#;
1436 assert_eq!(serde_json::from_str::<EngineState>(old).unwrap().endpoint_info, None);
1437 let info = EndpointInfo {
1438 probing: false,
1439 server: "llama.cpp".into(),
1440 context_tokens: Some(262_144),
1441 tools: ToolsMode::Native,
1442 vision: Some(true),
1443 slots: None,
1444 };
1445 assert_eq!(info.summary(), "llama.cpp · 262k ctx · native tools · vision");
1446 assert_eq!(EndpointInfo { slots: Some(4), ..info.clone() }.summary(), "llama.cpp · 262k ctx · native tools · vision · 4 slots");
1447 assert_eq!(EndpointInfo { probing: true, ..info }.summary(), "checking endpoint…");
1448 assert_eq!(EndpointInfo::default().summary(), "tools untested");
1449 }
1450
1451 #[test]
1452 fn media_messages_round_trip() {
1453 let msgs = vec![
1454 ClientMsg::SendMessage { text: "chart it".into(), attachments: vec!["uploads/sales.csv".into()] },
1455 ClientMsg::Upload { upload: 1, name: "a.csv".into(), size: 3, offset: 0, data: media::encode(b"a,b"), done: true },
1456 ClientMsg::GetMedia { path: "charts/x.chart.json".into() },
1457 ];
1458 for m in msgs {
1459 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1460 }
1461 let spec = byob_types::chart::validate(&serde_json::json!({"type": "bar", "x": "m", "series": ["v"], "data": [{"m": "a", "v": 1}]})).unwrap();
1462 let msgs = vec![
1463 ServerMsg::Uploaded { upload: 1, attachment: Some(MediaRef::new("uploads/a.csv", 3)), error: None },
1464 ServerMsg::Media { path: "c.chart.json".into(), content: MediaContent::Chart { spec } },
1465 ServerMsg::Media { path: "p.png".into(), content: MediaContent::Image { mime: "image/png".into(), data: "AA==".into() } },
1466 ServerMsg::Media { path: "p.png".into(), content: MediaContent::Error { message: "gone".into() } },
1467 ];
1468 for m in msgs {
1469 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1470 }
1471 let mut s = step(1, StepStatus::Done);
1472 s.media = vec![MediaRef::new("charts/x.chart.json", 10)];
1473 let m = ServerMsg::StepUpdated { entry: 1, step: s };
1474 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1475 }
1476
1477 #[test]
1478 fn artifact_messages_round_trip() {
1479 let v = ArtifactVersion { n: 2, path: ".byob/artifacts/calc/v2.html".into(), created_at: 1, note: "blue button".into(), size: 10, turn: String::new() };
1480 let a = Artifact {
1481 id: "calc".into(),
1482 kind: ArtifactKind::Html,
1483 content_type: artifact::TYPE_HTML.into(),
1484 title: "Calc".into(),
1485 filename: "calc.html".into(),
1486 versions: vec![v],
1487 network: false,
1488 };
1489 let msgs = vec![
1490 ServerMsg::Artifacts { chat: Some("c1".into()), artifacts: vec![a.clone()] },
1491 ServerMsg::Artifacts { chat: None, artifacts: vec![] },
1492 ServerMsg::ArtifactUpdated(a),
1493 ServerMsg::ArtifactFile { id: "calc".into(), version: 2, data: Some(media::encode(b"<p>")), error: None },
1494 ServerMsg::ArtifactFile { id: "calc".into(), version: 9, data: None, error: Some("no such version".into()) },
1495 ];
1496 for m in msgs {
1497 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1498 }
1499 let m = ClientMsg::GetArtifact { id: "calc".into(), version: 2 };
1500 assert_eq!(m.to_json(), r#"{"type":"get_artifact","id":"calc","version":2}"#);
1501 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1502 let mut s = step(1, StepStatus::Done);
1503 s.artifacts = vec![ArtifactRef { id: "calc".into(), version: 2 }];
1504 let m = ServerMsg::StepUpdated { entry: 1, step: s };
1505 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1506 let json = r#"{"id":1,"tool":"t","title":"T","access":"read","status":"done","detail":""}"#;
1508 assert!(serde_json::from_str::<Step>(json).unwrap().artifacts.is_empty());
1509 }
1510
1511 #[test]
1512 fn older_send_message_without_attachments_parses() {
1513 let m = ClientMsg::from_json(r#"{"type":"send_message","text":"hi"}"#).unwrap();
1514 assert_eq!(m, ClientMsg::SendMessage { text: "hi".into(), attachments: vec![] });
1515 assert_eq!(m.to_json(), r#"{"type":"send_message","text":"hi"}"#);
1516 }
1517
1518 #[test]
1519 fn compaction_messages_round_trip() {
1520 let c = Compaction {
1521 id: 1,
1522 after_entry: 7,
1523 tokens_before: 182_000,
1524 tokens_after: 9_000,
1525 summary: "## Goals".into(),
1526 manual: true,
1527 focus: Some("CSV".into()),
1528 created_at: 5,
1529 };
1530 let u = ChatUsage { chat: "c1".into(), context_used: 34_000, context_window: 262_144, compact_at: 209_715, model_calls: 3, ..Default::default() };
1531 for m in [ServerMsg::Usage(u), ServerMsg::Compactions { chat: Some("c1".into()), items: vec![c.clone()] }, ServerMsg::Compacted(c)] {
1532 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1533 }
1534 assert_eq!(ClientMsg::Compact { focus: None }.to_json(), r#"{"type":"compact"}"#);
1535 let m = ClientMsg::from_json(r#"{"type":"compact","focus":"keep the CSV"}"#).unwrap();
1536 assert_eq!(m, ClientMsg::Compact { focus: Some("keep the CSV".into()) });
1537 let s: TurnStats = serde_json::from_str(r#"{"prompt_tokens":1,"completion_tokens":2,"elapsed_ms":3}"#).unwrap();
1539 assert_eq!(s.model_calls, 0);
1540 }
1541
1542 #[test]
1543 fn connection_messages_round_trip() {
1544 for m in [
1545 ClientMsg::TestInference { base_url: "http://127.0.0.1:11434/v1".into(), model: "qwen3".into(), api_key: None },
1546 ClientMsg::TestInference { base_url: "https://api.openai.com/v1".into(), model: "m".into(), api_key: Some("sk".into()) },
1547 ClientMsg::DetectEndpoints,
1548 ClientMsg::Retry,
1549 ClientMsg::Rewind { entry: 7, text: "again, differently".into() },
1550 ClientMsg::NewUnattachedChat,
1551 ClientMsg::ChatToProject { chat: "c1".into() },
1552 ] {
1553 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1554 }
1555 assert_eq!(ClientMsg::Retry.to_json(), r#"{"type":"retry"}"#);
1556 let t = InferenceTest { base_url: "u".into(), model: "m".into(), ok: false, problem: Some(Problem::Unauthorized), detail: "x".into(), models: vec![] };
1557 let m = ServerMsg::InferenceTested(t);
1558 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1559 let state = EngineState {
1560 link: Link::failed("could not reach u: refused"),
1561 onboarded: true,
1562 detected: vec![Detected { preset: "ollama".into(), base_url: "http://127.0.0.1:11434/v1".into(), models: vec!["qwen3".into()] }],
1563 ..Default::default()
1564 };
1565 let m = ServerMsg::State(state);
1566 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1567 let old = r#"{"version":"0","inference_base_url":"u","inference_model":"m","has_api_key":false,"endpoint":null,"busy":false}"#;
1569 let s = serde_json::from_str::<EngineState>(old).unwrap();
1570 assert_eq!((s.link, s.onboarded, s.detected.len()), (Link::Unknown, false, 0));
1571 }
1572
1573 #[test]
1574 fn hello_negotiates_and_old_hellos_still_parse() {
1575 let m = ClientMsg::hello("desktop");
1576 let ClientMsg::Hello { protocol, minor, caps, .. } = &m else { panic!() };
1577 assert_eq!((*protocol, *minor), (PROTOCOL_MAJOR, PROTOCOL_MINOR));
1578 assert!(caps.iter().any(|c| c == version::CAP_PLUGIN_CHANNEL));
1579 assert!(m.check_sizes().is_ok());
1580 let old = ClientMsg::from_json(r#"{"type":"hello","protocol":12,"client":"old tab"}"#).unwrap();
1582 assert_eq!(old, ClientMsg::Hello { protocol: 12, minor: 0, client: "old tab".into(), caps: vec![] });
1583 let bad = ClientMsg::Hello { protocol: PROTOCOL_MAJOR, minor: 0, client: "x".into(), caps: vec!["NOT A CAP".into()] };
1584 assert!(bad.check_sizes().is_err());
1585 let w = ServerMsg::Welcome(Welcome::current());
1586 assert_eq!(ServerMsg::from_json(&w.to_json()).unwrap(), w);
1587 assert!(w.to_json().starts_with(r#"{"type":"welcome","protocol":13"#), "{}", w.to_json());
1588 }
1589
1590 #[test]
1591 fn plugin_channel_round_trips_and_is_capped() {
1592 let c = ClientMsg::Plugin { plugin: "sheets".into(), msg: serde_json::json!({"op": "get", "cell": "A1"}) };
1593 assert_eq!(c.to_json(), r#"{"type":"plugin","plugin":"sheets","msg":{"cell":"A1","op":"get"}}"#);
1594 assert_eq!(ClientMsg::from_json(&c.to_json()).unwrap(), c);
1595 assert!(c.check_sizes().is_ok());
1596 let s = ServerMsg::Plugin { plugin: "sheets".into(), msg: serde_json::json!([1, 2]) };
1597 assert_eq!(ServerMsg::from_json(&s.to_json()).unwrap(), s);
1598 for bad in [
1599 ClientMsg::Plugin { plugin: "Not/an id".into(), msg: serde_json::Value::Null },
1600 ClientMsg::Plugin { plugin: "sheets".into(), msg: serde_json::Value::String("x".repeat(version::MAX_PLUGIN_MSG_BYTES)) },
1601 ] {
1602 assert!(bad.check_sizes().is_err());
1603 }
1604 }
1605
1606 #[test]
1607 fn question_cards_round_trip_and_older_asks_still_parse() {
1608 let c = ClientMsg::AnswerQuestion { step: 4, text: "Metric".into() };
1609 assert_eq!(c.to_json(), r#"{"type":"answer_question","step":4,"text":"Metric"}"#);
1610 assert_eq!(ClientMsg::from_json(&c.to_json()).unwrap(), c);
1611 assert!(c.check_sizes().is_ok());
1612 assert!(ClientMsg::AnswerQuestion { step: 4, text: "x".repeat(MAX_ANSWER_CHARS + 1) }.check_sizes().is_err());
1613 let ask = Ask {
1614 text: "Which units?".into(),
1615 warning: None,
1616 always: true,
1617 choice: Some(Choice { options: vec!["Metric".into(), "Imperial".into()], free_text: true, answer: None }),
1618 card: None,
1619 };
1620 let json = serde_json::to_string(&ask).unwrap();
1621 assert_eq!(serde_json::from_str::<Ask>(&json).unwrap(), ask);
1622 let old: Ask = serde_json::from_str(r#"{"text":"t","always":true}"#).unwrap();
1624 assert!(old.choice.is_none());
1625 assert!(!serde_json::to_string(&old).unwrap().contains("choice"));
1626 }
1627
1628 #[test]
1630 fn unknown_messages_and_enum_values_decode_to_fallbacks() {
1631 assert_eq!(ServerMsg::from_json(r#"{"type":"hologram","x":1,"y":{"z":[]}}"#).unwrap(), ServerMsg::Unknown);
1632 assert_eq!(ClientMsg::from_json(r#"{"type":"teleport","to":"mars"}"#).unwrap(), ClientMsg::Unknown);
1633 assert!(ServerMsg::from_json(r#"{"type":"notice","level":"info"}"#).is_err());
1635 let n = ServerMsg::from_json(r#"{"type":"notice","level":"debug","text":"t"}"#).unwrap();
1636 assert_eq!(n, ServerMsg::Notice { level: NoticeLevel::Info, text: "t".into() });
1637 let a = ClientMsg::from_json(r#"{"type":"approve","step":1,"answer":"maybe_later"}"#).unwrap();
1638 assert_eq!(a, ClientMsg::Approve { step: 1, answer: ApprovalAnswer::Unknown });
1639 let json = r#"{"id":1,"tool":"t","title":"T","access":"read","status":"done","detail":"",
1641 "changes":[{"kind":"chmod","path":"a","mode":"755"}],
1642 "preview":{"kind":"hexdump","bytes":"00"},
1643 "media":[{"kind":"video","path":"a.mp4"}],
1644 "views":[{"kind":"sheets.grid","v":4,"data":{"rows":[]},"fallback":"a *grid*"}]}"#;
1645 let s: Step = serde_json::from_str(json).unwrap();
1646 assert_eq!((s.changes.clone(), s.preview.clone()), (vec![FileChange::Other], Some(Preview::Other)));
1647 assert_eq!(s.media[0].kind, MediaKind::File);
1648 assert_eq!((s.views[0].kind.as_str(), s.views[0].fallback.as_str()), ("sheets.grid", "a *grid*"));
1649 assert!(s.view::<PluginCard>().is_none());
1650 let art: Artifact = serde_json::from_str(r#"{"id":"a","kind":"spreadsheet","title":"A","filename":"a.xlsx","versions":[]}"#).unwrap();
1651 assert_eq!(art.kind, ArtifactKind::Text);
1652 assert_eq!(serde_json::from_str::<SlashKind>(r#""macro""#).unwrap(), SlashKind::Other);
1653 assert_eq!(serde_json::from_str::<PluginAction>(r#""forked""#).unwrap(), PluginAction::Other);
1654 let env = ClientMsg::from_json(r#"{"type":"workspace_env","action":{"kind":"rebuild","fast":true}}"#).unwrap();
1655 assert_eq!(env, ClientMsg::WorkspaceEnv { action: Some(EnvAction::Unsupported), workspace: None });
1656 let d = ServerMsg::from_json(r#"{"type":"delegation","entry":1,"step":2,"update":{"kind":"progress","pct":5}}"#).unwrap();
1657 assert_eq!(d, ServerMsg::Delegation { entry: 1, step: 2, update: DelegationUpdate::Other });
1658 }
1659
1660 #[test]
1661 fn plugin_cards_travel_as_views() {
1662 let card = PluginCard {
1663 plugin: "scratch".into(),
1664 scope: PluginScope::Chat,
1665 action: PluginAction::Made,
1666 tools: vec!["shout".into()],
1667 added: vec!["shout".into()],
1668 removed: vec![],
1669 test: Some(plugins::PluginTest { ok: true, output: "HI".into() }),
1670 problems: vec![],
1671 missing_settings: vec![],
1672 };
1673 let mut s = step(1, StepStatus::Done);
1674 s.views.push(View::of(&card));
1675 let json = ServerMsg::StepUpdated { entry: 1, step: s }.to_json();
1676 assert!(json.contains(r#""views":[{"kind":"byob.plugin_card","v":1,"data":{"action":"made""#), "{json}");
1677 let ServerMsg::StepUpdated { step: back, .. } = ServerMsg::from_json(&json).unwrap() else { panic!() };
1678 assert_eq!(back.view::<PluginCard>(), Some(card));
1679 assert!(back.views[0].fallback.contains("**Plugin scratch** (this chat) · tool made") && back.views[0].fallback.contains("shout"));
1680 assert!(!ServerMsg::StepUpdated { entry: 1, step: step(2, StepStatus::Done) }.to_json().contains("views"));
1682 }
1683
1684 #[test]
1685 fn state_never_carries_api_key() {
1686 let json = serde_json::to_string(&EngineState::default()).unwrap();
1687 assert!(!json.contains("\"api_key\""));
1688 }
1689}