Skip to main content

byob_protocol/
lib.rs

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