Skip to main content

mcpmesh_local_api/
client.rs

1//! A no-iroh mcpmesh-local/1 client: connect the UDS, read the server's `Hello`
2//! first frame, assert the api name, then issue typed request/response frames. Distinct
3//! from the CLI crate (`cli/`)'s ControlClient (which uses mcpmesh_net::framing) — this one links no
4//! iroh, so kb and the host shell can use it. kb calls this to self-register
5//! its `[services.kb]` socket backend with the running mcpmesh daemon.
6use std::path::Path;
7
8use serde_json::Value;
9
10use crate::codec::{FrameReader, Inbound, MAX_FRAME_BYTES, write_frame};
11use crate::protocol::{
12    AuditSummaryResult, BackendSpec, BlobFetchParams, BlobFetchResult, BlobGrantParams,
13    BlobPublishParams, BlobPublishResult, BlobScopeList, Hello, InviteParams, InviteResult,
14    OpenSessionParams, OrgJoinParams, OrgJoinResult, PairParams, PairResult, PeerRemoveParams,
15    PeerRenameParams, RegisterServiceParams, Request, RosterInstallParams, RosterInstallResult,
16    SetNicknameParams, SetRosterUrlParams, StatusResult, StreamFrame,
17};
18use crate::transport::{connect_local, split_local};
19
20/// The client's read half — boxed so ONE `ControlClient` serves every transport (the
21/// platform socket/pipe via [`connect_control`], or an embedder's in-memory duplex via
22/// [`connect_control_io`]).
23pub type ControlRead = Box<dyn tokio::io::AsyncRead + Send + Unpin>;
24/// The client's write half — see [`ControlRead`].
25pub type ControlWrite = Box<dyn tokio::io::AsyncWrite + Send + Unpin>;
26
27/// A connected mcpmesh-local/1 client: the framed stream + the server's `Hello`.
28pub struct ControlClient {
29    hello: Hello,
30    reader: FrameReader<ControlRead>,
31    writer: ControlWrite,
32}
33
34/// Hand-rolled (the boxed transport halves are not `Debug`): the `Hello` is the one
35/// diagnostic a `{:?}` needs — tests format `Result<ControlClient, _>` this way.
36impl std::fmt::Debug for ControlClient {
37    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38        f.debug_struct("ControlClient")
39            .field("hello", &self.hello)
40            .finish_non_exhaustive()
41    }
42}
43
44/// The error surface of the client — thin, so callers can `anyhow`-wrap it.
45///
46/// The `Display`/`Error`/`From` impls below are hand-rolled rather than derived: the
47/// `client` feature deliberately pulls ONLY tokio (no `thiserror`), and the hand-rolled
48/// impls are behavior-identical (same messages, same `?`-conversion from `io::Error`)
49/// with zero extra dependencies.
50#[derive(Debug)]
51pub enum ClientError {
52    Io(std::io::Error),
53    Closed(&'static str),
54    Malformed(&'static str),
55    WrongApi { got: String, want: &'static str },
56    Api(Value),
57}
58
59impl std::fmt::Display for ClientError {
60    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61        match self {
62            ClientError::Io(err) => write!(f, "io: {err}"),
63            ClientError::Closed(what) => write!(f, "connection closed before {what}"),
64            ClientError::Malformed(what) => write!(f, "malformed {what} frame"),
65            ClientError::WrongApi { got, want } => {
66                write!(f, "unexpected api: got {got:?}, want {want:?}")
67            }
68            ClientError::Api(err) => write!(f, "control API error: {err}"),
69        }
70    }
71}
72
73impl std::error::Error for ClientError {}
74
75impl From<std::io::Error> for ClientError {
76    fn from(err: std::io::Error) -> Self {
77        ClientError::Io(err)
78    }
79}
80
81impl ControlClient {
82    pub fn hello(&self) -> &Hello {
83        &self.hello
84    }
85
86    /// Issue a typed request; return the JSON-RPC `result` (or `ClientError::Api` on a
87    /// JSON-RPC `error`).
88    pub async fn request(&mut self, request: Request) -> Result<Value, ClientError> {
89        let frame = serde_json::to_value(&request).expect("Request serializes");
90        self.request_value(&frame).await
91    }
92
93    /// Issue a RAW request frame — the escape hatch for methods outside the typed
94    /// [`Request`] surface (the daemon-internal `shutdown`, third-party
95    /// `{"method":..,"params":{}}` shapes the dispatcher tolerates). Returns the JSON-RPC
96    /// `result` value (or `ClientError::Api` on a JSON-RPC `error`).
97    pub async fn request_value(&mut self, request: &Value) -> Result<Value, ClientError> {
98        write_frame(&mut self.writer, request).await?;
99        match self.reader.next().await? {
100            Some(Inbound::Frame(resp)) => {
101                if let Some(err) = resp.get("error") {
102                    return Err(ClientError::Api(err.clone()));
103                }
104                Ok(resp.get("result").cloned().unwrap_or(Value::Null))
105            }
106            Some(Inbound::Violation(_)) => Err(ClientError::Malformed("response")),
107            None => Err(ClientError::Closed("response")),
108        }
109    }
110
111    /// Send a request WITHOUT reading a response — for `OpenSession`, after which the
112    /// socket stops being JSON-RPC and becomes a raw MCP byte pipe (protocol.rs). Returns
113    /// the framed halves so the caller can pump the session — the SAME `FrameReader` that
114    /// read the Hello, so bytes the daemon pipelined behind it are never lost. A caller
115    /// that must re-box the read half calls `FrameReader::into_inner`, which returns the
116    /// BUFFERED reader (its read-ahead travels with it — see the pipelining test below).
117    pub async fn open_session(
118        mut self,
119        peer: String,
120        service: String,
121    ) -> Result<(FrameReader<ControlRead>, ControlWrite), ClientError> {
122        let frame = serde_json::to_value(Request::OpenSession(OpenSessionParams { peer, service }))
123            .expect("Request serializes");
124        write_frame(&mut self.writer, &frame).await?;
125        Ok((self.reader, self.writer))
126    }
127
128    /// Send a parameterless stream-upgrade request WITHOUT reading a response — like
129    /// [`open_session`](Self::open_session), but generic on the `method`: after this call the
130    /// socket stops being request/response and becomes a one-way push stream of frames the caller
131    /// READS (the `subscribe` telemetry surface). Returns the framed halves — the SAME
132    /// `FrameReader` that read the Hello, so any frame the daemon pipelined behind it is never
133    /// lost. The write half is handed back so the caller can hold the connection open (a watcher
134    /// only reads, but dropping the writer would half-close the socket).
135    pub async fn open_stream(
136        mut self,
137        method: &str,
138    ) -> Result<(FrameReader<ControlRead>, ControlWrite), ClientError> {
139        let frame = serde_json::json!({ "method": method });
140        write_frame(&mut self.writer, &frame).await?;
141        Ok((self.reader, self.writer))
142    }
143
144    /// Issue `request` and deserialize the JSON-RPC `result` into `T` — the shared core of every
145    /// typed helper below. `what` names the result in the [`ClientError::Malformed`] surface. The
146    /// wrong-type hazard the raw [`request`](Self::request) leaves to the caller is closed here:
147    /// each helper pairs its Request variant with its result type once, in this crate.
148    async fn request_typed<T: serde::de::DeserializeOwned>(
149        &mut self,
150        request: Request,
151        what: &'static str,
152    ) -> Result<T, ClientError> {
153        let v = self.request(request).await?;
154        serde_json::from_value(v).map_err(|_| ClientError::Malformed(what))
155    }
156
157    /// Issue `request` and discard the ack body (the daemon answers `{}` for verbs with no result
158    /// vocabulary). A JSON-RPC error still surfaces as [`ClientError::Api`].
159    async fn request_ack(&mut self, request: Request) -> Result<(), ClientError> {
160        self.request(request).await.map(|_| ())
161    }
162
163    /// The daemon's `status` picture: services served, known peers, roster/presence state,
164    /// self identity, recent pairings, and advisory reachability.
165    pub async fn status(&mut self) -> Result<StatusResult, ClientError> {
166        self.request_typed(Request::Status, "status result").await
167    }
168
169    /// Register/update a `[services.*]` entry idempotently (the daemon persists it and hot-reloads
170    /// serving). The daemon acks; the ack body is discarded.
171    pub async fn register_service(
172        &mut self,
173        name: &str,
174        backend: BackendSpec,
175        allow: Vec<String>,
176    ) -> Result<(), ClientError> {
177        self.register_service_with(name, backend, allow, false)
178            .await
179    }
180
181    /// [`register_service`](Self::register_service) with an explicit `ephemeral` flag (#36). When
182    /// `ephemeral` is true the registration lives only in daemon memory and is unregistered
183    /// automatically when THIS control connection closes — no config write, nothing to clean up.
184    /// Ideal for an embedder serving a `socket` backend from a fresh path each run.
185    pub async fn register_service_with(
186        &mut self,
187        name: &str,
188        backend: BackendSpec,
189        allow: Vec<String>,
190        ephemeral: bool,
191    ) -> Result<(), ClientError> {
192        self.request_ack(Request::RegisterService(RegisterServiceParams {
193            name: name.to_string(),
194            backend,
195            allow,
196            ephemeral,
197        }))
198        .await
199    }
200
201    /// Mint a one-time pairing invite granting `services`; return the copyable
202    /// `mcpmesh-invite:` line + its expiry.
203    pub async fn invite(&mut self, services: Vec<String>) -> Result<InviteResult, ClientError> {
204        self.invite_with(services, None).await
205    }
206
207    /// [`invite`](Self::invite) with an opaque `app_label` (#31) carried through to the redeemer's
208    /// `pair` result. mcpmesh never interprets the label; the embedder does (e.g. its own URN).
209    pub async fn invite_with(
210        &mut self,
211        services: Vec<String>,
212        app_label: Option<String>,
213    ) -> Result<InviteResult, ClientError> {
214        self.request_typed(
215            Request::Invite(InviteParams {
216                services,
217                app_label,
218            }),
219            "invite result",
220        )
221        .await
222    }
223
224    /// Redeem a pairing invite; return the inviter's suggested nickname, the display-only SAS
225    /// code, and the granted services.
226    pub async fn pair(&mut self, invite_line: &str) -> Result<PairResult, ClientError> {
227        self.request_typed(
228            Request::Pair(PairParams {
229                invite_line: invite_line.to_string(),
230            }),
231            "pair result",
232        )
233        .await
234    }
235
236    /// Unpair a peer by nickname: drops its identity row AND its every-`allow` membership
237    /// (idempotent; live sessions are not severed). The daemon acks; the ack body is discarded.
238    pub async fn peer_remove(&mut self, nickname: &str) -> Result<(), ClientError> {
239        self.request_ack(Request::PeerRemove(PeerRemoveParams {
240            nickname: nickname.to_string(),
241        }))
242        .await
243    }
244
245    /// Rename a contact's nickname to `to` — every device sharing `user_id` when given, else the
246    /// single provisional `nickname` entry — carrying its grants along. The daemon refuses (a
247    /// [`ClientError::Api`]) when `to` is empty or already names a different identity. The daemon
248    /// acks; the ack body is discarded.
249    pub async fn peer_rename(
250        &mut self,
251        user_id: Option<String>,
252        nickname: Option<String>,
253        to: &str,
254    ) -> Result<(), ClientError> {
255        self.request_ack(Request::PeerRename(PeerRenameParams {
256            user_id,
257            nickname,
258            to: to.to_string(),
259        }))
260        .await
261    }
262
263    /// Install a signed roster from the LOCAL file at `path` (`org_root_pk` pins the org root on
264    /// FIRST install); return the installed org id + serial + severed-session count.
265    pub async fn roster_install(
266        &mut self,
267        path: &str,
268        org_root_pk: Option<String>,
269    ) -> Result<RosterInstallResult, ClientError> {
270        self.request_typed(
271            Request::RosterInstall(RosterInstallParams {
272                path: path.to_string(),
273                org_root_pk,
274            }),
275            "roster_install result",
276        )
277        .await
278    }
279
280    /// Pin the org root on a JOINER (no roster yet). `user_key` is a LOCAL path — the key never
281    /// crosses the API. Returns the pinned org id.
282    pub async fn org_join(
283        &mut self,
284        org_id: &str,
285        org_root_pk: &str,
286        user_id: &str,
287        user_key: &str,
288    ) -> Result<OrgJoinResult, ClientError> {
289        self.request_typed(
290            Request::OrgJoin(OrgJoinParams {
291                org_id: org_id.to_string(),
292                org_root_pk: org_root_pk.to_string(),
293                user_id: user_id.to_string(),
294                user_key: user_key.to_string(),
295            }),
296            "org_join result",
297        )
298        .await
299    }
300
301    /// Pin the HTTPS roster URL (`[roster].url`) in the daemon's config. The daemon acks; the
302    /// ack body is discarded.
303    pub async fn set_roster_url(&mut self, url: &str) -> Result<(), ClientError> {
304        self.request_ack(Request::SetRosterUrl(SetRosterUrlParams {
305            url: url.to_string(),
306        }))
307        .await
308    }
309
310    /// Rename this node LIVE (#37): the daemon validates + persists `[identity].nickname`
311    /// under its own config lock and updates the name future invites present — no restart.
312    /// Peers keep their stored pairing-time nickname until a re-invite (display-only).
313    pub async fn set_nickname(&mut self, nickname: &str) -> Result<(), ClientError> {
314        self.request_ack(Request::SetNickname(SetNicknameParams {
315            nickname: nickname.to_string(),
316        }))
317        .await
318    }
319
320    /// Summarize the daemon's LOCAL audit log into per-peer / per-service session counts
321    /// (local-only — nothing is transmitted).
322    pub async fn audit_summary(&mut self) -> Result<AuditSummaryResult, ClientError> {
323        self.request_typed(Request::AuditSummary, "audit_summary result")
324            .await
325    }
326
327    /// Publish a local file into `scope`; return the minted `mcpmesh/blob/1` ticket + hash.
328    pub async fn blob_publish(
329        &mut self,
330        scope: &str,
331        path: &str,
332    ) -> Result<BlobPublishResult, ClientError> {
333        self.request_typed(
334            Request::BlobPublish(BlobPublishParams {
335                scope: scope.to_string(),
336                path: path.to_string(),
337            }),
338            "blob_publish result",
339        )
340        .await
341    }
342
343    /// List the daemon's blob scopes (name → hashes + grants).
344    pub async fn blob_list(&mut self) -> Result<BlobScopeList, ClientError> {
345        self.request_typed(Request::BlobList, "blob_list result")
346            .await
347    }
348
349    /// Fetch a `mcpmesh/blob/1` ticket THROUGH the daemon (BLAKE3-verified), export to
350    /// `dest_path`; return the verified hash + byte length.
351    pub async fn blob_fetch(
352        &mut self,
353        ticket: &str,
354        dest_path: &str,
355    ) -> Result<BlobFetchResult, ClientError> {
356        self.request_typed(
357            Request::BlobFetch(BlobFetchParams {
358                ticket: ticket.to_string(),
359                dest_path: dest_path.to_string(),
360            }),
361            "blob_fetch result",
362        )
363        .await
364    }
365
366    /// Grant a scope to a principal — any flat-namespace entry: a group name, a user_id,
367    /// or a nickname (the shared `principal_set` expansion).
368    /// The daemon acks; the ack body is discarded (a JSON-RPC error surfaces as
369    /// `ClientError::Api`). Granting a scope to your own user_id reaches ALL of that
370    /// person's devices.
371    pub async fn blob_grant(&mut self, scope: &str, principal: &str) -> Result<(), ClientError> {
372        self.request_ack(Request::BlobGrant(BlobGrantParams {
373            scope: scope.to_string(),
374            principal: principal.to_string(),
375        }))
376        .await
377    }
378
379    /// The TYPED `subscribe` upgrade: send [`Request::Subscribe`] (after which the connection
380    /// stops being request/response — see [`open_stream`](Self::open_stream)) and return a
381    /// [`StreamSubscription`] yielding [`StreamFrame`]s. For raw frames (e.g. to tolerate frame
382    /// types newer than this crate), use `open_stream("subscribe")` instead.
383    pub async fn subscribe(self) -> Result<StreamSubscription, ClientError> {
384        let (reader, writer) = self.open_stream("subscribe").await?;
385        Ok(StreamSubscription {
386            reader,
387            _writer: writer,
388        })
389    }
390}
391
392/// A live [`Request::Subscribe`] stream yielding typed [`StreamFrame`]s (snapshot, then
393/// events/lagged notices) until the daemon side closes. Holds the connection's write half for its
394/// lifetime — a subscriber only reads, but dropping the writer would half-close the socket. Drop
395/// the subscription to disconnect (there is no request channel back).
396pub struct StreamSubscription {
397    reader: FrameReader<ControlRead>,
398    _writer: ControlWrite,
399}
400
401/// Hand-rolled like [`ControlClient`]'s: the boxed transport halves are not `Debug`.
402impl std::fmt::Debug for StreamSubscription {
403    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
404        f.debug_struct("StreamSubscription").finish_non_exhaustive()
405    }
406}
407
408impl StreamSubscription {
409    /// The next frame, or `None` when the daemon closed the stream. A frame this crate's
410    /// [`StreamFrame`] does not model (a NEWER daemon's frame type) surfaces as
411    /// [`ClientError::Malformed`] — a forward-compatible consumer reads raw frames via
412    /// [`ControlClient::open_stream`] instead.
413    pub async fn next(&mut self) -> Result<Option<StreamFrame>, ClientError> {
414        match self.reader.next().await? {
415            Some(Inbound::Frame(v)) => serde_json::from_value(v)
416                .map(Some)
417                .map_err(|_| ClientError::Malformed("stream frame")),
418            Some(Inbound::Violation(_)) => Err(ClientError::Malformed("stream frame")),
419            None => Ok(None),
420        }
421    }
422}
423
424/// Complete the mcpmesh-local/1 hello handshake over ALREADY-CONNECTED byte halves —
425/// the transport-agnostic core of [`connect_control`], and the front door for in-process
426/// embedding (`mcpmesh-node`'s `Node::control` dials a tokio duplex through here).
427pub async fn connect_control_io(
428    reader: impl tokio::io::AsyncRead + Send + Unpin + 'static,
429    writer: impl tokio::io::AsyncWrite + Send + Unpin + 'static,
430) -> Result<ControlClient, ClientError> {
431    let mut reader = FrameReader::new(Box::new(reader) as ControlRead, MAX_FRAME_BYTES);
432    let hello: Hello = match reader.next().await? {
433        Some(Inbound::Frame(v)) => {
434            serde_json::from_value(v).map_err(|_| ClientError::Malformed("hello"))?
435        }
436        Some(Inbound::Violation(_)) => return Err(ClientError::Malformed("hello")),
437        None => return Err(ClientError::Closed("hello")),
438    };
439    if hello.api != crate::protocol::API_NAME {
440        return Err(ClientError::WrongApi {
441            got: hello.api,
442            want: crate::protocol::API_NAME,
443        });
444    }
445    Ok(ControlClient {
446        hello,
447        reader,
448        writer: Box::new(writer) as ControlWrite,
449    })
450}
451
452/// Connect + complete the hello handshake, asserting the api name is `mcpmesh-local/1`.
453pub async fn connect_control(path: &Path) -> Result<ControlClient, ClientError> {
454    let stream = connect_local(path).await?;
455    let (read_half, write_half) = split_local(stream);
456    connect_control_io(read_half, write_half).await
457}
458
459/// [`connect_control`] at the platform default endpoint ([`crate::paths::default_endpoint`]):
460/// the quickstart front door — a consumer dials the running daemon without reimplementing
461/// the platform endpoint rule. Resolution failure surfaces as [`ClientError::Io`]
462/// (`NotFound`), same as a daemon that is not running.
463pub async fn connect_control_default() -> Result<ControlClient, ClientError> {
464    connect_control(&crate::paths::default_endpoint()?).await
465}
466
467// Seam-ported (Task 6): every stub daemon binds via the platform seam
468// (`transport::bind_local` + `LocalListener::accept`) rather than a raw `UnixListener`,
469// so these exercise the platform-identical `ControlClient` on BOTH unix (UDS) and windows
470// (named pipe). Gated on `feature = "service"` (bind needs it) rather than `unix`: under
471// `cargo test --workspace` feature unification turns `service` on for this crate (cli
472// depends on local-api with features=["service"]), so the module compiles and RUNS on the
473// windows CI leg. `test_endpoint` yields a platform-appropriate unique endpoint.
474#[cfg(all(test, feature = "service"))]
475mod tests {
476    use super::*;
477    use crate::protocol::{API_NAME, API_VERSION, BackendKind, ServiceInfo, StatusResult};
478    use crate::transport::{LocalListener, bind_local, split_local};
479    use tokio::io::AsyncWriteExt;
480
481    /// A unique local endpoint for a stub daemon, platform-appropriate: a tempdir socket
482    /// path on unix, a per-process-unique `\\.\pipe\…` name on windows. Returns the
483    /// endpoint plus a guard that MUST outlive the listener (the `TempDir` on unix; unit
484    /// on windows, whose pipe namespace needs no filesystem cleanup).
485    #[cfg(unix)]
486    fn test_endpoint(tag: &str) -> (std::path::PathBuf, tempfile::TempDir) {
487        let dir = tempfile::tempdir().unwrap();
488        let path = dir.path().join(format!("{tag}.sock"));
489        (path, dir)
490    }
491    #[cfg(windows)]
492    fn test_endpoint(tag: &str) -> (std::path::PathBuf, ()) {
493        use std::sync::atomic::{AtomicU64, Ordering};
494        static SEQ: AtomicU64 = AtomicU64::new(0);
495        let n = SEQ.fetch_add(1, Ordering::Relaxed);
496        let path = std::path::PathBuf::from(format!(
497            r"\\.\pipe\mcpmesh-client-test-{}-{tag}-{n}",
498            std::process::id()
499        ));
500        (path, ())
501    }
502
503    /// A stub mcpmesh daemon: send Hello, then answer one `status` with a StatusResult.
504    async fn stub_daemon(mut listener: LocalListener) {
505        let stream = listener.accept().await.unwrap();
506        let (read_half, mut writer) = split_local(stream);
507        write_frame(
508            &mut writer,
509            &serde_json::to_value(Hello {
510                api: API_NAME.into(),
511                api_version: API_VERSION.into(),
512                api_minor: 0,
513                stack_version: "0.1.0".into(),
514            })
515            .unwrap(),
516        )
517        .await
518        .unwrap();
519        let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
520        let req = match reader.next().await.unwrap().unwrap() {
521            Inbound::Frame(v) => v,
522            Inbound::Violation(_) => panic!("violation"),
523        };
524        assert_eq!(req["method"], "status");
525        let result = StatusResult {
526            stack_version: "0.1.0".into(),
527            services: vec![ServiceInfo {
528                name: "kb".into(),
529                allow: vec![],
530                allow_display: vec![],
531                backend: BackendKind::Socket,
532                ephemeral: false,
533            }],
534            peers: vec![],
535            roster: None,
536            presence: vec![],
537            self_user_id: None,
538            recent_pairings: vec![],
539            reachability: vec![],
540            self_nickname: String::new(),
541        };
542        write_frame(
543            &mut writer,
544            &serde_json::json!({ "jsonrpc": "2.0", "id": 1, "result": result }),
545        )
546        .await
547        .unwrap();
548        writer.flush().await.unwrap();
549    }
550
551    /// The transport-agnostic front door: the same hello handshake over a plain in-memory
552    /// duplex — what an embedded node's `Node::control` dials through.
553    #[tokio::test]
554    async fn connect_control_io_handshakes_over_a_duplex() {
555        let (client_io, mut server_io) = tokio::io::duplex(4096);
556        tokio::spawn(async move {
557            write_frame(
558                &mut server_io,
559                &serde_json::to_value(Hello {
560                    api: API_NAME.into(),
561                    api_version: API_VERSION.into(),
562                    api_minor: 0,
563                    stack_version: "in-proc".into(),
564                })
565                .unwrap(),
566            )
567            .await
568            .unwrap();
569        });
570        let (r, w) = tokio::io::split(client_io);
571        let client = connect_control_io(r, w).await.expect("handshake");
572        assert_eq!(client.hello().stack_version, "in-proc");
573    }
574
575    #[tokio::test]
576    async fn connect_reads_hello_asserts_api_and_requests() {
577        let (sock, _guard) = test_endpoint("status");
578        let listener = bind_local(&sock).unwrap();
579        let server = tokio::spawn(stub_daemon(listener));
580
581        let mut client = connect_control(&sock).await.unwrap();
582        assert_eq!(client.hello().api, API_NAME);
583        let result = client.request(Request::Status).await.unwrap();
584        assert_eq!(result["services"][0]["name"], "kb");
585        assert_eq!(result["services"][0]["backend"], "socket");
586        server.await.unwrap();
587    }
588
589    #[tokio::test]
590    async fn wrong_api_hello_is_rejected() {
591        let (sock, _guard) = test_endpoint("wrongapi");
592        let listener = bind_local(&sock).unwrap();
593        tokio::spawn(async move {
594            let mut listener = listener;
595            let stream = listener.accept().await.unwrap();
596            let (_r, mut w) = split_local(stream);
597            write_frame(
598                &mut w,
599                &serde_json::json!({"api":"other/1","api_version":"1.0","stack_version":"0"}),
600            )
601            .await
602            .unwrap();
603            w.flush().await.unwrap();
604        });
605        match connect_control(&sock).await {
606            Err(ClientError::WrongApi { got, want }) => {
607                assert_eq!(got, "other/1");
608                assert_eq!(want, API_NAME);
609            }
610            other => panic!("expected WrongApi, got {other:?}"),
611        }
612    }
613
614    #[tokio::test]
615    async fn blob_fetch_and_publish_deserialize_typed_results() {
616        use crate::protocol::{BlobFetchResult, BlobPublishResult};
617        let (sock, _guard) = test_endpoint("blob");
618        let listener = bind_local(&sock).unwrap();
619        let server = tokio::spawn(async move {
620            let mut listener = listener;
621            let stream = listener.accept().await.unwrap();
622            let (read_half, mut writer) = split_local(stream);
623            write_frame(
624                &mut writer,
625                &serde_json::to_value(Hello {
626                    api: API_NAME.into(),
627                    api_version: API_VERSION.into(),
628                    api_minor: 0,
629                    stack_version: "0.1.0".into(),
630                })
631                .unwrap(),
632            )
633            .await
634            .unwrap();
635            let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
636            // First request: blob_publish -> a ticket + hash.
637            let req = match reader.next().await.unwrap().unwrap() {
638                Inbound::Frame(v) => v,
639                Inbound::Violation(_) => panic!("violation"),
640            };
641            assert_eq!(req["method"], "blob_publish");
642            assert_eq!(req["params"]["scope"], "eng");
643            write_frame(
644                &mut writer,
645                &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ticket":"blobT","hash":"ab"}}),
646            )
647            .await
648            .unwrap();
649            // Second request: blob_fetch -> a verified hash + length.
650            let req = match reader.next().await.unwrap().unwrap() {
651                Inbound::Frame(v) => v,
652                Inbound::Violation(_) => panic!("violation"),
653            };
654            assert_eq!(req["method"], "blob_fetch");
655            assert_eq!(req["params"]["ticket"], "blobT");
656            assert_eq!(req["params"]["dest_path"], "/tmp/out.bin");
657            write_frame(
658                &mut writer,
659                &serde_json::json!({"jsonrpc":"2.0","id":2,"result":{"hash":"cd","bytes_len":7}}),
660            )
661            .await
662            .unwrap();
663            let _ = (
664                BlobFetchResult {
665                    hash: "cd".into(),
666                    bytes_len: 7,
667                },
668                BlobPublishResult {
669                    ticket: "blobT".into(),
670                    hash: "ab".into(),
671                },
672            );
673        });
674
675        let mut client = connect_control(&sock).await.unwrap();
676        let pub_res = client.blob_publish("eng", "/tmp/a.bin").await.unwrap();
677        assert_eq!(pub_res.ticket, "blobT");
678        assert_eq!(pub_res.hash, "ab");
679        let fetch_res = client.blob_fetch("blobT", "/tmp/out.bin").await.unwrap();
680        assert_eq!(fetch_res.hash, "cd");
681        assert_eq!(fetch_res.bytes_len, 7);
682        server.await.unwrap();
683    }
684
685    /// Regression (lossless rebox): a frame the server PIPELINES in the same write as
686    /// the Hello must survive `open_session` + kb's production re-box shape
687    /// (`FrameReader::new(Box::new(reader.into_inner()), …)`, bridge/session.rs). Against
688    /// the old `into_inner -> R` — which unwrapped the internal `BufReader` and DROPPED
689    /// its read-ahead — the pipelined frame vanished and this test failed (EOF instead of
690    /// the frame). `into_inner -> BufReader<R>` carries the read-ahead across the rebox.
691    #[tokio::test]
692    async fn frame_pipelined_behind_hello_survives_open_session_rebox() {
693        use tokio::io::AsyncRead;
694
695        let (sock, _guard) = test_endpoint("pipelined");
696        let listener = bind_local(&sock).unwrap();
697        let server = tokio::spawn(async move {
698            let mut listener = listener;
699            let stream = listener.accept().await.unwrap();
700            let (read_half, mut writer) = split_local(stream);
701            // ONE write carrying the Hello AND a session frame → both land in the
702            // client's first BufReader fill (the read-ahead under test).
703            let mut bytes = serde_json::to_vec(
704                &serde_json::to_value(Hello {
705                    api: API_NAME.into(),
706                    api_version: API_VERSION.into(),
707                    api_minor: 0,
708                    stack_version: "0.1.0".into(),
709                })
710                .unwrap(),
711            )
712            .unwrap();
713            bytes.push(b'\n');
714            bytes.extend_from_slice(b"{\"jsonrpc\":\"2.0\",\"id\":42,\"result\":{}}\n");
715            writer.write_all(&bytes).await.unwrap();
716            writer.flush().await.unwrap();
717            // Absorb the client's open_session frame so its write never sees EPIPE.
718            let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
719            let req = match reader.next().await.unwrap().unwrap() {
720                Inbound::Frame(v) => v,
721                Inbound::Violation(_) => panic!("violation"),
722            };
723            assert_eq!(req["method"], "open_session");
724        });
725
726        let client = connect_control(&sock).await.unwrap();
727        let (reader, _writer) = client
728            .open_session("peer".into(), "kb".into())
729            .await
730            .unwrap();
731        // kb's production shape: erase the half type behind a boxed pipe, then re-frame.
732        let boxed: Box<dyn AsyncRead + Unpin + Send> = Box::new(reader.into_inner());
733        let mut reframed = FrameReader::new(boxed, MAX_FRAME_BYTES);
734        match reframed.next().await.unwrap() {
735            Some(Inbound::Frame(v)) => assert_eq!(v["id"], 42),
736            other => panic!("pipelined frame was lost across the rebox: {other:?}"),
737        }
738        server.await.unwrap();
739    }
740
741    #[tokio::test]
742    async fn blob_grant_issues_request_and_acks() {
743        let (sock, _guard) = test_endpoint("grant");
744        let listener = bind_local(&sock).unwrap();
745        let server = tokio::spawn(async move {
746            let mut listener = listener;
747            let stream = listener.accept().await.unwrap();
748            let (read_half, mut writer) = split_local(stream);
749            write_frame(
750                &mut writer,
751                &serde_json::to_value(Hello {
752                    api: API_NAME.into(),
753                    api_version: API_VERSION.into(),
754                    api_minor: 0,
755                    stack_version: "0.1.0".into(),
756                })
757                .unwrap(),
758            )
759            .await
760            .unwrap();
761            let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
762            let req = match reader.next().await.unwrap().unwrap() {
763                Inbound::Frame(v) => v,
764                Inbound::Violation(_) => panic!("violation"),
765            };
766            assert_eq!(req["method"], "blob_grant");
767            assert_eq!(req["params"]["scope"], "kb-sync");
768            assert_eq!(req["params"]["principal"], "alice");
769            write_frame(
770                &mut writer,
771                &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ok":true}}),
772            )
773            .await
774            .unwrap();
775        });
776        let mut client = connect_control(&sock).await.unwrap();
777        client.blob_grant("kb-sync", "alice").await.unwrap();
778        server.await.unwrap();
779    }
780
781    /// The typed `status()` helper pairs `Request::Status` with `StatusResult` — the caller gets
782    /// the struct, not a `Value` to hand-deserialize (and a malformed result surfaces as
783    /// `ClientError::Malformed`, never a silently-wrong type).
784    #[tokio::test]
785    async fn typed_status_helper_deserializes_the_result() {
786        let (sock, _guard) = test_endpoint("typedstatus");
787        let listener = bind_local(&sock).unwrap();
788        let server = tokio::spawn(stub_daemon(listener));
789
790        let mut client = connect_control(&sock).await.unwrap();
791        let status = client.status().await.unwrap();
792        assert_eq!(status.stack_version, "0.1.0");
793        assert_eq!(status.services[0].name, "kb");
794        assert_eq!(status.services[0].backend, BackendKind::Socket);
795        assert!(status.peers.is_empty());
796        server.await.unwrap();
797    }
798
799    /// The ack-shaped typed helpers issue the right wire method and discard the `{}` ack; a
800    /// JSON-RPC error frame surfaces as `ClientError::Api`.
801    #[tokio::test]
802    async fn typed_ack_helpers_issue_requests_and_surface_api_errors() {
803        let (sock, _guard) = test_endpoint("typedack");
804        let listener = bind_local(&sock).unwrap();
805        let server = tokio::spawn(async move {
806            let mut listener = listener;
807            let stream = listener.accept().await.unwrap();
808            let (read_half, mut writer) = split_local(stream);
809            write_frame(
810                &mut writer,
811                &serde_json::to_value(Hello {
812                    api: API_NAME.into(),
813                    api_version: API_VERSION.into(),
814                    api_minor: 0,
815                    stack_version: "0.1.0".into(),
816                })
817                .unwrap(),
818            )
819            .await
820            .unwrap();
821            let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
822            // peer_remove → ack.
823            let req = match reader.next().await.unwrap().unwrap() {
824                Inbound::Frame(v) => v,
825                Inbound::Violation(_) => panic!("violation"),
826            };
827            assert_eq!(req["method"], "peer_remove");
828            assert_eq!(req["params"]["nickname"], "bob");
829            write_frame(
830                &mut writer,
831                &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{}}),
832            )
833            .await
834            .unwrap();
835            // peer_rename → an error frame (collision refusal).
836            let req = match reader.next().await.unwrap().unwrap() {
837                Inbound::Frame(v) => v,
838                Inbound::Violation(_) => panic!("violation"),
839            };
840            assert_eq!(req["method"], "peer_rename");
841            assert_eq!(req["params"]["to"], "Bobby");
842            write_frame(
843                &mut writer,
844                &serde_json::json!({"jsonrpc":"2.0","id":2,"error":{"code":-32000,"message":"taken"}}),
845            )
846            .await
847            .unwrap();
848        });
849
850        let mut client = connect_control(&sock).await.unwrap();
851        client.peer_remove("bob").await.unwrap();
852        match client.peer_rename(None, Some("bob".into()), "Bobby").await {
853            Err(ClientError::Api(e)) => assert_eq!(e["message"], "taken"),
854            other => panic!("expected Api error, got {other:?}"),
855        }
856        server.await.unwrap();
857    }
858
859    /// The typed `subscribe()` upgrade yields `StreamFrame`s — snapshot, event, lagged — then
860    /// `None` when the daemon side closes.
861    #[tokio::test]
862    async fn typed_subscribe_yields_frames_then_end() {
863        use crate::protocol::{ActiveSession, AuditRecord, PeerReachability};
864
865        let (sock, _guard) = test_endpoint("subscribe");
866        let listener = bind_local(&sock).unwrap();
867        let server = tokio::spawn(async move {
868            let mut listener = listener;
869            let stream = listener.accept().await.unwrap();
870            let (read_half, mut writer) = split_local(stream);
871            write_frame(
872                &mut writer,
873                &serde_json::to_value(Hello {
874                    api: API_NAME.into(),
875                    api_version: API_VERSION.into(),
876                    api_minor: 0,
877                    stack_version: "0.1.0".into(),
878                })
879                .unwrap(),
880            )
881            .await
882            .unwrap();
883            let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
884            let req = match reader.next().await.unwrap().unwrap() {
885                Inbound::Frame(v) => v,
886                Inbound::Violation(_) => panic!("violation"),
887            };
888            assert_eq!(req["method"], "subscribe");
889            for frame in [
890                StreamFrame::Snapshot {
891                    active_sessions: vec![ActiveSession {
892                        peer: "bob".into(),
893                        service: "notes".into(),
894                        opened_at: 7,
895                    }],
896                    reachability: vec![PeerReachability {
897                        name: "bob".into(),
898                        reachable: true,
899                        rtt_ms: Some(42),
900                        age_secs: Some(3),
901                    }],
902                },
903                StreamFrame::Event {
904                    record: Box::new(AuditRecord::session_open(
905                        "2026-07-03T14:02:11.480Z".into(),
906                        Some("bob".into()),
907                        "notes".into(),
908                    )),
909                },
910                StreamFrame::Lagged { dropped: 12 },
911            ] {
912                write_frame(&mut writer, &serde_json::to_value(&frame).unwrap())
913                    .await
914                    .unwrap();
915            }
916            writer.flush().await.unwrap();
917            // Drop the connection: the client must see the stream END (Ok(None)), not an error.
918        });
919
920        let client = connect_control(&sock).await.unwrap();
921        let mut sub = client.subscribe().await.unwrap();
922        match sub.next().await.unwrap().unwrap() {
923            StreamFrame::Snapshot {
924                active_sessions,
925                reachability,
926            } => {
927                assert_eq!(active_sessions[0].peer, "bob");
928                assert_eq!(reachability[0].rtt_ms, Some(42));
929            }
930            other => panic!("expected the snapshot first, got {other:?}"),
931        }
932        match sub.next().await.unwrap().unwrap() {
933            StreamFrame::Event { record } => {
934                assert_eq!(record.peer.as_deref(), Some("bob"));
935                assert_eq!(record.service.as_deref(), Some("notes"));
936            }
937            other => panic!("expected the event, got {other:?}"),
938        }
939        assert_eq!(
940            sub.next().await.unwrap(),
941            Some(StreamFrame::Lagged { dropped: 12 })
942        );
943        assert_eq!(sub.next().await.unwrap(), None, "clean end of stream");
944        server.await.unwrap();
945    }
946}