Skip to main content

byob_protocol/
lib.rs

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