Skip to main content

byob_protocol/
lib.rs

1//! The wire protocol between byob clients (desktop window, browser tab) and the engine.
2//!
3//! Every client, including the in-process desktop window, talks to the engine only through
4//! these messages, so the desktop and web UIs can never drift apart. Messages travel as JSON
5//! text frames over a WebSocket, or through channels when in-process.
6#![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 sites;
16pub mod tree;
17pub mod usage;
18pub mod version;
19pub mod view;
20pub mod web;
21pub mod workspace;
22
23use serde::{Deserialize, Serialize};
24
25pub use artifact::{Artifact, ArtifactKind, ArtifactRef, ArtifactVersion};
26pub use connect::{Detected, InferenceTest, Link, PRESETS, Preset, Problem};
27pub use delegation::{Delegation, DelegationState, DelegationUpdate};
28pub use env::{ContainerEnv, EnvAction, EnvSupport, WorkspaceEnv};
29pub use media::{MediaContent, MediaKind, MediaRef};
30pub use plugins::{
31    BackendInfo, Extensions, PluginAction, PluginCard, PluginInfo, PluginLoadError, PluginOrigin, PluginScope, PluginSetting, PluginTest, RendererDecl,
32    ServerInfo, ServerState, SlashItem, SlashKind, StarterDecl,
33};
34pub use queue::{ChatQueue, QueuePause, QueuedMessage};
35pub use sites::{LiveView, Site, ViewDecl, ViewRef};
36pub use usage::{ChatUsage, Compaction};
37pub use version::{PROTOCOL_MAJOR, PROTOCOL_MINOR, Welcome};
38pub use view::{View, ViewData};
39pub use workspace::{ChatEndpoint, ConfigScope, ConfigView, FolderList, NewFolder, WorkspaceSummary};
40
41/// Hard cap on a single incoming frame, so a hostile peer can't make us allocate unboundedly.
42pub const MAX_FRAME_BYTES: usize = 4 * 1024 * 1024;
43
44/// Client -> engine.
45#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
46#[serde(tag = "type", rename_all = "snake_case")]
47pub enum ClientMsg {
48    /// First message on every connection: the client's [`PROTOCOL_MAJOR`] (`protocol`),
49    /// minor and caps (see [`version`]). Answered with [`ServerMsg::Welcome`], or an error
50    /// notice if the major differs.
51    Hello {
52        protocol: u32,
53        #[serde(default)]
54        minor: u32,
55        client: String,
56        #[serde(default)]
57        caps: Vec<String>,
58    },
59    /// Point the engine at a different inference endpoint (saved, then checked). `api_key`:
60    /// `None` keeps the stored key if the server (scheme, host, port) is unchanged and drops
61    /// it otherwise; `Some("")` removes it.
62    SetInference {
63        base_url: String,
64        model: String,
65        api_key: Option<String>,
66    },
67    /// Try an endpoint without switching to it; answered with [`ServerMsg::InferenceTested`].
68    /// `api_key` as for [`ClientMsg::SetInference`].
69    TestInference {
70        base_url: String,
71        model: String,
72        #[serde(default, skip_serializing_if = "Option::is_none")]
73        api_key: Option<String>,
74    },
75    /// Look again for inference servers on this machine's usual ports
76    /// ([`EngineState::detected`]).
77    DetectEndpoints,
78    /// Run the last message of the chat in view again, after its reply failed before
79    /// producing anything (e.g. the server was down). The failed reply is removed.
80    Retry,
81    /// Send a user message and start a turn; while a reply runs in the chat, queue it
82    /// instead (see [`queue`]). `attachments` are paths the engine returned in
83    /// [`ServerMsg::Uploaded`].
84    SendMessage {
85        text: String,
86        #[serde(default, skip_serializing_if = "Vec::is_empty")]
87        attachments: Vec<String>,
88    },
89    /// Stop the running turn. Pending approvals are denied; the chat's queue pauses.
90    Cancel,
91    /// Take queued message `id` out of the queue of the chat in view.
92    Unqueue {
93        id: u64,
94    },
95    /// Replace the text and attachments of queued message `id` (in place). Empty text and no
96    /// attachments removes it.
97    EditQueued {
98        id: u64,
99        text: String,
100        #[serde(default, skip_serializing_if = "Vec::is_empty")]
101        attachments: Vec<String>,
102    },
103    /// Move queued message `id` to position `to` (0 = next; past the end = last).
104    MoveQueued {
105        id: u64,
106        to: u32,
107    },
108    /// Run queued message `id` next, now: stop the running turn (if any) and resume the queue.
109    SendQueuedNow {
110        id: u64,
111    },
112    /// Let a paused queue go on (starts the next message if the chat is free).
113    ResumeQueue,
114    /// Answer a pending approval (a [`Step`] with status [`StepStatus::Waiting`]). Any
115    /// client may answer; the first answer wins and later ones are ignored.
116    Approve {
117        step: u64,
118        answer: ApprovalAnswer,
119    },
120    /// Reverse the file changes of assistant entry `entry` (see [`Entry::undoable`]). The
121    /// engine refuses, changing nothing, if any of those files changed since.
122    Undo {
123        entry: u64,
124    },
125    /// Ask for a page of the chat list (answered with [`ServerMsg::Chats`]). `after` is the
126    /// previous page's `next`; `None` asks for the first page (pinned chats included).
127    ListChats {
128        after: Option<ChatCursor>,
129        limit: u32,
130    },
131    /// Start a new, empty chat in this client, in workspace `workspace` (default: the
132    /// workspace of the chat in view, else the default one). The chat is created when the
133    /// first message is sent; until then this client sees an empty transcript.
134    NewChat {
135        #[serde(default, skip_serializing_if = "Option::is_none")]
136        workspace: Option<String>,
137    },
138    /// Look at another chat. Only this client switches; a turn running elsewhere goes on.
139    OpenChat {
140        id: String,
141    },
142    RenameChat {
143        id: String,
144        title: String,
145    },
146    /// Delete a chat and its messages. Refused while a reply is running in it.
147    DeleteChat {
148        id: String,
149    },
150    PinChat {
151        id: String,
152        pinned: bool,
153    },
154    /// One chunk of a file the user attaches. `upload` is chosen by the client (unique per
155    /// connection); chunks arrive in order, `offset` is where `data` (base64, at most
156    /// [`media::UPLOAD_CHUNK_BYTES`] raw) starts; `size` is the whole file's size. The engine
157    /// answers the last chunk (`done`) or the first problem with [`ServerMsg::Uploaded`].
158    Upload {
159        upload: u64,
160        name: String,
161        size: u64,
162        offset: u64,
163        data: String,
164        done: bool,
165    },
166    /// Ask for the content of a [`MediaRef`] in the transcript; answered with [`ServerMsg::Media`].
167    GetMedia {
168        path: String,
169    },
170    /// Ask for the bytes of version `version` of artifact `id` in the chat this client looks
171    /// at; answered with [`ServerMsg::ArtifactFile`].
172    GetArtifact {
173        id: String,
174        version: u32,
175    },
176    /// Summarise the conversation in view now, so later requests start from the summary
177    /// (also typed as `/compact [focus]`). `focus` says what the summary must keep.
178    Compact {
179        #[serde(default, skip_serializing_if = "Option::is_none")]
180        focus: Option<String>,
181    },
182    /// Ask for the environment state of workspace `workspace` (default: the chat in view's),
183    /// after applying `action` if given; answered with [`ServerMsg::WorkspaceEnv`].
184    WorkspaceEnv {
185        #[serde(default, skip_serializing_if = "Option::is_none")]
186        action: Option<EnvAction>,
187        #[serde(default, skip_serializing_if = "Option::is_none")]
188        workspace: Option<String>,
189    },
190    /// Make a workspace: a name, a folder on the engine's machine, its own settings
191    /// (validated for the workspace level). Answered with [`ServerMsg::WorkspaceCreated`];
192    /// on success this client starts a new chat in it.
193    CreateWorkspace {
194        name: String,
195        folder: NewFolder,
196        #[serde(default)]
197        config: workspace::Layer,
198    },
199    RenameWorkspace {
200        id: String,
201        name: String,
202    },
203    /// Remove a workspace from byob with its chats; the folder and its files stay. `clean`
204    /// also deletes what byob keeps for it elsewhere (installed packages, its container).
205    RemoveWorkspace {
206        id: String,
207        #[serde(default)]
208        clean: bool,
209    },
210    /// Ask for one level's settings; answered with [`ServerMsg::Config`].
211    GetConfig {
212        scope: ConfigScope,
213    },
214    /// Replace one level's own settings (`None` fields inherit). `api_key` as for
215    /// [`ClientMsg::SetInference`], for a level with its own URL. Answered with
216    /// [`ServerMsg::Config`].
217    SetConfig {
218        scope: ConfigScope,
219        layer: workspace::Layer,
220        #[serde(default, skip_serializing_if = "Option::is_none")]
221        api_key: Option<String>,
222    },
223    /// List the subfolders of `path` on the engine's machine (default: the home folder);
224    /// answered with [`ServerMsg::Folders`].
225    ListFolders {
226        #[serde(default, skip_serializing_if = "Option::is_none")]
227        path: Option<String>,
228    },
229    /// Is Docker/Podman reachable? Answered with [`ServerMsg::ContainersChecked`].
230    CheckContainers,
231    /// Ask for the plugins of the chat in view; answered with [`ServerMsg::Extensions`].
232    GetExtensions,
233    /// Turn plugin `plugin` on (`Some(true)`) or off (`Some(false)`) at one level of the
234    /// layered settings, or forget that level's switch (`None`: inherit). Applies from the
235    /// next turn. Answered with [`ServerMsg::Extensions`].
236    SetPluginEnabled {
237        scope: ConfigScope,
238        plugin: String,
239        enabled: Option<bool>,
240    },
241    /// Set (or clear, `None`) a setting the plugin declares. Secret settings go to
242    /// secrets.json, the others to settings.json; values are never sent back, only whether
243    /// each is set ([`PluginSetting::set`]).
244    SetPluginSetting {
245        plugin: String,
246        key: String,
247        value: Option<String>,
248    },
249    /// Keep plugin `plugin` of the chat in view (its scratch copy, or whichever copy the chat
250    /// uses) in the chat's workspace or everywhere, as `new_id` if given. The user asked, so
251    /// there is no approval card.
252    KeepPlugin {
253        plugin: String,
254        scope: PluginScope,
255        #[serde(default, skip_serializing_if = "Option::is_none")]
256        new_id: Option<String>,
257    },
258    /// Delete the copy of plugin `plugin` in `scope` (the chat in view's scratch folder, its
259    /// workspace's `.byob/plugins`, or the global plugins folder).
260    RemovePlugin {
261        plugin: String,
262        scope: PluginScope,
263    },
264    /// Read the plugin folders of the chat in view again now.
265    ReloadPlugins,
266    /// Let the plugins that came with workspace `workspace`'s folder run their tools and
267    /// servers (`trust: true`), or keep them to skills and prompt lines without asking again
268    /// (`false`). `plugins` empty: all of them.
269    TrustPlugins {
270        workspace: String,
271        #[serde(default)]
272        plugins: Vec<String>,
273        trust: bool,
274    },
275    /// A message for plugin `plugin`'s handler in the engine (the plugin channel; only when
276    /// the engine lists [`version::CAP_PLUGIN_CHANNEL`]). Its meaning is the plugin's.
277    Plugin {
278        plugin: String,
279        msg: serde_json::Value,
280    },
281    /// This client shows live view `view` at its site (13.3+, only when the engine lists
282    /// [`sites::CAP_VIEW_SITES`]): answered with a [`ServerMsg::LiveView`] holding its tree,
283    /// then its changes until [`ClientMsg::CloseView`] or another chat is opened.
284    OpenView {
285        view: ViewRef,
286    },
287    /// This client no longer shows `view`.
288    CloseView {
289        view: ViewRef,
290    },
291    /// The user did something in live view `view` (a click, Enter in a field, a cell edit):
292    /// for the plugin's backend, which answers with a new view.
293    ViewEvent {
294        view: ViewRef,
295        event: tree::Event,
296    },
297    /// A call from a web surface for the engine (13.5+, only when the engine lists
298    /// [`web::CAP_WEB_BRIDGE`]): JSON-RPC `method` + `params` from the page whose calls
299    /// `owner` answers. Answered with one [`ServerMsg::WebReply`] of the same `call` number.
300    /// `approved`: the user allowed it after a reply asked ([`web::WebError::approval`]).
301    WebCall {
302        call: u64,
303        owner: web::WebOwner,
304        method: String,
305        #[serde(default)]
306        params: serde_json::Value,
307        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
308        approved: bool,
309    },
310    /// A message from a newer client this engine doesn't know (answered with a notice).
311    #[serde(other)]
312    Unknown,
313}
314
315/// Engine -> client(s).
316#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
317#[serde(tag = "type", rename_all = "snake_case")]
318pub enum ServerMsg {
319    /// The answer to [`ClientMsg::Hello`], first: the engine's version and caps.
320    Welcome(Welcome),
321    /// Full engine state; sent on connect and whenever it changes.
322    State(EngineState),
323    /// A human-readable message for the user (errors, warnings).
324    Notice { level: NoticeLevel, text: String },
325    /// The whole conversation; sent on connect.
326    Transcript { entries: Vec<Entry> },
327    /// A new entry was appended.
328    EntryAdded(Entry),
329    /// Streamed text appended to an entry.
330    EntryDelta { id: u64, content: String, reasoning: String },
331    /// An entry finished streaming.
332    EntryFinished { id: u64, error: Option<String>, stats: Option<TurnStats> },
333    /// A tool step of entry `entry` was added or changed (replace by `step.id`).
334    StepUpdated { entry: u64, step: Step },
335    /// Whether entry `id`'s file changes can be undone, or have been.
336    EntryUndo { id: u64, undoable: bool, undone: bool },
337    /// A page of the chat list. With `after: None` it replaces the client's list (pinned
338    /// chats are in `pinned`); otherwise `recent` continues the list after `after`.
339    Chats { pinned: Vec<ChatSummary>, recent: Vec<ChatSummary>, after: Option<ChatCursor>, next: Option<ChatCursor> },
340    /// A chat was created or changed (title, pin, activity, busy). Sent to every client.
341    ChatUpdated(ChatSummary),
342    /// A chat was deleted. Sent to every client.
343    ChatDeleted { id: String },
344    /// This client now looks at `chat` (`None`: a new chat, not sent yet), which is in
345    /// workspace `workspace`. The chat's [`ServerMsg::Transcript`] follows; entry messages
346    /// only arrive for the chat in view.
347    ChatOpened {
348        chat: Option<ChatSummary>,
349        #[serde(default)]
350        workspace: Option<String>,
351    },
352    /// An upload finished (`attachment`) or failed (`error`). Only sent to the uploader.
353    Uploaded { upload: u64, attachment: Option<MediaRef>, error: Option<String> },
354    /// Answer to [`ClientMsg::GetMedia`].
355    Media { path: String, content: MediaContent },
356    /// Every artifact of the chat this client looks at (`chat`, `None` for a new chat).
357    /// Sent after [`ServerMsg::Transcript`]; replaces the client's list.
358    Artifacts { chat: Option<String>, artifacts: Vec<Artifact> },
359    /// An artifact of the chat in view was created or got a new version.
360    ArtifactUpdated(Artifact),
361    /// Answer to [`ClientMsg::GetArtifact`]: the file, base64 (see [`media::encode`]), or why not.
362    ArtifactFile { id: String, version: u32, data: Option<String>, error: Option<String> },
363    /// Context usage of the chat in view; sent after the transcript and whenever it changes.
364    Usage(ChatUsage),
365    /// Every compaction of the chat in view, oldest first (`chat`, `None` for a new chat).
366    /// Sent after [`ServerMsg::Transcript`] (before `Artifacts`); replaces the client's list.
367    Compactions { chat: Option<String>, items: Vec<Compaction> },
368    /// The chat in view was just compacted.
369    Compacted(Compaction),
370    /// The subagent run of step `step` (in entry `entry`) changed.
371    Delegation { entry: u64, step: u64, update: DelegationUpdate },
372    /// Answer to [`ClientMsg::TestInference`].
373    InferenceTested(InferenceTest),
374    /// Answer to [`ClientMsg::WorkspaceEnv`]: the environment of a workspace.
375    WorkspaceEnv(WorkspaceEnv),
376    /// Every workspace, most recently active first; sent on connect and whenever one is
377    /// added, renamed, removed or changes its chat count. `current` is where new chats go
378    /// by default; `root` is where fresh workspace folders are created.
379    Workspaces { items: Vec<WorkspaceSummary>, current: Option<String>, root: String, support: EnvSupport },
380    /// Answer to [`ClientMsg::GetConfig`] / [`ClientMsg::SetConfig`].
381    Config(Box<ConfigView>),
382    /// Answer to [`ClientMsg::ListFolders`].
383    Folders(FolderList),
384    /// Answer to [`ClientMsg::CheckContainers`].
385    ContainersChecked { ok: bool, message: String },
386    /// Answer to [`ClientMsg::CreateWorkspace`].
387    WorkspaceCreated { id: Option<String>, error: Option<String> },
388    /// The queue of the chat in view; sent after [`ServerMsg::Transcript`] and whenever it
389    /// changes.
390    Queue(ChatQueue),
391    /// The plugins of the chat in view; sent after [`ServerMsg::ChatOpened`], on
392    /// [`ClientMsg::GetExtensions`], and whenever they change.
393    Extensions(Box<Extensions>),
394    /// A message from plugin `plugin` in the engine (the plugin channel; only to clients
395    /// that list [`version::CAP_PLUGIN_CHANNEL`]).
396    Plugin { plugin: String, msg: serde_json::Value },
397    /// A live view's tree, a change to it, or why it can't be shown (13.3+; only to clients
398    /// that listed [`sites::CAP_VIEW_SITES`] and opened it, see [`sites`]).
399    LiveView(LiveView),
400    /// The answer to [`ClientMsg::WebCall`] `call` (only to the client that called): a
401    /// JSON-RPC `result` or an `error`.
402    WebReply {
403        call: u64,
404        /// `Some(Value::Null)` for a JSON-RPC `null` result, which is sent as `null`.
405        #[serde(default, deserialize_with = "present_even_if_null", skip_serializing_if = "Option::is_none")]
406        result: Option<serde_json::Value>,
407        #[serde(default, skip_serializing_if = "Option::is_none")]
408        error: Option<web::WebError>,
409    },
410    /// A JSON-RPC message (a notification) for the web surfaces `owner` answers, from the
411    /// owner (a plugin's backend; only to clients that listed [`web::CAP_WEB_BRIDGE`]).
412    WebPush { owner: web::WebOwner, msg: serde_json::Value },
413    /// A message from a newer engine this client doesn't know: skip it.
414    #[serde(other)]
415    Unknown,
416}
417
418/// A chat as shown in the sidebar.
419#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
420pub struct ChatSummary {
421    pub id: String,
422    pub title: String,
423    /// Milliseconds since the Unix epoch of the last activity; the list is ordered by it.
424    pub updated_at: i64,
425    /// When it was pinned (ms since the epoch), if it is. Pinned chats list first.
426    pub pinned_at: Option<i64>,
427    /// A reply is running in this chat.
428    #[serde(default)]
429    pub busy: bool,
430    /// The workspace it belongs to.
431    #[serde(default, skip_serializing_if = "Option::is_none")]
432    pub workspace: Option<String>,
433}
434
435impl ChatSummary {
436    pub fn cursor(&self) -> ChatCursor {
437        ChatCursor { updated_at: self.updated_at, id: self.id.clone() }
438    }
439}
440
441/// Position in the recent-first chat list, for paging.
442#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
443pub struct ChatCursor {
444    pub updated_at: i64,
445    pub id: String,
446}
447
448#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
449#[serde(rename_all = "snake_case")]
450pub enum EntryRole {
451    User,
452    Assistant,
453}
454
455/// One message in the conversation as shown to users.
456#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
457pub struct Entry {
458    pub id: u64,
459    pub role: EntryRole,
460    pub content: String,
461    pub reasoning: String,
462    /// False while the reply is still streaming.
463    pub done: bool,
464    pub error: Option<String>,
465    pub stats: Option<TurnStats>,
466    /// Tool calls made while producing this reply, in order. Part of the transcript so a
467    /// client that connects late sees them and can answer pending approvals.
468    #[serde(default)]
469    pub steps: Vec<Step>,
470    /// Every file change of this reply can be reversed with [`ClientMsg::Undo`].
471    #[serde(default)]
472    pub undoable: bool,
473    /// The reply's file changes were undone.
474    #[serde(default)]
475    pub undone: bool,
476    /// Files the user attached to this message.
477    #[serde(default, skip_serializing_if = "Vec::is_empty")]
478    pub attachments: Vec<MediaRef>,
479}
480
481impl Entry {
482    /// Apply a [`ServerMsg::EntryDelta`].
483    pub fn append(&mut self, content: &str, reasoning: &str) {
484        self.content.push_str(content);
485        self.reasoning.push_str(reasoning);
486    }
487
488    /// Apply a [`ServerMsg::StepUpdated`]: replace the step with the same id, or append it.
489    pub fn upsert_step(&mut self, step: Step) {
490        match self.steps.iter_mut().find(|s| s.id == step.id) {
491            Some(existing) => *existing = step,
492            None => self.steps.push(step),
493        }
494    }
495
496    /// Steps waiting for a user's approval, subagents' steps included.
497    pub fn pending_approvals(&self) -> impl Iterator<Item = &Step> {
498        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)
499    }
500
501    /// Apply a [`ServerMsg::Delegation`] to step `step`'s subagent run.
502    pub fn apply_delegation(&mut self, step: u64, update: &DelegationUpdate) {
503        if let Some(d) = self.steps.iter_mut().find(|s| s.id == step).and_then(|s| s.delegation.as_deref_mut()) {
504            d.apply(update);
505        }
506    }
507}
508
509/// How dangerous a tool call is; drives the permission gate. Mirrors `byob_tools::Access`.
510#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
511#[serde(rename_all = "snake_case")]
512pub enum ToolAccess {
513    Read,
514    Write,
515    Network,
516    Execute,
517}
518
519impl ToolAccess {
520    pub fn label(self) -> &'static str {
521        match self {
522            Self::Read => "read",
523            Self::Write => "write",
524            Self::Network => "network",
525            Self::Execute => "execute",
526        }
527    }
528}
529
530#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
531#[serde(rename_all = "snake_case")]
532pub enum StepStatus {
533    Running,
534    /// An approval request: blocked until a client sends [`ClientMsg::Approve`].
535    Waiting,
536    Done,
537    /// The tool ran (or could not run) and reported an error.
538    Failed,
539    /// The user (or the policy) said no, or the turn was stopped while waiting.
540    Denied,
541}
542
543impl StepStatus {
544    pub fn finished(self) -> bool {
545        matches!(self, Self::Done | Self::Failed | Self::Denied)
546    }
547}
548
549/// A user's answer to an approval request.
550#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
551#[serde(rename_all = "snake_case")]
552pub enum ApprovalAnswer {
553    Allow,
554    /// Allow, and stop asking about this tool in this chat (remembered across restarts).
555    Always,
556    Deny,
557    /// Allow, and stop asking about this tool in every chat.
558    AlwaysEverywhere,
559    /// An answer from a newer client this engine doesn't know: treated as Deny.
560    #[serde(other)]
561    Unknown,
562}
563
564/// A file-system effect of a tool call. Paths are for display (workspace-relative when possible).
565#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
566#[serde(tag = "kind", rename_all = "snake_case")]
567pub enum FileChange {
568    Created {
569        path: String,
570    },
571    Modified {
572        path: String,
573    },
574    Deleted {
575        path: String,
576    },
577    Moved {
578        from: String,
579        to: String,
580    },
581    /// A change a newer engine reports that this client doesn't know (not shown).
582    #[serde(other)]
583    Other,
584}
585
586/// One tool call inside an assistant reply.
587#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
588pub struct Step {
589    /// Unique within the engine; also the approval id.
590    pub id: u64,
591    /// Tool name, e.g. `read_file`.
592    pub tool: String,
593    /// Short human title, e.g. "Read notes.md".
594    pub title: String,
595    pub access: ToolAccess,
596    pub status: StepStatus,
597    /// Short detail: the arguments while running or waiting, then a result excerpt or reason.
598    pub detail: String,
599    #[serde(default)]
600    pub changes: Vec<FileChange>,
601    /// Byte offset into the entry's `content` when the step started, for interleaving.
602    #[serde(default)]
603    pub at: usize,
604    /// Charts and images this call made, shown inline.
605    #[serde(default, skip_serializing_if = "Vec::is_empty")]
606    pub media: Vec<MediaRef>,
607    /// What the call will do, readable, for the approval card and the expanded row.
608    #[serde(default, skip_serializing_if = "Option::is_none")]
609    pub preview: Option<Preview>,
610    /// Artifact versions this call made, shown as cards where it happened.
611    #[serde(default, skip_serializing_if = "Vec::is_empty")]
612    pub artifacts: Vec<ArtifactRef>,
613    /// The subagent run of a `delegate` step: its live transcript.
614    #[serde(default, skip_serializing_if = "Option::is_none")]
615    pub delegation: Option<Box<Delegation>>,
616    /// Set when the approval card isn't an ordinary tool call: a question a tool asks while
617    /// it runs, or a call a person must confirm every time. Such cards offer only Allow
618    /// and Deny.
619    #[serde(default, skip_serializing_if = "Option::is_none")]
620    pub ask: Option<Box<Ask>>,
621    /// Cards shown under the step ([`View`]s, e.g. a `byob.plugin_card` when it made,
622    /// changed, kept or removed a plugin). Set on the finished step, and stored with it (a
623    /// transcript loaded from storage has them too).
624    #[serde(default, skip_serializing_if = "Vec::is_empty")]
625    pub views: Vec<View>,
626}
627
628impl Step {
629    /// The step's first view of type `T` this build can read.
630    pub fn view<T: ViewData>(&self) -> Option<T> {
631        self.views.iter().find_map(View::get)
632    }
633}
634
635/// The special part of an approval card (see [`Step::ask`]).
636#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
637pub struct Ask {
638    /// What saying yes means.
639    #[serde(default)]
640    pub text: String,
641    /// Shown prominently, e.g. that it installs system-wide.
642    #[serde(default, skip_serializing_if = "Option::is_none")]
643    pub warning: Option<String>,
644    /// Only a person can allow it: no policy, grant or `--auto-approve` does.
645    #[serde(default)]
646    pub always: bool,
647}
648
649/// Most lines in a [`Preview`]'s line lists.
650pub const MAX_PREVIEW_LINES: usize = 40;
651/// Most characters in one preview line or value.
652pub const MAX_PREVIEW_LINE_CHARS: usize = 300;
653
654/// A readable account of a tool call, built from its (untrusted, bounded) arguments.
655#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
656#[serde(tag = "kind", rename_all = "snake_case")]
657pub enum Preview {
658    /// Create or replace a file. `lines` is the start of the new content, or for a
659    /// replacement a compact line diff against the current file.
660    Write {
661        path: String,
662        bytes: u64,
663        /// The file exists and will be replaced.
664        replaces: bool,
665        lines: Vec<DiffLine>,
666        /// Lines (or changes) not shown.
667        #[serde(default)]
668        more: usize,
669    },
670    /// Move or rename: `(from, to)` pairs.
671    Move {
672        moves: Vec<(String, String)>,
673        #[serde(default)]
674        more: usize,
675    },
676    /// Move something to the trash; `what` describes it, e.g. "file, 2.1 KB".
677    Delete { path: String, what: String },
678    /// Any other tool: its key arguments. `code` is command/script text, shown monospaced.
679    Args {
680        fields: Vec<(String, String)>,
681        #[serde(default, skip_serializing_if = "Option::is_none")]
682        code: Option<String>,
683        #[serde(default)]
684        more: usize,
685    },
686    /// A preview a newer engine sends that this client doesn't know (not shown).
687    #[serde(other)]
688    Other,
689}
690
691/// One line of a preview's content or diff.
692#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
693pub struct DiffLine {
694    pub kind: LineKind,
695    pub text: String,
696}
697
698#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
699#[serde(rename_all = "snake_case")]
700pub enum LineKind {
701    /// Unchanged (or, for a new file, plain content).
702    Same,
703    Added,
704    Removed,
705    /// Unchanged lines left out; `text` says how many.
706    Skipped,
707}
708
709#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
710pub struct TurnStats {
711    pub prompt_tokens: u64,
712    pub completion_tokens: u64,
713    pub elapsed_ms: u64,
714    /// Model requests the reply took (tool rounds and compactions included).
715    #[serde(default)]
716    pub model_calls: u64,
717}
718
719#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
720#[serde(rename_all = "snake_case")]
721pub enum NoticeLevel {
722    Error,
723    /// Also any level a newer engine sends that this client doesn't know.
724    #[serde(other)]
725    Info,
726}
727
728/// What clients may know about the engine. Secrets (API keys) never leave the engine.
729#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
730pub struct EngineState {
731    pub version: String,
732    pub inference_base_url: String,
733    pub inference_model: String,
734    pub has_api_key: bool,
735    /// Resolved `chat/completions` URL, if the base URL is valid.
736    pub endpoint: Option<String>,
737    /// A turn is running in the chat this client is looking at.
738    pub busy: bool,
739    /// What the engine knows about the inference endpoint (from its capability probe).
740    #[serde(default)]
741    pub endpoint_info: Option<EndpointInfo>,
742    /// Whether the current endpoint answers.
743    #[serde(default)]
744    pub link: Link,
745    /// An endpoint has worked before (saved in settings.json): returning users skip the
746    /// welcome screen.
747    #[serde(default)]
748    pub onboarded: bool,
749    /// Inference servers found on this machine's usual ports.
750    #[serde(default)]
751    pub detected: Vec<Detected>,
752    /// The engine is looking for them.
753    #[serde(default)]
754    pub detecting: bool,
755    /// The chat in view uses another endpoint than the one above (its workspace's or its
756    /// own); `None`: it uses the global one.
757    #[serde(default, skip_serializing_if = "Option::is_none")]
758    pub chat_endpoint: Option<ChatEndpoint>,
759}
760
761/// How turns pass tools to the model.
762#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
763#[serde(rename_all = "snake_case")]
764pub enum ToolsMode {
765    /// The server's structured `tools` / `tool_calls`.
766    Native,
767    /// Tools described in the system prompt; calls parsed from the reply text.
768    Prompt,
769    /// Not known yet: native first, switching to prompt mode if the server rejects tools.
770    #[default]
771    Unknown,
772}
773
774/// Capability summary of the inference endpoint, for a small header detail.
775#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
776pub struct EndpointInfo {
777    /// The probe is still running.
778    #[serde(default)]
779    pub probing: bool,
780    /// Server software, e.g. "llama.cpp", "vLLM", "Ollama"; empty if unknown.
781    #[serde(default)]
782    pub server: String,
783    /// Context window in tokens, if the server reports it.
784    #[serde(default)]
785    pub context_tokens: Option<u64>,
786    #[serde(default)]
787    pub tools: ToolsMode,
788    /// Takes image input: `Some(true)` yes, `Some(false)` no, `None` unknown.
789    #[serde(default)]
790    pub vision: Option<bool>,
791}
792
793impl EndpointInfo {
794    /// One short line, e.g. "llama.cpp · 262k ctx · native tools · vision".
795    pub fn summary(&self) -> String {
796        if self.probing {
797            return "checking endpoint…".into();
798        }
799        let mut parts = Vec::new();
800        if !self.server.is_empty() {
801            parts.push(self.server.clone());
802        }
803        if let Some(n) = self.context_tokens {
804            parts.push(if n >= 1000 { format!("{}k ctx", n / 1000) } else { format!("{n} ctx") });
805        }
806        parts.push(
807            match self.tools {
808                ToolsMode::Native => "native tools",
809                ToolsMode::Prompt => "prompt tools",
810                ToolsMode::Unknown => "tools untested",
811            }
812            .into(),
813        );
814        if self.vision == Some(true) {
815            parts.push("vision".into());
816        }
817        parts.join(" · ")
818    }
819}
820
821impl ClientMsg {
822    /// This build's [`ClientMsg::Hello`].
823    pub fn hello(client: &str) -> Self {
824        Self::Hello { protocol: PROTOCOL_MAJOR, minor: PROTOCOL_MINOR, client: client.to_owned(), caps: version::client_caps() }
825    }
826
827    pub fn to_json(&self) -> String {
828        serde_json::to_string(self).unwrap_or_default()
829    }
830
831    /// Parse an untrusted frame.
832    pub fn from_json(text: &str) -> Result<Self, String> {
833        if text.len() > MAX_FRAME_BYTES {
834            return Err(format!("frame too large ({} bytes)", text.len()));
835        }
836        serde_json::from_str(text).map_err(|e| e.to_string())
837    }
838}
839
840impl ServerMsg {
841    pub fn to_json(&self) -> String {
842        serde_json::to_string(self).unwrap_or_default()
843    }
844
845    /// The frame for a remote client: the JSON, or, if that is over [`MAX_FRAME_BYTES`] (the
846    /// client would refuse it and wait forever), a small message in its place that the
847    /// client acts on: a view change becomes `reset` (the client opens the view again and
848    /// gets the whole tree), a view's tree an `error` at its site, a web reply an error
849    /// answer to its call, anything else a notice.
850    pub fn to_frame(&self) -> String {
851        let json = self.to_json();
852        if json.len() <= MAX_FRAME_BYTES {
853            return json;
854        }
855        let why = format!("it is too large to send over this connection ({} KB, at most {} KB)", json.len() / 1024, MAX_FRAME_BYTES / 1024);
856        let instead = match self {
857            Self::LiveView(lv) if lv.tree.is_none() => Self::LiveView(LiveView { view: lv.view.clone(), reset: true, ..Default::default() }),
858            Self::LiveView(lv) => {
859                Self::LiveView(LiveView { view: lv.view.clone(), error: Some(format!("This view can't be shown here: {why}.")), ..Default::default() })
860            }
861            Self::WebReply { call, .. } => {
862                Self::WebReply { call: *call, result: None, error: Some(web::WebError::new(-32000, format!("byob couldn't send the answer: {why}"))) }
863            }
864            _ => Self::Notice { level: NoticeLevel::Error, text: format!("byob couldn't send an update: {why}.") },
865        };
866        instead.to_json()
867    }
868
869    /// Parse an untrusted frame.
870    pub fn from_json(text: &str) -> Result<Self, String> {
871        if text.len() > MAX_FRAME_BYTES {
872            return Err(format!("frame too large ({} bytes)", text.len()));
873        }
874        serde_json::from_str(text).map_err(|e| e.to_string())
875    }
876}
877
878/// A client's link to an engine, in-process or over a WebSocket. Never blocks.
879pub trait Connection {
880    fn send(&mut self, msg: ClientMsg);
881    /// Next pending message, if any. Called every UI frame.
882    fn try_recv(&mut self) -> Option<ServerMsg>;
883}
884
885/// An optional field where a present `null` is `Some(Value::Null)`, not `None` (serde's
886/// default for `Option`); pair with `#[serde(default)]` so a missing one is `None`.
887fn present_even_if_null<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<serde_json::Value>, D::Error> {
888    serde_json::Value::deserialize(d).map(Some)
889}
890
891#[cfg(test)]
892mod tests {
893    use super::*;
894
895    /// Regression: a `null` result decoded as `None`, so remote clients answered the page
896    /// with `{}` where the desktop answered `null`.
897    #[test]
898    fn web_reply_keeps_a_null_result() {
899        let null = ServerMsg::WebReply { call: 3, result: Some(serde_json::Value::Null), error: None };
900        assert_eq!(null.to_json(), r#"{"type":"web_reply","call":3,"result":null}"#);
901        assert_eq!(ServerMsg::from_json(&null.to_json()).unwrap(), null);
902        let none = ServerMsg::WebReply { call: 3, result: None, error: None };
903        assert_eq!(none.to_json(), r#"{"type":"web_reply","call":3}"#);
904        assert_eq!(ServerMsg::from_json(&none.to_json()).unwrap(), none);
905        let value = ServerMsg::WebReply { call: 3, result: Some(serde_json::json!({"a": [1]})), error: None };
906        assert_eq!(ServerMsg::from_json(&value.to_json()).unwrap(), value);
907    }
908
909    #[test]
910    fn client_msg_round_trips() {
911        let m = ClientMsg::hello("test");
912        assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
913    }
914
915    #[test]
916    fn wire_format_is_tagged() {
917        let json = ServerMsg::Notice { level: NoticeLevel::Info, text: "hi".into() }.to_json();
918        assert_eq!(json, r#"{"type":"notice","level":"info","text":"hi"}"#);
919    }
920
921    #[test]
922    fn a_message_too_large_for_a_frame_is_sent_as_something_the_client_acts_on() {
923        let big = "x".repeat(MAX_FRAME_BYTES);
924        let r = ViewRef::new("p", "v", "k");
925        let small = ServerMsg::Notice { level: NoticeLevel::Info, text: "hi".into() };
926        assert_eq!(small.to_frame(), small.to_json());
927        let frame = |m: ServerMsg| {
928            let f = m.to_frame();
929            assert!(f.len() < 1024, "{} bytes", f.len());
930            ServerMsg::from_json(&f).unwrap()
931        };
932        let mut values = serde_json::Map::new();
933        values.insert("f".into(), serde_json::json!(big));
934        let change = LiveView { view: r.clone(), values, ..Default::default() };
935        assert_eq!(frame(ServerMsg::LiveView(change)), ServerMsg::LiveView(LiveView { view: r.clone(), reset: true, ..Default::default() }));
936        // Within the tree caps (64 K characters a text), over a frame all the same.
937        let texts: Vec<_> = (0..100).map(|_| serde_json::json!({"type": "text", "text": "y".repeat(60_000)})).collect();
938        let (tree, faults) = tree::decode(serde_json::json!({"type": "column", "children": texts}));
939        assert!(faults.is_empty(), "{faults:?}");
940        match frame(ServerMsg::LiveView(LiveView { view: r.clone(), tree: Some(tree), ..Default::default() })) {
941            ServerMsg::LiveView(lv) => assert!(lv.view == r && lv.tree.is_none() && lv.error.is_some_and(|e| e.contains("too large"))),
942            other => panic!("{other:?}"),
943        }
944        match frame(ServerMsg::WebReply { call: 9, result: Some(serde_json::json!(big)), error: None }) {
945            ServerMsg::WebReply { call: 9, result: None, error: Some(e) } => assert!(e.message.contains("too large")),
946            other => panic!("{other:?}"),
947        }
948        let plugin = ServerMsg::Plugin { plugin: "p".into(), msg: serde_json::json!(big) };
949        assert!(matches!(frame(plugin), ServerMsg::Notice { level: NoticeLevel::Error, .. }));
950    }
951
952    #[test]
953    fn rejects_garbage_and_oversized_frames() {
954        assert!(ClientMsg::from_json("{not json").is_err());
955        assert!(ClientMsg::from_json(&" ".repeat(MAX_FRAME_BYTES + 1)).is_err());
956    }
957
958    #[test]
959    fn approve_wire_format() {
960        let m = ClientMsg::Approve { step: 7, answer: ApprovalAnswer::Always };
961        assert_eq!(m.to_json(), r#"{"type":"approve","step":7,"answer":"always"}"#);
962        assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
963    }
964
965    fn step(id: u64, status: StepStatus) -> Step {
966        Step {
967            id,
968            tool: "t".into(),
969            title: "T".into(),
970            access: ToolAccess::Write,
971            status,
972            detail: String::new(),
973            changes: vec![],
974            at: 0,
975            preview: None,
976            media: vec![],
977            artifacts: vec![],
978            delegation: None,
979            ask: None,
980            views: vec![],
981        }
982    }
983
984    #[test]
985    fn delegations_stream_into_their_step_and_round_trip() {
986        let mut parent = step(1, StepStatus::Running);
987        parent.delegation = Some(Box::new(Delegation { agent: "explorer".into(), task: "count lines".into(), ..Default::default() }));
988        let mut e = Entry {
989            id: 9,
990            role: EntryRole::Assistant,
991            content: String::new(),
992            reasoning: String::new(),
993            done: false,
994            error: None,
995            stats: None,
996            steps: vec![parent],
997            undoable: false,
998            undone: false,
999            attachments: vec![],
1000        };
1001        let updates = [
1002            DelegationUpdate::Status { state: DelegationState::Running, prompt_tokens: 0, completion_tokens: 0, error: None },
1003            DelegationUpdate::Delta { content: "Reading".into(), reasoning: "hm".into() },
1004            DelegationUpdate::Step(Box::new(step(2, StepStatus::Waiting))),
1005            DelegationUpdate::Delta { content: " a.txt".into(), reasoning: String::new() },
1006        ];
1007        for u in &updates {
1008            let msg = ServerMsg::Delegation { entry: 9, step: 1, update: u.clone() };
1009            assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1010            e.apply_delegation(1, u);
1011        }
1012        // An unknown step is ignored.
1013        e.apply_delegation(77, &updates[1]);
1014        let d = e.steps[0].delegation.as_deref().unwrap();
1015        assert_eq!((d.content.as_str(), d.reasoning.as_str(), d.state), ("Reading a.txt", "hm", DelegationState::Running));
1016        assert_eq!(d.status_line(), "explorer · 1 tool · waiting for approval");
1017        // A child's approval card counts as pending in the entry.
1018        assert_eq!(e.pending_approvals().map(|s| s.id).collect::<Vec<_>>(), vec![2]);
1019        e.apply_delegation(1, &DelegationUpdate::Step(Box::new(step(2, StepStatus::Done))));
1020        e.apply_delegation(1, &DelegationUpdate::Status { state: DelegationState::Done, prompt_tokens: 50, completion_tokens: 5, error: None });
1021        assert_eq!(e.steps[0].delegation.as_deref().unwrap().status_line(), "explorer · 1 tool · done");
1022        assert_eq!(e.pending_approvals().count(), 0);
1023        let msg = ServerMsg::StepUpdated { entry: 9, step: e.steps[0].clone() };
1024        assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1025        // Steps from an older engine have no delegation.
1026        let json = r#"{"id":1,"tool":"t","title":"T","access":"read","status":"done","detail":""}"#;
1027        assert!(serde_json::from_str::<Step>(json).unwrap().delegation.is_none());
1028    }
1029
1030    #[test]
1031    fn steps_upsert_and_round_trip() {
1032        let mut e = Entry {
1033            id: 1,
1034            role: EntryRole::Assistant,
1035            content: String::new(),
1036            reasoning: String::new(),
1037            done: false,
1038            error: None,
1039            stats: None,
1040            steps: vec![],
1041            undoable: false,
1042            undone: false,
1043            attachments: vec![],
1044        };
1045        e.upsert_step(step(3, StepStatus::Running));
1046        e.upsert_step(step(4, StepStatus::Waiting));
1047        e.upsert_step(step(3, StepStatus::Done));
1048        assert_eq!(e.steps.len(), 2);
1049        assert_eq!(e.steps[0].status, StepStatus::Done);
1050        assert_eq!(e.pending_approvals().map(|s| s.id).collect::<Vec<_>>(), vec![4]);
1051        let mut s = step(5, StepStatus::Done);
1052        s.changes = vec![FileChange::Moved { from: "a".into(), to: "b".into() }];
1053        let msg = ServerMsg::StepUpdated { entry: 1, step: s };
1054        assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1055    }
1056
1057    #[test]
1058    fn entry_without_steps_still_parses() {
1059        let json = r#"{"id":1,"role":"user","content":"hi","reasoning":"","done":true,"error":null,"stats":null}"#;
1060        let e: Entry = serde_json::from_str(json).unwrap();
1061        assert!(e.steps.is_empty());
1062    }
1063
1064    #[test]
1065    fn undo_and_preview_wire_format() {
1066        let m = ClientMsg::Undo { entry: 4 };
1067        assert_eq!(m.to_json(), r#"{"type":"undo","entry":4}"#);
1068        assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1069        let mut s = step(1, StepStatus::Waiting);
1070        s.preview =
1071            Some(Preview::Write { path: "a.md".into(), bytes: 3, replaces: true, lines: vec![DiffLine { kind: LineKind::Added, text: "hi".into() }], more: 0 });
1072        let msg = ServerMsg::StepUpdated { entry: 1, step: s };
1073        assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1074        let msg = ServerMsg::EntryUndo { id: 1, undoable: false, undone: true };
1075        assert_eq!(ServerMsg::from_json(&msg.to_json()).unwrap(), msg);
1076    }
1077
1078    #[test]
1079    fn chat_messages_round_trip() {
1080        let summary = ChatSummary { id: "c1".into(), title: "Plans".into(), updated_at: 5, pinned_at: None, busy: true, workspace: Some("w1".into()) };
1081        for m in [
1082            ServerMsg::Chats { pinned: vec![], recent: vec![summary.clone()], after: None, next: Some(summary.cursor()) },
1083            ServerMsg::ChatUpdated(summary.clone()),
1084            ServerMsg::ChatOpened { chat: Some(summary), workspace: None },
1085            ServerMsg::ChatDeleted { id: "c1".into() },
1086        ] {
1087            assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1088        }
1089        let m = ClientMsg::ListChats { after: Some(ChatCursor { updated_at: 1, id: "x".into() }), limit: 50 };
1090        assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1091        assert_eq!(ClientMsg::NewChat { workspace: None }.to_json(), r#"{"type":"new_chat"}"#);
1092    }
1093
1094    #[test]
1095    fn endpoint_info_is_optional_and_summarised() {
1096        let old = r#"{"version":"0","inference_base_url":"u","inference_model":"m","has_api_key":false,"endpoint":null,"busy":false}"#;
1097        assert_eq!(serde_json::from_str::<EngineState>(old).unwrap().endpoint_info, None);
1098        let info = EndpointInfo { probing: false, server: "llama.cpp".into(), context_tokens: Some(262_144), tools: ToolsMode::Native, vision: Some(true) };
1099        assert_eq!(info.summary(), "llama.cpp · 262k ctx · native tools · vision");
1100        assert_eq!(EndpointInfo { probing: true, ..info }.summary(), "checking endpoint…");
1101        assert_eq!(EndpointInfo::default().summary(), "tools untested");
1102    }
1103
1104    #[test]
1105    fn media_messages_round_trip() {
1106        let msgs = vec![
1107            ClientMsg::SendMessage { text: "chart it".into(), attachments: vec!["uploads/sales.csv".into()] },
1108            ClientMsg::Upload { upload: 1, name: "a.csv".into(), size: 3, offset: 0, data: media::encode(b"a,b"), done: true },
1109            ClientMsg::GetMedia { path: "charts/x.chart.json".into() },
1110        ];
1111        for m in msgs {
1112            assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1113        }
1114        let spec = byob_types::chart::validate(&serde_json::json!({"type": "bar", "x": "m", "series": ["v"], "data": [{"m": "a", "v": 1}]})).unwrap();
1115        let msgs = vec![
1116            ServerMsg::Uploaded { upload: 1, attachment: Some(MediaRef::new("uploads/a.csv", 3)), error: None },
1117            ServerMsg::Media { path: "c.chart.json".into(), content: MediaContent::Chart { spec } },
1118            ServerMsg::Media { path: "p.png".into(), content: MediaContent::Image { mime: "image/png".into(), data: "AA==".into() } },
1119            ServerMsg::Media { path: "p.png".into(), content: MediaContent::Error { message: "gone".into() } },
1120        ];
1121        for m in msgs {
1122            assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1123        }
1124        let mut s = step(1, StepStatus::Done);
1125        s.media = vec![MediaRef::new("charts/x.chart.json", 10)];
1126        let m = ServerMsg::StepUpdated { entry: 1, step: s };
1127        assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1128    }
1129
1130    #[test]
1131    fn artifact_messages_round_trip() {
1132        let v = ArtifactVersion { n: 2, path: ".byob/artifacts/calc/v2.html".into(), created_at: 1, note: "blue button".into(), size: 10 };
1133        let a = Artifact {
1134            id: "calc".into(),
1135            kind: ArtifactKind::Html,
1136            content_type: artifact::TYPE_HTML.into(),
1137            title: "Calc".into(),
1138            filename: "calc.html".into(),
1139            versions: vec![v],
1140        };
1141        let msgs = vec![
1142            ServerMsg::Artifacts { chat: Some("c1".into()), artifacts: vec![a.clone()] },
1143            ServerMsg::Artifacts { chat: None, artifacts: vec![] },
1144            ServerMsg::ArtifactUpdated(a),
1145            ServerMsg::ArtifactFile { id: "calc".into(), version: 2, data: Some(media::encode(b"<p>")), error: None },
1146            ServerMsg::ArtifactFile { id: "calc".into(), version: 9, data: None, error: Some("no such version".into()) },
1147        ];
1148        for m in msgs {
1149            assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1150        }
1151        let m = ClientMsg::GetArtifact { id: "calc".into(), version: 2 };
1152        assert_eq!(m.to_json(), r#"{"type":"get_artifact","id":"calc","version":2}"#);
1153        assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1154        let mut s = step(1, StepStatus::Done);
1155        s.artifacts = vec![ArtifactRef { id: "calc".into(), version: 2 }];
1156        let m = ServerMsg::StepUpdated { entry: 1, step: s };
1157        assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1158        // A step from an older engine has no artifacts.
1159        let json = r#"{"id":1,"tool":"t","title":"T","access":"read","status":"done","detail":""}"#;
1160        assert!(serde_json::from_str::<Step>(json).unwrap().artifacts.is_empty());
1161    }
1162
1163    #[test]
1164    fn older_send_message_without_attachments_parses() {
1165        let m = ClientMsg::from_json(r#"{"type":"send_message","text":"hi"}"#).unwrap();
1166        assert_eq!(m, ClientMsg::SendMessage { text: "hi".into(), attachments: vec![] });
1167        assert_eq!(m.to_json(), r#"{"type":"send_message","text":"hi"}"#);
1168    }
1169
1170    #[test]
1171    fn compaction_messages_round_trip() {
1172        let c = Compaction {
1173            id: 1,
1174            after_entry: 7,
1175            tokens_before: 182_000,
1176            tokens_after: 9_000,
1177            summary: "## Goals".into(),
1178            manual: true,
1179            focus: Some("CSV".into()),
1180            created_at: 5,
1181        };
1182        let u = ChatUsage { chat: "c1".into(), context_used: 34_000, context_window: 262_144, compact_at: 209_715, model_calls: 3, ..Default::default() };
1183        for m in [ServerMsg::Usage(u), ServerMsg::Compactions { chat: Some("c1".into()), items: vec![c.clone()] }, ServerMsg::Compacted(c)] {
1184            assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1185        }
1186        assert_eq!(ClientMsg::Compact { focus: None }.to_json(), r#"{"type":"compact"}"#);
1187        let m = ClientMsg::from_json(r#"{"type":"compact","focus":"keep the CSV"}"#).unwrap();
1188        assert_eq!(m, ClientMsg::Compact { focus: Some("keep the CSV".into()) });
1189        // Stats from an older engine have no call count.
1190        let s: TurnStats = serde_json::from_str(r#"{"prompt_tokens":1,"completion_tokens":2,"elapsed_ms":3}"#).unwrap();
1191        assert_eq!(s.model_calls, 0);
1192    }
1193
1194    #[test]
1195    fn connection_messages_round_trip() {
1196        for m in [
1197            ClientMsg::TestInference { base_url: "http://127.0.0.1:11434/v1".into(), model: "qwen3".into(), api_key: None },
1198            ClientMsg::TestInference { base_url: "https://api.openai.com/v1".into(), model: "m".into(), api_key: Some("sk".into()) },
1199            ClientMsg::DetectEndpoints,
1200            ClientMsg::Retry,
1201        ] {
1202            assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m);
1203        }
1204        assert_eq!(ClientMsg::Retry.to_json(), r#"{"type":"retry"}"#);
1205        let t = InferenceTest { base_url: "u".into(), model: "m".into(), ok: false, problem: Some(Problem::Unauthorized), detail: "x".into(), models: vec![] };
1206        let m = ServerMsg::InferenceTested(t);
1207        assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1208        let state = EngineState {
1209            link: Link::failed("could not reach u: refused"),
1210            onboarded: true,
1211            detected: vec![Detected { preset: "ollama".into(), base_url: "http://127.0.0.1:11434/v1".into(), models: vec!["qwen3".into()] }],
1212            ..Default::default()
1213        };
1214        let m = ServerMsg::State(state);
1215        assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
1216        // State from an older engine: link unknown, not onboarded.
1217        let old = r#"{"version":"0","inference_base_url":"u","inference_model":"m","has_api_key":false,"endpoint":null,"busy":false}"#;
1218        let s = serde_json::from_str::<EngineState>(old).unwrap();
1219        assert_eq!((s.link, s.onboarded, s.detected.len()), (Link::Unknown, false, 0));
1220    }
1221
1222    #[test]
1223    fn hello_negotiates_and_old_hellos_still_parse() {
1224        let m = ClientMsg::hello("desktop");
1225        let ClientMsg::Hello { protocol, minor, caps, .. } = &m else { panic!() };
1226        assert_eq!((*protocol, *minor), (PROTOCOL_MAJOR, PROTOCOL_MINOR));
1227        assert!(caps.iter().any(|c| c == version::CAP_PLUGIN_CHANNEL));
1228        assert!(m.check_sizes().is_ok());
1229        // A protocol-12 client says only its version: it parses, so the engine can tell it why not.
1230        let old = ClientMsg::from_json(r#"{"type":"hello","protocol":12,"client":"old tab"}"#).unwrap();
1231        assert_eq!(old, ClientMsg::Hello { protocol: 12, minor: 0, client: "old tab".into(), caps: vec![] });
1232        let bad = ClientMsg::Hello { protocol: PROTOCOL_MAJOR, minor: 0, client: "x".into(), caps: vec!["NOT A CAP".into()] };
1233        assert!(bad.check_sizes().is_err());
1234        let w = ServerMsg::Welcome(Welcome::current());
1235        assert_eq!(ServerMsg::from_json(&w.to_json()).unwrap(), w);
1236        assert!(w.to_json().starts_with(r#"{"type":"welcome","protocol":13"#), "{}", w.to_json());
1237    }
1238
1239    #[test]
1240    fn plugin_channel_round_trips_and_is_capped() {
1241        let c = ClientMsg::Plugin { plugin: "sheets".into(), msg: serde_json::json!({"op": "get", "cell": "A1"}) };
1242        assert_eq!(c.to_json(), r#"{"type":"plugin","plugin":"sheets","msg":{"cell":"A1","op":"get"}}"#);
1243        assert_eq!(ClientMsg::from_json(&c.to_json()).unwrap(), c);
1244        assert!(c.check_sizes().is_ok());
1245        let s = ServerMsg::Plugin { plugin: "sheets".into(), msg: serde_json::json!([1, 2]) };
1246        assert_eq!(ServerMsg::from_json(&s.to_json()).unwrap(), s);
1247        for bad in [
1248            ClientMsg::Plugin { plugin: "Not/an id".into(), msg: serde_json::Value::Null },
1249            ClientMsg::Plugin { plugin: "sheets".into(), msg: serde_json::Value::String("x".repeat(version::MAX_PLUGIN_MSG_BYTES)) },
1250        ] {
1251            assert!(bad.check_sizes().is_err());
1252        }
1253    }
1254
1255    /// A newer peer's additions decode into fallbacks instead of failing the whole frame.
1256    #[test]
1257    fn unknown_messages_and_enum_values_decode_to_fallbacks() {
1258        assert_eq!(ServerMsg::from_json(r#"{"type":"hologram","x":1,"y":{"z":[]}}"#).unwrap(), ServerMsg::Unknown);
1259        assert_eq!(ClientMsg::from_json(r#"{"type":"teleport","to":"mars"}"#).unwrap(), ClientMsg::Unknown);
1260        // Malformed known messages are still errors.
1261        assert!(ServerMsg::from_json(r#"{"type":"notice","level":"info"}"#).is_err());
1262        let n = ServerMsg::from_json(r#"{"type":"notice","level":"debug","text":"t"}"#).unwrap();
1263        assert_eq!(n, ServerMsg::Notice { level: NoticeLevel::Info, text: "t".into() });
1264        let a = ClientMsg::from_json(r#"{"type":"approve","step":1,"answer":"maybe_later"}"#).unwrap();
1265        assert_eq!(a, ClientMsg::Approve { step: 1, answer: ApprovalAnswer::Unknown });
1266        // A step with a preview, a change, media, an artifact and a view this build doesn't know.
1267        let json = r#"{"id":1,"tool":"t","title":"T","access":"read","status":"done","detail":"",
1268            "changes":[{"kind":"chmod","path":"a","mode":"755"}],
1269            "preview":{"kind":"hexdump","bytes":"00"},
1270            "media":[{"kind":"video","path":"a.mp4"}],
1271            "views":[{"kind":"sheets.grid","v":4,"data":{"rows":[]},"fallback":"a *grid*"}]}"#;
1272        let s: Step = serde_json::from_str(json).unwrap();
1273        assert_eq!((s.changes.clone(), s.preview.clone()), (vec![FileChange::Other], Some(Preview::Other)));
1274        assert_eq!(s.media[0].kind, MediaKind::File);
1275        assert_eq!((s.views[0].kind.as_str(), s.views[0].fallback.as_str()), ("sheets.grid", "a *grid*"));
1276        assert!(s.view::<PluginCard>().is_none());
1277        let art: Artifact = serde_json::from_str(r#"{"id":"a","kind":"spreadsheet","title":"A","filename":"a.xlsx","versions":[]}"#).unwrap();
1278        assert_eq!(art.kind, ArtifactKind::Text);
1279        assert_eq!(serde_json::from_str::<SlashKind>(r#""macro""#).unwrap(), SlashKind::Other);
1280        assert_eq!(serde_json::from_str::<PluginAction>(r#""forked""#).unwrap(), PluginAction::Other);
1281        let env = ClientMsg::from_json(r#"{"type":"workspace_env","action":{"kind":"rebuild","fast":true}}"#).unwrap();
1282        assert_eq!(env, ClientMsg::WorkspaceEnv { action: Some(EnvAction::Unsupported), workspace: None });
1283        let d = ServerMsg::from_json(r#"{"type":"delegation","entry":1,"step":2,"update":{"kind":"progress","pct":5}}"#).unwrap();
1284        assert_eq!(d, ServerMsg::Delegation { entry: 1, step: 2, update: DelegationUpdate::Other });
1285    }
1286
1287    #[test]
1288    fn plugin_cards_travel_as_views() {
1289        let card = PluginCard {
1290            plugin: "scratch".into(),
1291            scope: PluginScope::Chat,
1292            action: PluginAction::Made,
1293            tools: vec!["shout".into()],
1294            added: vec!["shout".into()],
1295            removed: vec![],
1296            test: Some(plugins::PluginTest { ok: true, output: "HI".into() }),
1297            problems: vec![],
1298            missing_settings: vec![],
1299        };
1300        let mut s = step(1, StepStatus::Done);
1301        s.views.push(View::of(&card));
1302        let json = ServerMsg::StepUpdated { entry: 1, step: s }.to_json();
1303        assert!(json.contains(r#""views":[{"kind":"byob.plugin_card","v":1,"data":{"action":"made""#), "{json}");
1304        let ServerMsg::StepUpdated { step: back, .. } = ServerMsg::from_json(&json).unwrap() else { panic!() };
1305        assert_eq!(back.view::<PluginCard>(), Some(card));
1306        assert!(back.views[0].fallback.contains("**Plugin scratch** (this chat) · tool made") && back.views[0].fallback.contains("shout"));
1307        // No views: nothing on the wire.
1308        assert!(!ServerMsg::StepUpdated { entry: 1, step: step(2, StepStatus::Done) }.to_json().contains("views"));
1309    }
1310
1311    #[test]
1312    fn state_never_carries_api_key() {
1313        let json = serde_json::to_string(&EngineState::default()).unwrap();
1314        assert!(!json.contains("\"api_key\""));
1315    }
1316}