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::{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    /// Summarize the daemon's LOCAL audit log into per-peer / per-service session counts
311    /// (local-only — nothing is transmitted).
312    pub async fn audit_summary(&mut self) -> Result<AuditSummaryResult, ClientError> {
313        self.request_typed(Request::AuditSummary, "audit_summary result")
314            .await
315    }
316
317    /// Publish a local file into `scope`; return the minted `mcpmesh/blob/1` ticket + hash.
318    pub async fn blob_publish(
319        &mut self,
320        scope: &str,
321        path: &str,
322    ) -> Result<BlobPublishResult, ClientError> {
323        self.request_typed(
324            Request::BlobPublish(BlobPublishParams {
325                scope: scope.to_string(),
326                path: path.to_string(),
327            }),
328            "blob_publish result",
329        )
330        .await
331    }
332
333    /// List the daemon's blob scopes (name → hashes + grants).
334    pub async fn blob_list(&mut self) -> Result<BlobScopeList, ClientError> {
335        self.request_typed(Request::BlobList, "blob_list result")
336            .await
337    }
338
339    /// Fetch a `mcpmesh/blob/1` ticket THROUGH the daemon (BLAKE3-verified), export to
340    /// `dest_path`; return the verified hash + byte length.
341    pub async fn blob_fetch(
342        &mut self,
343        ticket: &str,
344        dest_path: &str,
345    ) -> Result<BlobFetchResult, ClientError> {
346        self.request_typed(
347            Request::BlobFetch(BlobFetchParams {
348                ticket: ticket.to_string(),
349                dest_path: dest_path.to_string(),
350            }),
351            "blob_fetch result",
352        )
353        .await
354    }
355
356    /// Grant a scope to a principal — any flat-namespace entry: a group name, a user_id,
357    /// or a nickname (the shared `principal_set` expansion).
358    /// The daemon acks; the ack body is discarded (a JSON-RPC error surfaces as
359    /// `ClientError::Api`). Granting a scope to your own user_id reaches ALL of that
360    /// person's devices.
361    pub async fn blob_grant(&mut self, scope: &str, principal: &str) -> Result<(), ClientError> {
362        self.request_ack(Request::BlobGrant(BlobGrantParams {
363            scope: scope.to_string(),
364            principal: principal.to_string(),
365        }))
366        .await
367    }
368
369    /// The TYPED `subscribe` upgrade: send [`Request::Subscribe`] (after which the connection
370    /// stops being request/response — see [`open_stream`](Self::open_stream)) and return a
371    /// [`StreamSubscription`] yielding [`StreamFrame`]s. For raw frames (e.g. to tolerate frame
372    /// types newer than this crate), use `open_stream("subscribe")` instead.
373    pub async fn subscribe(self) -> Result<StreamSubscription, ClientError> {
374        let (reader, writer) = self.open_stream("subscribe").await?;
375        Ok(StreamSubscription {
376            reader,
377            _writer: writer,
378        })
379    }
380}
381
382/// A live [`Request::Subscribe`] stream yielding typed [`StreamFrame`]s (snapshot, then
383/// events/lagged notices) until the daemon side closes. Holds the connection's write half for its
384/// lifetime — a subscriber only reads, but dropping the writer would half-close the socket. Drop
385/// the subscription to disconnect (there is no request channel back).
386pub struct StreamSubscription {
387    reader: FrameReader<ControlRead>,
388    _writer: ControlWrite,
389}
390
391/// Hand-rolled like [`ControlClient`]'s: the boxed transport halves are not `Debug`.
392impl std::fmt::Debug for StreamSubscription {
393    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
394        f.debug_struct("StreamSubscription").finish_non_exhaustive()
395    }
396}
397
398impl StreamSubscription {
399    /// The next frame, or `None` when the daemon closed the stream. A frame this crate's
400    /// [`StreamFrame`] does not model (a NEWER daemon's frame type) surfaces as
401    /// [`ClientError::Malformed`] — a forward-compatible consumer reads raw frames via
402    /// [`ControlClient::open_stream`] instead.
403    pub async fn next(&mut self) -> Result<Option<StreamFrame>, ClientError> {
404        match self.reader.next().await? {
405            Some(Inbound::Frame(v)) => serde_json::from_value(v)
406                .map(Some)
407                .map_err(|_| ClientError::Malformed("stream frame")),
408            Some(Inbound::Violation(_)) => Err(ClientError::Malformed("stream frame")),
409            None => Ok(None),
410        }
411    }
412}
413
414/// Complete the mcpmesh-local/1 hello handshake over ALREADY-CONNECTED byte halves —
415/// the transport-agnostic core of [`connect_control`], and the front door for in-process
416/// embedding (`mcpmesh-node`'s `Node::control` dials a tokio duplex through here).
417pub async fn connect_control_io(
418    reader: impl tokio::io::AsyncRead + Send + Unpin + 'static,
419    writer: impl tokio::io::AsyncWrite + Send + Unpin + 'static,
420) -> Result<ControlClient, ClientError> {
421    let mut reader = FrameReader::new(Box::new(reader) as ControlRead, MAX_FRAME_BYTES);
422    let hello: Hello = match reader.next().await? {
423        Some(Inbound::Frame(v)) => {
424            serde_json::from_value(v).map_err(|_| ClientError::Malformed("hello"))?
425        }
426        Some(Inbound::Violation(_)) => return Err(ClientError::Malformed("hello")),
427        None => return Err(ClientError::Closed("hello")),
428    };
429    if hello.api != crate::protocol::API_NAME {
430        return Err(ClientError::WrongApi {
431            got: hello.api,
432            want: crate::protocol::API_NAME,
433        });
434    }
435    Ok(ControlClient {
436        hello,
437        reader,
438        writer: Box::new(writer) as ControlWrite,
439    })
440}
441
442/// Connect + complete the hello handshake, asserting the api name is `mcpmesh-local/1`.
443pub async fn connect_control(path: &Path) -> Result<ControlClient, ClientError> {
444    let stream = connect_local(path).await?;
445    let (read_half, write_half) = split_local(stream);
446    connect_control_io(read_half, write_half).await
447}
448
449/// [`connect_control`] at the platform default endpoint ([`crate::paths::default_endpoint`]):
450/// the quickstart front door — a consumer dials the running daemon without reimplementing
451/// the platform endpoint rule. Resolution failure surfaces as [`ClientError::Io`]
452/// (`NotFound`), same as a daemon that is not running.
453pub async fn connect_control_default() -> Result<ControlClient, ClientError> {
454    connect_control(&crate::paths::default_endpoint()?).await
455}
456
457// Seam-ported (Task 6): every stub daemon binds via the platform seam
458// (`transport::bind_local` + `LocalListener::accept`) rather than a raw `UnixListener`,
459// so these exercise the platform-identical `ControlClient` on BOTH unix (UDS) and windows
460// (named pipe). Gated on `feature = "service"` (bind needs it) rather than `unix`: under
461// `cargo test --workspace` feature unification turns `service` on for this crate (cli
462// depends on local-api with features=["service"]), so the module compiles and RUNS on the
463// windows CI leg. `test_endpoint` yields a platform-appropriate unique endpoint.
464#[cfg(all(test, feature = "service"))]
465mod tests {
466    use super::*;
467    use crate::protocol::{API_NAME, API_VERSION, BackendKind, ServiceInfo, StatusResult};
468    use crate::transport::{LocalListener, bind_local, split_local};
469    use tokio::io::AsyncWriteExt;
470
471    /// A unique local endpoint for a stub daemon, platform-appropriate: a tempdir socket
472    /// path on unix, a per-process-unique `\\.\pipe\…` name on windows. Returns the
473    /// endpoint plus a guard that MUST outlive the listener (the `TempDir` on unix; unit
474    /// on windows, whose pipe namespace needs no filesystem cleanup).
475    #[cfg(unix)]
476    fn test_endpoint(tag: &str) -> (std::path::PathBuf, tempfile::TempDir) {
477        let dir = tempfile::tempdir().unwrap();
478        let path = dir.path().join(format!("{tag}.sock"));
479        (path, dir)
480    }
481    #[cfg(windows)]
482    fn test_endpoint(tag: &str) -> (std::path::PathBuf, ()) {
483        use std::sync::atomic::{AtomicU64, Ordering};
484        static SEQ: AtomicU64 = AtomicU64::new(0);
485        let n = SEQ.fetch_add(1, Ordering::Relaxed);
486        let path = std::path::PathBuf::from(format!(
487            r"\\.\pipe\mcpmesh-client-test-{}-{tag}-{n}",
488            std::process::id()
489        ));
490        (path, ())
491    }
492
493    /// A stub mcpmesh daemon: send Hello, then answer one `status` with a StatusResult.
494    async fn stub_daemon(mut listener: LocalListener) {
495        let stream = listener.accept().await.unwrap();
496        let (read_half, mut writer) = split_local(stream);
497        write_frame(
498            &mut writer,
499            &serde_json::to_value(Hello {
500                api: API_NAME.into(),
501                api_version: API_VERSION.into(),
502                api_minor: 0,
503                stack_version: "0.1.0".into(),
504            })
505            .unwrap(),
506        )
507        .await
508        .unwrap();
509        let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
510        let req = match reader.next().await.unwrap().unwrap() {
511            Inbound::Frame(v) => v,
512            Inbound::Violation(_) => panic!("violation"),
513        };
514        assert_eq!(req["method"], "status");
515        let result = StatusResult {
516            stack_version: "0.1.0".into(),
517            services: vec![ServiceInfo {
518                name: "kb".into(),
519                allow: vec![],
520                backend: BackendKind::Socket,
521                ephemeral: false,
522            }],
523            peers: vec![],
524            roster: None,
525            presence: vec![],
526            self_user_id: None,
527            recent_pairings: vec![],
528            reachability: vec![],
529        };
530        write_frame(
531            &mut writer,
532            &serde_json::json!({ "jsonrpc": "2.0", "id": 1, "result": result }),
533        )
534        .await
535        .unwrap();
536        writer.flush().await.unwrap();
537    }
538
539    /// The transport-agnostic front door: the same hello handshake over a plain in-memory
540    /// duplex — what an embedded node's `Node::control` dials through.
541    #[tokio::test]
542    async fn connect_control_io_handshakes_over_a_duplex() {
543        let (client_io, mut server_io) = tokio::io::duplex(4096);
544        tokio::spawn(async move {
545            write_frame(
546                &mut server_io,
547                &serde_json::to_value(Hello {
548                    api: API_NAME.into(),
549                    api_version: API_VERSION.into(),
550                    api_minor: 0,
551                    stack_version: "in-proc".into(),
552                })
553                .unwrap(),
554            )
555            .await
556            .unwrap();
557        });
558        let (r, w) = tokio::io::split(client_io);
559        let client = connect_control_io(r, w).await.expect("handshake");
560        assert_eq!(client.hello().stack_version, "in-proc");
561    }
562
563    #[tokio::test]
564    async fn connect_reads_hello_asserts_api_and_requests() {
565        let (sock, _guard) = test_endpoint("status");
566        let listener = bind_local(&sock).unwrap();
567        let server = tokio::spawn(stub_daemon(listener));
568
569        let mut client = connect_control(&sock).await.unwrap();
570        assert_eq!(client.hello().api, API_NAME);
571        let result = client.request(Request::Status).await.unwrap();
572        assert_eq!(result["services"][0]["name"], "kb");
573        assert_eq!(result["services"][0]["backend"], "socket");
574        server.await.unwrap();
575    }
576
577    #[tokio::test]
578    async fn wrong_api_hello_is_rejected() {
579        let (sock, _guard) = test_endpoint("wrongapi");
580        let listener = bind_local(&sock).unwrap();
581        tokio::spawn(async move {
582            let mut listener = listener;
583            let stream = listener.accept().await.unwrap();
584            let (_r, mut w) = split_local(stream);
585            write_frame(
586                &mut w,
587                &serde_json::json!({"api":"other/1","api_version":"1.0","stack_version":"0"}),
588            )
589            .await
590            .unwrap();
591            w.flush().await.unwrap();
592        });
593        match connect_control(&sock).await {
594            Err(ClientError::WrongApi { got, want }) => {
595                assert_eq!(got, "other/1");
596                assert_eq!(want, API_NAME);
597            }
598            other => panic!("expected WrongApi, got {other:?}"),
599        }
600    }
601
602    #[tokio::test]
603    async fn blob_fetch_and_publish_deserialize_typed_results() {
604        use crate::protocol::{BlobFetchResult, BlobPublishResult};
605        let (sock, _guard) = test_endpoint("blob");
606        let listener = bind_local(&sock).unwrap();
607        let server = tokio::spawn(async move {
608            let mut listener = listener;
609            let stream = listener.accept().await.unwrap();
610            let (read_half, mut writer) = split_local(stream);
611            write_frame(
612                &mut writer,
613                &serde_json::to_value(Hello {
614                    api: API_NAME.into(),
615                    api_version: API_VERSION.into(),
616                    api_minor: 0,
617                    stack_version: "0.1.0".into(),
618                })
619                .unwrap(),
620            )
621            .await
622            .unwrap();
623            let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
624            // First request: blob_publish -> a ticket + hash.
625            let req = match reader.next().await.unwrap().unwrap() {
626                Inbound::Frame(v) => v,
627                Inbound::Violation(_) => panic!("violation"),
628            };
629            assert_eq!(req["method"], "blob_publish");
630            assert_eq!(req["params"]["scope"], "eng");
631            write_frame(
632                &mut writer,
633                &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ticket":"blobT","hash":"ab"}}),
634            )
635            .await
636            .unwrap();
637            // Second request: blob_fetch -> a verified hash + length.
638            let req = match reader.next().await.unwrap().unwrap() {
639                Inbound::Frame(v) => v,
640                Inbound::Violation(_) => panic!("violation"),
641            };
642            assert_eq!(req["method"], "blob_fetch");
643            assert_eq!(req["params"]["ticket"], "blobT");
644            assert_eq!(req["params"]["dest_path"], "/tmp/out.bin");
645            write_frame(
646                &mut writer,
647                &serde_json::json!({"jsonrpc":"2.0","id":2,"result":{"hash":"cd","bytes_len":7}}),
648            )
649            .await
650            .unwrap();
651            let _ = (
652                BlobFetchResult {
653                    hash: "cd".into(),
654                    bytes_len: 7,
655                },
656                BlobPublishResult {
657                    ticket: "blobT".into(),
658                    hash: "ab".into(),
659                },
660            );
661        });
662
663        let mut client = connect_control(&sock).await.unwrap();
664        let pub_res = client.blob_publish("eng", "/tmp/a.bin").await.unwrap();
665        assert_eq!(pub_res.ticket, "blobT");
666        assert_eq!(pub_res.hash, "ab");
667        let fetch_res = client.blob_fetch("blobT", "/tmp/out.bin").await.unwrap();
668        assert_eq!(fetch_res.hash, "cd");
669        assert_eq!(fetch_res.bytes_len, 7);
670        server.await.unwrap();
671    }
672
673    /// Regression (lossless rebox): a frame the server PIPELINES in the same write as
674    /// the Hello must survive `open_session` + kb's production re-box shape
675    /// (`FrameReader::new(Box::new(reader.into_inner()), …)`, bridge/session.rs). Against
676    /// the old `into_inner -> R` — which unwrapped the internal `BufReader` and DROPPED
677    /// its read-ahead — the pipelined frame vanished and this test failed (EOF instead of
678    /// the frame). `into_inner -> BufReader<R>` carries the read-ahead across the rebox.
679    #[tokio::test]
680    async fn frame_pipelined_behind_hello_survives_open_session_rebox() {
681        use tokio::io::AsyncRead;
682
683        let (sock, _guard) = test_endpoint("pipelined");
684        let listener = bind_local(&sock).unwrap();
685        let server = tokio::spawn(async move {
686            let mut listener = listener;
687            let stream = listener.accept().await.unwrap();
688            let (read_half, mut writer) = split_local(stream);
689            // ONE write carrying the Hello AND a session frame → both land in the
690            // client's first BufReader fill (the read-ahead under test).
691            let mut bytes = serde_json::to_vec(
692                &serde_json::to_value(Hello {
693                    api: API_NAME.into(),
694                    api_version: API_VERSION.into(),
695                    api_minor: 0,
696                    stack_version: "0.1.0".into(),
697                })
698                .unwrap(),
699            )
700            .unwrap();
701            bytes.push(b'\n');
702            bytes.extend_from_slice(b"{\"jsonrpc\":\"2.0\",\"id\":42,\"result\":{}}\n");
703            writer.write_all(&bytes).await.unwrap();
704            writer.flush().await.unwrap();
705            // Absorb the client's open_session frame so its write never sees EPIPE.
706            let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
707            let req = match reader.next().await.unwrap().unwrap() {
708                Inbound::Frame(v) => v,
709                Inbound::Violation(_) => panic!("violation"),
710            };
711            assert_eq!(req["method"], "open_session");
712        });
713
714        let client = connect_control(&sock).await.unwrap();
715        let (reader, _writer) = client
716            .open_session("peer".into(), "kb".into())
717            .await
718            .unwrap();
719        // kb's production shape: erase the half type behind a boxed pipe, then re-frame.
720        let boxed: Box<dyn AsyncRead + Unpin + Send> = Box::new(reader.into_inner());
721        let mut reframed = FrameReader::new(boxed, MAX_FRAME_BYTES);
722        match reframed.next().await.unwrap() {
723            Some(Inbound::Frame(v)) => assert_eq!(v["id"], 42),
724            other => panic!("pipelined frame was lost across the rebox: {other:?}"),
725        }
726        server.await.unwrap();
727    }
728
729    #[tokio::test]
730    async fn blob_grant_issues_request_and_acks() {
731        let (sock, _guard) = test_endpoint("grant");
732        let listener = bind_local(&sock).unwrap();
733        let server = tokio::spawn(async move {
734            let mut listener = listener;
735            let stream = listener.accept().await.unwrap();
736            let (read_half, mut writer) = split_local(stream);
737            write_frame(
738                &mut writer,
739                &serde_json::to_value(Hello {
740                    api: API_NAME.into(),
741                    api_version: API_VERSION.into(),
742                    api_minor: 0,
743                    stack_version: "0.1.0".into(),
744                })
745                .unwrap(),
746            )
747            .await
748            .unwrap();
749            let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
750            let req = match reader.next().await.unwrap().unwrap() {
751                Inbound::Frame(v) => v,
752                Inbound::Violation(_) => panic!("violation"),
753            };
754            assert_eq!(req["method"], "blob_grant");
755            assert_eq!(req["params"]["scope"], "kb-sync");
756            assert_eq!(req["params"]["principal"], "alice");
757            write_frame(
758                &mut writer,
759                &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ok":true}}),
760            )
761            .await
762            .unwrap();
763        });
764        let mut client = connect_control(&sock).await.unwrap();
765        client.blob_grant("kb-sync", "alice").await.unwrap();
766        server.await.unwrap();
767    }
768
769    /// The typed `status()` helper pairs `Request::Status` with `StatusResult` — the caller gets
770    /// the struct, not a `Value` to hand-deserialize (and a malformed result surfaces as
771    /// `ClientError::Malformed`, never a silently-wrong type).
772    #[tokio::test]
773    async fn typed_status_helper_deserializes_the_result() {
774        let (sock, _guard) = test_endpoint("typedstatus");
775        let listener = bind_local(&sock).unwrap();
776        let server = tokio::spawn(stub_daemon(listener));
777
778        let mut client = connect_control(&sock).await.unwrap();
779        let status = client.status().await.unwrap();
780        assert_eq!(status.stack_version, "0.1.0");
781        assert_eq!(status.services[0].name, "kb");
782        assert_eq!(status.services[0].backend, BackendKind::Socket);
783        assert!(status.peers.is_empty());
784        server.await.unwrap();
785    }
786
787    /// The ack-shaped typed helpers issue the right wire method and discard the `{}` ack; a
788    /// JSON-RPC error frame surfaces as `ClientError::Api`.
789    #[tokio::test]
790    async fn typed_ack_helpers_issue_requests_and_surface_api_errors() {
791        let (sock, _guard) = test_endpoint("typedack");
792        let listener = bind_local(&sock).unwrap();
793        let server = tokio::spawn(async move {
794            let mut listener = listener;
795            let stream = listener.accept().await.unwrap();
796            let (read_half, mut writer) = split_local(stream);
797            write_frame(
798                &mut writer,
799                &serde_json::to_value(Hello {
800                    api: API_NAME.into(),
801                    api_version: API_VERSION.into(),
802                    api_minor: 0,
803                    stack_version: "0.1.0".into(),
804                })
805                .unwrap(),
806            )
807            .await
808            .unwrap();
809            let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
810            // peer_remove → ack.
811            let req = match reader.next().await.unwrap().unwrap() {
812                Inbound::Frame(v) => v,
813                Inbound::Violation(_) => panic!("violation"),
814            };
815            assert_eq!(req["method"], "peer_remove");
816            assert_eq!(req["params"]["nickname"], "bob");
817            write_frame(
818                &mut writer,
819                &serde_json::json!({"jsonrpc":"2.0","id":1,"result":{}}),
820            )
821            .await
822            .unwrap();
823            // peer_rename → an error frame (collision refusal).
824            let req = match reader.next().await.unwrap().unwrap() {
825                Inbound::Frame(v) => v,
826                Inbound::Violation(_) => panic!("violation"),
827            };
828            assert_eq!(req["method"], "peer_rename");
829            assert_eq!(req["params"]["to"], "Bobby");
830            write_frame(
831                &mut writer,
832                &serde_json::json!({"jsonrpc":"2.0","id":2,"error":{"code":-32000,"message":"taken"}}),
833            )
834            .await
835            .unwrap();
836        });
837
838        let mut client = connect_control(&sock).await.unwrap();
839        client.peer_remove("bob").await.unwrap();
840        match client.peer_rename(None, Some("bob".into()), "Bobby").await {
841            Err(ClientError::Api(e)) => assert_eq!(e["message"], "taken"),
842            other => panic!("expected Api error, got {other:?}"),
843        }
844        server.await.unwrap();
845    }
846
847    /// The typed `subscribe()` upgrade yields `StreamFrame`s — snapshot, event, lagged — then
848    /// `None` when the daemon side closes.
849    #[tokio::test]
850    async fn typed_subscribe_yields_frames_then_end() {
851        use crate::protocol::{ActiveSession, AuditRecord, PeerReachability};
852
853        let (sock, _guard) = test_endpoint("subscribe");
854        let listener = bind_local(&sock).unwrap();
855        let server = tokio::spawn(async move {
856            let mut listener = listener;
857            let stream = listener.accept().await.unwrap();
858            let (read_half, mut writer) = split_local(stream);
859            write_frame(
860                &mut writer,
861                &serde_json::to_value(Hello {
862                    api: API_NAME.into(),
863                    api_version: API_VERSION.into(),
864                    api_minor: 0,
865                    stack_version: "0.1.0".into(),
866                })
867                .unwrap(),
868            )
869            .await
870            .unwrap();
871            let mut reader = FrameReader::new(read_half, MAX_FRAME_BYTES);
872            let req = match reader.next().await.unwrap().unwrap() {
873                Inbound::Frame(v) => v,
874                Inbound::Violation(_) => panic!("violation"),
875            };
876            assert_eq!(req["method"], "subscribe");
877            for frame in [
878                StreamFrame::Snapshot {
879                    active_sessions: vec![ActiveSession {
880                        peer: "bob".into(),
881                        service: "notes".into(),
882                        opened_at: 7,
883                    }],
884                    reachability: vec![PeerReachability {
885                        name: "bob".into(),
886                        reachable: true,
887                        rtt_ms: Some(42),
888                        age_secs: Some(3),
889                    }],
890                },
891                StreamFrame::Event {
892                    record: Box::new(AuditRecord::session_open(
893                        "2026-07-03T14:02:11.480Z".into(),
894                        Some("bob".into()),
895                        "notes".into(),
896                    )),
897                },
898                StreamFrame::Lagged { dropped: 12 },
899            ] {
900                write_frame(&mut writer, &serde_json::to_value(&frame).unwrap())
901                    .await
902                    .unwrap();
903            }
904            writer.flush().await.unwrap();
905            // Drop the connection: the client must see the stream END (Ok(None)), not an error.
906        });
907
908        let client = connect_control(&sock).await.unwrap();
909        let mut sub = client.subscribe().await.unwrap();
910        match sub.next().await.unwrap().unwrap() {
911            StreamFrame::Snapshot {
912                active_sessions,
913                reachability,
914            } => {
915                assert_eq!(active_sessions[0].peer, "bob");
916                assert_eq!(reachability[0].rtt_ms, Some(42));
917            }
918            other => panic!("expected the snapshot first, got {other:?}"),
919        }
920        match sub.next().await.unwrap().unwrap() {
921            StreamFrame::Event { record } => {
922                assert_eq!(record.peer.as_deref(), Some("bob"));
923                assert_eq!(record.service.as_deref(), Some("notes"));
924            }
925            other => panic!("expected the event, got {other:?}"),
926        }
927        assert_eq!(
928            sub.next().await.unwrap(),
929            Some(StreamFrame::Lagged { dropped: 12 })
930        );
931        assert_eq!(sub.next().await.unwrap(), None, "clean end of stream");
932        server.await.unwrap();
933    }
934}