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