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