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