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