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