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