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