1#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]
7
8pub mod artifact;
9pub mod connect;
10pub mod delegation;
11pub mod env;
12pub mod media;
13pub mod plugins;
14pub mod queue;
15pub mod usage;
16pub mod workspace;
17
18use serde::{Deserialize, Serialize};
19
20pub use artifact::{Artifact, ArtifactKind, ArtifactRef, ArtifactVersion};
21pub use connect::{Detected, InferenceTest, Link, PRESETS, Preset, Problem};
22pub use delegation::{Delegation, DelegationState, DelegationUpdate};
23pub use env::{ContainerEnv, EnvAction, EnvSupport, WorkspaceEnv};
24pub use media::{MediaContent, MediaKind, MediaRef};
25pub use plugins::{
26 Extensions, PluginAction, PluginCard, PluginInfo, PluginLoadError, PluginOrigin, PluginScope, PluginSetting, PluginTest, ServerInfo, ServerState,
27 SlashItem, SlashKind,
28};
29pub use queue::{ChatQueue, QueuePause, QueuedMessage};
30pub use usage::{ChatUsage, Compaction};
31pub use workspace::{ChatEndpoint, ConfigScope, ConfigView, FolderList, NewFolder, WorkspaceSummary};
32
33pub const PROTOCOL_VERSION: u32 = 12;
35
36pub const MAX_FRAME_BYTES: usize = 4 * 1024 * 1024;
38
39#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
41#[serde(tag = "type", rename_all = "snake_case")]
42pub enum ClientMsg {
43 Hello {
45 protocol: u32,
46 client: String,
47 },
48 SetInference {
52 base_url: String,
53 model: String,
54 api_key: Option<String>,
55 },
56 TestInference {
59 base_url: String,
60 model: String,
61 #[serde(default, skip_serializing_if = "Option::is_none")]
62 api_key: Option<String>,
63 },
64 DetectEndpoints,
67 Retry,
70 SendMessage {
74 text: String,
75 #[serde(default, skip_serializing_if = "Vec::is_empty")]
76 attachments: Vec<String>,
77 },
78 Cancel,
80 Unqueue {
82 id: u64,
83 },
84 EditQueued {
87 id: u64,
88 text: String,
89 #[serde(default, skip_serializing_if = "Vec::is_empty")]
90 attachments: Vec<String>,
91 },
92 MoveQueued {
94 id: u64,
95 to: u32,
96 },
97 SendQueuedNow {
99 id: u64,
100 },
101 ResumeQueue,
103 Approve {
106 step: u64,
107 answer: ApprovalAnswer,
108 },
109 Undo {
112 entry: u64,
113 },
114 ListChats {
117 after: Option<ChatCursor>,
118 limit: u32,
119 },
120 NewChat {
124 #[serde(default, skip_serializing_if = "Option::is_none")]
125 workspace: Option<String>,
126 },
127 OpenChat {
129 id: String,
130 },
131 RenameChat {
132 id: String,
133 title: String,
134 },
135 DeleteChat {
137 id: String,
138 },
139 PinChat {
140 id: String,
141 pinned: bool,
142 },
143 Upload {
148 upload: u64,
149 name: String,
150 size: u64,
151 offset: u64,
152 data: String,
153 done: bool,
154 },
155 GetMedia {
157 path: String,
158 },
159 GetArtifact {
162 id: String,
163 version: u32,
164 },
165 Compact {
168 #[serde(default, skip_serializing_if = "Option::is_none")]
169 focus: Option<String>,
170 },
171 WorkspaceEnv {
174 #[serde(default, skip_serializing_if = "Option::is_none")]
175 action: Option<EnvAction>,
176 #[serde(default, skip_serializing_if = "Option::is_none")]
177 workspace: Option<String>,
178 },
179 CreateWorkspace {
183 name: String,
184 folder: NewFolder,
185 #[serde(default)]
186 config: workspace::Layer,
187 },
188 RenameWorkspace {
189 id: String,
190 name: String,
191 },
192 RemoveWorkspace {
195 id: String,
196 #[serde(default)]
197 clean: bool,
198 },
199 GetConfig {
201 scope: ConfigScope,
202 },
203 SetConfig {
207 scope: ConfigScope,
208 layer: workspace::Layer,
209 #[serde(default, skip_serializing_if = "Option::is_none")]
210 api_key: Option<String>,
211 },
212 ListFolders {
215 #[serde(default, skip_serializing_if = "Option::is_none")]
216 path: Option<String>,
217 },
218 CheckContainers,
220 GetExtensions,
222 SetPluginEnabled {
226 scope: ConfigScope,
227 plugin: String,
228 enabled: Option<bool>,
229 },
230 SetPluginSetting {
234 plugin: String,
235 key: String,
236 value: Option<String>,
237 },
238 KeepPlugin {
242 plugin: String,
243 scope: PluginScope,
244 #[serde(default, skip_serializing_if = "Option::is_none")]
245 new_id: Option<String>,
246 },
247 RemovePlugin {
250 plugin: String,
251 scope: PluginScope,
252 },
253 ReloadPlugins,
255 TrustPlugins {
259 workspace: String,
260 #[serde(default)]
261 plugins: Vec<String>,
262 trust: bool,
263 },
264}
265
266#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
268#[serde(tag = "type", rename_all = "snake_case")]
269pub enum ServerMsg {
270 State(EngineState),
272 Notice { level: NoticeLevel, text: String },
274 Transcript { entries: Vec<Entry> },
276 EntryAdded(Entry),
278 EntryDelta { id: u64, content: String, reasoning: String },
280 EntryFinished { id: u64, error: Option<String>, stats: Option<TurnStats> },
282 StepUpdated { entry: u64, step: Step },
284 EntryUndo { id: u64, undoable: bool, undone: bool },
286 Chats { pinned: Vec<ChatSummary>, recent: Vec<ChatSummary>, after: Option<ChatCursor>, next: Option<ChatCursor> },
289 ChatUpdated(ChatSummary),
291 ChatDeleted { id: String },
293 ChatOpened {
297 chat: Option<ChatSummary>,
298 #[serde(default)]
299 workspace: Option<String>,
300 },
301 Uploaded { upload: u64, attachment: Option<MediaRef>, error: Option<String> },
303 Media { path: String, content: MediaContent },
305 Artifacts { chat: Option<String>, artifacts: Vec<Artifact> },
308 ArtifactUpdated(Artifact),
310 ArtifactFile { id: String, version: u32, data: Option<String>, error: Option<String> },
312 Usage(ChatUsage),
314 Compactions { chat: Option<String>, items: Vec<Compaction> },
317 Compacted(Compaction),
319 Delegation { entry: u64, step: u64, update: DelegationUpdate },
321 InferenceTested(InferenceTest),
323 WorkspaceEnv(WorkspaceEnv),
325 Workspaces { items: Vec<WorkspaceSummary>, current: Option<String>, root: String, support: EnvSupport },
329 Config(Box<ConfigView>),
331 Folders(FolderList),
333 ContainersChecked { ok: bool, message: String },
335 WorkspaceCreated { id: Option<String>, error: Option<String> },
337 Queue(ChatQueue),
340 Extensions(Box<Extensions>),
343}
344
345#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
347pub struct ChatSummary {
348 pub id: String,
349 pub title: String,
350 pub updated_at: i64,
352 pub pinned_at: Option<i64>,
354 #[serde(default)]
356 pub busy: bool,
357 #[serde(default, skip_serializing_if = "Option::is_none")]
359 pub workspace: Option<String>,
360}
361
362impl ChatSummary {
363 pub fn cursor(&self) -> ChatCursor {
364 ChatCursor { updated_at: self.updated_at, id: self.id.clone() }
365 }
366}
367
368#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
370pub struct ChatCursor {
371 pub updated_at: i64,
372 pub id: String,
373}
374
375#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
376#[serde(rename_all = "snake_case")]
377pub enum EntryRole {
378 User,
379 Assistant,
380}
381
382#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
384pub struct Entry {
385 pub id: u64,
386 pub role: EntryRole,
387 pub content: String,
388 pub reasoning: String,
389 pub done: bool,
391 pub error: Option<String>,
392 pub stats: Option<TurnStats>,
393 #[serde(default)]
396 pub steps: Vec<Step>,
397 #[serde(default)]
399 pub undoable: bool,
400 #[serde(default)]
402 pub undone: bool,
403 #[serde(default, skip_serializing_if = "Vec::is_empty")]
405 pub attachments: Vec<MediaRef>,
406}
407
408impl Entry {
409 pub fn append(&mut self, content: &str, reasoning: &str) {
411 self.content.push_str(content);
412 self.reasoning.push_str(reasoning);
413 }
414
415 pub fn upsert_step(&mut self, step: Step) {
417 match self.steps.iter_mut().find(|s| s.id == step.id) {
418 Some(existing) => *existing = step,
419 None => self.steps.push(step),
420 }
421 }
422
423 pub fn pending_approvals(&self) -> impl Iterator<Item = &Step> {
425 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)
426 }
427
428 pub fn apply_delegation(&mut self, step: u64, update: &DelegationUpdate) {
430 if let Some(d) = self.steps.iter_mut().find(|s| s.id == step).and_then(|s| s.delegation.as_deref_mut()) {
431 d.apply(update);
432 }
433 }
434}
435
436#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
438#[serde(rename_all = "snake_case")]
439pub enum ToolAccess {
440 Read,
441 Write,
442 Network,
443 Execute,
444}
445
446impl ToolAccess {
447 pub fn label(self) -> &'static str {
448 match self {
449 Self::Read => "read",
450 Self::Write => "write",
451 Self::Network => "network",
452 Self::Execute => "execute",
453 }
454 }
455}
456
457#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
458#[serde(rename_all = "snake_case")]
459pub enum StepStatus {
460 Running,
461 Waiting,
463 Done,
464 Failed,
466 Denied,
468}
469
470impl StepStatus {
471 pub fn finished(self) -> bool {
472 matches!(self, Self::Done | Self::Failed | Self::Denied)
473 }
474}
475
476#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
478#[serde(rename_all = "snake_case")]
479pub enum ApprovalAnswer {
480 Allow,
481 Always,
483 Deny,
484 AlwaysEverywhere,
486}
487
488#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
490#[serde(tag = "kind", rename_all = "snake_case")]
491pub enum FileChange {
492 Created { path: String },
493 Modified { path: String },
494 Deleted { path: String },
495 Moved { from: String, to: String },
496}
497
498#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
500pub struct Step {
501 pub id: u64,
503 pub tool: String,
505 pub title: String,
507 pub access: ToolAccess,
508 pub status: StepStatus,
509 pub detail: String,
511 #[serde(default)]
512 pub changes: Vec<FileChange>,
513 #[serde(default)]
515 pub at: usize,
516 #[serde(default, skip_serializing_if = "Vec::is_empty")]
518 pub media: Vec<MediaRef>,
519 #[serde(default, skip_serializing_if = "Option::is_none")]
521 pub preview: Option<Preview>,
522 #[serde(default, skip_serializing_if = "Vec::is_empty")]
524 pub artifacts: Vec<ArtifactRef>,
525 #[serde(default, skip_serializing_if = "Option::is_none")]
527 pub delegation: Option<Box<Delegation>>,
528 #[serde(default, skip_serializing_if = "Option::is_none")]
532 pub ask: Option<Box<Ask>>,
533 #[serde(default, skip_serializing_if = "Option::is_none")]
536 pub plugin: Option<Box<PluginCard>>,
537}
538
539#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
541pub struct Ask {
542 #[serde(default)]
544 pub text: String,
545 #[serde(default, skip_serializing_if = "Option::is_none")]
547 pub warning: Option<String>,
548 #[serde(default)]
550 pub always: bool,
551}
552
553pub const MAX_PREVIEW_LINES: usize = 40;
555pub const MAX_PREVIEW_LINE_CHARS: usize = 300;
557
558#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
560#[serde(tag = "kind", rename_all = "snake_case")]
561pub enum Preview {
562 Write {
565 path: String,
566 bytes: u64,
567 replaces: bool,
569 lines: Vec<DiffLine>,
570 #[serde(default)]
572 more: usize,
573 },
574 Move {
576 moves: Vec<(String, String)>,
577 #[serde(default)]
578 more: usize,
579 },
580 Delete { path: String, what: String },
582 Args {
584 fields: Vec<(String, String)>,
585 #[serde(default, skip_serializing_if = "Option::is_none")]
586 code: Option<String>,
587 #[serde(default)]
588 more: usize,
589 },
590}
591
592#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
594pub struct DiffLine {
595 pub kind: LineKind,
596 pub text: String,
597}
598
599#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
600#[serde(rename_all = "snake_case")]
601pub enum LineKind {
602 Same,
604 Added,
605 Removed,
606 Skipped,
608}
609
610#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
611pub struct TurnStats {
612 pub prompt_tokens: u64,
613 pub completion_tokens: u64,
614 pub elapsed_ms: u64,
615 #[serde(default)]
617 pub model_calls: u64,
618}
619
620#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
621#[serde(rename_all = "snake_case")]
622pub enum NoticeLevel {
623 Info,
624 Error,
625}
626
627#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
629pub struct EngineState {
630 pub version: String,
631 pub inference_base_url: String,
632 pub inference_model: String,
633 pub has_api_key: bool,
634 pub endpoint: Option<String>,
636 pub busy: bool,
638 #[serde(default)]
640 pub endpoint_info: Option<EndpointInfo>,
641 #[serde(default)]
643 pub link: Link,
644 #[serde(default)]
647 pub onboarded: bool,
648 #[serde(default)]
650 pub detected: Vec<Detected>,
651 #[serde(default)]
653 pub detecting: bool,
654 #[serde(default, skip_serializing_if = "Option::is_none")]
657 pub chat_endpoint: Option<ChatEndpoint>,
658}
659
660#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
662#[serde(rename_all = "snake_case")]
663pub enum ToolsMode {
664 Native,
666 Prompt,
668 #[default]
670 Unknown,
671}
672
673#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
675pub struct EndpointInfo {
676 #[serde(default)]
678 pub probing: bool,
679 #[serde(default)]
681 pub server: String,
682 #[serde(default)]
684 pub context_tokens: Option<u64>,
685 #[serde(default)]
686 pub tools: ToolsMode,
687 #[serde(default)]
689 pub vision: Option<bool>,
690}
691
692impl EndpointInfo {
693 pub fn summary(&self) -> String {
695 if self.probing {
696 return "checking endpoint…".into();
697 }
698 let mut parts = Vec::new();
699 if !self.server.is_empty() {
700 parts.push(self.server.clone());
701 }
702 if let Some(n) = self.context_tokens {
703 parts.push(if n >= 1000 { format!("{}k ctx", n / 1000) } else { format!("{n} ctx") });
704 }
705 parts.push(
706 match self.tools {
707 ToolsMode::Native => "native tools",
708 ToolsMode::Prompt => "prompt tools",
709 ToolsMode::Unknown => "tools untested",
710 }
711 .into(),
712 );
713 if self.vision == Some(true) {
714 parts.push("vision".into());
715 }
716 parts.join(" · ")
717 }
718}
719
720impl ClientMsg {
721 pub fn to_json(&self) -> String {
722 serde_json::to_string(self).unwrap_or_default()
723 }
724
725 pub fn from_json(text: &str) -> Result<Self, String> {
727 if text.len() > MAX_FRAME_BYTES {
728 return Err(format!("frame too large ({} bytes)", text.len()));
729 }
730 serde_json::from_str(text).map_err(|e| e.to_string())
731 }
732}
733
734impl ServerMsg {
735 pub fn to_json(&self) -> String {
736 serde_json::to_string(self).unwrap_or_default()
737 }
738
739 pub fn from_json(text: &str) -> Result<Self, String> {
741 if text.len() > MAX_FRAME_BYTES {
742 return Err(format!("frame too large ({} bytes)", text.len()));
743 }
744 serde_json::from_str(text).map_err(|e| e.to_string())
745 }
746}
747
748pub trait Connection {
750 fn send(&mut self, msg: ClientMsg);
751 fn try_recv(&mut self) -> Option<ServerMsg>;
753}
754
755#[cfg(test)]
756mod tests {
757 use super::*;
758
759 #[test]
760 fn client_msg_round_trips() {
761 let m = ClientMsg::Hello { protocol: PROTOCOL_VERSION, client: "test".into() };
762 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
763 }
764
765 #[test]
766 fn wire_format_is_tagged() {
767 let json = ServerMsg::Notice { level: NoticeLevel::Info, text: "hi".into() }.to_json();
768 assert_eq!(json, r#"{"type":"notice","level":"info","text":"hi"}"#);
769 }
770
771 #[test]
772 fn rejects_garbage_and_oversized_frames() {
773 assert!(ClientMsg::from_json("{not json").is_err());
774 assert!(ClientMsg::from_json(&" ".repeat(MAX_FRAME_BYTES + 1)).is_err());
775 }
776
777 #[test]
778 fn approve_wire_format() {
779 let m = ClientMsg::Approve { step: 7, answer: ApprovalAnswer::Always };
780 assert_eq!(m.to_json(), r#"{"type":"approve","step":7,"answer":"always"}"#);
781 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
782 }
783
784 fn step(id: u64, status: StepStatus) -> Step {
785 Step {
786 id,
787 tool: "t".into(),
788 title: "T".into(),
789 access: ToolAccess::Write,
790 status,
791 detail: String::new(),
792 changes: vec![],
793 at: 0,
794 preview: None,
795 media: vec![],
796 artifacts: vec![],
797 delegation: None,
798 ask: None,
799 plugin: None,
800 }
801 }
802
803 #[test]
804 fn delegations_stream_into_their_step_and_round_trip() {
805 let mut parent = step(1, StepStatus::Running);
806 parent.delegation = Some(Box::new(Delegation { agent: "explorer".into(), task: "count lines".into(), ..Default::default() }));
807 let mut e = Entry {
808 id: 9,
809 role: EntryRole::Assistant,
810 content: String::new(),
811 reasoning: String::new(),
812 done: false,
813 error: None,
814 stats: None,
815 steps: vec![parent],
816 undoable: false,
817 undone: false,
818 attachments: vec![],
819 };
820 let updates = [
821 DelegationUpdate::Status { state: DelegationState::Running, prompt_tokens: 0, completion_tokens: 0, error: None },
822 DelegationUpdate::Delta { content: "Reading".into(), reasoning: "hm".into() },
823 DelegationUpdate::Step(Box::new(step(2, StepStatus::Waiting))),
824 DelegationUpdate::Delta { content: " a.txt".into(), reasoning: String::new() },
825 ];
826 for u in &updates {
827 let msg = ServerMsg::Delegation { entry: 9, step: 1, update: u.clone() };
828 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
829 e.apply_delegation(1, u);
830 }
831 e.apply_delegation(77, &updates[1]);
833 let d = e.steps[0].delegation.as_deref().unwrap();
834 assert_eq!((d.content.as_str(), d.reasoning.as_str(), d.state), ("Reading a.txt", "hm", DelegationState::Running));
835 assert_eq!(d.status_line(), "explorer · 1 tool · waiting for approval");
836 assert_eq!(e.pending_approvals().map(|s| s.id).collect::<Vec<_>>(), vec![2]);
838 e.apply_delegation(1, &DelegationUpdate::Step(Box::new(step(2, StepStatus::Done))));
839 e.apply_delegation(1, &DelegationUpdate::Status { state: DelegationState::Done, prompt_tokens: 50, completion_tokens: 5, error: None });
840 assert_eq!(e.steps[0].delegation.as_deref().unwrap().status_line(), "explorer · 1 tool · done");
841 assert_eq!(e.pending_approvals().count(), 0);
842 let msg = ServerMsg::StepUpdated { entry: 9, step: e.steps[0].clone() };
843 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
844 let json = r#"{"id":1,"tool":"t","title":"T","access":"read","status":"done","detail":""}"#;
846 assert!(serde_json::from_str::<Step>(json).unwrap().delegation.is_none());
847 }
848
849 #[test]
850 fn steps_upsert_and_round_trip() {
851 let mut e = Entry {
852 id: 1,
853 role: EntryRole::Assistant,
854 content: String::new(),
855 reasoning: String::new(),
856 done: false,
857 error: None,
858 stats: None,
859 steps: vec![],
860 undoable: false,
861 undone: false,
862 attachments: vec![],
863 };
864 e.upsert_step(step(3, StepStatus::Running));
865 e.upsert_step(step(4, StepStatus::Waiting));
866 e.upsert_step(step(3, StepStatus::Done));
867 assert_eq!(e.steps.len(), 2);
868 assert_eq!(e.steps[0].status, StepStatus::Done);
869 assert_eq!(e.pending_approvals().map(|s| s.id).collect::<Vec<_>>(), vec![4]);
870 let mut s = step(5, StepStatus::Done);
871 s.changes = vec![FileChange::Moved { from: "a".into(), to: "b".into() }];
872 let msg = ServerMsg::StepUpdated { entry: 1, step: s };
873 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
874 }
875
876 #[test]
877 fn entry_without_steps_still_parses() {
878 let json = r#"{"id":1,"role":"user","content":"hi","reasoning":"","done":true,"error":null,"stats":null}"#;
879 let e: Entry = serde_json::from_str(json).unwrap();
880 assert!(e.steps.is_empty());
881 }
882
883 #[test]
884 fn undo_and_preview_wire_format() {
885 let m = ClientMsg::Undo { entry: 4 };
886 assert_eq!(m.to_json(), r#"{"type":"undo","entry":4}"#);
887 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
888 let mut s = step(1, StepStatus::Waiting);
889 s.preview =
890 Some(Preview::Write { path: "a.md".into(), bytes: 3, replaces: true, lines: vec![DiffLine { kind: LineKind::Added, text: "hi".into() }], more: 0 });
891 let msg = ServerMsg::StepUpdated { entry: 1, step: s };
892 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
893 let msg = ServerMsg::EntryUndo { id: 1, undoable: false, undone: true };
894 assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
895 }
896
897 #[test]
898 fn chat_messages_round_trip() {
899 let summary = ChatSummary { id: "c1".into(), title: "Plans".into(), updated_at: 5, pinned_at: None, busy: true, workspace: Some("w1".into()) };
900 for m in [
901 ServerMsg::Chats { pinned: vec![], recent: vec![summary.clone()], after: None, next: Some(summary.cursor()) },
902 ServerMsg::ChatUpdated(summary.clone()),
903 ServerMsg::ChatOpened { chat: Some(summary), workspace: None },
904 ServerMsg::ChatDeleted { id: "c1".into() },
905 ] {
906 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
907 }
908 let m = ClientMsg::ListChats { after: Some(ChatCursor { updated_at: 1, id: "x".into() }), limit: 50 };
909 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
910 assert_eq!(ClientMsg::NewChat { workspace: None }.to_json(), r#"{"type":"new_chat"}"#);
911 }
912
913 #[test]
914 fn endpoint_info_is_optional_and_summarised() {
915 let old = r#"{"version":"0","inference_base_url":"u","inference_model":"m","has_api_key":false,"endpoint":null,"busy":false}"#;
916 assert_eq!(serde_json::from_str::<EngineState>(old).unwrap().endpoint_info, None);
917 let info = EndpointInfo { probing: false, server: "llama.cpp".into(), context_tokens: Some(262_144), tools: ToolsMode::Native, vision: Some(true) };
918 assert_eq!(info.summary(), "llama.cpp · 262k ctx · native tools · vision");
919 assert_eq!(EndpointInfo { probing: true, ..info }.summary(), "checking endpoint…");
920 assert_eq!(EndpointInfo::default().summary(), "tools untested");
921 }
922
923 #[test]
924 fn media_messages_round_trip() {
925 let msgs = vec![
926 ClientMsg::SendMessage { text: "chart it".into(), attachments: vec!["uploads/sales.csv".into()] },
927 ClientMsg::Upload { upload: 1, name: "a.csv".into(), size: 3, offset: 0, data: media::encode(b"a,b"), done: true },
928 ClientMsg::GetMedia { path: "charts/x.chart.json".into() },
929 ];
930 for m in msgs {
931 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
932 }
933 let spec = byob_types::chart::validate(&serde_json::json!({"type": "bar", "x": "m", "series": ["v"], "data": [{"m": "a", "v": 1}]})).unwrap();
934 let msgs = vec![
935 ServerMsg::Uploaded { upload: 1, attachment: Some(MediaRef::new("uploads/a.csv", 3)), error: None },
936 ServerMsg::Media { path: "c.chart.json".into(), content: MediaContent::Chart { spec } },
937 ServerMsg::Media { path: "p.png".into(), content: MediaContent::Image { mime: "image/png".into(), data: "AA==".into() } },
938 ServerMsg::Media { path: "p.png".into(), content: MediaContent::Error { message: "gone".into() } },
939 ];
940 for m in msgs {
941 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
942 }
943 let mut s = step(1, StepStatus::Done);
944 s.media = vec![MediaRef::new("charts/x.chart.json", 10)];
945 let m = ServerMsg::StepUpdated { entry: 1, step: s };
946 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
947 }
948
949 #[test]
950 fn artifact_messages_round_trip() {
951 let v = ArtifactVersion { n: 2, path: ".byob/artifacts/calc/v2.html".into(), created_at: 1, note: "blue button".into(), size: 10 };
952 let a = Artifact { id: "calc".into(), kind: ArtifactKind::Html, title: "Calc".into(), filename: "calc.html".into(), versions: vec![v] };
953 let msgs = vec![
954 ServerMsg::Artifacts { chat: Some("c1".into()), artifacts: vec![a.clone()] },
955 ServerMsg::Artifacts { chat: None, artifacts: vec![] },
956 ServerMsg::ArtifactUpdated(a),
957 ServerMsg::ArtifactFile { id: "calc".into(), version: 2, data: Some(media::encode(b"<p>")), error: None },
958 ServerMsg::ArtifactFile { id: "calc".into(), version: 9, data: None, error: Some("no such version".into()) },
959 ];
960 for m in msgs {
961 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
962 }
963 let m = ClientMsg::GetArtifact { id: "calc".into(), version: 2 };
964 assert_eq!(m.to_json(), r#"{"type":"get_artifact","id":"calc","version":2}"#);
965 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
966 let mut s = step(1, StepStatus::Done);
967 s.artifacts = vec![ArtifactRef { id: "calc".into(), version: 2 }];
968 let m = ServerMsg::StepUpdated { entry: 1, step: s };
969 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
970 let json = r#"{"id":1,"tool":"t","title":"T","access":"read","status":"done","detail":""}"#;
972 assert!(serde_json::from_str::<Step>(json).unwrap().artifacts.is_empty());
973 }
974
975 #[test]
976 fn older_send_message_without_attachments_parses() {
977 let m = ClientMsg::from_json(r#"{"type":"send_message","text":"hi"}"#).unwrap();
978 assert_eq!(m, ClientMsg::SendMessage { text: "hi".into(), attachments: vec![] });
979 assert_eq!(m.to_json(), r#"{"type":"send_message","text":"hi"}"#);
980 }
981
982 #[test]
983 fn compaction_messages_round_trip() {
984 let c = Compaction {
985 id: 1,
986 after_entry: 7,
987 tokens_before: 182_000,
988 tokens_after: 9_000,
989 summary: "## Goals".into(),
990 manual: true,
991 focus: Some("CSV".into()),
992 created_at: 5,
993 };
994 let u = ChatUsage { chat: "c1".into(), context_used: 34_000, context_window: 262_144, compact_at: 209_715, model_calls: 3, ..Default::default() };
995 for m in [ServerMsg::Usage(u), ServerMsg::Compactions { chat: Some("c1".into()), items: vec![c.clone()] }, ServerMsg::Compacted(c)] {
996 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
997 }
998 assert_eq!(ClientMsg::Compact { focus: None }.to_json(), r#"{"type":"compact"}"#);
999 let m = ClientMsg::from_json(r#"{"type":"compact","focus":"keep the CSV"}"#).unwrap();
1000 assert_eq!(m, ClientMsg::Compact { focus: Some("keep the CSV".into()) });
1001 let s: TurnStats = serde_json::from_str(r#"{"prompt_tokens":1,"completion_tokens":2,"elapsed_ms":3}"#).unwrap();
1003 assert_eq!(s.model_calls, 0);
1004 }
1005
1006 #[test]
1007 fn connection_messages_round_trip() {
1008 for m in [
1009 ClientMsg::TestInference { base_url: "http://127.0.0.1:11434/v1".into(), model: "qwen3".into(), api_key: None },
1010 ClientMsg::TestInference { base_url: "https://api.openai.com/v1".into(), model: "m".into(), api_key: Some("sk".into()) },
1011 ClientMsg::DetectEndpoints,
1012 ClientMsg::Retry,
1013 ] {
1014 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1015 }
1016 assert_eq!(ClientMsg::Retry.to_json(), r#"{"type":"retry"}"#);
1017 let t = InferenceTest { base_url: "u".into(), model: "m".into(), ok: false, problem: Some(Problem::Unauthorized), detail: "x".into(), models: vec![] };
1018 let m = ServerMsg::InferenceTested(t);
1019 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1020 let state = EngineState {
1021 link: Link::failed("could not reach u: refused"),
1022 onboarded: true,
1023 detected: vec![Detected { preset: "ollama".into(), base_url: "http://127.0.0.1:11434/v1".into(), models: vec!["qwen3".into()] }],
1024 ..Default::default()
1025 };
1026 let m = ServerMsg::State(state);
1027 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1028 let old = r#"{"version":"0","inference_base_url":"u","inference_model":"m","has_api_key":false,"endpoint":null,"busy":false}"#;
1030 let s = serde_json::from_str::<EngineState>(old).unwrap();
1031 assert_eq!((s.link, s.onboarded, s.detected.len()), (Link::Unknown, false, 0));
1032 }
1033
1034 #[test]
1035 fn state_never_carries_api_key() {
1036 let json = serde_json::to_string(&EngineState::default()).unwrap();
1037 assert!(!json.contains("\"api_key\""));
1038 }
1039}