Skip to main content

agentmux_srv_core/backend/
dev_proxy.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Native reverse proxy for container-agent dev servers.
5//!
6//! Routes `http://<project>-<agent_id>.localhost:{DEV_PROXY_PORT}/...` to
7//! whatever internal `ip:port` that agent's dev server registered via the
8//! `RegisterDevServer` MCP tool (the HTTP endpoint backing that tool lives
9//! in `crates/srv/src/server/app_api/dev_server.rs`; this module owns the
10//! routing table and the proxy server itself). See
11//! `docs/specs/SPEC_NATIVE_CONTAINER_DEV_PROXY_2026_09_19.md`.
12//!
13//! Deliberately NOT a general-purpose reverse proxy (spec §4): Host-header
14//! → backend address is the entire feature. No path routing, no TLS, no
15//! auth, no rate limiting. WebSocket upgrades are passed through (a dev server's hot reload
16//! needs one), and a container whose address the host cannot reach (Docker Desktop) is reached
17//! through the relay in `dev_relay`.
18
19pub mod forward;
20
21use std::collections::HashMap;
22use std::net::SocketAddr;
23use std::sync::atomic::{AtomicU16, Ordering};
24use std::sync::Arc;
25
26use axum::extract::{Request, State};
27use axum::http::{header, StatusCode};
28use axum::response::{IntoResponse, Response};
29use axum::routing::any;
30use axum::Router;
31use tokio::sync::RwLock;
32
33/// The local port the proxy tries first. Nothing else in `agentmux-srv` binds it
34/// (checked: no other `TcpListener::bind` or config default references 8090
35/// anywhere in this crate). See spec §5. A second instance on the same host
36/// finds it held and takes a free port instead; [`port`] says which one this
37/// instance got.
38pub const DEV_PROXY_PORT: u16 = 8090;
39
40/// The port the proxy actually bound, or 0 before it has bound (or when it could not).
41static BOUND_PORT: AtomicU16 = AtomicU16::new(0);
42
43/// The port this instance's proxy listens on: the one it bound, which is
44/// [`DEV_PROXY_PORT`] unless another instance on the host held it. Before the
45/// proxy has bound, the preferred port is the best answer there is.
46pub fn port() -> u16 {
47    match BOUND_PORT.load(Ordering::Relaxed) {
48        0 => DEV_PROXY_PORT,
49        bound => bound,
50    }
51}
52
53/// One registered dev server: where to actually send the request, and
54/// the container it came from.
55#[derive(Debug, Clone)]
56struct Route {
57    target: Target,
58    /// The container it was registered from, when known: what stopping or removing a container clears.
59    container: Option<String>,
60}
61
62/// How to reach a registered dev server.
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub enum Target {
65    /// Straight to the container's address on the agents network.
66    Direct(SocketAddr),
67    /// Through the relay (`dev_relay`), to a container by name.
68    Relay { via: crate::backend::dev_relay::RelayEndpoint, container: String, port: u16 },
69}
70
71impl From<SocketAddr> for Target {
72    fn from(addr: SocketAddr) -> Self {
73        Target::Direct(addr)
74    }
75}
76
77/// `"<project>-<agent_id>"` → the container's internal `ip:port` its dev
78/// server is actually listening on. Cleared per-agent when that agent's
79/// container stops (`ContainerManager::stop`/`remove` in `container.rs`
80/// call `unregister_container` — see that module's `cleanup_dev_proxy_routes`).
81///
82/// Cheap to clone (one `Arc` inside) — held directly by `AppState` and
83/// passed to the proxy's own axum router as state.
84#[derive(Clone, Default)]
85pub struct DevProxyRegistry {
86    routes: Arc<RwLock<HashMap<String, Route>>>,
87}
88
89impl DevProxyRegistry {
90    pub fn new() -> Self {
91        Self::default()
92    }
93
94    /// The exact routing key both `register` and the Host-header lookup
95    /// use — kept as one function so the two can never drift apart.
96    /// Lowercased: hostnames are case-insensitive, and a browser may send
97    /// whatever case the URL bar has, so registration and lookup must
98    /// agree regardless of how either side capitalized `project`/`agent_id`.
99    pub fn routing_key(project: &str, agent_id: &str) -> String {
100        format!("{}-{}", project.to_lowercase(), agent_id.to_lowercase())
101    }
102
103    pub async fn register(&self, project: &str, agent_id: &str, target: impl Into<Target>) {
104        self.register_from(project, agent_id, None, target).await
105    }
106
107    /// [`register`](Self::register) for a dev server in `container`, so that container stopping or being removed
108    /// clears the route ([`unregister_container`](Self::unregister_container)).
109    pub async fn register_from(&self, project: &str, agent_id: &str, container: Option<&str>, target: impl Into<Target>) {
110        let key = Self::routing_key(project, agent_id);
111        self.routes.write().await.insert(
112            key,
113            Route { target: target.into(), container: container.map(str::to_string) },
114        );
115    }
116
117    /// Removes every registration made from `container`. A container is named from its definition's uuid and
118    /// a route from the agent's id, which are not the same string, so this is how a stopped container's routes go.
119    pub async fn unregister_container(&self, container: &str) {
120        self.routes.write().await.retain(|_, route| route.container.as_deref() != Some(container));
121    }
122
123    pub async fn lookup(&self, key: &str) -> Option<Target> {
124        self.routes.read().await.get(key).map(|r| r.target.clone())
125    }
126
127    #[cfg(test)]
128    async fn len(&self) -> usize {
129        self.routes.read().await.len()
130    }
131}
132
133/// Host header → routing key. `"pulse-korp.localhost:8090"` and
134/// `"pulse-korp.localhost"` both become `"pulse-korp"`. A Host that isn't
135/// `.localhost` is still accepted (minus port, lowercased) rather than
136/// rejected outright — an empty/missing Host is the only thing that
137/// produces `None`. Whether the key actually resolves to anything is the
138/// registry lookup's job, not this function's; either way the caller gets
139/// a clear "no dev server registered for `<key>`" 404, never a confusing
140/// hostname-format error.
141pub fn routing_key_from_host(host: &str) -> Option<String> {
142    let host = host.trim();
143    if host.is_empty() {
144        return None;
145    }
146    // Lowercase BEFORE stripping the `.localhost` suffix, not after — a
147    // literal `.strip_suffix(".localhost")` is case-sensitive, so an
148    // upper/mixed-case Host (e.g. from a client that title-cases URLs)
149    // would otherwise fail to match and fall through with the suffix
150    // still attached.
151    let without_port = host.split(':').next().unwrap_or(host).to_lowercase();
152    let key = without_port.strip_suffix(".localhost").unwrap_or(&without_port);
153    if key.is_empty() {
154        None
155    } else {
156        Some(key.to_string())
157    }
158}
159
160#[derive(Clone)]
161struct ProxyState {
162    registry: DevProxyRegistry,
163}
164
165/// Builds the proxy's axum router. Split out from [`serve`] so tests can
166/// drive it directly (via a real bound listener) without needing the fixed
167/// [`DEV_PROXY_PORT`] to be free.
168pub fn router(registry: DevProxyRegistry) -> Router {
169    let state = ProxyState { registry };
170    // `.fallback` (not a path route): routing here is entirely by Host
171    // header, so every path/method for every host is the same handler.
172    Router::new()
173        .fallback(any(proxy_handler))
174        .with_state(state)
175}
176
177/// Binds `preferred` on loopback, or, when it is held (another AgentMux instance on this host has the proxy
178/// on it; Windows says 10048), a free port the OS picks.
179async fn bind_loopback(preferred: u16) -> std::io::Result<tokio::net::TcpListener> {
180    match tokio::net::TcpListener::bind(SocketAddr::from(([127, 0, 0, 1], preferred))).await {
181        Ok(l) => Ok(l),
182        Err(e) => {
183            tracing::info!(port = preferred, error = %e, "dev-proxy: port taken, picking a free one");
184            tokio::net::TcpListener::bind(SocketAddr::from(([127, 0, 0, 1], 0))).await
185        }
186    }
187}
188
189/// Binds [`DEV_PROXY_PORT`] on loopback (or a free port when another instance holds it) and serves the proxy
190/// until the process exits. Spawned once at srv startup (`main.rs`). A bind failure is logged and the proxy is
191/// simply unavailable for this run — never fatal to srv startup; dev-server routing is an additive convenience,
192/// not core functionality.
193pub async fn serve(registry: DevProxyRegistry) {
194    let listener = match bind_loopback(DEV_PROXY_PORT).await {
195        Ok(l) => l,
196        Err(e) => {
197            tracing::warn!(
198                error = %e,
199                "dev-proxy: failed to bind — dev-server routing unavailable this run"
200            );
201            return;
202        }
203    };
204    let bound = listener.local_addr().map(|a| a.port()).unwrap_or(DEV_PROXY_PORT);
205    BOUND_PORT.store(bound, Ordering::Relaxed);
206    tracing::info!(port = bound, "dev-proxy: listening");
207    if let Err(e) = axum::serve(listener, router(registry)).await {
208        tracing::error!(error = %e, "dev-proxy: server error");
209    }
210}
211
212fn not_found_response(key: &str) -> Response {
213    (
214        StatusCode::NOT_FOUND,
215        format!(
216            "AgentMux dev proxy: no dev server registered for \"{key}\". \
217             Call RegisterDevServer from the owning agent once its dev server is listening."
218        ),
219    )
220        .into_response()
221}
222
223/// The one handler this proxy has. Reads `Host`, looks up the backend, opens a connection to it
224/// (direct, or through the relay) and forwards the request over it, streaming the body both ways so
225/// a large or long-lived response isn't buffered whole in memory. A WebSocket upgrade becomes a
226/// byte pipe between the two ends.
227async fn proxy_handler(State(state): State<ProxyState>, req: Request) -> Response {
228    let host = req
229        .headers()
230        .get(header::HOST)
231        .and_then(|v| v.to_str().ok())
232        .unwrap_or("")
233        .to_string();
234
235    let Some(key) = routing_key_from_host(&host) else {
236        return not_found_response(&host);
237    };
238
239    let Some(target) = state.registry.lookup(&key).await else {
240        return not_found_response(&key);
241    };
242
243    let (stream, backend_host) = match &target {
244        Target::Direct(addr) => (tokio::net::TcpStream::connect(addr).await, addr.to_string()),
245        Target::Relay { via, container, port } => {
246            (crate::backend::dev_relay::connect(via, container, *port).await, format!("localhost:{port}"))
247        }
248    };
249    let stream = match stream {
250        Ok(s) => s,
251        Err(e) => return bad_gateway(&key, &target, &e.to_string()),
252    };
253    match forward::forward(req, stream, &backend_host).await {
254        Ok(response) => response,
255        Err(e) => bad_gateway(&key, &target, &e),
256    }
257}
258
259fn bad_gateway(key: &str, target: &Target, why: &str) -> Response {
260    tracing::warn!(key = %key, ?target, error = %why, "dev-proxy: upstream request failed");
261    (
262        StatusCode::BAD_GATEWAY,
263        format!("AgentMux dev proxy: could not reach dev server for \"{key}\": {why}"),
264    )
265        .into_response()
266}
267
268#[cfg(test)]
269mod tests {
270    use super::*;
271
272    fn addr(port: u16) -> SocketAddr {
273        SocketAddr::from(([127, 0, 0, 1], port))
274    }
275
276    #[test]
277    fn routing_key_is_project_dash_agent_lowercased() {
278        assert_eq!(DevProxyRegistry::routing_key("Pulse", "Korp"), "pulse-korp");
279        assert_eq!(DevProxyRegistry::routing_key("api", "agent1"), "api-agent1");
280    }
281
282    #[test]
283    fn host_parsing_strips_port_and_localhost_suffix() {
284        assert_eq!(
285            routing_key_from_host("pulse-korp.localhost:8090"),
286            Some("pulse-korp".to_string())
287        );
288        assert_eq!(
289            routing_key_from_host("pulse-korp.localhost"),
290            Some("pulse-korp".to_string())
291        );
292        assert_eq!(
293            routing_key_from_host("Pulse-Korp.LOCALHOST:8090"),
294            Some("pulse-korp".to_string())
295        );
296    }
297
298    #[test]
299    fn host_parsing_passes_through_a_non_localhost_host_minus_port() {
300        // Not rejected outright — the registry lookup (empty for anything
301        // never registered) is what actually 404s an unrecognized host,
302        // not this parsing step.
303        assert_eq!(
304            routing_key_from_host("example.com:8090"),
305            Some("example.com".to_string())
306        );
307    }
308
309    #[test]
310    fn host_parsing_rejects_only_empty_host() {
311        assert_eq!(routing_key_from_host(""), None);
312        assert_eq!(routing_key_from_host("   "), None);
313    }
314
315    #[tokio::test]
316    async fn register_then_lookup_finds_the_backend() {
317        let registry = DevProxyRegistry::new();
318        registry.register("pulse", "korp", addr(4000)).await;
319        assert_eq!(
320            registry
321                .lookup(&DevProxyRegistry::routing_key("pulse", "korp"))
322                .await,
323            Some(Target::Direct(addr(4000)))
324        );
325    }
326
327    #[tokio::test]
328    async fn lookup_of_an_unregistered_key_is_none() {
329        let registry = DevProxyRegistry::new();
330        assert_eq!(registry.lookup("nope-nobody").await, None);
331    }
332
333    #[tokio::test]
334    async fn unregister_container_removes_what_was_registered_from_it_whatever_the_agent_is_called() {
335        let reg = DevProxyRegistry::new();
336        let addr: SocketAddr = "127.0.0.1:5173".parse().unwrap();
337        // The route is under the agent's id; the container is named from the definition's uuid.
338        reg.register_from("app", "kcont", Some("agentmux-a5e772db"), addr).await;
339        reg.register_from("api", "kcont", Some("agentmux-a5e772db"), addr).await;
340        reg.register_from("app", "other", Some("agentmux-ffff"), addr).await;
341        reg.register("loose", "kcont", addr).await;
342        reg.unregister_container("agentmux-a5e772db").await;
343        assert!(reg.lookup("app-kcont").await.is_none() && reg.lookup("api-kcont").await.is_none());
344        assert!(reg.lookup("app-other").await.is_some(), "another container's route stays");
345        assert!(reg.lookup("loose-kcont").await.is_some(), "a route with no container isn't a container's to lose");
346    }
347
348    #[tokio::test]
349    async fn re_registering_the_same_key_overwrites_the_address() {
350        let registry = DevProxyRegistry::new();
351        registry.register("pulse", "korp", addr(4000)).await;
352        registry.register("pulse", "korp", addr(5000)).await;
353        assert_eq!(
354            registry
355                .lookup(&DevProxyRegistry::routing_key("pulse", "korp"))
356                .await,
357            Some(Target::Direct(addr(5000)))
358        );
359    }
360
361    /// End-to-end through real HTTP: a tiny backend server, the proxy
362    /// router in front of it, and a real client request carrying a Host
363    /// header — not an in-process function call. Confirms the whole
364    /// request path (Host parsing → lookup → forward → stream response
365    /// back) actually works, and that an unregistered Host 404s cleanly
366    /// instead of hanging or producing a confusing proxy error.
367    #[tokio::test]
368    async fn proxies_a_real_request_and_404s_an_unregistered_host() {
369        // Fake dev server: echoes back a fixed, recognizable body.
370        let backend_listener = tokio::net::TcpListener::bind("127.0.0.1:0")
371            .await
372            .expect("bind fake backend");
373        let backend_addr = backend_listener.local_addr().unwrap();
374        let backend_router = Router::new().fallback(any(|| async {
375            (StatusCode::OK, "hello from the fake dev server")
376        }));
377        tokio::spawn(async move {
378            let _ = axum::serve(backend_listener, backend_router).await;
379        });
380
381        let registry = DevProxyRegistry::new();
382        registry.register("pulse", "korp", backend_addr).await;
383
384        let proxy_listener = tokio::net::TcpListener::bind("127.0.0.1:0")
385            .await
386            .expect("bind proxy");
387        let proxy_addr = proxy_listener.local_addr().unwrap();
388        tokio::spawn(async move {
389            let _ = axum::serve(proxy_listener, router(registry)).await;
390        });
391
392        let client = reqwest::Client::new();
393
394        // Correct Host — should reach the fake backend.
395        let ok_resp = client
396            .get(format!("http://{proxy_addr}/anything"))
397            .header(header::HOST, "pulse-korp.localhost:8090")
398            .send()
399            .await
400            .expect("request through proxy");
401        assert_eq!(ok_resp.status(), StatusCode::OK);
402        let body = ok_resp.text().await.expect("body");
403        assert_eq!(body, "hello from the fake dev server");
404
405        // Wrong/unregistered Host — clean 404, not a hang or a raw
406        // connection-refused error.
407        let missing_resp = client
408            .get(format!("http://{proxy_addr}/anything"))
409            .header(header::HOST, "nobody-here.localhost:8090")
410            .send()
411            .await
412            .expect("request through proxy");
413        assert_eq!(missing_resp.status(), StatusCode::NOT_FOUND);
414        let missing_body = missing_resp.text().await.expect("body");
415        assert!(missing_body.contains("no dev server registered"));
416    }
417
418    /// reagent P1, PR #3439: hop-by-hop headers describing the CLIENT's
419    /// connection to THIS proxy (`Transfer-Encoding`, `Connection`) must not
420    /// be forwarded to the backend — the outbound body is independently
421    /// re-streamed via `reqwest::Body::wrap_stream`, so a forwarded
422    /// `Transfer-Encoding: chunked` would assert an encoding reqwest isn't
423    /// actually producing. Confirmed by having the fake backend report back
424    /// exactly which headers it received, not by inspecting the proxy's
425    /// outbound request in isolation — the same "real HTTP, not an
426    /// in-process function call" standard as the test above.
427    #[tokio::test]
428    async fn hop_by_hop_request_headers_are_not_forwarded_to_the_backend() {
429        let backend_listener = tokio::net::TcpListener::bind("127.0.0.1:0")
430            .await
431            .expect("bind fake backend");
432        let backend_addr = backend_listener.local_addr().unwrap();
433        let backend_router = Router::new().fallback(any(
434            |req: Request| async move {
435                let saw_transfer_encoding =
436                    req.headers().contains_key(header::TRANSFER_ENCODING);
437                let saw_connection = req.headers().contains_key(header::CONNECTION);
438                (
439                    StatusCode::OK,
440                    format!("te={saw_transfer_encoding} conn={saw_connection}"),
441                )
442            },
443        ));
444        tokio::spawn(async move {
445            let _ = axum::serve(backend_listener, backend_router).await;
446        });
447
448        let registry = DevProxyRegistry::new();
449        registry.register("pulse", "korp", backend_addr).await;
450
451        let proxy_listener = tokio::net::TcpListener::bind("127.0.0.1:0")
452            .await
453            .expect("bind proxy");
454        let proxy_addr = proxy_listener.local_addr().unwrap();
455        tokio::spawn(async move {
456            let _ = axum::serve(proxy_listener, router(registry)).await;
457        });
458
459        let client = reqwest::Client::new();
460        let resp = client
461            .get(format!("http://{proxy_addr}/anything"))
462            .header(header::HOST, "pulse-korp.localhost:8090")
463            .header(header::TRANSFER_ENCODING, "chunked")
464            .header(header::CONNECTION, "keep-alive")
465            .send()
466            .await
467            .expect("request through proxy");
468        assert_eq!(resp.status(), StatusCode::OK);
469        let body = resp.text().await.expect("body");
470        assert_eq!(body, "te=false conn=false");
471    }
472
473    /// A fake dev server that answers a WebSocket handshake and echoes frames.
474    async fn websocket_echo_backend() -> SocketAddr {
475        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.expect("bind ws backend");
476        let addr = listener.local_addr().unwrap();
477        tokio::spawn(async move {
478            while let Ok((stream, _)) = listener.accept().await {
479                tokio::spawn(async move {
480                    use futures_util::{SinkExt, StreamExt};
481                    let Ok(mut ws) = tokio_tungstenite::accept_async(stream).await else { return };
482                    while let Some(Ok(msg)) = ws.next().await {
483                        if msg.is_text() || msg.is_binary() {
484                            let _ = ws.send(msg).await;
485                        }
486                    }
487                });
488            }
489        });
490        addr
491    }
492
493    async fn serve_proxy(registry: DevProxyRegistry) -> SocketAddr {
494        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.expect("bind proxy");
495        let addr = listener.local_addr().unwrap();
496        tokio::spawn(async move {
497            let _ = axum::serve(listener, router(registry)).await;
498        });
499        addr
500    }
501
502    /// Hot reload: a WebSocket opened through the proxy reaches the dev server and carries frames both ways.
503    #[tokio::test]
504    async fn a_websocket_upgrade_is_passed_through() {
505        use futures_util::{SinkExt, StreamExt};
506        use tokio_tungstenite::tungstenite::client::IntoClientRequest;
507        use tokio_tungstenite::tungstenite::Message;
508
509        let registry = DevProxyRegistry::new();
510        registry.register("pulse", "korp", websocket_echo_backend().await).await;
511        let proxy = serve_proxy(registry).await;
512
513        let request = "ws://pulse-korp.localhost:8090/hmr".into_client_request().unwrap();
514        let stream = tokio::net::TcpStream::connect(proxy).await.unwrap();
515        let (mut ws, response) = tokio_tungstenite::client_async(request, stream).await.expect("handshake through the proxy");
516        assert_eq!(response.status(), StatusCode::SWITCHING_PROTOCOLS);
517        ws.send(Message::text("update")).await.unwrap();
518        let echoed = tokio::time::timeout(std::time::Duration::from_secs(5), ws.next()).await.expect("an answer").unwrap().unwrap();
519        assert_eq!(echoed, Message::text("update"));
520    }
521
522    /// The same request through a relay: the proxy opens the connection by the relay's line protocol.
523    #[tokio::test]
524    async fn a_dev_server_behind_the_relay_is_reached_through_it() {
525        use tokio::io::{AsyncReadExt, AsyncWriteExt};
526        let backend_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
527        let backend_addr = backend_listener.local_addr().unwrap();
528        tokio::spawn(async move {
529            let _ = axum::serve(backend_listener, Router::new().fallback(any(|req: Request| async move {
530                format!("host={}", req.headers().get(header::HOST).and_then(|v| v.to_str().ok()).unwrap_or(""))
531            }))).await;
532        });
533        // A relay that checks the request line and then joins the connection to the backend.
534        let relay_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
535        let relay_addr = relay_listener.local_addr().unwrap();
536        tokio::spawn(async move {
537            while let Ok((mut client, _)) = relay_listener.accept().await {
538                tokio::spawn(async move {
539                    let mut line = Vec::new();
540                    loop {
541                        let mut b = [0u8; 1];
542                        if client.read(&mut b).await.unwrap_or(0) == 0 { return; }
543                        if b[0] == b'\n' { break; }
544                        line.push(b[0]);
545                    }
546                    if String::from_utf8_lossy(&line) != "tok agentmux-korp 7000" {
547                        let _ = client.write_all(b"ERR refused\n").await;
548                        return;
549                    }
550                    let Ok(mut backend) = tokio::net::TcpStream::connect(backend_addr).await else { return };
551                    let _ = client.write_all(b"OK\n").await;
552                    let _ = tokio::io::copy_bidirectional(&mut client, &mut backend).await;
553                });
554            }
555        });
556
557        let registry = DevProxyRegistry::new();
558        let via = crate::backend::dev_relay::RelayEndpoint { addr: relay_addr, token: "tok".into() };
559        registry.register("pulse", "korp", Target::Relay { via, container: "agentmux-korp".into(), port: 7000 }).await;
560        let proxy = serve_proxy(registry).await;
561
562        let resp = reqwest::Client::new()
563            .get(format!("http://{proxy}/"))
564            .header(header::HOST, "pulse-korp.localhost:8090")
565            .send()
566            .await
567            .expect("through the proxy and the relay");
568        assert_eq!(resp.status(), StatusCode::OK);
569        assert_eq!(resp.text().await.unwrap(), "host=localhost:7000", "the dev server is asked for as localhost, which every dev server allows");
570    }
571
572    /// A relay that refuses is a 502 that says why, not a hang.
573    #[tokio::test]
574    async fn a_relay_that_cannot_be_reached_is_a_bad_gateway() {
575        let gone = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap().local_addr().unwrap();
576        let registry = DevProxyRegistry::new();
577        let via = crate::backend::dev_relay::RelayEndpoint { addr: gone, token: "tok".into() };
578        registry.register("pulse", "korp", Target::Relay { via, container: "agentmux-korp".into(), port: 7000 }).await;
579        let proxy = serve_proxy(registry).await;
580        let resp = reqwest::Client::new().get(format!("http://{proxy}/")).header(header::HOST, "pulse-korp.localhost:8090").send().await.unwrap();
581        assert_eq!(resp.status(), StatusCode::BAD_GATEWAY);
582        assert!(resp.text().await.unwrap().contains("could not reach dev server"));
583    }
584
585    #[tokio::test]
586    async fn a_taken_preferred_port_falls_back_to_a_free_one() {
587        // Hold a port the way the first instance holds 8090, then ask for it again.
588        let holder = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
589        let held = holder.local_addr().unwrap().port();
590        let second = bind_loopback(held).await.expect("falls back instead of failing");
591        let got = second.local_addr().unwrap().port();
592        assert_ne!(got, held);
593        assert_ne!(got, 0);
594    }
595
596    #[tokio::test]
597    async fn a_free_preferred_port_is_used() {
598        let probe = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
599        let free = probe.local_addr().unwrap().port();
600        drop(probe);
601        let l = bind_loopback(free).await.unwrap();
602        assert_eq!(l.local_addr().unwrap().port(), free);
603    }
604}