diff --git a/docs/README.md b/docs/README.md index 9ddf1fccb..e8fe27200 100644 --- a/docs/README.md +++ b/docs/README.md @@ -7,7 +7,7 @@ each crate's `docs.md`. | --- | --- | | [glossary.md](glossary.md) | Canonical terms for actors, turns, sessions, and tools | | [turn-lifecycle.md](turn-lifecycle.md) | Turn state, `session/update` routing, and cancellation | -| [remote-control.md](remote-control.md) | Remote ACP transport behind `--remote` and `/remote-control` | +| [remote-control.md](remote-control.md) | Remote ACP transport, authenticated background hosts, and attached terminals | | [nori-client-mcp.md](nori-client-mcp.md) | The backend-owned `nori-client` MCP server and goals | | [headless.md](headless.md) | `nori exec` plaintext mode and the ACP stdio facade | | [transcripts.md](transcripts.md) | Transcript file locations and schema | diff --git a/docs/remote-control.md b/docs/remote-control.md index 92a406fd7..6a792ecdb 100644 --- a/docs/remote-control.md +++ b/docs/remote-control.md @@ -1,9 +1,5 @@ # Remote ACP Transport -**Status:** Implemented ACP transport plus feature-gated managed-session transport - -**Date:** 2026-08-23 (revised 2026-11-15) - **Upstream:** [ACP Streamable HTTP & WebSocket Transport RFD](https://agentclientprotocol.com/rfds/streamable-http-websocket-transport) ## 1. Decision @@ -21,8 +17,10 @@ wildcard listener or separate session-host crate is introduced. Without `[features] multi_session`, `nori exec --acp` remains a bounded, terminal-independent stdio facade and `/acp` exposes the interactive harness. With the flag, `/sessions` and the existing exec facade share the managed -session commands described in section 10. This adds transport primitives only; -it does not introduce host/attach commands or a persistent host lifecycle. +session commands described in section 10. The separate `nori host` process +owns sessions without a terminal; `nori attach` is its feature-gated terminal +frontend. Its authenticated endpoint and controller/watcher policy are +described in section 11. Sections 3–6 describe the legacy `/acp` projection unless stated otherwise. ## 2. Topology @@ -277,8 +275,9 @@ nori-rs/ ``` The `--remote` flag lives on the interactive CLI surface and is normalized into -the same TUI-owned manager as runtime commands; the `cli` crate itself remains -unchanged. Remote prompts use the same harness-originated user-message +the same TUI-owned manager as runtime commands. Background host commands are +dispatched separately by [`cli/src/host`](../nori-rs/cli/src/host/docs.md). +Remote prompts use the same harness-originated user-message notifications as local prompts, so their original content is visible in the observing TUI and every attached frontend. @@ -301,9 +300,11 @@ v1 transport: - An initialized socket receives live session updates before it explicitly attaches to the session through `session/load` or `session/resume`. -Authentication, TLS, endpoint discovery, broker routing, Handroll federation, -capability aggregation across hosts, Streamable HTTP/SSE, and replay across a -host-process restart remain outside this implementation. Legacy `/acp` retains +The legacy `--remote` surface remains unauthenticated. The background host +requires a token and supports same-machine discovery (section 11). TLS +termination, broker routing, Handroll federation, capability aggregation across +hosts, Streamable HTTP/SSE, and replay across a host-process restart remain +outside this implementation. Legacy `/acp` retains its transcript-based recovery; managed envelopes add bounded reconnect replay within the current manager lifetime. @@ -406,9 +407,9 @@ supply `replay_cursors` for all-session live following, or the chosen row's `latest_seq` for one session. This is an explicit new observation point, not recovery of the missing prefix. -`/acp` and `/sessions` share one controller slot across all exact listeners; -last connect wins. Whether future clients can both control, or one can control -while another watches, remains a pending D2 decision. Disconnect or listener +On the legacy `--remote` surface, `/acp` and `/sessions` share one controller +slot across all exact listeners; last connect wins. The background host uses +the controller/watcher policy below instead. Disconnect or listener shutdown detaches managed clients without stopping sessions, cancelling admitted turns, or answering pending permissions. Those permissions remain visible and answerable after reconnect or from the TUI. A slow managed consumer is dropped when its bounded live queue @@ -421,3 +422,127 @@ resubscribe share the same cursor validation, so expiry cannot silently lose history. Stdio encoding or writer failure cannot guarantee an ending notification. At the exec process boundary, stdin EOF shuts down all managed sessions. + +## 11. Background host and attached terminals + +`nori host` starts a detached Unix process with an initially empty +`SessionManager`. The host owns the agent processes and remains alive when +every terminal detaches or the last session ends. It binds only loopback, +defaults to port 7420, and accepts `--port 0` to allocate a port. `nori host stop` +authenticates, requests shutdown, and waits for the host's singleton lock to be +released after cleanup. Startup and stop do not require a terminal. + +| Command | Behavior | +| --- | --- | +| `nori host` | Start the background host, or report the already-running host. | +| `nori host ls` | Print the flat `ID AGENT STATUS AGE TITLE` table; TTY output colors status and truncates titles to the terminal width, while piped output keeps full titles without color. | +| `nori attach` | Open the host session list; requires `[features] multi_session = true`. | +| `nori attach ` | Open the named Nori conversation. | +| `nori attach --host --token-file ` | Connect to an explicit managed endpoint using a private token file. | +| `nori host stop` | Stop the listener and all host-owned sessions. | + +The CLI stores discovery state, token, log, and lock under `$NORI_HOME/host`. +The directory is created with mode `0700`; files are created with mode `0600`. +Existing paths must be owned by the effective user and inaccessible to group +and other users; files must be regular and cannot be symlinks. An OS-held lock, +not the saved PID, determines whether the host is running. Each host start +generates a new token and publishes its endpoint only after binding. Local +commands read that token automatically; startup prints its path, never its +value. Background hosting is refused on platforms without the implemented Unix +permission checks. + +`RemoteAcpServer::bind_host` exposes only `/sessions`, with no legacy `/acp` +route. A valid `Authorization: Bearer ` header is required before the +WebSocket upgrade, including on loopback; a missing or wrong token returns +HTTP 401. This policy applies to `nori host`, not the separate `--remote` or +`/remote-control` listeners. + +Successful authenticated upgrades include `x-nori-host-instance`, a UUID +generated for that router lifetime independently of the bearer token. It stays +stable across connections and changes when a new host router starts, even if +the address and token are reused. Reconnecting clients check this identity +before initialization or replay so an old cursor cannot silently target a new +manager. + +The terminal table budgets display cells, preserving grapheme boundaries and +adding an ellipsis when a title exceeds the remaining width. If the terminal +cannot fit the metadata columns, the row prefix is clipped too. Piped output +has no width limit; control characters are sanitized in either mode. + +```text +attached controller -- commands --+ + v +attached watchers --------> authenticated /sessions --> HostService + ^ | | + | +-- role changes v + +---------- ordered replay/live events ------ SessionManager + | + ACP agent processes +``` + +### Control and lifecycle requests + +The first successful interactive `initialize` claims control when the slot is +empty. Later clients remain connected as watchers. `initialize` with +`{"observe":true}` never claims the slot, so polling `host ls` and running +administrative stop do not take control. Initialization returns +`result.control` containing `role` and `controller_connected`. + +| Method | Meaning | +| --- | --- | +| `_nori/control/status` | Return this connection's role and whether a controller is connected. | +| `_nori/control/take` | Transfer control to the caller without closing another connection. | +| `_nori/session/new` | Start a session with the host configuration; optional `agent` selects its agent. | +| `_nori/session/close`, `_nori/session/cancel`, `_nori/session/resume` | Apply the operation to the required `session_id`; resume retains the Nori conversation ID. | +| `_nori/host/stop` | Request host shutdown; any authenticated initialized client may call it. | + +`_nori/control/changed` notifications carry the new `role` to terminals affected +by a handoff. The admission mutex serializes the ownership check with handoff, +then releases before awaiting the backend. An already-admitted operation may +finish after control moves; new mutations from the previous controller are +refused. A slow operation on one connection does not hold up another client's +initialization, list, takeover, or stop. Watchers can list, subscribe, and take +control; session mutations, including prompts and permission answers, fail with +`-32016` and a read-only error. When the controller disconnects, existing +watchers are not automatically promoted. They may take control explicitly, or +a new interactive initializer may claim the empty slot. + +### Attached frontend and recovery + +The dedicated [`attach` frontend](../nori-rs/tui/src/attach/docs.md) uses the +managed client through harness re-exports. It owns terminal state and replay +cursors, never the host's agent processes. Alt+T takes control; Ctrl+D or +`/quit` detaches. The configured `hotkeys.open_session_list` binding, Left with +an empty composer, or `/sessions` opens the session list. Ctrl+R resumes its +highlighted failed session with the same conversation ID. The status line shows +controlling, watching/read-only, reconnecting, or disconnected state. The +current session marker appears inside TITLE, leaving its short ID visible. +Session commands address the host; they do not launch local agents. + +Socket loss or a receive-liveness deadline starts recovery. Periodic session +list requests keep idle connections observable; receiving JSON renews the +deadline, while outgoing traffic alone does not. The deadline also bounds +blocked sends. The frontend retains its rendered sessions, reconnects, verifies +the host-instance identity, initializes again, and subscribes to the selected +conversation with its last applied cursor. Switching conversations uses that conversation's saved cursor; +the session list refreshes independently without subscribing to every session. +It advances a cursor only after applying that envelope and ignores duplicates. +Transcript restoration is distinct: `ReplayStarted` replaces the rendered +conversation and pending permissions without resetting transport sequence +tracking. Permission prompts also clear when the turn becomes idle or begins +cancelling, the session ends, or a matching answer is resolved. The frontend +does not retransmit mutations whose acknowledgement may have been lost. +Replay expiry or an unexpected sequence gap is visible as an error; the +frontend does not silently jump to live output. Replay is bounded to the +current host process lifetime, so a fresh attachment may also encounter an +expired prefix. Restarting a host does not restore its in-memory manager. + +On HTTP 401 or 403 during reconnect, a locally discovered attachment rereads +the current token file using the same ownership, permission, and regular-file +checks as startup, then retries once. An explicit `--host` attachment never +rediscovers local credentials. An unavailable token, failed retry, or changed +or unavailable host identity stops recovery and leaves a persistent message +in the terminal. A confirmed identity change reports that the host restarted +and its sessions were lost; authentication failures report that the host may +have restarted. The rendered history and unsent draft remain visible. Detach +with Ctrl+D and rerun `nori attach` to connect afresh. diff --git a/nori-rs/Cargo.lock b/nori-rs/Cargo.lock index 6286e719d..b30cf1bfb 100644 --- a/nori-rs/Cargo.lock +++ b/nori-rs/Cargo.lock @@ -3812,6 +3812,7 @@ dependencies = [ "codex-sandbox", "codex-stdio-to-uds", "codex-windows-sandbox", + "crossterm", "ctor 0.5.0", "libc", "nori-config", @@ -3823,12 +3824,16 @@ dependencies = [ "predicates", "pretty_assertions", "regex-lite", + "serde", "serde_json", "supports-color", "tempfile", "tokio", "toml", "tracing", + "unicode-segmentation", + "unicode-width 0.2.1", + "uuid", "which", ] diff --git a/nori-rs/acp-host/Cargo.toml b/nori-rs/acp-host/Cargo.toml index 3d22afc26..23b39c783 100644 --- a/nori-rs/acp-host/Cargo.toml +++ b/nori-rs/acp-host/Cargo.toml @@ -42,13 +42,13 @@ tokio = { workspace = true, features = [ "time", ] } tokio-util = { workspace = true, features = ["compat"] } +tokio-tungstenite = { workspace = true } tracing = { workspace = true, features = ["log"] } uuid = { workspace = true, features = ["v4"] } which = { workspace = true } [dev-dependencies] pretty_assertions = { workspace = true } -tokio-tungstenite = { workspace = true } rmcp = { workspace = true, features = [ "client", "transport-streamable-http-client-reqwest", diff --git a/nori-rs/acp-host/docs.md b/nori-rs/acp-host/docs.md index 9d3c20e01..c4f37e439 100644 --- a/nori-rs/acp-host/docs.md +++ b/nori-rs/acp-host/docs.md @@ -14,6 +14,8 @@ implementing the WebSocket profile of the upstream ACP "Streamable HTTP & WebSocket Transport" RFD, serving the hosted harness session outward as an ACP Agent. The optional `/sessions` endpoint carries managed session commands and full manager envelopes (see [the wire contract](../../docs/remote-control.md)). +The background-host listener has a separate authenticated `/sessions` route +with controller/watcher ownership and a reusable managed WebSocket client. ### How it fits into the larger codebase @@ -77,7 +79,7 @@ the session registry nor replay retention. The dependency direction stays `features.goals = false`, leaving Nori-owned goal state to the `nori-client` MCP server. `error_category.rs` preserves structured ACP errors before falling back to message classification. -- `remote/` serves one logical ACP surface through one or more exact-address +- The legacy remote surface serves ACP through one or more exact-address axum listeners. `RemoteAcpServer::bind_many` binds every socket before any begins serving; a zero port after the first address reuses the first listener's allocated port. The listeners share one active-connection slot @@ -91,6 +93,27 @@ the session registry nor replay retention. The dependency direction stays bounded live queues and timed socket writes prevent a slow client from blocking manager publication. The frontend opts into this route only with runtime `multi_session` enabled. +- `bind_host` serves only authenticated `/sessions`, using + [`host_wire.rs`](src/remote/host_wire.rs) and + [`host_control.rs`](src/remote/host_control.rs). The first interactive + initializer controls; other clients watch until an explicit takeover. + Observation-only initialization never claims control. A mutex serializes + mutation admission with handoff, then releases before backend work. An + admitted operation may finish after takeover, while later old-owner mutations + are refused. Slow backend operations cannot lock out other clients' control + or administrative requests. Role notifications preserve every connection. + Watcher mutations fail before reaching `ManagedAgent`; listing, + subscribing, taking control, and authenticated host stop remain available. + Successful authenticated upgrades include `x-nori-host-instance`, a UUID + generated once per router lifetime independently of the bearer token. Clients + can compare it before replaying against a replacement listener at the same + address. +- [`ManagedClient`](src/remote/client.rs) authenticates the upgrade and exposes + the optional host-instance UUID and HTTP 401/403 authentication classification, + alongside streaming send/receive for frontends that retain notifications. + Its sequential request helper intentionally ignores intervening notifications and is used by + short-lived administrative commands. Reconnect policy and cursor state belong + to the frontend, not this socket wrapper. - Each `/acp` listener sends a fresh `Acp-Connection-Id` on a 101 upgrade and `426 Upgrade Required` for plain HTTP. One JSON-RPC message occupies each UTF-8 text frame, adapted into the SDK's `Lines` transport @@ -195,7 +218,7 @@ the session registry nor replay retention. The dependency direction stays - Terminal and extension request families are not advertised by the current host. Adding them requires an explicit host-policy decision, not a generic protocol mirror. -- The remote WebSocket server is unauthenticated. `parse_bind_addr` treats a +- The legacy `--remote` WebSocket surface is unauthenticated. `parse_bind_addr` treats a bare port as a loopback bind and refuses non-loopback addresses without the caller's explicit opt-in flag. Exact-address selection, wildcard rejection, dangerous-exposure confirmation, endpoint reporting, and runtime listener @@ -204,6 +227,12 @@ the session registry nor replay retention. The dependency direction stays snapshots `local_addrs()` and consumes the old server; if the new bind fails, it uses `bind_many` to restore the previous exact surface. A failed restore is distinct from the original bind failure and leaves no server running. +- The background-host listener requires a nonempty bearer token, even on + loopback, and returns HTTP 401 before upgrade for missing or invalid tokens. + It exposes no `/acp` fallback. The CLI owns token generation, private file + validation, daemon lifetime, and loopback bind policy; this crate owns + authentication and connection roles. A disconnected controller leaves the + slot empty without promoting an existing watcher. - Every accepted upgrade receives a child of the server-wide cancellation token. Consuming `RemoteAcpServer::shutdown` cancels that token before the active controller, then aborts and awaits every accept task; an upgrade whose diff --git a/nori-rs/acp-host/src/remote/client.rs b/nori-rs/acp-host/src/remote/client.rs new file mode 100644 index 000000000..b927a16c0 --- /dev/null +++ b/nori-rs/acp-host/src/remote/client.rs @@ -0,0 +1,118 @@ +//! Client connection to an authenticated managed host. + +use std::time::Duration; + +use futures::SinkExt; +use futures::StreamExt; +use serde_json::Value; +use serde_json::json; +use tokio_tungstenite::MaybeTlsStream; +use tokio_tungstenite::WebSocketStream; +use tokio_tungstenite::connect_async; +use tokio_tungstenite::tungstenite::Message; +use tokio_tungstenite::tungstenite::client::IntoClientRequest; + +/// A managed WebSocket connection. Streaming frontends use `send` and `recv` +/// to correlate replies while processing every event notification. +pub struct ManagedClient { + socket: WebSocketStream>, + next_id: i64, + host_instance: Option, +} + +impl ManagedClient { + /// Authenticate the WebSocket upgrade. The caller sends initialization. + pub async fn connect(url: &str, token: &str) -> anyhow::Result { + anyhow::ensure!(!token.trim().is_empty(), "host token must not be empty"); + let mut request = url.into_client_request()?; + let mut authorization = format!("Bearer {token}") + .parse::()?; + authorization.set_sensitive(true); + request.headers_mut().insert("Authorization", authorization); + let (socket, response) = + tokio::time::timeout(Duration::from_secs(10), connect_async(request)) + .await + .map_err(|_| anyhow::anyhow!("host connection timed out"))??; + let host_instance = response + .headers() + .get("x-nori-host-instance") + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse().ok()); + Ok(Self { + socket, + next_id: 1, + host_instance, + }) + } + + /// Continuity metadata from the authenticated upgrade, independent of credentials. + pub fn host_instance(&self) -> Option { + self.host_instance + } + + /// Authentication rejection is terminal unless local credentials can be refreshed. + pub fn is_authentication_error(error: &anyhow::Error) -> bool { + matches!(error.downcast_ref::(), + Some(tokio_tungstenite::tungstenite::Error::Http(response)) + if matches!(response.status().as_u16(), 401 | 403)) + } + + pub async fn send(&mut self, message: Value) -> anyhow::Result<()> { + tokio::time::timeout( + Duration::from_secs(30), + self.socket.send(Message::Text(message.to_string().into())), + ) + .await + .map_err(|_| anyhow::anyhow!("host write timed out"))??; + Ok(()) + } + + pub async fn recv(&mut self) -> anyhow::Result { + loop { + let message = self + .socket + .next() + .await + .ok_or_else(|| anyhow::anyhow!("host connection closed"))??; + match message { + Message::Text(text) => return Ok(serde_json::from_str(&text)?), + Message::Ping(bytes) => self.socket.send(Message::Pong(bytes)).await?, + Message::Pong(_) | Message::Frame(_) => {} + Message::Close(_) => anyhow::bail!("host connection closed"), + Message::Binary(_) => anyhow::bail!("host sent a binary frame instead of JSON"), + } + } + } + + /// Execute one sequential request, ignoring intervening notifications. + /// Use `send`/`recv` instead when notifications must be retained. + pub async fn request(&mut self, method: &str, params: Value) -> anyhow::Result { + let id = self.next_id; + self.next_id = id + .checked_add(1) + .ok_or_else(|| anyhow::anyhow!("host request IDs exhausted"))?; + self.send(json!({"jsonrpc":"2.0","id":id,"method":method,"params":params})) + .await?; + tokio::time::timeout(Duration::from_secs(30), async { + loop { + let response = self.recv().await?; + if response.get("id") != Some(&json!(id)) { + continue; + } + if let Some(error) = response.get("error") { + anyhow::bail!( + "host error {}: {}", + error["code"], + error["message"].as_str().unwrap_or("request failed") + ); + } + return response + .get("result") + .cloned() + .ok_or_else(|| anyhow::anyhow!("host response has no result")); + } + }) + .await + .map_err(|_| anyhow::anyhow!("host request timed out"))? + } +} diff --git a/nori-rs/acp-host/src/remote/host_control.rs b/nori-rs/acp-host/src/remote/host_control.rs new file mode 100644 index 000000000..563efa417 --- /dev/null +++ b/nori-rs/acp-host/src/remote/host_control.rs @@ -0,0 +1,111 @@ +//! Connection ownership and serialized mutation admission for managed hosts. + +use std::collections::HashMap; + +use serde_json::Value; +use serde_json::json; +use tokio::sync::watch; + +use super::managed::ManagedReply; + +pub(super) enum HostRequest { + Reply(ManagedReply), + Forward(Value), +} + +#[derive(Default)] +pub(super) struct HostControl { + controller: Option, + clients: HashMap>, +} + +impl HostControl { + pub(super) fn connected(&self) -> bool { + self.controller.is_some() + } + + pub(super) fn remove(&mut self, id: i64) { + self.clients.remove(&id); + if self.controller == Some(id) { + self.controller = None; + } + } + + fn role(&self, id: i64) -> &'static str { + if self.controller == Some(id) { + "controller" + } else { + "watcher" + } + } + + fn status(&self, id: i64) -> Value { + json!({"role":self.role(id), "controller_connected":self.connected()}) + } + + /// Register only after the host has successfully initialized this client. + pub(super) fn register( + &mut self, + client: i64, + changes: &watch::Sender<&'static str>, + observe: bool, + ) -> Value { + if let std::collections::hash_map::Entry::Vacant(entry) = self.clients.entry(client) { + entry.insert(changes.clone()); + if !observe && self.controller.is_none() { + self.controller = Some(client); + } + } + self.status(client) + } + + /// Decide ownership at admission. The caller releases the mutex before + /// dispatching forwarded work; admitted requests may finish after handoff. + pub(super) fn admit( + &mut self, + client: i64, + changes: &watch::Sender<&'static str>, + request: Value, + ) -> HostRequest { + let id = request["id"].clone(); + let method = request["method"].as_str().unwrap_or_default(); + match method { + "_nori/control/status" => HostRequest::Reply(success(id, self.status(client))), + "_nori/control/take" => { + if self.controller != Some(client) { + let previous = self.controller.replace(client); + if let Some(previous) = previous + && let Some(changes) = self.clients.get(&previous) + { + changes.send_replace("watcher"); + } + changes.send_replace("controller"); + } + HostRequest::Reply(success(id, self.status(client))) + } + "_nori/session/list" | "_nori/session/subscribe" | "_nori/host/stop" => { + HostRequest::Forward(request) + } + _ if self.controller == Some(client) => HostRequest::Forward(request), + _ => HostRequest::Reply(failure( + id, + -32016, + "watcher is read-only; take control before changing a session", + )), + } + } +} + +fn success(id: Value, result: Value) -> ManagedReply { + ManagedReply { + response: json!({"jsonrpc":"2.0","id":id,"result":result}), + subscription: None, + } +} + +pub(super) fn failure(id: Value, code: i32, message: &str) -> ManagedReply { + ManagedReply { + response: json!({"jsonrpc":"2.0","id":id,"error":{"code":code,"message":message}}), + subscription: None, + } +} diff --git a/nori-rs/acp-host/src/remote/host_wire.rs b/nori-rs/acp-host/src/remote/host_wire.rs new file mode 100644 index 000000000..8dc77b219 --- /dev/null +++ b/nori-rs/acp-host/src/remote/host_wire.rs @@ -0,0 +1,207 @@ +//! Authenticated managed-only WebSocket endpoint for a background host. + +use std::sync::Arc; +use std::sync::atomic::AtomicI64; +use std::sync::atomic::Ordering; + +use axum::extract::State; +use axum::extract::WebSocketUpgrade; +use axum::extract::ws::Message; +use axum::extract::ws::WebSocket; +use axum::extract::ws::rejection::WebSocketUpgradeRejection; +use axum::http::HeaderMap; +use axum::http::StatusCode; +use axum::response::IntoResponse; +use axum::response::Response; +use futures::StreamExt; +use serde_json::Value; +use serde_json::json; +use tokio::sync::Mutex; +use tokio::sync::watch; +use tokio_util::sync::CancellationToken; + +use super::host_control::HostControl; +use super::host_control::HostRequest; +use super::host_control::failure; +use super::managed::ManagedAgent; +use super::managed::ManagedSubscription; +use super::managed::managed_event; +use super::managed_wire::send_frame; + +struct HostState { + host: Arc, + token: Arc, + instance: uuid::Uuid, + control: Arc>, + generation: Arc, + shutdown: CancellationToken, +} + +impl Clone for HostState { + fn clone(&self) -> Self { + Self { + host: self.host.clone(), + token: self.token.clone(), + instance: self.instance, + control: self.control.clone(), + generation: self.generation.clone(), + shutdown: self.shutdown.clone(), + } + } +} + +pub(super) fn router( + host: Arc, + token: String, + control: Arc>, + shutdown: CancellationToken, +) -> axum::Router { + axum::Router::new() + .route("/sessions", axum::routing::any(route::)) + .with_state(HostState { + host, + token: token.into(), + instance: uuid::Uuid::new_v4(), + control, + generation: Arc::new(AtomicI64::new(0)), + shutdown, + }) +} + +async fn route( + State(state): State>, + headers: HeaderMap, + upgrade: Result, +) -> Response { + let supplied = headers + .get(axum::http::header::AUTHORIZATION) + .and_then(|header| header.to_str().ok()) + .and_then(|header| header.strip_prefix("Bearer ")); + let authorized = supplied.is_some_and(|supplied| { + supplied.len() == state.token.len() + && supplied + .bytes() + .zip(state.token.bytes()) + .fold(0, |difference, (left, right)| difference | (left ^ right)) + == 0 + }); + if !authorized { + return ( + StatusCode::UNAUTHORIZED, + "A valid host bearer token is required.", + ) + .into_response(); + } + let Ok(upgrade) = upgrade else { + return ( + StatusCode::UPGRADE_REQUIRED, + "Use a WebSocket connection for managed sessions.", + ) + .into_response(); + }; + let instance = state.instance.to_string(); + let response = upgrade + .on_upgrade(move |socket| async move { + let client = state.generation.fetch_add(1, Ordering::Relaxed); + let cancel = state.shutdown.child_token(); + tokio::select! { + _ = cancel.cancelled() => {}, + result = serve(socket, &state, client, cancel.clone()) => { + if let Err(error) = result { + tracing::debug!(%error, "managed host connection ended"); + } + } + } + state.control.lock().await.remove(client); + }) + .into_response(); + ([("x-nori-host-instance", instance)], response).into_response() +} + +async fn serve( + socket: WebSocket, + state: &HostState, + client: i64, + cancel: CancellationToken, +) -> anyhow::Result<()> { + let (mut sink, mut incoming) = socket.split(); + let mut subscription: Option = None; + let mut initialized = false; + let (changes, mut roles) = watch::channel("watcher"); + loop { + tokio::select! { + biased; + _ = cancel.cancelled() => break, + changed = roles.changed(), if initialized => { + changed?; + let role = *roles.borrow_and_update(); + send_frame(&mut sink, Message::Text(json!({"jsonrpc":"2.0","method":"_nori/control/changed","params":{"role":role}}).to_string().into())).await?; + } + frame = incoming.next() => { + let Some(frame) = frame else { break; }; + match frame? { + Message::Text(text) => { + let request: Value = match serde_json::from_str(&text) { + Ok(request) => request, + Err(_) => { + send_frame(&mut sink, Message::Text(failure(Value::Null, -32700, "invalid JSON").response.to_string().into())).await?; + continue; + } + }; + let id = request.get("id").cloned().unwrap_or(Value::Null); + let valid = request["jsonrpc"] == "2.0" + && request["method"].is_string() + && request.get("id").is_some() + && (id.is_string() || id.is_i64() || id.is_null()) + && request.get("params").is_none_or(Value::is_object); + if !valid { + send_frame(&mut sink, Message::Text(failure(id, -32600, "expected a JSON-RPC request with an id and object params").response.to_string().into())).await?; + continue; + } + if !initialized && request["method"] != "initialize" { + send_frame(&mut sink, Message::Text(failure(id, -32001, "initialize must be the first request").response.to_string().into())).await?; + break; + } + let reply = if request["method"] == "initialize" { + let observe = request["params"]["observe"] == true; + let mut reply = state.host.request(request).await; + if reply.response.get("error").is_none() { + reply.response["result"]["control"] = state.control.lock().await.register(client, &changes, observe); + } + reply + } else { + let admitted = state.control.lock().await.admit(client, &changes, request); + match admitted { + HostRequest::Reply(reply) => reply, + HostRequest::Forward(request) => state.host.request(request).await, + } + }; + initialized |= reply.response.get("error").is_none(); + send_frame(&mut sink, Message::Text(reply.response.to_string().into())).await?; + if let Some(mut next) = reply.subscription { + for envelope in next.replay.drain(..) { + send_frame(&mut sink, Message::Text(managed_event(&envelope).to_string().into())).await?; + } + subscription = Some(next); + } + } + Message::Ping(bytes) => send_frame(&mut sink, Message::Pong(bytes)).await?, + Message::Close(_) => break, + Message::Pong(_) => {}, + Message::Binary(_) => anyhow::bail!("managed sessions require text JSON frames"), + } + } + event = async { + match subscription.as_mut() { + Some(subscription) => subscription.events.recv().await, + None => std::future::pending().await, + } + } => { + let Some(envelope) = event else { break; }; + send_frame(&mut sink, Message::Text(managed_event(&envelope).to_string().into())).await?; + } + } + } + let _ = send_frame(&mut sink, Message::Close(None)).await; + Ok(()) +} diff --git a/nori-rs/acp-host/src/remote/managed_wire.rs b/nori-rs/acp-host/src/remote/managed_wire.rs index 5a1d0f5ec..36874aa20 100644 --- a/nori-rs/acp-host/src/remote/managed_wire.rs +++ b/nori-rs/acp-host/src/remote/managed_wire.rs @@ -145,7 +145,7 @@ async fn serve( Ok(()) } -async fn send_frame( +pub(super) async fn send_frame( sink: &mut futures::stream::SplitSink, frame: Message, ) -> anyhow::Result<()> { diff --git a/nori-rs/acp-host/src/remote/mod.rs b/nori-rs/acp-host/src/remote/mod.rs index 577bbab51..4be2f2516 100644 --- a/nori-rs/acp-host/src/remote/mod.rs +++ b/nori-rs/acp-host/src/remote/mod.rs @@ -1,20 +1,24 @@ //! Optional remote ACP transport: the WebSocket profile of the upstream //! [Streamable HTTP & WebSocket Transport RFD]. //! -//! Serves the hosted harness session as an ACP Agent on a single `/acp` -//! endpoint. Disabled unless remote mode is explicitly enabled; loopback by -//! default. See `docs/remote-control.md`. +//! Legacy remote control serves a harness session as an ACP Agent on `/acp`. +//! Managed hosts expose authenticated `/sessions` connections with one +//! controller and any number of watchers. See `docs/remote-control.md`. //! //! [Streamable HTTP & WebSocket Transport RFD]: //! https://agentclientprotocol.com/rfds/streamable-http-websocket-transport +mod client; mod connection; +mod host_control; +mod host_wire; mod hosted_agent; mod managed; mod managed_wire; mod server; mod wire; +pub use client::ManagedClient; pub use hosted_agent::HostedAgent; pub use hosted_agent::HostedEventReceiver; pub use hosted_agent::HostedSubscription; diff --git a/nori-rs/acp-host/src/remote/server.rs b/nori-rs/acp-host/src/remote/server.rs index c90f25b52..da8fd1e1b 100644 --- a/nori-rs/acp-host/src/remote/server.rs +++ b/nori-rs/acp-host/src/remote/server.rs @@ -1,10 +1,8 @@ //! Listener and WebSocket upgrade for the remote ACP transport. //! -//! One `/acp` endpoint, WebSocket-only (the RFD permits WS-only servers). -//! Plain HTTP requests get `426 Upgrade Required`. Each upgrade response -//! carries a fresh `Acp-Connection-Id`; the server keeps a single live -//! connection, and a newer connection replaces the current one (last connect -//! wins). +//! Legacy `/acp` listeners keep one live connection; a newer connection +//! replaces it. Background hosts use authenticated `/sessions` listeners +//! with separate controller and watcher connections. use std::net::IpAddr; use std::net::Ipv4Addr; @@ -58,6 +56,7 @@ pub struct RemoteAcpServer { local_addrs: Vec, serve_tasks: Vec>, active: ActiveConnection, + host_control: Option>>, shutdown: CancellationToken, } @@ -65,6 +64,35 @@ type ManagedRouterFactory = Box, CancellationToken) -> axum::Router + Send>; impl RemoteAcpServer { + /// Bind an authenticated managed-only background host. Legacy ACP is not + /// exposed on this listener, and every connection requires the token. + pub async fn bind_host( + addr: SocketAddr, + managed: Arc, + token: String, + ) -> anyhow::Result { + anyhow::ensure!(!token.trim().is_empty(), "host token must not be empty"); + let listener = tokio::net::TcpListener::bind(addr).await?; + let local_addr = listener.local_addr()?; + let shutdown = CancellationToken::new(); + let control = Arc::new(tokio::sync::Mutex::new( + super::host_control::HostControl::default(), + )); + let router = super::host_wire::router(managed, token, control.clone(), shutdown.clone()); + let task = tokio::spawn(async move { + if let Err(error) = axum::serve(listener, router).await { + tracing::warn!(%error, "managed host listener exited"); + } + }); + Ok(Self { + local_addrs: vec![local_addr], + serve_tasks: vec![task], + active: Arc::new(tokio::sync::Mutex::new(None)), + host_control: Some(control), + shutdown, + }) + } + /// Bind the listener and start serving `/acp`. pub async fn bind(addr: SocketAddr, hosted: Arc) -> anyhow::Result { Self::bind_many([addr], hosted).await @@ -153,6 +181,7 @@ impl RemoteAcpServer { local_addrs, serve_tasks, active, + host_control: None, shutdown, }) } @@ -164,7 +193,11 @@ impl RemoteAcpServer { /// Whether a remote controller currently owns the WebSocket connection. pub async fn controller_connected(&self) -> bool { - self.active.lock().await.is_some() + if let Some(control) = &self.host_control { + control.lock().await.connected() + } else { + self.active.lock().await.is_some() + } } /// The address the listener actually bound (resolves port 0). diff --git a/nori-rs/acp-host/tests/managed_host.rs b/nori-rs/acp-host/tests/managed_host.rs new file mode 100644 index 000000000..e2b1ac333 --- /dev/null +++ b/nori-rs/acp-host/tests/managed_host.rs @@ -0,0 +1,395 @@ +//! Authenticated host ownership through real WebSocket connections. +#![allow(clippy::unwrap_used)] + +use std::sync::Arc; +use std::sync::atomic::AtomicI64; +use std::sync::atomic::Ordering; +use std::time::Duration; + +use futures::SinkExt; +use futures::StreamExt; +use nori_acp_host::remote::ManagedAgent; +use nori_acp_host::remote::ManagedReply; +use nori_acp_host::remote::RemoteAcpServer; +use pretty_assertions::assert_eq; +use serde_json::Value; +use serde_json::json; +use tokio_tungstenite::MaybeTlsStream; +use tokio_tungstenite::WebSocketStream; +use tokio_tungstenite::connect_async; +use tokio_tungstenite::tungstenite::Message; +use tokio_tungstenite::tungstenite::client::IntoClientRequest; + +type Socket = WebSocketStream>; + +#[derive(Default)] +struct Host { + mutations: AtomicI64, +} + +impl ManagedAgent for Host { + async fn request(&self, request: Value) -> ManagedReply { + let result = match request["method"].as_str().unwrap() { + "initialize" => json!({"capabilities":{}}), + "_nori/session/list" => json!({"mutations":self.mutations.load(Ordering::SeqCst)}), + _ => json!({"mutations":self.mutations.fetch_add(1, Ordering::SeqCst) + 1}), + }; + ManagedReply { + response: json!({"jsonrpc":"2.0","id":request["id"],"result":result}), + subscription: None, + } + } +} + +async fn start() -> RemoteAcpServer { + RemoteAcpServer::bind_host( + "127.0.0.1:0".parse().unwrap(), + Arc::new(Host::default()), + "secret".into(), + ) + .await + .unwrap() +} + +async fn connect( + server: &RemoteAcpServer, + token: Option<&str>, + path: &str, +) -> anyhow::Result { + let mut request = format!("ws://{}{path}", server.local_addr()).into_client_request()?; + if let Some(token) = token { + request + .headers_mut() + .insert("Authorization", format!("Bearer {token}").parse()?); + } + Ok(connect_async(request).await?.0) +} + +async fn send(socket: &mut Socket, id: i64, method: &str, params: Value) { + socket + .send(Message::Text( + json!({"jsonrpc":"2.0","id":id,"method":method,"params":params}) + .to_string() + .into(), + )) + .await + .unwrap(); +} + +async fn receive(socket: &mut Socket) -> Value { + tokio::time::timeout(Duration::from_secs(3), async { + loop { + match socket.next().await.unwrap().unwrap() { + Message::Text(text) => return serde_json::from_str(&text).unwrap(), + Message::Ping(bytes) => socket.send(Message::Pong(bytes)).await.unwrap(), + other => panic!("unexpected frame {other:?}"), + } + } + }) + .await + .unwrap() +} + +async fn initialized(server: &RemoteAcpServer, observe: bool) -> (Socket, Value) { + let mut socket = connect(server, Some("secret"), "/sessions").await.unwrap(); + send(&mut socket, 1, "initialize", json!({"observe":observe})).await; + let response = receive(&mut socket).await; + (socket, response) +} + +#[tokio::test] +async fn loopback_requires_token_and_host_does_not_expose_an_acp_bypass() { + let server = start().await; + assert!(connect(&server, None, "/sessions").await.is_err()); + assert!(connect(&server, Some("wrong"), "/sessions").await.is_err()); + assert!(connect(&server, Some("secret"), "/acp").await.is_err()); + assert!(connect(&server, Some("secret"), "/sessions").await.is_ok()); + server.shutdown().await; + assert!( + RemoteAcpServer::bind_host( + "127.0.0.1:0".parse().unwrap(), + Arc::new(Host::default()), + String::new() + ) + .await + .is_err() + ); +} + +#[tokio::test] +async fn watcher_cannot_mutate_and_takeover_notifies_both_without_disconnecting() { + let server = start().await; + let (mut first, response) = initialized(&server, false).await; + assert_eq!(response["result"]["control"]["role"], "controller"); + let (mut second, response) = initialized(&server, false).await; + assert_eq!(response["result"]["control"]["role"], "watcher"); + for method in [ + "_nori/session/prompt", + "_nori/session/respond", + "_nori/session/new", + "_nori/session/close", + "_nori/session/cancel", + "_nori/session/resume", + ] { + send(&mut second, 2, method, json!({})).await; + let response = receive(&mut second).await; + assert_eq!(response["error"]["code"], -32016); + assert!( + response["error"]["message"] + .as_str() + .unwrap() + .contains("watcher") + ); + } + send(&mut first, 3, "_nori/session/list", json!({})).await; + assert_eq!(receive(&mut first).await["result"]["mutations"], 0); + send(&mut second, 4, "_nori/control/take", json!({})).await; + assert_eq!(receive(&mut second).await["result"]["role"], "controller"); + assert_eq!(receive(&mut second).await["params"]["role"], "controller"); + let changed = receive(&mut first).await; + assert_eq!(changed["method"], "_nori/control/changed"); + assert_eq!(changed["params"]["role"], "watcher"); + send(&mut first, 5, "_nori/session/prompt", json!({})).await; + assert_eq!(receive(&mut first).await["error"]["code"], -32016); + send(&mut second, 6, "_nori/session/prompt", json!({})).await; + assert_eq!(receive(&mut second).await["result"]["mutations"], 1); + send(&mut first, 7, "_nori/host/stop", json!({})).await; + assert!(receive(&mut first).await.get("result").is_some()); + server.shutdown().await; +} + +#[tokio::test] +async fn observer_does_not_claim_control_and_disconnect_allows_a_new_controller() { + let server = start().await; + let (mut observer, response) = initialized(&server, true).await; + assert_eq!(response["result"]["control"]["role"], "watcher"); + let (mut controller, response) = initialized(&server, false).await; + assert_eq!(response["result"]["control"]["role"], "controller"); + controller.close(None).await.unwrap(); + // A status round trip observes the controller's departure without relying on a sleep. + for _ in 0..100 { + send(&mut observer, 2, "_nori/control/status", json!({})).await; + if receive(&mut observer).await["result"]["controller_connected"] == false { + break; + } + tokio::task::yield_now().await; + } + let (_next, response) = initialized(&server, false).await; + assert_eq!(response["result"]["control"]["role"], "controller"); + server.shutdown().await; +} + +#[tokio::test] +async fn client_round_trips_requests_and_reports_watcher_errors() { + use nori_acp_host::remote::ManagedClient; + let server = start().await; + let url = format!("ws://{}/sessions", server.local_addr()); + assert!(ManagedClient::connect(&url, "wrong").await.is_err()); + let mut client = ManagedClient::connect(&url, "secret").await.unwrap(); + assert_eq!( + client.request("initialize", json!({})).await.unwrap()["control"]["role"], + "controller" + ); + let (mut other, _) = initialized(&server, false).await; + send(&mut other, 2, "_nori/control/take", json!({})).await; + assert_eq!(receive(&mut other).await["result"]["role"], "controller"); + assert_eq!(client.recv().await.unwrap()["params"]["role"], "watcher"); + assert!( + client + .request("_nori/session/prompt", json!({})) + .await + .unwrap_err() + .to_string() + .contains("watcher") + ); + client + .send(json!({"jsonrpc":"2.0","id":20,"method":"_nori/session/list","params":{}})) + .await + .unwrap(); + assert_eq!(client.recv().await.unwrap()["result"]["mutations"], 0); + server.shutdown().await; +} + +#[derive(Default)] +struct BlockingHost { + entered: tokio::sync::Notify, + release: tokio::sync::Notify, +} + +impl ManagedAgent for BlockingHost { + async fn request(&self, request: Value) -> ManagedReply { + if request["params"]["hold"] == true { + self.entered.notify_one(); + self.release.notified().await; + } + ManagedReply { + response: json!({"jsonrpc":"2.0","id":request["id"],"result":{"method":request["method"]}}), + subscription: None, + } + } +} + +async fn blocking_server() -> (RemoteAcpServer, Arc) { + let host = Arc::new(BlockingHost::default()); + let server = RemoteAcpServer::bind_host( + "127.0.0.1:0".parse().unwrap(), + host.clone(), + "secret".into(), + ) + .await + .unwrap(); + (server, host) +} + +#[tokio::test] +async fn takeover_does_not_wait_for_admitted_work_and_refuses_later_old_owner_requests() { + let (server, host) = blocking_server().await; + let (mut controller, _) = initialized(&server, false).await; + let (mut watcher, _) = initialized(&server, false).await; + send( + &mut controller, + 2, + "_nori/session/prompt", + json!({"hold":true}), + ) + .await; + tokio::time::timeout(Duration::from_secs(3), host.entered.notified()) + .await + .unwrap(); + send(&mut watcher, 3, "_nori/control/take", json!({})).await; + assert_eq!(receive(&mut watcher).await["result"]["role"], "controller"); + assert_eq!(receive(&mut watcher).await["params"]["role"], "controller"); + send(&mut watcher, 4, "_nori/session/prompt", json!({})).await; + assert_eq!( + receive(&mut watcher).await["result"]["method"], + "_nori/session/prompt" + ); + + // This request arrives after takeover while its sender's earlier work is + // still pending. Admission must use its current role when processing it. + send(&mut controller, 5, "_nori/session/prompt", json!({})).await; + host.release.notify_one(); + let admitted = receive(&mut controller).await; + assert_eq!(admitted["id"], 2); + assert_eq!(admitted["result"]["method"], "_nori/session/prompt"); + assert_eq!(receive(&mut controller).await["params"]["role"], "watcher"); + let rejected = receive(&mut controller).await; + assert_eq!(rejected["id"], 5); + assert_eq!(rejected["error"]["code"], -32016); + server.shutdown().await; +} + +#[tokio::test] +async fn blocked_agent_work_does_not_prevent_observer_initialize_list_or_host_stop() { + let (server, host) = blocking_server().await; + let (mut controller, _) = initialized(&server, false).await; + send( + &mut controller, + 2, + "_nori/session/prompt", + json!({"hold":true}), + ) + .await; + tokio::time::timeout(Duration::from_secs(3), host.entered.notified()) + .await + .unwrap(); + + let (mut observer, reply) = initialized(&server, true).await; + assert_eq!(reply["result"]["control"]["role"], "watcher"); + for (id, method) in [(3, "_nori/session/list"), (4, "_nori/host/stop")] { + send(&mut observer, id, method, json!({})).await; + let reply = receive(&mut observer).await; + assert_eq!(reply["id"], id); + assert_eq!(reply["result"]["method"], method); + } + host.release.notify_one(); + assert_eq!(receive(&mut controller).await["id"], 2); + server.shutdown().await; +} + +#[tokio::test] +async fn slow_initialize_does_not_reserve_control_or_block_other_clients() { + let (server, host) = blocking_server().await; + let mut slow = connect(&server, Some("secret"), "/sessions").await.unwrap(); + send(&mut slow, 1, "initialize", json!({"hold":true})).await; + tokio::time::timeout(Duration::from_secs(3), host.entered.notified()) + .await + .unwrap(); + + let (mut first_ready, reply) = initialized(&server, false).await; + assert_eq!(reply["result"]["control"]["role"], "controller"); + send(&mut first_ready, 2, "_nori/session/list", json!({})).await; + assert_eq!( + receive(&mut first_ready).await["result"]["method"], + "_nori/session/list" + ); + host.release.notify_one(); + assert_eq!( + receive(&mut slow).await["result"]["control"]["role"], + "watcher" + ); + server.shutdown().await; +} + +#[tokio::test] +async fn host_identity_is_stable_across_connections_but_not_host_lifetimes() { + let first = start().await; + let second = start().await; + let mut identities = Vec::new(); + for server in [&first, &first, &second] { + let mut request = format!("ws://{}/sessions", server.local_addr()) + .into_client_request() + .unwrap(); + request + .headers_mut() + .insert("Authorization", "Bearer secret".parse().unwrap()); + let (mut socket, response) = connect_async(request).await.unwrap(); + let identity = response + .headers() + .get("x-nori-host-instance") + .expect("authenticated connection must identify its host lifetime") + .to_str() + .unwrap() + .to_owned(); + assert!(!identity.is_empty()); + identities.push(identity); + socket.close(None).await.unwrap(); + } + assert_eq!(identities[0], identities[1]); + assert_ne!( + identities[0], identities[2], + "same token must not imply the same host" + ); + first.shutdown().await; + second.shutdown().await; +} + +#[tokio::test] +async fn missing_or_malformed_host_identity_is_unavailable_for_safe_replay() { + use nori_acp_host::remote::ManagedClient; + use tokio_tungstenite::tungstenite::handshake::server::Request; + use tokio_tungstenite::tungstenite::handshake::server::Response; + for identity in [None, Some("not-a-host-uuid")] { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("ws://{}/sessions", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + tokio_tungstenite::accept_hdr_async( + stream, + move |_: &Request, mut response: Response| { + if let Some(identity) = identity { + response + .headers_mut() + .insert("x-nori-host-instance", identity.parse().unwrap()); + } + Ok(response) + }, + ) + .await + .unwrap() + }); + let connection = ManagedClient::connect(&endpoint, "token").await; + let _socket = server.await.unwrap(); + assert_eq!(connection.unwrap().host_instance(), None); + } +} diff --git a/nori-rs/cli/Cargo.toml b/nori-rs/cli/Cargo.toml index 6b88dc85c..d7d98546c 100644 --- a/nori-rs/cli/Cargo.toml +++ b/nori-rs/cli/Cargo.toml @@ -31,10 +31,15 @@ codex-process-hardening = { workspace = true } codex-stdio-to-uds = { workspace = true } nori-tui = { workspace = true } ctor = { workspace = true } +crossterm = { workspace = true } +unicode-segmentation = { workspace = true } +unicode-width = { workspace = true } libc = { workspace = true } owo-colors = { workspace = true } regex-lite = { workspace = true} serde_json = { workspace = true } +serde = { workspace = true, features = ["derive"] } +uuid = { workspace = true, features = ["v4"] } supports-color = { workspace = true } toml = { workspace = true } tokio = { workspace = true, features = [ diff --git a/nori-rs/cli/docs.md b/nori-rs/cli/docs.md index 85b0b52ea..ad00e7fd9 100644 --- a/nori-rs/cli/docs.md +++ b/nori-rs/cli/docs.md @@ -13,6 +13,9 @@ This crate is the primary entry point that ties together the core crates: - **Always included:** `nori-tui`, `nori-exec`, `nori-harness`, `nori-config`, `codex-sandbox` - **Uses** `codex-arg0` for arg0-based dispatch (Linux sandbox embedding) - **Uses** `codex-sandbox` (`@/nori-rs/sandbox/`) for the `nori sandbox` debug subcommand's seatbelt/landlock/windows spawn helpers +- Owns the background [host lifecycle](src/host/docs.md), composing the + harness session manager with an authenticated managed transport. The + [attached frontend](../tui/src/attach/docs.md) owns only terminal state. - Maps each agent-bearing entrypoint to the stable product analytics modes in [`nori-installed`](../installed/docs.md): ordinary and resumed TUI sessions are `interactive`, `nori cloud` is `cloud`, plaintext execution is `exec`, and @@ -45,19 +48,16 @@ PostHog identity or organization membership itself. - `nori resume --all` - Lets picker/last selection search all transcript projects instead of only the current working directory - TUI flags such as `--agent`, approval-bypass options, prompts, images, `-c`, and working-directory overrides can be passed after `resume`; they are merged into the normal interactive CLI configuration before `nori_tui::run_main()` -```rust -match subcommand { - None if print => run_exec(...), // `-p` / `--print`: same path as `exec` - None => nori_tui::run_main(...), // Interactive TUI - Some(Subcommand::Resume(cmd)) => nori_tui::run_main(...), - Some(Subcommand::Cloud(cmd)) => nori_tui::run_main(...), // Pinned nori-handroll agent - Some(Subcommand::Exec(cmd)) => run_exec(cmd), - Some(Subcommand::Sandbox(args)) => debug_sandbox::run_*(...), - Some(Subcommand::Skillsets(cmd)) => run_skillsets_command(...), - Some(Subcommand::Completions(cmd)) => clap_complete::generate(...), - // ... other subcommands -} -``` +**Host and attach:** `nori host` starts a detached Unix process owning an empty +session manager; `host ls` reads its flat table and `host stop` shuts it down. +The host outlives both attached terminals and its final session. `nori attach` +requires `multi_session`, discovers the local host and token, then opens the +session list or a supplied conversation ID. Explicit `--host` and +`--token-file` must be supplied together. Startup and attach resolve ordinary +Nori configuration without entering the local process-owning TUI `App`. +Administrative list and stop use host discovery directly, so a later malformed +configuration file cannot prevent shutdown. +See [the command and wire contract](../../docs/remote-control.md#11-background-host-and-attached-terminals). **ExecCommand**: Provides two terminal-independent execution surfaces: - `nori exec [PROMPT]` runs one prompt through the selected ACP agent and writes only the complete assistant text to stdout. The prompt may come from the positional argument, from piped stdin, or from both (see **Prompt Sources**). Diagnostics and failures remain on stderr so the answer can be piped or redirected directly. @@ -75,7 +75,7 @@ match subcommand { - **Stdin is read only after `exec --acp` has taken its early return into the facade.** The ACP stdio facade speaks JSON-RPC over stdin and must keep exclusive ownership of it, so the CLI must never ingest stdin during dispatch or anywhere upstream of the mode decision. This ordering is the load-bearing constraint of the piped-prompt path; violating it silently corrupts the ACP protocol rather than failing loudly. - Piping into bare `nori` does not select headless behavior. The piped text seeds the first turn and the TUI starts normally, which requires only that a controlling terminal is reachable for key input (see `@/nori-rs/tui/docs.md`). Environments with no terminal at all must use `exec` or `-p`. -**CloudCommand** (`cloud.rs`): Runs a TUI session backed by Nori Sessions by delegating everything cloud-related to the external `nori-handroll` binary (from the nori-sessions repo). The CLI no longer contains any broker client, OAuth flow, or WebSocket transport -- it does not know the word "broker" beyond translating one config value: +**CloudCommand** (`cloud.rs`): Runs a TUI session backed by Nori Sessions by delegating everything cloud-related to the external `nori-handroll` binary. The cloud route contains no broker client, OAuth flow, or cloud WebSocket transport; it only translates the broker configuration passed to Handroll: - `resolve_handroll_bin()` resolves the `nori-handroll` binary. A `NORI_HANDROLL_BIN` env override wins when set and must point at an existing file (a dangling override is an error, not a fallback); otherwise the first `nori-handroll` on `PATH` is used. A missing binary fails with an actionable "install Nori Sessions" error before the TUI starts - `cloud_agent_config()` builds a synthetic registry entry (slug `nori-cloud`): a local distribution running ` cloud-acp`, with the read-only `[cloud] broker_url` from `config.toml` (when present) translated to a `NORI_BROKER_URL` environment variable on the child, and an auth hint pointing at `nori-handroll login`. When the `--onboard` flag is set, `--onboard` is appended to the spawned `cloud-acp` argv so the handroll child acquires-or-resumes the org's broker-side onboarding session server-side - The dispatch in `main.rs` forces `interactive.agent = "nori-cloud"` AFTER flag merging, so `--agent` cannot bypass Sessions, passes the entry via the clap-skipped `TuiCli.extra_agents` field, and sets the clap-skipped `TuiCli.cloud_mode` launch-origin flag (see `@/nori-rs/tui/src/cli.rs`). Cloud entry is picker-first: the TUI prepares one live agent connection, lists sessions when advertised, and opens the session picker before anything can claim a VM, with "Start a new session" as an explicit pick. The chosen new or existing session is activated on that prepared connection rather than a second child (see `@/nori-rs/tui/docs.md`) diff --git a/nori-rs/cli/src/host/docs.md b/nori-rs/cli/src/host/docs.md new file mode 100644 index 000000000..1887bee45 --- /dev/null +++ b/nori-rs/cli/src/host/docs.md @@ -0,0 +1,76 @@ +# Noridoc: Background session host + +Path: @/nori-rs/cli/src/host + +### Overview + +- Implements `nori host`, its administrative commands, and `nori attach` + discovery so agent sessions can outlive every terminal. +- Owns Unix process lifetime and private host files; protocol framing remains + in [acp-host](../../../acp-host/docs.md), and session policy remains in the + [harness](../../../harness/docs.md). + +### How it fits into the larger codebase + +- [CLI dispatch](../main.rs) resolves ordinary Nori configuration for startup + and attach. Administrative list and stop only need host discovery, so they + remain available if the configuration file becomes invalid. Attach requires + `multi_session` and invokes the dedicated + [terminal frontend](../../../tui/src/attach/docs.md), bypassing the + local process-owning TUI application. +- [HostService](service.rs) implements `ManagedAgent`, delegates envelope + operations to `ManagedRemoteHost`, and adds lifecycle commands over the same + `SessionManager`. Agent initialization and transcript recording follow the + ordinary harness path. +- The host starts with an empty manager and retains it until explicit stop or + process termination. Ending the last session never ends the host. + +```text +host command -> detached host -> authenticated /sessions -> HostService + ^ | +attach TUI ------------------------+ v +host ls / host stop ---------------+ SessionManager + | + agent processes +``` + +### Core Implementation + +- [Startup](mod.rs) launches the same executable with a private foreground + argument, starts a Unix process session, disconnects stdin, and redirects + output to the host log. The launching command waits for an authenticated + readiness check before reporting success. +- [HostFiles](state.rs) creates the host directory beneath `NORI_HOME` with + owner-only permissions. It validates ownership, rejects file symlinks and + nonregular files, and holds an OS file lock for the entire host lifetime. + Discovery state contains the endpoint and PID; the lock decides liveness. +- Each start generates a token and binds loopback before publishing discovery + state. Administrative clients initialize with `observe: true`, so list and + stop do not claim the controller slot. [List formatting](table.rs) sanitizes + control characters and colors status only on a terminal. Terminal rows fit + the available display cells by truncating titles with an ellipsis at grapheme + boundaries; if metadata alone exceeds the width, that prefix is clipped. + Piped output retains full titles without color or a width limit. +- Lifecycle requests prepare agents using the host's configuration. Resume + uses the stored agent and working directory while retaining the conversation + identity. Stop closes the server, shuts down the manager, removes discovery + state, then releases the lock. + +### Things to Know + +- Tokens are mandatory even for loopback. Local attach reads the private token + automatically and receives a callback that rereads it with the same private + file validation after a reconnect authentication failure. Explicit endpoints + require `--host` together with `--token-file` and receive no local credential + rediscovery callback. Token contents never appear in startup output. +- The authenticated listener exposes only `/sessions`; it does not change the + legacy interactive remote-control listener. See the + [wire contract](../../../../docs/remote-control.md#11-background-host-and-attached-terminals). +- The host has no persistent manager snapshot. Transcripts survive normally, + but in-memory registry state and reconnect replay belong to the current host + process. The token rotates when that process starts again. +- [Lifecycle tests](../../tests/host_lifecycle.rs) use isolated homes and + bounded process waits to cover detached startup, privacy, lock ownership, + occupied ports, and explicit stop. + +Created and maintained by Nori. diff --git a/nori-rs/cli/src/host/mod.rs b/nori-rs/cli/src/host/mod.rs new file mode 100644 index 000000000..df17d2b6c --- /dev/null +++ b/nori-rs/cli/src/host/mod.rs @@ -0,0 +1,276 @@ +//! Background session host commands and local discovery. + +mod service; +mod state; +mod table; + +use std::io::IsTerminal; +use std::path::PathBuf; +use std::process::Command; +use std::process::Stdio; +use std::sync::Arc; +use std::time::Duration; +use std::time::Instant; + +use anyhow::Context; +use clap::Parser; +use nori_config::NoriConfig; +use nori_harness::remote_agent::ManagedClient; +use nori_harness::remote_agent::ManagedRemoteHost; +use nori_harness::remote_agent::RemoteAcpServer; +use nori_harness::session_manager::SessionManager; +use nori_harness::session_manager::SessionManagerConfig; +use serde_json::json; + +use self::service::HostService; +use self::state::HostFiles; +use self::state::HostState; + +#[derive(Debug, Parser)] +pub(crate) struct HostCommand { + #[command(subcommand)] + action: Option, + /// Loopback port; zero chooses an available port. + #[arg(long, default_value = "7420")] + port: i32, + #[arg(long, hide = true)] + foreground: bool, +} + +#[derive(Debug, clap::Subcommand)] +enum HostAction { + /// Stop the host and all of its sessions. + Stop, + /// List sessions in a flat table, plain when piped. + Ls, +} + +impl HostCommand { + pub(crate) fn needs_config(&self) -> bool { + self.action.is_none() + } +} + +#[derive(Debug, Parser)] +pub(crate) struct AttachCommand { + /// Session to open; omit to open the session list. + session_id: Option, + /// Remote managed WebSocket URL; omit to discover the local host. + #[arg(long, requires = "token_file")] + host: Option, + /// Private token file for a remote host. + #[arg(long, requires = "host")] + token_file: Option, +} + +pub(crate) async fn attach(command: AttachCommand, config: NoriConfig) -> anyhow::Result<()> { + anyhow::ensure!( + config.multi_session, + "nori attach requires [features] multi_session = true" + ); + let mut refresh_local_token = None; + let (endpoint, token) = if let Some(endpoint) = command.host { + let path = command.token_file.context("--token-file is required")?; + (endpoint, state::read_token(&path)?) + } else { + let files = HostFiles::new(&config.nori_home)?; + let (host, token) = files.read()?; + let token_path = files.directory.join("token"); + refresh_local_token = Some(Box::new(move || state::read_token(&token_path)) + as Box anyhow::Result + Send + Sync>); + (host.endpoint, token) + }; + nori_tui::run_attach( + config, + nori_tui::AttachOptions { + endpoint, + token, + session_id: command.session_id, + refresh_local_token, + }, + ) + .await +} + +pub(crate) async fn run(command: HostCommand, config: Option) -> anyhow::Result<()> { + let home = match &config { + Some(config) => config.nori_home.clone(), + None => nori_config::find_nori_home()?, + }; + let files = HostFiles::new(&home)?; + match command.action { + Some(HostAction::Ls) => { + let (mut client, _) = connect(&files).await?; + let listing = client.request("_nori/session/list", json!({})).await?; + let tty = std::io::stdout().is_terminal(); + let width = tty + .then(|| crossterm::terminal::size().map_or(80, |(width, _)| usize::from(width))); + print!("{}", table::format_table(&listing, width, tty)); + Ok(()) + } + Some(HostAction::Stop) => { + if !files.running()? { + println!("No host running."); + return Ok(()); + } + let (mut client, _) = connect(&files).await?; + // Shutdown may close the socket before its reply. Ownership is + // released only after session cleanup, so wait for the lock below. + client + .send(json!({"jsonrpc":"2.0","id":2,"method":"_nori/host/stop","params":{}})) + .await?; + let deadline = Instant::now() + Duration::from_secs(30); + while files.running()? { + anyhow::ensure!( + Instant::now() < deadline, + "host is still shutting down; check {}", + files.directory.join("host.log").display() + ); + tokio::time::sleep(Duration::from_millis(50)).await; + } + println!("Host stopped."); + Ok(()) + } + None if command.foreground => { + serve( + command.port, + config.context("host configuration is required")?, + &files, + ) + .await + } + None => start(&files).await, + } +} + +async fn connect(files: &HostFiles) -> anyhow::Result<(ManagedClient, HostState)> { + let (host, token) = files.read()?; + let client = tokio::time::timeout(Duration::from_secs(3), async { + let mut client = ManagedClient::connect(&host.endpoint, &token).await?; + client + .request("initialize", json!({"observe":true})) + .await?; + anyhow::Ok(client) + }) + .await + .context("host did not answer")??; + Ok((client, host)) +} + +async fn start(files: &HostFiles) -> anyhow::Result<()> { + if let Ok((_, host)) = connect(files).await { + println!("Host already running (pid {}) {}", host.pid, host.endpoint); + return Ok(()); + } + let log_path = files.directory.join("host.log"); + let log = state::private_open(&log_path, true)?; + // Append through cloned handles without exposing output pipes to the daemon. + use std::io::Seek; + let mut log = log; + log.seek(std::io::SeekFrom::End(0))?; + let mut command = Command::new(std::env::current_exe()?); + command + .args(std::env::args_os().skip(1)) + .arg("--foreground") + .stdin(Stdio::null()) + .stdout(log.try_clone()?) + .stderr(log); + #[cfg(unix)] + { + use std::os::unix::process::CommandExt; + // Only the async-signal-safe syscall runs between fork and exec. + unsafe { + command.pre_exec(|| { + if libc::setsid() == -1 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + }); + } + } + let mut child = command.spawn().context("could not start host process")?; + let deadline = Instant::now() + Duration::from_secs(15); + loop { + if let Ok((_, host)) = connect(files).await { + println!("Host started (pid {}) {}", host.pid, host.endpoint); + println!( + "Token: {} (owner-only)", + files.directory.join("token").display() + ); + return Ok(()); + } + if let Some(status) = child.try_wait()? { + anyhow::bail!( + "host exited during startup ({status}); check {}", + log_path.display() + ); + } + if Instant::now() >= deadline { + // This is the child we just spawned, not a PID from stale state. + let _ = child.kill(); + let _ = child.wait(); + anyhow::bail!("host startup timed out; check {}", log_path.display()); + } + tokio::time::sleep(Duration::from_millis(50)).await; + } +} + +async fn serve(port: i32, config: NoriConfig, files: &HostFiles) -> anyhow::Result<()> { + anyhow::ensure!( + (0..=65535).contains(&port), + "port must be between 0 and 65535" + ); + let lock = files.lock()?; + let deadline = Instant::now() + Duration::from_secs(2); + loop { + match lock.try_lock() { + Ok(()) => break, + Err(std::fs::TryLockError::WouldBlock) if Instant::now() < deadline => { + // Discovery probes briefly acquire the same lock. Only a + // persistent owner means another daemon is running. + tokio::time::sleep(Duration::from_millis(25)).await; + } + Err(error) => return Err(error).context("another host is already starting or running"), + } + } + // A crash can leave discovery state, but cannot retain the OS lock. + let _ = std::fs::remove_file(files.directory.join("state.json")); + let token = files.new_token()?; + nori_harness::initialize_registry(config.agents.clone())?; + let manager = SessionManager::new(SessionManagerConfig { + max_sessions: config.max_sessions, + ..Default::default() + }); + let host = Arc::new(HostService { + managed: ManagedRemoteHost::new(manager.clone()), + manager, + config: Arc::new(config), + stop: tokio::sync::Notify::new(), + }); + let server = + RemoteAcpServer::bind_host(format!("127.0.0.1:{port}").parse()?, host.clone(), token) + .await?; + files.publish(&HostState { + endpoint: format!("ws://{}/sessions", server.local_addr()), + pid: i64::from(std::process::id()), + })?; + #[cfg(unix)] + let mut terminate = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?; + #[cfg(unix)] + tokio::select! { + _ = host.stop.notified() => {}, + _ = tokio::signal::ctrl_c() => {}, + _ = terminate.recv() => {}, + } + #[cfg(not(unix))] + host.stop.notified().await; + server.shutdown().await; + let report = host.manager.shutdown(Duration::ZERO).await; + std::fs::remove_file(files.directory.join("state.json"))?; + anyhow::ensure!( + report.timed_out.is_empty() && report.failed.is_empty(), + "some sessions did not stop cleanly: {report:?}" + ); + drop(lock); + Ok(()) +} diff --git a/nori-rs/cli/src/host/service.rs b/nori-rs/cli/src/host/service.rs new file mode 100644 index 000000000..e6692a7d4 --- /dev/null +++ b/nori-rs/cli/src/host/service.rs @@ -0,0 +1,128 @@ +//! Host lifecycle commands layered on the existing managed-session protocol. + +use std::sync::Arc; +use std::time::Duration; + +use nori_config::NoriConfig; +use nori_harness::ConversationId; +use nori_harness::remote_agent::ManagedAgent; +use nori_harness::remote_agent::ManagedRemoteHost; +use nori_harness::remote_agent::ManagedReply; +use nori_harness::runtime::AgentPrepareSpec; +use nori_harness::runtime::SessionStart; +use nori_harness::session_manager::SessionAgent; +use nori_harness::session_manager::SessionManager; +use nori_harness::session_manager::SessionSource; +use nori_harness::session_manager::StartSession; +use serde_json::Value; +use serde_json::json; +use tokio::sync::Notify; + +pub(super) struct HostService { + pub manager: SessionManager, + pub managed: ManagedRemoteHost, + pub config: Arc, + pub stop: Notify, +} + +impl HostService { + async fn lifecycle(&self, method: &str, params: &Value) -> anyhow::Result { + if method == "_nori/host/stop" { + self.stop.notify_one(); + return Ok(json!({"stopping":true})); + } + let mut config = (*self.config).clone(); + if method == "_nori/session/new" { + if let Some(agent) = params.get("agent") { + config.active_agent = agent + .as_str() + .ok_or_else(|| anyhow::anyhow!("agent must be a string"))? + .to_owned(); + } + let session = self.manager.start(StartSession { + agent: SessionAgent::Prepare(AgentPrepareSpec { + config: Arc::new(config), + cli_version: env!("CARGO_PKG_VERSION").into(), + session_context: None, + initial_context: None, + }), + start: SessionStart::New, + parent: None, + source: SessionSource::User, + })?; + self.managed + .set_selected_session(Some(session.conversation_id)); + return Ok(json!({"session_id":session.conversation_id.to_string()})); + } + let id = params["session_id"] + .as_str() + .ok_or_else(|| anyhow::anyhow!("session_id is required"))?; + let id = ConversationId::from_string(id)?; + let record = self + .manager + .get(&id) + .ok_or_else(|| anyhow::anyhow!("unknown session id"))?; + match method { + "_nori/session/close" => self.manager.close(&id, Duration::ZERO).await?, + "_nori/session/cancel" => { + self.manager + .handle(&id) + .ok_or_else(|| anyhow::anyhow!("session is not running"))? + .cancel() + .await? + } + "_nori/session/resume" => { + config.active_agent = record.agent; + config.cwd = record.cwd; + self.manager + .resume( + &id, + AgentPrepareSpec { + config: Arc::new(config), + cli_version: env!("CARGO_PKG_VERSION").into(), + session_context: None, + initial_context: None, + }, + ) + .await?; + } + _ => anyhow::bail!("unknown host operation"), + } + Ok(json!({"session_id":id.to_string()})) + } +} + +impl ManagedAgent for HostService { + async fn request(&self, request: Value) -> ManagedReply { + let method = request["method"].as_str().unwrap_or_default(); + if !matches!( + method, + "_nori/host/stop" + | "_nori/session/new" + | "_nori/session/close" + | "_nori/session/cancel" + | "_nori/session/resume" + ) { + return self.managed.request(request).await; + } + let params = request.get("params").cloned().unwrap_or_else(|| json!({})); + let result = + if request["jsonrpc"] == "2.0" && request.get("id").is_some() && params.is_object() { + self.lifecycle(method, ¶ms).await + } else { + Err(anyhow::anyhow!( + "expected a JSON-RPC request with an id and object params" + )) + }; + let response = match result { + Ok(result) => json!({"jsonrpc":"2.0","id":request["id"],"result":result}), + Err(error) => { + json!({"jsonrpc":"2.0","id":request["id"],"error":{"code":-32000,"message":error.to_string()}}) + } + }; + ManagedReply { + response, + subscription: None, + } + } +} diff --git a/nori-rs/cli/src/host/state.rs b/nori-rs/cli/src/host/state.rs new file mode 100644 index 000000000..8ce6ed4c8 --- /dev/null +++ b/nori-rs/cli/src/host/state.rs @@ -0,0 +1,140 @@ +//! Private host discovery and singleton ownership. The lock inode is never removed. + +use std::fs::File; +use std::fs::OpenOptions; +use std::io::Read; +use std::io::Write; +use std::path::Path; +use std::path::PathBuf; + +use anyhow::Context; +use serde::Deserialize; +use serde::Serialize; + +#[derive(Serialize, Deserialize)] +pub(super) struct HostState { + pub endpoint: String, + pub pid: i64, +} + +pub(super) struct HostFiles { + pub directory: PathBuf, +} + +impl HostFiles { + pub fn new(home: &Path) -> anyhow::Result { + let directory = home.join("host"); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + let mut builder = std::fs::DirBuilder::new(); + builder.mode(0o700); + match builder.create(&directory) { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(error) => return Err(error.into()), + } + let metadata = std::fs::symlink_metadata(&directory)?; + anyhow::ensure!( + metadata.is_dir() && !metadata.file_type().is_symlink(), + "host directory must not be a symlink" + ); + validate(&metadata, &directory)?; + } + #[cfg(not(unix))] + anyhow::bail!("background hosts require Unix owner-only file permissions on this platform"); + #[allow(unreachable_code)] + Ok(Self { directory }) + } + + pub fn lock(&self) -> anyhow::Result { + private_open(&self.directory.join("lock"), true) + } + + pub fn running(&self) -> anyhow::Result { + let lock = self.lock()?; + match lock.try_lock() { + Ok(()) => Ok(false), + Err(std::fs::TryLockError::WouldBlock) => Ok(true), + Err(error) => Err(error.into()), + } + } + + pub fn read(&self) -> anyhow::Result<(HostState, String)> { + anyhow::ensure!( + self.running()?, + "no host running; start one with `nori host`" + ); + let mut state = String::new(); + private_open(&self.directory.join("state.json"), false)?.read_to_string(&mut state)?; + let token = read_token(&self.directory.join("token"))?; + Ok((serde_json::from_str(&state)?, token)) + } + + pub fn publish(&self, state: &HostState) -> anyhow::Result<()> { + let mut file = private_open(&self.directory.join("state.json"), true)?; + file.set_len(0)?; + file.write_all(&serde_json::to_vec(state)?)?; + file.sync_all()?; + Ok(()) + } + + pub fn new_token(&self) -> anyhow::Result { + let token = format!( + "{}{}", + uuid::Uuid::new_v4().simple(), + uuid::Uuid::new_v4().simple() + ); + let mut file = private_open(&self.directory.join("token"), true)?; + file.set_len(0)?; + file.write_all(token.as_bytes())?; + file.sync_all()?; + Ok(token) + } +} + +pub(super) fn read_token(path: &Path) -> anyhow::Result { + let mut token = String::new(); + private_open(path, false)?.read_to_string(&mut token)?; + let token = token.trim().to_owned(); + anyhow::ensure!(!token.is_empty(), "host token is empty"); + Ok(token) +} + +pub(super) fn private_open(path: &Path, create: bool) -> anyhow::Result { + let mut options = OpenOptions::new(); + options.read(true).write(create).create(create); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK); + } + let file = options + .open(path) + .with_context(|| format!("cannot open private host file {}", path.display()))?; + let metadata = file.metadata()?; + anyhow::ensure!( + metadata.is_file(), + "host file must be a regular file: {}", + path.display() + ); + #[cfg(unix)] + validate(&metadata, path)?; + Ok(file) +} + +#[cfg(unix)] +fn validate(metadata: &std::fs::Metadata, path: &Path) -> anyhow::Result<()> { + use std::os::unix::fs::MetadataExt; + use std::os::unix::fs::PermissionsExt; + // geteuid reads the current process identity without accessing memory. + let uid = unsafe { libc::geteuid() }; + anyhow::ensure!( + metadata.uid() == uid && metadata.permissions().mode() & 0o077 == 0, + "host path must be owned by this user with owner-only permissions: {}", + path.display() + ); + Ok(()) +} diff --git a/nori-rs/cli/src/host/table.rs b/nori-rs/cli/src/host/table.rs new file mode 100644 index 000000000..e8391ce93 --- /dev/null +++ b/nori-rs/cli/src/host/table.rs @@ -0,0 +1,126 @@ +//! Flat host listing with terminal-cell budgets; piped output retains complete values. + +use owo_colors::OwoColorize; +use serde_json::Value; +use unicode_segmentation::UnicodeSegmentation; +use unicode_width::UnicodeWidthStr; + +pub(super) fn format_table(listing: &Value, width: Option, color: bool) -> String { + let header = format!( + "{:<36} {:<16} {:<16} {:>6} TITLE", + "ID", "AGENT", "STATUS", "AGE" + ); + let mut output = format!( + "{}\n", + width.map_or_else(|| header.clone(), |width| truncate(&header, width)) + ); + for row in listing["sessions"].as_array().into_iter().flatten() { + let clean = |key: &str| { + row[key] + .as_str() + .unwrap_or("-") + .chars() + .map(|c| if c.is_control() { ' ' } else { c }) + .collect::() + }; + let id = clean("session_id"); + let agent = clean("agent"); + let status = clean("status").replace('_', " "); + let title = clean("title"); + let seconds = row["age_seconds"].as_i64().unwrap_or(0).max(0); + let age = if seconds < 60 { + format!("{seconds}s") + } else if seconds < 3600 { + format!("{}m", seconds / 60) + } else { + format!("{}h", seconds / 3600) + }; + let prefix = format!("{id:<36} {agent:<16} {status:<16} {age:>6} "); + let prefix_width = prefix.width(); + if let Some(width) = width + && width < prefix_width + { + output.push_str(&truncate(&prefix, width)); + output.push('\n'); + continue; + } + let title = width.map_or_else( + || title.clone(), + |width| truncate(&title, width.saturating_sub(prefix_width)), + ); + let status = format!("{status:<16}"); + let status = if color { + match row["status"].as_str().unwrap_or_default() { + "failed" => status.red().to_string(), + "waiting_on_you" | "working" | "starting" => status.yellow().to_string(), + "ready" => status.green().to_string(), + _ => status.dimmed().to_string(), + } + } else { + status + }; + output.push_str(&format!( + "{id:<36} {agent:<16} {status} {age:>6} {title}\n" + )); + } + output +} + +fn truncate(value: &str, width: usize) -> String { + if value.width() <= width { + return value.into(); + } + if width == 0 { + return String::new(); + } + let mut end = 0; + for (index, grapheme) in value.grapheme_indices(true) { + let next = index + grapheme.len(); + if value[..next].width() > width - 1 { + break; + } + end = next; + } + format!("{}…", &value[..end]) +} + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + use serde_json::json; + + #[test] + fn tty_titles_respect_display_columns_and_keep_graphemes_intact() { + for (title, budget, expected) in [ + ("abcdef", 4, "abc…"), + ("abcd", 4, "abcd"), + ("界界界", 4, "界…"), + ("e\u{301}e\u{301}e\u{301}", 2, "e\u{301}…"), + ("👩‍💻👩‍💻👩‍💻", 4, "👩‍💻…"), + ("abcdef", 1, "…"), + ("abcdef", 0, ""), + ] { + let listing = json!({"sessions":[{"session_id":"id", "agent":"agent", "status":"ready", "title":title}]}); + let rendered = format_table(&listing, Some(82 + budget), false); + let row = rendered.lines().nth(1).unwrap(); + assert_eq!(row.get(82..).unwrap_or(""), expected, "title {title}"); + } + } + + #[test] + fn tty_title_budget_accounts_for_expanded_metadata_columns() { + let listing = json!({"sessions":[{"session_id":"id", "agent":"abcdefghijklmnopqrst", "status":"ready", "title":"long title"}]}); + let rendered = format_table(&listing, Some(90), false); + assert!(rendered.lines().nth(1).unwrap().ends_with("lon…")); + } + + #[test] + fn piped_table_keeps_complete_plain_titles() { + let title = "A title much longer than the remaining terminal width 界 e\u{301} 👩‍💻"; + let listing = json!({"sessions":[{"session_id":"id", "agent":"agent", "status":"working", "title":title}]}); + let rendered = format_table(&listing, None, false); + assert!(rendered.lines().nth(1).unwrap().ends_with(title)); + assert!(!rendered.contains('\u{1b}')); + } +} diff --git a/nori-rs/cli/src/main.rs b/nori-rs/cli/src/main.rs index 9cd35e0b3..c2ab5819e 100644 --- a/nori-rs/cli/src/main.rs +++ b/nori-rs/cli/src/main.rs @@ -25,6 +25,7 @@ use std::path::PathBuf; use std::sync::Arc; use supports_color::Stream; +mod host; mod stdin_prompt; #[cfg(not(windows))] mod wsl_paths; @@ -63,6 +64,11 @@ struct MultitoolCli { #[derive(Debug, clap::Subcommand)] enum Subcommand { + /// Start or manage a background session host. + Host(host::HostCommand), + + /// Attach a terminal to host-owned sessions. + Attach(host::AttachCommand), /// Run commands within a Nori-provided sandbox. #[clap(visible_alias = "debug")] Sandbox(SandboxArgs), @@ -370,6 +376,18 @@ async fn cli_main(codex_linux_sandbox_exe: Option) -> anyhow::Result<() } match subcommand { + Some(Subcommand::Host(command)) => { + let config = if command.needs_config() { + Some(host_config(interactive, root_config_overrides)?) + } else { + None + }; + host::run(command, config).await?; + } + Some(Subcommand::Attach(command)) => { + let config = host_config(interactive, root_config_overrides)?; + host::attach(command, config).await?; + } None if print => { // `run_exec` has no way to attach images, so accepting them here // would silently answer without the attachment. @@ -547,6 +565,29 @@ async fn cli_main(codex_linux_sandbox_exe: Option) -> anyhow::Result<() Ok(()) } +fn host_config( + interactive: TuiCli, + root: CliConfigOverrides, +) -> anyhow::Result { + let mut raw_overrides = root.raw_overrides; + raw_overrides.extend(interactive.config_overrides.raw_overrides); + let raw_overrides = CliConfigOverrides { raw_overrides } + .parse_overrides() + .map_err(anyhow::Error::msg)?; + nori_config::NoriConfig::load_with_overrides(NoriConfigOverrides { + agent: interactive.agent, + cwd: interactive.cwd, + raw_overrides, + additional_writable_roots: interactive.add_dir, + approval_policy: interactive + .dangerously_bypass_approvals_and_sandbox + .then_some(AskForApproval::Never), + sandbox_mode: interactive + .dangerously_bypass_approvals_and_sandbox + .then_some(SandboxMode::DangerFullAccess), + }) +} + async fn run_exec( cmd: ExecCommand, interactive: TuiCli, diff --git a/nori-rs/cli/tests/host_lifecycle.rs b/nori-rs/cli/tests/host_lifecycle.rs new file mode 100644 index 000000000..e9afe8d84 --- /dev/null +++ b/nori-rs/cli/tests/host_lifecycle.rs @@ -0,0 +1,178 @@ +#![cfg(unix)] +#![allow(clippy::unwrap_used)] + +use std::io::Read; +use std::io::Seek; +use std::io::SeekFrom; +use std::os::unix::fs::PermissionsExt; +use std::process::Command; +use std::process::Output; +use std::process::Stdio; +use std::time::Duration; +use std::time::Instant; +use tempfile::TempDir; + +fn bounded_output(command: &mut Command) -> Output { + // Files avoid waiting for pipe EOF if a broken daemon inherits stdout. + let mut stdout = tempfile::tempfile().unwrap(); + let mut stderr = tempfile::tempfile().unwrap(); + let mut child = command + .stdin(Stdio::null()) + .stdout(stdout.try_clone().unwrap()) + .stderr(stderr.try_clone().unwrap()) + .spawn() + .unwrap(); + let timeout = Duration::from_secs(35); + let deadline = Instant::now() + timeout; + let mut timed_out = false; + let status = loop { + if let Some(status) = child.try_wait().unwrap() { + break status; + } + if Instant::now() >= deadline { + timed_out = true; + let _ = child.kill(); + break child.wait().unwrap(); + } + std::thread::sleep(Duration::from_millis(30)); + }; + stdout.seek(SeekFrom::Start(0)).unwrap(); + stderr.seek(SeekFrom::Start(0)).unwrap(); + let mut output = Output { + status, + stdout: Vec::new(), + stderr: Vec::new(), + }; + stdout.read_to_end(&mut output.stdout).unwrap(); + stderr.read_to_end(&mut output.stderr).unwrap(); + if timed_out && !std::thread::panicking() { + panic!( + "command {command:?} did not exit within {timeout:?}: {}", + String::from_utf8_lossy(&output.stderr) + ); + } + output +} + +struct Host(TempDir); + +impl Host { + fn new() -> Self { + Self(TempDir::new().unwrap()) + } + + fn run(&self, args: &[&str]) -> Output { + bounded_output( + Command::new(env!("CARGO_BIN_EXE_nori")) + .env("NORI_HOME", self.0.path()) + .args(["-c", "features.multi_session=true"]) + .args(args), + ) + } +} + +impl Drop for Host { + fn drop(&mut self) { + let _ = self.run(&["host", "stop"]); + } +} + +fn success(output: Output) -> String { + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout).unwrap() +} + +#[test] +fn detached_host_stays_alive_empty_and_stops_explicitly() { + let host = Host::new(); + let started = success(host.run(&["host", "--port", "0"])); + assert!(started.contains("started"), "{started}"); + let listing = success(host.run(&["host", "ls"])); + assert_eq!( + listing.split_whitespace().collect::>(), + ["ID", "AGENT", "STATUS", "AGE", "TITLE"] + ); + assert!(!listing.contains('\u{1b}'), "piped output must be plain"); + let again = success(host.run(&["host"])); + assert!(again.contains("already running"), "{again}"); + assert_eq!(listing, success(host.run(&["host", "ls"]))); + success(host.run(&["host", "stop"])); + assert!(!host.run(&["host", "ls"]).status.success()); + success(host.run(&["host", "--port", "0"])); + success(host.run(&["host", "stop"])); +} + +#[test] +fn host_token_is_private_and_never_printed() { + let host = Host::new(); + let output = success(host.run(&["host", "--port", "0"])); + let token_path = host.0.path().join("host/token"); + let token = std::fs::read_to_string(&token_path).unwrap(); + assert!(token.trim().len() >= 43); + assert!(!output.contains(token.trim())); + assert_eq!( + std::fs::metadata(token_path).unwrap().permissions().mode() & 0o777, + 0o600 + ); + assert_eq!( + std::fs::metadata(host.0.path().join("host")) + .unwrap() + .permissions() + .mode() + & 0o777, + 0o700 + ); +} + +#[test] +fn occupied_port_fails_without_publishing_a_host() { + let host = Host::new(); + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port().to_string(); + assert!(!host.run(&["host", "--port", &port]).status.success()); + assert!(!host.run(&["host", "ls"]).status.success()); + drop(listener); + success(host.run(&["host", "--port", &port])); +} + +#[test] +fn attach_requires_multi_session_before_opening_terminal() { + let host = Host::new(); + let result = bounded_output( + Command::new(env!("CARGO_BIN_EXE_nori")) + .env("NORI_HOME", host.0.path()) + .args(["attach"]), + ); + assert!(!result.status.success()); + assert!(String::from_utf8_lossy(&result.stderr).contains("multi_session")); +} + +#[test] +fn token_symlink_is_refused_without_overwriting_target() { + let host = Host::new(); + let directory = host.0.path().join("host"); + std::fs::create_dir(&directory).unwrap(); + std::fs::set_permissions(&directory, std::fs::Permissions::from_mode(0o700)).unwrap(); + let target = host.0.path().join("unrelated"); + std::fs::write(&target, "leave me alone").unwrap(); + std::os::unix::fs::symlink(&target, directory.join("token")).unwrap(); + assert!(!host.run(&["host", "--port", "0"]).status.success()); + assert_eq!(std::fs::read_to_string(target).unwrap(), "leave me alone"); +} + +#[test] +fn host_can_be_stopped_even_if_configuration_was_broken_after_start() { + let host = Host::new(); + success(host.run(&["host", "--port", "0"])); + std::fs::write( + host.0.path().join("config.toml"), + "this is not valid TOML = [", + ) + .unwrap(); + success(host.run(&["host", "ls"])); + success(host.run(&["host", "stop"])); +} diff --git a/nori-rs/docs.md b/nori-rs/docs.md index 469bce719..252ec674f 100644 --- a/nori-rs/docs.md +++ b/nori-rs/docs.md @@ -28,10 +28,15 @@ used in production. ### Core Implementation -- `cli/` dispatches the `nori` binary and sandbox debug commands. +- `cli/` dispatches the `nori` binary and sandbox debug commands. Its + [host module](cli/src/host/docs.md) owns the detached process, private token, + and session manager used by `nori host`. - `exec/` projects the harness into a final-answer plaintext command or a bounded standard ACP-over-stdio agent facade. - `tui/` renders events and forwards user intent through typed harness methods. + Its [attach frontend](tui/src/attach/docs.md) instead consumes host-owned + envelopes and sends managed commands; closing that terminal never ends the + host's sessions. - `harness/` owns session orchestration, private reduction, transcripts, goals, undo, hooks, worktrees, history, and the embeddable runtime API. Its public event stream is an ordered fan-out: one primary frontend receiver plus @@ -45,7 +50,9 @@ used in production. through a `HostedAgent` trait that `harness/` implements, preserving the `nori-harness -> nori-acp-host` dependency direction. The TUI owns startup `--remote` and runtime `/remote-control` listener policy around that server - (see `@/docs/remote-control.md`). + (see [the wire contract](../docs/remote-control.md)). A separate authenticated + managed listener serves the background host with controller/watcher roles; + its server and client retain the same downward dependency boundary. - `nori-protocol/` owns no behavior. It exports `nori_protocol::acp`, `SessionEvent::{Acp, Nori}`, and the session manager's `SessionEnvelope` and `SessionStatus` types. @@ -81,11 +88,10 @@ product crates. - Product analytics distinguishes `interactive`, `cloud`, `exec`, and `acp` session modes. Resume is not a mode or event; a resumed interactive session reports only if a new prompt reaches the transport. -- There are two outward ACP agent surfaces: `nori exec --acp` (a bounded, - one-session stdio facade) and the remote WebSocket transport (the long-lived - interactive session, enabled at startup or runtime, loopback by default, - stable Nori conversation ids as outward session ids). They are deliberately - separate; neither replaces the other. +- The outward ACP surfaces are `nori exec --acp` and the interactive remote + WebSocket projection. With `multi_session`, exec also exposes managed-session + commands. The background host serves authenticated managed envelopes without + a legacy ACP projection; its lifetime is independent of connected terminals. - Rust 2024 and strict workspace lints apply. Add only the derive traits a public boundary type actually needs. diff --git a/nori-rs/harness/docs.md b/nori-rs/harness/docs.md index cf6e44324..af6b26b29 100644 --- a/nori-rs/harness/docs.md +++ b/nori-rs/harness/docs.md @@ -388,6 +388,15 @@ They use the remote responder label, so TUI and remote observers see the same `RequestResolved`. Managed disconnect does not cancel a turn or resolve its pending permission: the continuing session can be controlled after reconnect. +The background [`HostService`](../cli/src/host/service.rs) composes this +adapter with manager lifecycle operations for new, close, cancel, and resume. +It owns the manager independently of every attached terminal. Transport +authentication and controller/watcher admission live below this layer in +[`acp-host`](../acp-host/src/remote/host_control.rs); the harness remains the +authority for prompt, permission, transcript, and session state. The +`ManagedClient` re-export lets an attached frontend consume this transport +without importing the ACP host crate directly. + #### Goal ownership and MCP routing Thread goals are Nori-owned live state. The harness is the authority for their @@ -791,8 +800,9 @@ temp dir is removed. - Consumers should correlate raw requests and responses only by the supplied ACP `RequestId`. - The legacy `HarnessRemoteHost` exposes one attached session; the managed - host exposes the manager registry. WebSocket endpoints share one controller - slot (last connect wins). Bounded consumers close on overflow without + host exposes the manager registry. Legacy `--remote` WebSocket endpoints + share one controller slot (last connect wins); the background host instead + admits one controller and independent watchers. Bounded consumers close on overflow without blocking sessions. [Legacy remote tests](tests/remote_host.rs) exercise the ACP projection; [managed WebSocket tests](tests/managed_remote.rs) compare reconnect delivery against the manager's envelope stream. diff --git a/nori-rs/harness/src/remote_agent.rs b/nori-rs/harness/src/remote_agent.rs index c95ab6f9f..636efc340 100644 --- a/nori-rs/harness/src/remote_agent.rs +++ b/nori-rs/harness/src/remote_agent.rs @@ -25,6 +25,7 @@ pub use nori_acp_host::remote::HostedAgent; pub use nori_acp_host::remote::HostedSubscription; pub use nori_acp_host::remote::LoadedSession; pub use nori_acp_host::remote::ManagedAgent; +pub use nori_acp_host::remote::ManagedClient; pub use nori_acp_host::remote::ManagedReply; pub use nori_acp_host::remote::ManagedSubscription; pub use nori_acp_host::remote::RemoteAcpServer; diff --git a/nori-rs/tui-pty-e2e/docs.md b/nori-rs/tui-pty-e2e/docs.md index e9074f20d..97911f8f6 100644 --- a/nori-rs/tui-pty-e2e/docs.md +++ b/nori-rs/tui-pty-e2e/docs.md @@ -79,6 +79,16 @@ paths share one listener owner, disabling listeners preserves the harness, and the stable endpoint exposes a replacement only after its `SessionStarted` commit. +The [host attachment scenarios](tests/host_attach.rs) run a detached host and +independent attached PTYs sharing a disposable Nori home. They cover the flat +script-facing list, session creation, controller/watcher handoff, refused +watcher prompts and permission answers, detach/reattach, and host survival +after its last session closes. A local TCP proxy either drops one terminal's +connection or silently stops forwarding traffic while the controller continues, +then checks the reconnecting marker and replay of missed output without +duplicates. Cleanup owns both clients and the host so a failed assertion does +not leave background agents running. + Prepared-startup scenarios wrap `mock-acp-agent` behind the exact registered `nori-handroll acp --type remote` argv while recording process identity. They prove that ordinary and remote-adapter startup initialize, optionally list, and diff --git a/nori-rs/tui-pty-e2e/src/lib.rs b/nori-rs/tui-pty-e2e/src/lib.rs index c15b22d21..5bf1031ac 100644 --- a/nori-rs/tui-pty-e2e/src/lib.rs +++ b/nori-rs/tui-pty-e2e/src/lib.rs @@ -246,22 +246,23 @@ impl TuiSession { cmd.cwd(cwd); } - // Run a subcommand (e.g. `nori cloud`) if requested - if let Some(subcommand) = &config.subcommand { - cmd.arg(subcommand); - } - - // Use mock-acp-agent agent - cmd.arg("--agent"); - cmd.arg(&config.agent); - - // Skip trust directory prompt for E2E tests (avoids interactive prompts) - if config.skip_trust_directory { - cmd.arg("--skip-trust-directory"); - } - - for arg in &config.args { - cmd.arg(arg); + if let Some(args) = &config.command_args { + for arg in args { + cmd.arg(arg); + } + } else { + // Run a subcommand (e.g. `nori cloud`) if requested. + if let Some(subcommand) = &config.subcommand { + cmd.arg(subcommand); + } + cmd.arg("--agent"); + cmd.arg(&config.agent); + if config.skip_trust_directory { + cmd.arg("--skip-trust-directory"); + } + for arg in &config.args { + cmd.arg(arg); + } } // Set TERM to enable terminal features @@ -439,6 +440,12 @@ trust_level = "trusted" } } + /// Kill a test client and reap it within a bounded interval. + pub fn terminate_and_wait(&mut self, timeout: Duration) -> bool { + let _ = self.child.kill(); + self.wait_for_process_exit(timeout) + } + /// Read any available output and update screen state /// /// This method attempts to read available data without blocking. @@ -746,6 +753,8 @@ fn find_acp_log_file(nori_home: &std::path::Path) -> Option /// Configuration for spawning a test session pub struct SessionConfig { pub agent: String, + /// Exact command arguments, bypassing the default interactive TUI flags. + pub command_args: Option>, /// Subcommand to run before the flags (e.g. "cloud" for `nori cloud`). pub subcommand: Option, /// Positional arguments appended after the standard test flags. @@ -790,6 +799,7 @@ impl SessionConfig { pub fn new() -> Self { Self { agent: "mock-model".to_string(), + command_args: None, subcommand: None, args: Vec::new(), mock_agent_env: HashMap::new(), @@ -830,6 +840,12 @@ impl SessionConfig { self } + /// Drive a CLI subcommand with its own argument grammar in the PTY. + pub fn with_command_args(mut self, args: impl IntoIterator>) -> Self { + self.command_args = Some(args.into_iter().map(Into::into).collect()); + self + } + pub fn with_arg(mut self, arg: impl Into) -> Self { self.args.push(arg.into()); self diff --git a/nori-rs/tui-pty-e2e/tests/host_attach.rs b/nori-rs/tui-pty-e2e/tests/host_attach.rs new file mode 100644 index 000000000..d933b1669 --- /dev/null +++ b/nori-rs/tui-pty-e2e/tests/host_attach.rs @@ -0,0 +1,794 @@ +//! Detached hosts and independent attached terminal clients. +#![cfg(target_os = "linux")] + +use std::io::Read; +use std::io::Seek; +use std::io::SeekFrom; +use std::io::Write; +use std::net::Shutdown; +use std::net::SocketAddr; +use std::net::TcpListener; +use std::net::TcpStream; +use std::ops::Deref; +use std::ops::DerefMut; +use std::path::PathBuf; +use std::process::Command; +use std::process::Output; +use std::process::Stdio; +use std::sync::mpsc; +use std::thread::JoinHandle; +use std::time::Duration; +use std::time::Instant; + +use tui_pty_e2e::Key; +use tui_pty_e2e::SessionConfig; +use tui_pty_e2e::TIMEOUT; +use tui_pty_e2e::TuiSession; + +const ANSWER: &str = "D2 host agent response"; +const CLEANUP_TIMEOUT: Duration = Duration::from_secs(35); + +/// Own the host's home until all clients have been dropped and the host stopped. +struct Host { + home: tempfile::TempDir, + binary: PathBuf, +} + +impl Host { + fn new() -> Self { + let home = tempfile::tempdir().unwrap(); + let cwd = home.path().join("project"); + std::fs::create_dir(&cwd).unwrap(); + let quoted_cwd = serde_json::to_string(&cwd.to_string_lossy()).unwrap(); + std::fs::write( + home.path().join("config.toml"), + format!( + "agent = \"mock-model\"\n[features]\nmulti_session = true\n\ + [projects.{quoted_cwd}]\ntrust_level = \"trusted\"\n" + ), + ) + .unwrap(); + let binary = std::env::current_exe() + .unwrap() + .parent() + .unwrap() + .parent() + .unwrap() + .join("nori"); + Self { home, binary } + } + + fn args(args: &[&str]) -> Vec { + ["-c", "features.multi_session=true", "--agent", "mock-model"] + .into_iter() + .chain(args.iter().copied()) + .map(str::to_owned) + .collect() + } + + fn terminal(&self, args: &[&str]) -> Client { + let home = self.home.path().to_string_lossy(); + let mut config = SessionConfig::new() + .with_command_args(Self::args(args)) + .with_agent_env("NORI_HOME", home.as_ref()) + .with_agent_env("CODEX_HOME", home.as_ref()) + .with_agent_env("NORI_NO_ANALYTICS", "1") + .with_agent_env("MOCK_AGENT_RESPONSE", ANSWER) + .with_extra_path(self.binary.parent().unwrap().to_path_buf()); + config.cwd = Some(self.home.path().join("project")); + Client(TuiSession::spawn_with_config(40, 120, config).unwrap()) + } + + fn command(&self, args: &[&str], timeout: Duration) -> Output { + let mut stdout = tempfile::tempfile().unwrap(); + let mut stderr = tempfile::tempfile().unwrap(); + let path = std::env::join_paths( + std::iter::once(self.binary.parent().unwrap().to_path_buf()).chain( + std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()), + ), + ) + .unwrap(); + let mut child = Command::new(&self.binary) + .args(Self::args(args)) + .current_dir(self.home.path().join("project")) + .env("NORI_HOME", self.home.path()) + .env("CODEX_HOME", self.home.path()) + .env("PATH", path) + .env("NORI_NO_ANALYTICS", "1") + .env("MOCK_AGENT_RESPONSE", ANSWER) + .stdin(Stdio::null()) + .stdout(stdout.try_clone().unwrap()) + .stderr(stderr.try_clone().unwrap()) + .spawn() + .unwrap(); + let deadline = Instant::now() + timeout; + let status = loop { + if let Some(status) = child.try_wait().unwrap() { + break status; + } + if Instant::now() >= deadline { + let _ = child.kill(); + let status = child.wait().unwrap(); + if !std::thread::panicking() { + panic!("nori {args:?} did not exit within {timeout:?}: {status}"); + } + break status; + } + std::thread::sleep(Duration::from_millis(30)); + }; + stdout.seek(SeekFrom::Start(0)).unwrap(); + stderr.seek(SeekFrom::Start(0)).unwrap(); + let mut output = Output { + status, + stdout: Vec::new(), + stderr: Vec::new(), + }; + stdout.read_to_end(&mut output.stdout).unwrap(); + stderr.read_to_end(&mut output.stderr).unwrap(); + output + } + + fn start(&self) { + let mut terminal = self.terminal(&["host", "--port", "0"]); + terminal + .wait_for(|screen| screen.to_lowercase().contains("started"), TIMEOUT) + .expect("nori host reports a ready background host"); + assert!( + terminal.wait_for_process_exit(TIMEOUT), + "host command must detach" + ); + self.list(); + } + + fn list(&self) -> String { + let output = self.command(&["host", "ls"], TIMEOUT); + assert!( + output.status.success(), + "host ls failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + let text = String::from_utf8(output.stdout).unwrap(); + assert!( + !text.contains('\u{1b}'), + "piped host ls must be plain: {text:?}" + ); + assert_eq!( + text.lines() + .next() + .unwrap_or_default() + .split_whitespace() + .collect::>(), + ["ID", "AGENT", "STATUS", "AGE", "TITLE"], + "host ls exposes the accepted flat table" + ); + text + } + + fn session_id(&self) -> String { + self.list() + .lines() + .nth(1) + .expect("one session row") + .split_whitespace() + .next() + .unwrap() + .to_owned() + } + + fn attach(&self, id: Option<&str>) -> Client { + let mut client = match id { + Some(id) => self.terminal(&["attach", id]), + None => self.terminal(&["attach"]), + }; + client + .wait_for_text(if id.is_some() { "›" } else { "Sessions" }, TIMEOUT) + .unwrap(); + client + } + + fn create_session(&self) -> Client { + let mut client = self.attach(None); + client.send_key(Key::Escape).unwrap(); + client + .wait_for( + |screen| screen.contains("No session selected. Use"), + TIMEOUT, + ) + .unwrap(); + client.submit_input("/new").unwrap(); + client.wait_for_text("mock-model", TIMEOUT).unwrap(); + client.wait_for_text("ready", TIMEOUT).unwrap(); + client + } +} + +impl Drop for Host { + fn drop(&mut self) { + let _ = self.command(&["host", "stop"], CLEANUP_TIMEOUT); + } +} + +struct Client(TuiSession); + +impl Deref for Client { + type Target = TuiSession; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for Client { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +impl Drop for Client { + fn drop(&mut self) { + self.0.terminate_and_wait(Duration::from_secs(2)); + } +} + +fn ask(client: &mut Client, prompt: &str) { + let before = client.history_contents().matches(ANSWER).count(); + client.submit_input(prompt).unwrap(); + let deadline = Instant::now() + TIMEOUT; + loop { + if client.history_contents().matches(ANSWER).count() > before { + break; + } + assert!( + Instant::now() < deadline, + "host did not answer {prompt:?}:\n{}", + client.screen_contents() + ); + client.settle(Duration::from_millis(50)); + } + client.settle(Duration::from_millis(200)); +} + +fn wait_watching(client: &mut Client) { + client + .wait_for( + |screen| { + let text = screen.to_lowercase(); + (text.contains("watching") || text.contains("watcher")) + && text.contains("read-only") + }, + TIMEOUT, + ) + .expect("watcher role is visible and explicitly read-only"); +} + +fn wait_controlling(client: &mut Client) { + client + .wait_for( + |screen| { + let text = screen.to_lowercase(); + text.contains("controlling") || text.contains("controller") + }, + TIMEOUT, + ) + .expect("controller role is visible"); +} + +fn refusal_count(client: &mut Client) -> usize { + client + .history_contents() + .to_lowercase() + .lines() + .filter(|line| { + line.contains("read-only") || line.contains("not allowed") || line.contains("cannot") + }) + .count() +} + +fn wait_refusal(client: &mut Client, before: usize) { + let deadline = Instant::now() + TIMEOUT; + while refusal_count(client) <= before { + assert!( + Instant::now() < deadline, + "watcher action must show an error:\n{}", + client.screen_contents() + ); + client.settle(Duration::from_millis(50)); + } +} + +#[test] +fn host_starts_without_a_terminal_session_and_stops_explicitly() { + let host = Host::new(); + host.start(); + assert_eq!(host.list().lines().count(), 1, "new host starts empty"); + let mut client = host.attach(None); + client.wait_for_text("Sessions 0", TIMEOUT).unwrap(); + client.send_key(Key::Ctrl('d')).unwrap(); + assert!( + client.wait_for_process_exit(TIMEOUT), + "Ctrl+D detaches the client" + ); + assert_eq!( + host.list().lines().count(), + 1, + "empty host survives detachment" + ); + let stop = host.command(&["host", "stop"], CLEANUP_TIMEOUT); + assert!( + stop.status.success(), + "{}", + String::from_utf8_lossy(&stop.stderr) + ); + assert!( + !host.command(&["host", "ls"], TIMEOUT).status.success(), + "stopped host is unavailable" + ); +} + +#[test] +fn detach_and_named_reattach_keep_the_session_history_and_host_alive() { + let host = Host::new(); + host.start(); + let mut client = host.create_session(); + ask(&mut client, "D2 durable history"); + let id = host.session_id(); + assert!( + host.list().contains("D2 durable history"), + "host list includes the session title" + ); + client.send_key(Key::Ctrl('d')).unwrap(); + assert!(client.wait_for_process_exit(TIMEOUT)); + + let mut list = host.attach(None); + list.wait_for_text("D2 durable history", TIMEOUT).unwrap(); + list.send_key(Key::Enter).unwrap(); + list.wait_for_text(ANSWER, TIMEOUT) + .expect("opening a listed session replays its output"); + list.submit_input("/quit").unwrap(); + assert!( + list.wait_for_process_exit(TIMEOUT), + "/quit detaches without stopping the host" + ); + + let mut reattached = host.attach(Some(&id)); + reattached + .wait_for_text(ANSWER, TIMEOUT) + .expect("named attach restores output"); + ask(&mut reattached, "D2 after reattach"); + assert_eq!( + host.session_id(), + id, + "reattach preserves conversation identity" + ); + reattached.submit_input("/close").unwrap(); + let deadline = Instant::now() + TIMEOUT; + loop { + let table = host.list(); + if table.lines().skip(1).all(|row| row.contains("closed")) { + break; + } + assert!( + Instant::now() < deadline, + "last session must close: {table}" + ); + reattached.settle(Duration::from_millis(100)); + } + assert!( + host.command(&["host", "ls"], TIMEOUT).status.success(), + "host outlives its last session" + ); +} + +#[test] +fn two_terminals_watch_take_control_and_refuse_the_previous_controllers_prompt() { + let host = Host::new(); + host.start(); + let mut first = host.create_session(); + ask(&mut first, "D2 shared session"); + let id = host.session_id(); + let mut second = host.attach(Some(&id)); + wait_controlling(&mut first); + wait_watching(&mut second); + second.wait_for_text(ANSWER, TIMEOUT).unwrap(); + + let before_refusal = refusal_count(&mut second); + let before_answers = first.history_contents().matches(ANSWER).count(); + second.send_str("D2 watcher must not run").unwrap(); + second.settle(Duration::from_millis(500)); + second.send_key(Key::Enter).unwrap(); + wait_refusal(&mut second, before_refusal); + first.settle(Duration::from_millis(500)); + assert_eq!( + first.history_contents().matches(ANSWER).count(), + before_answers, + "watcher prompt never reaches the agent" + ); + + second.send_key(Key::Ctrl('u')).unwrap(); + second.send_key(Key::Alt('t')).unwrap(); + wait_controlling(&mut second); + wait_watching(&mut first); + ask(&mut second, "D2 new controller"); + let deadline = Instant::now() + TIMEOUT; + while first.history_contents().matches(ANSWER).count() <= before_answers { + assert!( + Instant::now() < deadline, + "former controller must receive the new answer as a watcher:\n{}", + first.screen_contents() + ); + first.settle(Duration::from_millis(50)); + } + + let before_refusal = refusal_count(&mut first); + first.send_str("D2 former controller must not run").unwrap(); + first.settle(Duration::from_millis(500)); + first.send_key(Key::Enter).unwrap(); + wait_refusal(&mut first, before_refusal); + assert!( + !second.wait_for_process_exit(Duration::from_millis(200)), + "takeover preserves both connections" + ); +} + +#[test] +fn watcher_cannot_answer_a_permission_request_but_controller_can() { + let host = Host::new(); + host.start(); + let mut controller = host.create_session(); + ask(&mut controller, "D2 approval session"); + let mut watcher = host.attach(Some(&host.session_id())); + wait_watching(&mut watcher); + controller + .submit_input("mock:request-permission:echo D2-permission") + .unwrap(); + controller.wait_for_text("D2-permission", TIMEOUT).unwrap(); + watcher.wait_for_text("D2-permission", TIMEOUT).unwrap(); + let deadline = Instant::now() + TIMEOUT; + while !host.list().contains("waiting on you") { + assert!( + Instant::now() < deadline, + "permission request should block the session" + ); + watcher.settle(Duration::from_millis(50)); + controller.settle(Duration::from_millis(50)); + } + let before = refusal_count(&mut watcher); + watcher.send_key(Key::Enter).unwrap(); + wait_refusal(&mut watcher, before); + assert!( + host.list().contains("waiting on you"), + "watcher answer leaves permission pending" + ); + controller.send_key(Key::Enter).unwrap(); + controller + .wait_for_text("Permission granted with option: allow", TIMEOUT) + .unwrap(); + watcher + .wait_for_text("Permission granted with option: allow", TIMEOUT) + .expect("watcher receives the controller-approved result"); +} + +enum ProxyCommand { + Pause(mpsc::Sender<()>), + Blackhole(mpsc::Sender<()>), + Resume, + Stop, +} + +/// A real TCP link whose outages do not affect the host or its other clients. +/// Nonblocking sockets keep the single worker responsive to teardown commands. +struct InterruptibleProxy { + endpoint: String, + commands: mpsc::Sender, + worker: Option>, +} + +struct ForwardedConnection { + client: TcpStream, + host: TcpStream, + to_host: Vec, + to_client: Vec, +} + +impl Drop for ForwardedConnection { + fn drop(&mut self) { + let _ = self.client.shutdown(Shutdown::Both); + let _ = self.host.shutdown(Shutdown::Both); + } +} + +impl ForwardedConnection { + fn forward(&mut self) -> std::io::Result { + fn pump( + source: &mut TcpStream, + destination: &mut TcpStream, + pending: &mut Vec, + ) -> std::io::Result { + if pending.len() < 64 * 1024 { + let mut buffer = [0; 8192]; + match source.read(&mut buffer) { + Ok(0) => return Ok(false), + Ok(count) => pending.extend_from_slice(&buffer[..count]), + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {} + Err(error) => return Err(error), + } + } + if !pending.is_empty() { + match destination.write(pending) { + Ok(0) => return Ok(false), + Ok(count) => { + pending.drain(..count); + } + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {} + Err(error) => return Err(error), + } + } + Ok(true) + } + Ok(pump(&mut self.client, &mut self.host, &mut self.to_host)? + && pump(&mut self.host, &mut self.client, &mut self.to_client)?) + } +} + +impl InterruptibleProxy { + fn new(target: SocketAddr) -> Self { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let endpoint = format!("ws://{}/sessions", listener.local_addr().unwrap()); + let (commands, incoming) = mpsc::channel(); + let worker = std::thread::spawn(move || { + let mut enabled = true; + let mut forwarding = true; + let mut connection: Option = None; + loop { + while let Ok(command) = incoming.try_recv() { + match command { + ProxyCommand::Pause(done) => { + enabled = false; + connection = None; + let _ = done.send(()); + } + ProxyCommand::Blackhole(done) => { + // Keep both sockets open. Neither EOF nor a TCP reset + // can tell the attached client that traffic has stopped. + forwarding = false; + let _ = done.send(()); + } + ProxyCommand::Resume => { + enabled = true; + forwarding = true; + } + ProxyCommand::Stop => return, + } + } + match listener.accept() { + Ok((client, _)) if enabled && connection.is_none() => { + if let Ok(host) = + TcpStream::connect_timeout(&target, Duration::from_millis(200)) + { + client.set_nonblocking(true).unwrap(); + host.set_nonblocking(true).unwrap(); + connection = Some(ForwardedConnection { + client, + host, + to_host: Vec::new(), + to_client: Vec::new(), + }); + } + } + Ok((client, _)) => { + let _ = client.shutdown(Shutdown::Both); + } + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {} + Err(error) => panic!("proxy listener: {error}"), + } + if forwarding + && let Some(active) = connection.as_mut() + && !matches!(active.forward(), Ok(true)) + { + connection = None; + } + std::thread::sleep(Duration::from_millis(10)); + } + }); + Self { + endpoint, + commands, + worker: Some(worker), + } + } + + fn pause(&self) { + let (done, ack) = mpsc::channel(); + self.commands.send(ProxyCommand::Pause(done)).unwrap(); + ack.recv_timeout(Duration::from_secs(1)) + .expect("proxy closed both socket directions"); + } + + fn resume(&self) { + self.commands.send(ProxyCommand::Resume).unwrap(); + } + + fn blackhole(&self) { + let (done, ack) = mpsc::channel(); + self.commands.send(ProxyCommand::Blackhole(done)).unwrap(); + ack.recv_timeout(Duration::from_secs(1)) + .expect("proxy stopped forwarding without closing its sockets"); + } +} + +impl Drop for InterruptibleProxy { + fn drop(&mut self) { + let _ = self.commands.send(ProxyCommand::Stop); + if let Some(worker) = self.worker.take() { + let _ = worker.join(); + } + } +} + +#[test] +fn dropped_tcp_connection_shows_reconnecting_and_replays_missed_output_once() { + assert_reconnect_after_outage(false); +} + +#[test] +fn silently_blackholed_connection_shows_reconnecting_and_replays_missed_output_once() { + assert_reconnect_after_outage(true); +} + +fn assert_reconnect_after_outage(blackhole: bool) { + let host = Host::new(); + host.start(); + let mut controller = host.create_session(); + ask(&mut controller, "D2 before network outage"); + let id = host.session_id(); + let state: serde_json::Value = + serde_json::from_slice(&std::fs::read(host.home.path().join("host/state.json")).unwrap()) + .unwrap(); + let target: SocketAddr = state["endpoint"] + .as_str() + .unwrap() + .strip_prefix("ws://") + .unwrap() + .split('/') + .next() + .unwrap() + .parse() + .unwrap(); + let proxy = InterruptibleProxy::new(target); + let token_path = host.home.path().join("host/token"); + let mut viewer = host.terminal(&[ + "attach", + &id, + "--host", + &proxy.endpoint, + "--token-file", + token_path.to_str().unwrap(), + ]); + wait_watching(&mut viewer); + viewer.wait_for_text(ANSWER, TIMEOUT).unwrap(); + assert_eq!(viewer.history_contents().matches(ANSWER).count(), 1); + + let detection_timeout = if blackhole { + proxy.blackhole(); + Duration::from_secs(20) + } else { + proxy.pause(); + TIMEOUT + }; + viewer + .wait_for_text("RECONNECTING", detection_timeout) + .expect("an unresponsive transport is visible even without EOF or a TCP reset"); + ask(&mut controller, "D2 output created during outage"); + assert!( + !viewer + .history_contents() + .contains("D2 output created during outage") + ); + assert_eq!(viewer.history_contents().matches(ANSWER).count(), 1); + + proxy.resume(); + wait_watching(&mut viewer); + let deadline = Instant::now() + TIMEOUT; + while viewer.history_contents().matches(ANSWER).count() < 2 { + assert!( + Instant::now() < deadline, + "reconnect must deliver missed output:\n{}", + viewer.screen_contents() + ); + viewer.settle(Duration::from_millis(50)); + } + assert!(!viewer.screen_contents().contains("RECONNECTING")); + assert_eq!( + viewer.history_contents().matches(ANSWER).count(), + 2, + "resume cursor must not replay already displayed answers" + ); + assert_eq!( + viewer + .history_contents() + .matches("D2 output created during outage") + .count(), + 1, + "missed prompt is replayed once" + ); + + viewer.send_key(Key::Alt('t')).unwrap(); + wait_controlling(&mut viewer); + wait_watching(&mut controller); + ask(&mut viewer, "D2 prompt after network recovery"); + assert_eq!( + viewer.history_contents().matches(ANSWER).count(), + 3, + "recovered connection carries new prompts without duplicating replay" + ); +} + +#[test] +fn same_port_host_restart_stops_reconnecting_and_explains_session_loss() { + let host = Host::new(); + host.start(); + let mut client = host.create_session(); + ask(&mut client, "Session before restart"); + let state: serde_json::Value = + serde_json::from_slice(&std::fs::read(host.home.path().join("host/state.json")).unwrap()) + .unwrap(); + let address: SocketAddr = state["endpoint"] + .as_str() + .unwrap() + .trim_start_matches("ws://") + .trim_end_matches("/sessions") + .parse() + .unwrap(); + let old_token = std::fs::read(host.home.path().join("host/token")).unwrap(); + let stopped = host.command(&["host", "stop"], CLEANUP_TIMEOUT); + assert!(stopped.status.success()); + client.wait_for_text("RECONNECTING", TIMEOUT).unwrap(); + let started = host.command(&["host", "--port", &address.port().to_string()], TIMEOUT); + assert!( + started.status.success(), + "{}", + String::from_utf8_lossy(&started.stderr) + ); + assert_ne!( + std::fs::read(host.home.path().join("host/token")).unwrap(), + old_token + ); + client.wait_for_text("Host restarted", TIMEOUT).unwrap(); + let screen = client.screen_contents(); + assert!( + screen.contains("sessions were lost") && screen.contains("nori attach"), + "{screen}" + ); + assert!( + !screen.contains("RECONNECTING") && !screen.contains("sessions continue"), + "{screen}" + ); + client.send_key(Key::Escape).unwrap(); + client.send_key(Key::Alt('t')).unwrap(); + client.settle(Duration::from_millis(200)); + assert!(client.screen_contents().contains("Host restarted")); + let mut fresh = host.attach(None); + fresh.wait_for_text("Sessions 0", TIMEOUT).unwrap(); + client.send_key(Key::Ctrl('d')).unwrap(); + assert!(client.wait_for_process_exit(TIMEOUT)); +} + +#[test] +fn host_list_truncates_tty_title_without_losing_piped_title() { + let host = Host::new(); + host.start(); + let mut client = host.create_session(); + let title = "Long title aligned columns should preserve the entire title without putting continuation text into the ID column"; + ask(&mut client, title); + assert!(host.list().contains(title)); + let id = host.session_id(); + let mut listing = host.terminal(&["host", "ls"]); + assert!(listing.wait_for_process_exit(TIMEOUT)); + let screen = listing.screen_contents(); + let row = screen + .lines() + .find(|line| line.contains(&id)) + .expect("session row"); + assert!(row.trim_end().ends_with('…'), "{screen}"); + assert!(!screen.contains("continuation text"), "{screen}"); +} diff --git a/nori-rs/tui/docs.md b/nori-rs/tui/docs.md index 8bfcf9db3..31a170023 100644 --- a/nori-rs/tui/docs.md +++ b/nori-rs/tui/docs.md @@ -1039,6 +1039,27 @@ The ignored `jump_timing_on_a_long_history` PTY test measures a jump to a long history; the reprint is bounded by the same cell and row caps as resize reflow. +#### Host attachment + +[`attach`](src/attach/docs.md) is the dedicated frontend for `nori attach`, +entered only with `multi_session`. It consumes host-owned manager envelopes +through the harness's `ManagedClient` re-export. It does not construct the +local process-owning `App`, launch agents, or shut down sessions when its +terminal closes. Its session list and selected conversation are terminal-local; +the host remains authoritative for session lifecycle and controller ownership. +The attachment composer submits raw slash commands to this frontend rather +than the local app's command router; that mode is disabled for ordinary TUI +composers. It honors the configured session-list hotkey and resumes highlighted +failed sessions with Ctrl+R under the existing conversation ID. + +The status line keeps control, watch/read-only, and reconnecting states visible. +Alt+T requests control without disconnecting another terminal. Prompts and +permission answers require controller status locally and on the server. Socket +recovery retains view state and resumes from applied per-session sequence +cursors; mutation requests are never retransmitted. See the +[host contract](../../docs/remote-control.md#11-background-host-and-attached-terminals) +for command behavior and the distinction from the legacy listener below. + #### Remote ACP transport activation `--remote ` (in [`cli.rs`](src/cli.rs)) serves the running interactive @@ -1083,6 +1104,13 @@ controller disconnected and able to reconnect. Only a restoration bind failure leaves remote control off, and the user-visible error includes both failures. Repeating the active target is idempotent. +The same-port replacement and rollback tests in +[`remote_control.rs`](src/remote_control.rs) each run in an isolated test +process. Concurrent subprocess launches elsewhere in the suite can briefly +inherit a listening socket until exec, keeping its address occupied after the +owning test closes it. Isolation preserves the close/rebind assertions without +retrying replacement or rollback. + Without `multi_session`, on every active session's `SessionStarted`, [`App`](src/app/event_handling.rs) attaches its stable host using the observed identity, even if listeners are diff --git a/nori-rs/tui/src/attach/connection.rs b/nori-rs/tui/src/attach/connection.rs new file mode 100644 index 000000000..23be17093 --- /dev/null +++ b/nori-rs/tui/src/attach/connection.rs @@ -0,0 +1,121 @@ +//! Socket ownership and reconnect scheduling, independent of terminal rendering. + +use nori_harness::remote_agent::ManagedClient; +use serde_json::Value; +use std::time::Duration; +use tokio::sync::mpsc; +use tokio::time::Instant; + +// Session-list replies arrive every second, including when no session is active. +const LIVENESS_TIMEOUT: Duration = Duration::from_secs(10); + +use super::AttachOptions; + +pub(super) enum ConnectionEvent { + Connected, + Message(Value), + Disconnected(String), + Stopped(String), +} + +/// Requests are never replayed. Only event subscriptions resume from a cursor. +pub(super) async fn drive( + mut options: AttachOptions, + initial: ManagedClient, + mut requests: mpsc::UnboundedReceiver, + events: mpsc::UnboundedSender, +) { + let instance = initial.host_instance(); + let mut client = initial; + loop { + if events.send(ConnectionEvent::Connected).is_err() { + return; + } + let mut deadline = Instant::now() + LIVENESS_TIMEOUT; + let error = loop { + tokio::select! { + _ = tokio::time::sleep_until(deadline) => { + break "Host stopped responding".to_string(); + } + request = requests.recv() => { + let Some(request) = request else { return; }; + match tokio::time::timeout_at(deadline, client.send(request)).await { + Ok(Ok(())) => {}, + Ok(Err(error)) => break error.to_string(), + Err(_) => break "Host stopped responding".to_string(), + } + } + incoming = client.recv() => { + match incoming { + Ok(message) => { + deadline = Instant::now() + LIVENESS_TIMEOUT; + if events.send(ConnectionEvent::Message(message)).is_err() { + return; + } + } + Err(error) => break error.to_string(), + } + } + } + }; + // Release the failed socket before opening its replacement, including + // when liveness expired without a TCP error. + drop(client); + if events.send(ConnectionEvent::Disconnected(error)).is_err() { + return; + } + // The transport cannot determine whether a sent mutation was applied. + // Clear queued work before reconnecting, so it cannot run unexpectedly. + while requests.try_recv().is_ok() {} + loop { + tokio::select! { + _ = events.closed() => return, + _ = tokio::time::sleep(std::time::Duration::from_millis(750)) => {} + } + let attempt = ManagedClient::connect(&options.endpoint, &options.token).await; + let attempt = match attempt { + Err(error) if ManagedClient::is_authentication_error(&error) => { + let refreshed = options + .refresh_local_token + .as_ref() + .and_then(|read| read().ok()); + let Some(token) = refreshed else { + let _ = events.send(ConnectionEvent::Stopped( + "Authentication failed; host may have restarted. Re-run nori attach." + .into(), + )); + return; + }; + options.token = token; + // One attempt with freshly read credentials, never an endless auth loop. + match ManagedClient::connect(&options.endpoint, &options.token).await { + Ok(connected) => Ok(connected), + Err(_) => { + let _ = events.send(ConnectionEvent::Stopped( + "Authentication failed after token refresh; host may have restarted. Re-run nori attach.".into(), + )); + return; + } + } + } + attempt => attempt, + }; + if let Ok(connected) = attempt { + let reason = if instance.is_none() { + Some("Host identity unavailable; cannot safely resume. Re-run nori attach.") + } else if connected.host_instance() != instance { + Some("Host restarted; sessions were lost. Re-run nori attach.") + } else { + None + }; + if let Some(reason) = reason { + let _ = events.send(ConnectionEvent::Stopped(reason.into())); + return; + } + while requests.try_recv().is_ok() {} + client = connected; + break; + } + } + } +} diff --git a/nori-rs/tui/src/attach/connection_tests.rs b/nori-rs/tui/src/attach/connection_tests.rs new file mode 100644 index 000000000..5b6e2a31a --- /dev/null +++ b/nori-rs/tui/src/attach/connection_tests.rs @@ -0,0 +1,143 @@ +use std::sync::Arc; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering; +use std::time::Duration; + +use nori_harness::remote_agent::ManagedAgent; +use nori_harness::remote_agent::ManagedClient; +use nori_harness::remote_agent::ManagedReply; +use nori_harness::remote_agent::RemoteAcpServer; +use serde_json::Value; +use serde_json::json; +use tokio::sync::mpsc; + +use super::AttachOptions; +use super::connection::ConnectionEvent; +use super::connection::drive; + +struct EmptyHost; +impl ManagedAgent for EmptyHost { + async fn request(&self, request: Value) -> ManagedReply { + ManagedReply { + response: json!({"jsonrpc":"2.0", "id":request["id"], "result":{}}), + subscription: None, + } + } +} + +async fn replacement_failure( + local: bool, + valid_refresh: Option, + rotate_token: bool, +) -> (String, usize) { + let original = RemoteAcpServer::bind_host( + "127.0.0.1:0".parse().unwrap(), + Arc::new(EmptyHost), + "old".into(), + ) + .await + .unwrap(); + let initial = + ManagedClient::connect(&format!("ws://{}/sessions", original.local_addr()), "old") + .await + .unwrap(); + let replacement = RemoteAcpServer::bind_host( + "127.0.0.1:0".parse().unwrap(), + Arc::new(EmptyHost), + if rotate_token { "new" } else { "old" }.into(), + ) + .await + .unwrap(); + let endpoint = format!("ws://{}/sessions", replacement.local_addr()); + let reads = Arc::new(AtomicUsize::new(0)); + let counter = reads.clone(); + let options = AttachOptions { + endpoint, + token: "old".into(), + session_id: None, + refresh_local_token: local.then(|| { + Box::new(move || { + counter.fetch_add(1, Ordering::SeqCst); + match valid_refresh { + Some(true) => Ok("new".into()), + Some(false) => Ok("invalid".into()), + None => Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied).into()), + } + }) as Box anyhow::Result + Send + Sync> + }), + }; + let (_requests, request_rx) = mpsc::unbounded_channel(); + let (events, mut event_rx) = mpsc::unbounded_channel(); + let driver = tokio::spawn(drive(options, initial, request_rx, events)); + assert!(matches!( + tokio::time::timeout(Duration::from_secs(3), event_rx.recv()).await, + Ok(Some(ConnectionEvent::Connected)) + )); + original.shutdown().await; + let failure = tokio::time::timeout(Duration::from_secs(5), async { + loop { + match event_rx.recv().await { + Some(ConnectionEvent::Stopped(reason)) => break Ok(reason), + Some(ConnectionEvent::Connected) => { + break Err("replacement must not initialize or replay"); + } + None => break Err("driver must report a terminal failure"), + Some(ConnectionEvent::Disconnected(_) | ConnectionEvent::Message(_)) => {} + } + } + }) + .await; + driver.abort(); + let _ = driver.await; + replacement.shutdown().await; + ( + failure + .expect("reconnect must stop") + .expect("terminal failure"), + reads.load(Ordering::SeqCst), + ) +} + +#[tokio::test] +async fn reconnect_refreshes_local_token_once_then_detects_restarted_host() { + let (reason, reads) = replacement_failure(true, Some(true), true).await; + assert_eq!(reads, 1); + assert!( + reason.contains("Host restarted") && reason.contains("sessions were lost"), + "{reason}" + ); +} + +#[tokio::test] +async fn reconnect_stops_after_refreshed_token_is_rejected() { + let (reason, reads) = replacement_failure(true, Some(false), true).await; + assert_eq!(reads, 1); + assert!( + reason.contains("Authentication failed") && reason.contains("nori attach"), + "{reason}" + ); +} + +#[tokio::test] +async fn remote_reconnect_auth_failure_stops_without_local_discovery() { + let (reason, reads) = replacement_failure(false, Some(false), true).await; + assert_eq!(reads, 0); + assert!(reason.contains("Authentication failed"), "{reason}"); +} + +#[tokio::test] +async fn reconnect_rejects_a_different_host_even_with_the_same_token() { + let (reason, reads) = replacement_failure(true, Some(true), false).await; + assert_eq!(reads, 0); + assert!(reason.contains("Host restarted"), "{reason}"); +} + +#[tokio::test] +async fn reconnect_stops_when_local_token_cannot_be_read() { + let (reason, reads) = replacement_failure(true, None, true).await; + assert_eq!(reads, 1); + assert!( + reason.contains("Authentication failed") && reason.contains("nori attach"), + "{reason}" + ); +} diff --git a/nori-rs/tui/src/attach/docs.md b/nori-rs/tui/src/attach/docs.md new file mode 100644 index 000000000..62003eba9 --- /dev/null +++ b/nori-rs/tui/src/attach/docs.md @@ -0,0 +1,81 @@ +# Noridoc: Attached host frontend + +Path: @/nori-rs/tui/src/attach + +### Overview + +- Renders a terminal attached to a background host without owning its sessions + or agent processes. +- Keeps conversation presentation, session selection, connection role, and + replay cursors local to this terminal. + +### How it fits into the larger codebase + +- [CLI host dispatch](../../../cli/src/host/docs.md) supplies a resolved endpoint + and token after enforcing `multi_session`. This frontend is separate from the + local TUI `App`, whose shutdown owns its local sessions. +- The harness re-exports [ManagedClient](../../../acp-host/src/remote/client.rs) + to preserve the frontend dependency boundary. The host retains mutation + policy and broadcasts complete manager envelopes to controllers and watchers. +- Presentation reuses the TUI's [normalizer](../presentation), composer, + Markdown, tool cells, and picker components. The + [attachment composer](../public_widgets/composer_input.rs) submits slash + commands literally for this frontend to interpret; the local TUI keeps its + ordinary command handling. A terminal's selected session does not change + another terminal's selection. + +### Core Implementation + +- [Connection driving](connection.rs) separates socket ownership and reconnect + attempts from rendering. Received JSON messages renew a liveness deadline; + periodic session-list replies keep an idle connection alive. Reads and sends + share that deadline, so silent traffic loss also produces the reconnecting + state. Recovery authenticates again and compares the upgrade's host-instance + UUID with the initial connection before initializing or resuming replay. + Authentication rejection permits a secure local-token reread and one retry + through the callback supplied by CLI dispatch; explicit endpoints have no + such callback. +- [Runtime correlation](runtime.rs) tracks request IDs while processing every + notification. Initialization supplies the role, refreshes the session list, + and subscribes to the selected conversation using its applied cursor. + Switching sessions replaces the subscription; listing remains independent of + envelope delivery. Subscription errors apply only while their conversation + remains selected. Role-change notices update both the persistent status line + and conversation feedback. +- [AttachState](state.rs) routes envelopes by conversation identity. It applies + ACP presentation and Nori lifecycle events before advancing each cursor, + ignores already-applied envelopes, and rejects sequence gaps. Transcript + restoration's `ReplayStarted` replaces presentation and permissions while + retaining transport cursors; reconnect replay only deduplicates by sequence. + Permissions also clear on matching `RequestResolved`, idle or cancelling + phases, and session end. +- [Rendering](render.rs) keeps role and connectivity visible beside the + selected conversation or session list. Watchers receive the same content and + permissions but must take control before sending mutations. The current + session marker appears in TITLE, preserving the short ID in its own column. + +### Things to Know + +- [Input routing](input.rs) honors `hotkeys.open_session_list`, also opens the + list with Left on an empty composer or `/sessions`, and resumes a highlighted + failed session with Ctrl+R while retaining its conversation identity. +- Detach closes only the client. Session close, cancellation, and resume are + explicit host commands, and a role handoff never closes the old controller. +- Unacknowledged mutations are not replayed after reconnect because the host + may already have applied them. Recovery clears pending correlations and + warns when an outcome is uncertain; only the event subscription resumes. +- Replay failure preserves existing conversation content and displays the + error. It does not silently substitute a new live cursor. Cursors are local + memory, and a fresh attachment starts from the host journal's beginning. +- A changed or unavailable host identity, an unrecoverable authentication + failure, or rejected initialization stops recovery. The terminal retains + conversation history and the composer draft, displays a persistent reason + with instructions to rerun `nori attach`, and remains open for Ctrl+D detach. + No initialization or replay reaches a replacement host after identity + comparison rejects it; token equality alone cannot establish continuity. +- Snapshot and reducer [tests](tests.rs) cover roles, read-only behavior, and + sequence application. The [PTY scenarios](../../../tui-pty-e2e/tests/host_attach.rs) + exercise the complete host, multiple terminals, and dropped or silently + stalled TCP connections. + +Created and maintained by Nori. diff --git a/nori-rs/tui/src/attach/input.rs b/nori-rs/tui/src/attach/input.rs new file mode 100644 index 000000000..98a9b6b42 --- /dev/null +++ b/nori-rs/tui/src/attach/input.rs @@ -0,0 +1,261 @@ +//! Input belongs to this attachment; mutations require the current control role. + +use crossterm::event::KeyCode; +use crossterm::event::KeyEvent; +use crossterm::event::KeyEventKind; +use crossterm::event::KeyModifiers; +use nori_protocol::acp::v1 as acp; +use nori_tui_components::PickerAction; +use nori_tui_components::PickerOutcome; +use serde_json::json; + +use super::runtime::Pending; +use super::runtime::Runtime; + +impl Runtime { + /// False means detach. It never requests host or session shutdown. + pub fn key(&mut self, key: KeyEvent) -> bool { + if key.kind == KeyEventKind::Release { + return true; + } + if key.code == KeyCode::Char('d') && key.modifiers.contains(KeyModifiers::CONTROL) { + return false; + } + if crate::nori::hotkey_match::matches_binding(&self.session_list_binding, &key) { + self.state.list_open = !self.state.list_open; + self.refresh_list(); + return true; + } + if key.modifiers.contains(KeyModifiers::ALT) && key.code == KeyCode::Char('t') { + if self.state.connected { + self.send("_nori/control/take", json!({}), Pending::TakeControl); + } else { + self.state + .show_notice("Reconnecting. Take control after the connection is restored."); + } + return true; + } + if key.code == KeyCode::Esc { + if self.state.list_open && self.state.picker.search_active { + self.state.picker.handle(PickerAction::ClearQuery); + self.state.picker.handle(PickerAction::DeactivateSearch); + } else { + self.state.list_open = false; + self.state.notice = None; + } + return true; + } + if key.code == KeyCode::Left && key.modifiers.is_empty() && self.composer.is_empty() { + self.state.list_open = true; + self.refresh_list(); + return true; + } + if self.state.list_open + && key.code == KeyCode::Char('r') + && key.modifiers.contains(KeyModifiers::CONTROL) + { + if let Err(error) = self.require_mutation() { + self.state.show_notice(error.to_string()); + } else if let Some(item) = self.state.picker.selected_item() { + let id = item.key.clone(); + if self.state.sessions.iter().any(|row| { + row.session_id == id && row.status == nori_protocol::SessionStatus::Failed + }) { + self.send( + "_nori/session/resume", + json!({"session_id":id}), + Pending::Mutation { draft: None }, + ); + } else { + self.state + .show_notice("Only failed sessions can be resumed."); + } + } + return true; + } + if self.state.list_open && self.picker_key(key) { + return true; + } + if self.composer.is_empty() && !self.state.list_open && self.permission_key(key) { + return true; + } + if key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL) { + if self.composer.is_empty() { + self.submit("/cancel".into()); + } else { + self.composer.clear(); + } + return true; + } + match key.code { + KeyCode::PageUp => { + self.state.scroll = self.state.scroll.saturating_add(10); + return true; + } + KeyCode::PageDown => { + self.state.scroll = self.state.scroll.saturating_sub(10); + return true; + } + _ => {} + } + if let crate::ComposerAction::Submitted(text) = self.composer.input(key) { + return self.submit(text); + } + true + } + + fn picker_key(&mut self, key: KeyEvent) -> bool { + let action = match (key.code, key.modifiers) { + (KeyCode::Char('f'), KeyModifiers::CONTROL) => PickerAction::ActivateSearch, + (KeyCode::Up, _) => PickerAction::MoveUp, + (KeyCode::Down, _) => PickerAction::MoveDown, + (KeyCode::Enter, _) if self.composer.is_empty() => PickerAction::Submit, + (KeyCode::Backspace, _) if self.state.picker.search_active => PickerAction::Backspace, + (KeyCode::Char(character), KeyModifiers::NONE | KeyModifiers::SHIFT) + if self.state.picker.search_active => + { + PickerAction::AppendQuery(character) + } + _ => return false, + }; + if let PickerOutcome::Selected(id) = self.state.picker.handle(action) { + self.state.selected = Some(id); + self.state.list_open = false; + self.state.scroll = 0; + self.state.notice = None; + self.state.replay_error = None; + self.subscribe_selected(); + } + true + } + + fn permission_key(&mut self, key: KeyEvent) -> bool { + let Some(id) = self.state.selected.clone() else { + return false; + }; + let Some(permission) = self + .state + .conversations + .get_mut(&id) + .and_then(|conversation| conversation.permissions.first_mut()) + else { + return false; + }; + let selected = match key.code { + KeyCode::Up => { + permission.selected = permission.selected.saturating_sub(1); + return true; + } + KeyCode::Down => { + permission.selected = + (permission.selected + 1).min(permission.options.len().saturating_sub(1)); + return true; + } + KeyCode::Enter => permission.selected, + KeyCode::Char(character @ '1'..='9') if key.modifiers.is_empty() => { + usize::try_from(character.to_digit(10).unwrap_or(1)).unwrap_or(1) - 1 + } + _ => return false, + }; + let Some(option) = permission.options.get(selected) else { + return true; + }; + let request_id = permission.request_id.clone(); + let option_id = option.option_id.clone(); + if let Err(error) = self.require_mutation() { + self.state.show_notice(error.to_string()); + return true; + } + let response = acp::RequestPermissionResponse::new( + acp::RequestPermissionOutcome::Selected(acp::SelectedPermissionOutcome::new(option_id)), + ); + self.send( + "_nori/session/respond", + json!({"session_id":id, "request_id":request_id, "response":response}), + Pending::Mutation { draft: None }, + ); + true + } + + fn require_mutation(&self) -> anyhow::Result<()> { + if let Some(reason) = &self.state.stopped { + anyhow::bail!("{reason}"); + } + anyhow::ensure!( + self.state.connected, + "Reconnecting. Your draft is preserved; send it after the connection is restored." + ); + self.state.require_control()?; + anyhow::ensure!( + self.state.replay_error.is_none(), + "Session history has a replay gap. Resolve it before sending more work." + ); + Ok(()) + } + + fn submit(&mut self, text: String) -> bool { + let command = text.trim(); + if matches!(command, "/quit" | "/exit" | "/detach") { + return false; + } + if command == "/sessions" { + self.state.list_open = true; + self.refresh_list(); + return true; + } + if command.is_empty() { + return true; + } + if let Err(error) = self.require_mutation() { + self.composer.handle_paste(text); + self.state.show_notice(error.to_string()); + return true; + } + self.state.notice = None; + if command == "/new" || command.starts_with("/new ") { + let agent = command + .strip_prefix("/new ") + .map(str::trim) + .filter(|agent| !agent.is_empty()); + self.send( + "_nori/session/new", + agent.map_or_else(|| json!({}), |agent| json!({"agent":agent})), + Pending::New, + ); + return true; + } + let Some(id) = self.state.selected.clone() else { + self.composer.handle_paste(text); + self.state + .show_notice("Choose a session with /sessions or start one with /new."); + return true; + }; + let method = match command { + "/close" => Some("_nori/session/close"), + "/cancel" => Some("_nori/session/cancel"), + "/resume" => Some("_nori/session/resume"), + _ => None, + }; + if let Some(method) = method { + self.send( + method, + json!({"session_id":id}), + Pending::Mutation { draft: None }, + ); + } else { + match self.state.prompt(&id, &text) { + Ok(params) => self.send( + "_nori/session/prompt", + params, + Pending::Mutation { draft: Some(text) }, + ), + Err(error) => { + self.composer.handle_paste(text); + self.state.show_notice(error.to_string()); + } + } + } + self.state.scroll = 0; + true + } +} diff --git a/nori-rs/tui/src/attach/mod.rs b/nori-rs/tui/src/attach/mod.rs new file mode 100644 index 000000000..51f160ece --- /dev/null +++ b/nori-rs/tui/src/attach/mod.rs @@ -0,0 +1,105 @@ +//! A terminal attachment observes host-owned sessions without owning their lifetime. + +mod connection; +#[cfg(test)] +mod connection_tests; +mod input; +mod render; +mod runtime; +mod state; +#[cfg(test)] +mod tests; + +use nori_harness::remote_agent::ManagedClient; +use tokio_stream::StreamExt; + +/// Connection parameters resolved by the CLI before entering the terminal. +/// The token is deliberately excluded from Debug output. +pub struct AttachOptions { + pub endpoint: String, + pub token: String, + pub session_id: Option, + /// Secure local discovery only; explicit remote credentials are never refreshed. + pub refresh_local_token: Option anyhow::Result + Send + Sync>>, +} + +/// Attach to an existing host. Leaving this frontend never stops host sessions. +pub async fn run_attach( + config: nori_config::NoriConfig, + options: AttachOptions, +) -> anyhow::Result<()> { + anyhow::ensure!( + config.multi_session, + "nori attach requires [features] multi_session = true" + ); + let initial = ManagedClient::connect(&options.endpoint, &options.token).await?; + let mut tui = crate::tui::Tui::new(crate::tui::init()?); + let result = async { + tui.enter_alt_screen()?; + run(&mut tui, options, initial, config.hotkeys.open_session_list).await + } + .await; + let leave = tui.leave_alt_screen(); + let restore = crate::tui::restore(); + result?; + leave?; + restore?; + Ok(()) +} + +async fn run( + tui: &mut crate::tui::Tui, + options: AttachOptions, + initial: ManagedClient, + session_list_binding: nori_config::HotkeyBinding, +) -> anyhow::Result<()> { + let (request_tx, request_rx) = tokio::sync::mpsc::unbounded_channel(); + let (event_tx, mut event_rx) = tokio::sync::mpsc::unbounded_channel(); + let mut runtime = runtime::Runtime::new(options.session_id.clone(), request_tx); + runtime.set_session_list_binding(session_list_binding); + let connection = tokio::spawn(connection::drive(options, initial, request_rx, event_tx)); + let mut events = tui.event_stream(); + let mut refresh = tokio::time::interval(std::time::Duration::from_secs(1)); + let result = async { + loop { + tokio::select! { + incoming = event_rx.recv(), if runtime.state.stopped.is_none() => { + let Some(incoming) = incoming else { anyhow::bail!("Host connection worker stopped"); }; + if let Err(error) = runtime.connection_event(incoming) { + runtime.state.show_notice(error.to_string()); + } + if runtime.state.stopped.is_some() { + connection.abort(); + } + } + event = events.next() => { + match event { + Some(crate::tui::TuiEvent::Key(key)) => { + if !runtime.key(key) { break; } + } + Some(crate::tui::TuiEvent::Paste(text)) => { runtime.composer.handle_paste(text); } + Some(crate::tui::TuiEvent::Draw) => {} + None => break, + } + } + _ = refresh.tick() => runtime.refresh_list(), + } + runtime.composer.flush_paste_burst_if_due(); + let height = tui.terminal.size()?.height; + tui.draw(height, |frame| { + let area = frame.area(); + render::render(&runtime.state, &runtime.composer, area, frame.buffer_mut()); + if let Some(position) = runtime.composer.cursor_pos(render::composer_area(&runtime.state, &runtime.composer, area)) { + frame.set_cursor_position(position); + } + })?; + if runtime.composer.is_in_paste_burst() { + tui.frame_requester().schedule_frame_in(crate::ComposerInput::recommended_flush_delay()); + } + } + Ok(()) + }.await; + connection.abort(); + let _ = connection.await; + result +} diff --git a/nori-rs/tui/src/attach/render.rs b/nori-rs/tui/src/attach/render.rs new file mode 100644 index 000000000..f626a443f --- /dev/null +++ b/nori-rs/tui/src/attach/render.rs @@ -0,0 +1,253 @@ +//! Terminal views shared by live attachments and snapshot tests. + +use nori_tui_components::KeyHint; +use nori_tui_components::Picker; +use nori_tui_components::PickerDensity; +use ratatui::buffer::Buffer; +use ratatui::layout::Rect; +use ratatui::style::Stylize; +use ratatui::text::Line; +use ratatui::widgets::Paragraph; +use ratatui::widgets::Widget; + +use super::state::AttachState; +use super::state::Part; +use crate::history_cell::HistoryCell; +use crate::presentation::MessageStream; + +pub(super) fn composer_area( + state: &AttachState, + composer: &crate::ComposerInput, + area: Rect, +) -> Rect { + let reserved = u16::try_from(notice_lines(state, area.width).len()) + .unwrap_or(u16::MAX) + .min(area.height.saturating_sub(6)); + let height = composer + .desired_height(area.width) + .max(3) + .min(area.height.saturating_sub(3 + reserved)); + Rect::new( + area.x, + area.bottom().saturating_sub(height), + area.width, + height, + ) +} + +pub(super) fn render( + state: &AttachState, + composer: &crate::ComposerInput, + area: Rect, + buf: &mut Buffer, +) { + if area.height < 4 || area.width < 12 { + return; + } + let mut header = vec![" Nori host ".bold()]; + if state.stopped.is_some() { + header.push("DISCONNECTED · ctrl+d to detach".red()); + } else if state.connected { + header.push(if state.watching { + state.role_label().cyan() + } else { + state.role_label().green() + }); + } else { + header.push("RECONNECTING · sessions continue on the host".cyan()); + } + Line::from(header).render(Rect::new(area.x, area.y, area.width, 1), buf); + let identity = state + .selected + .as_ref() + .map(|id| { + let row = state.sessions.iter().find(|row| &row.session_id == id); + format!( + " {} · {} · {}", + row.map_or("session", |row| row.agent.as_str()), + id, + row.map_or("", |row| crate::session_status::status_label(row.status)) + ) + }) + .unwrap_or_else(|| " Sessions · /new starts a session · ctrl+d detaches".into()); + Line::from(identity.dim()).render(Rect::new(area.x, area.y + 1, area.width, 1), buf); + let input = composer_area(state, composer, area); + let notice_lines = notice_lines(state, area.width); + let notice_height = u16::try_from(notice_lines.len()) + .unwrap_or(u16::MAX) + .min(input.y.saturating_sub(area.y + 3)); + let body = Rect::new( + area.x, + area.y + 3, + area.width, + input.y.saturating_sub(area.y + 3 + notice_height), + ); + Paragraph::new(notice_lines).render( + Rect::new( + area.x, + input.y.saturating_sub(notice_height), + area.width, + notice_height, + ), + buf, + ); + if state.list_open { + if state.sessions.is_empty() { + Paragraph::new(vec![ + Line::from(" Sessions 0".bold()), + Line::default(), + Line::from(" No sessions yet. Type /new and press Enter."), + Line::from(" The host keeps running when you detach.".dim()), + ]) + .render(body, buf); + } else { + Picker::new(&state.picker) + .theme(crate::style::component_theme()) + .density(PickerDensity::Compact) + .show_details(false) + .fullscreen_selection_rails(true) + .footer_hints([ + KeyHint::new("↑↓", "move"), + KeyHint::new("enter", "open"), + KeyHint::new("ctrl+r", "resume"), + KeyHint::new("ctrl+f", "search"), + KeyHint::new("esc", "back"), + ]) + .render(body, buf); + } + } else if let Some(id) = &state.selected { + render_conversation(state, id, body, buf); + } else { + Paragraph::new(" No session selected. Use /sessions to browse or /new to start.") + .render(body, buf); + } + composer.render_ref(input, buf); +} + +fn notice_lines(state: &AttachState, width: u16) -> Vec> { + state + .stopped + .as_ref() + .or(state.replay_error.as_ref()) + .or(state.notice.as_ref()) + .map(|notice| { + crate::wrapping::word_wrap_lines( + [Line::from(format!(" {notice}").red())], + usize::from(width), + ) + }) + .unwrap_or_default() +} + +fn render_conversation(state: &AttachState, id: &str, area: Rect, buf: &mut Buffer) { + let Some(conversation) = state.conversations.get(id) else { + Paragraph::new(" Waiting for session history…").render(area, buf); + return; + }; + let permission = conversation.permissions.first(); + let permission_height = permission.map_or(0, |request| { + u16::try_from(request.options.len() + 4) + .unwrap_or(u16::MAX) + .min(area.height) + }); + let history_area = Rect::new( + area.x + 1, + area.y, + area.width.saturating_sub(2), + area.height.saturating_sub(permission_height), + ); + let mut lines = Vec::new(); + for part in &conversation.parts { + match part { + Part::Message { stream, text, .. } => { + match stream { + MessageStream::User => lines.push(Line::from("› You".bold())), + MessageStream::Reasoning => lines.push(Line::from("Thinking".dim())), + MessageStream::Answer => {} + } + crate::markdown::append_markdown_with_cwd( + text, + Some(usize::from(history_area.width)), + Some(&conversation.cwd), + &mut lines, + ); + } + Part::Tool(snapshot) => { + let cell = crate::client_tool_cell::ClientToolCell::new( + (**snapshot).clone(), + conversation.cwd.clone(), + false, + ); + lines.extend(cell.display_lines(history_area.width)); + } + Part::Plan(plan) => { + lines.push(Line::from("Plan".bold())); + for entry in &plan.entries { + let marker = match entry.status { + crate::presentation::PlanStatus::Completed => "✓", + crate::presentation::PlanStatus::InProgress => "›", + crate::presentation::PlanStatus::Pending => "·", + }; + lines.push(Line::from(format!("{marker} {}", entry.step))); + } + } + Part::Notice(notice) => { + lines.extend(crate::wrapping::word_wrap_lines( + [Line::from(notice.clone().cyan())], + usize::from(history_area.width), + )); + } + } + lines.push(Line::default()); + } + if state.transcript_text(id).is_empty() { + lines.push(Line::from("Ready. Send a prompt to begin.".dim())); + } + let start = lines + .len() + .saturating_sub(usize::from(history_area.height)) + .saturating_sub(state.scroll); + Paragraph::new( + lines + .into_iter() + .skip(start) + .take(usize::from(history_area.height)) + .collect::>(), + ) + .render(history_area, buf); + if let Some(permission) = permission { + let mut rows = vec![Line::from( + format!("Permission · {}", permission.title).bold(), + )]; + for (index, option) in permission.options.iter().enumerate() { + let prefix = if permission.selected == index { + "›" + } else { + " " + }; + rows.push(Line::from(vec![ + format!("{prefix} {} ", index + 1).green(), + option.name.clone().into(), + ])); + } + rows.push(Line::from(if state.watching { + "Watching · read-only · alt+t to take control".cyan() + } else { + "↑↓ choose · enter answer · number selects an option".dim() + })); + if state.permission_count(id) > 1 { + rows.push(Line::from( + format!("{} requests waiting", state.permission_count(id)).dim(), + )); + } + Paragraph::new(rows).render( + Rect::new( + area.x + 1, + area.bottom().saturating_sub(permission_height), + area.width.saturating_sub(2), + permission_height, + ), + buf, + ); + } +} diff --git a/nori-rs/tui/src/attach/runtime.rs b/nori-rs/tui/src/attach/runtime.rs new file mode 100644 index 000000000..5dfd29cfa --- /dev/null +++ b/nori-rs/tui/src/attach/runtime.rs @@ -0,0 +1,232 @@ +//! Correlation of managed requests with UI actions; notification ordering stays intact. + +use std::collections::HashMap; + +use serde_json::Value; +use serde_json::json; +use tokio::sync::mpsc; + +use super::connection::ConnectionEvent; +use super::state::AttachState; + +pub(super) enum Pending { + Initialize, + List, + Subscribe { session_id: String }, + New, + TakeControl, + Mutation { draft: Option }, +} + +pub(super) struct Runtime { + pub state: AttachState, + pub composer: crate::ComposerInput, + requests: mpsc::UnboundedSender, + pending: HashMap, + next_id: i64, + uncertain_delivery: bool, + pub session_list_binding: nori_config::HotkeyBinding, +} + +impl Runtime { + pub fn set_session_list_binding(&mut self, binding: nori_config::HotkeyBinding) { + self.session_list_binding = binding; + self.composer.set_hint_items(vec![ + (self.session_list_binding.as_str(), "sessions"), + ("alt+t", "take control"), + ("ctrl+d", "detach"), + ("/new", "new session"), + ]); + } + + pub fn new(selected: Option, requests: mpsc::UnboundedSender) -> Self { + let mut composer = crate::ComposerInput::for_attachment(); + composer.set_hint_items(vec![ + ("alt+s", "sessions"), + ("alt+t", "take control"), + ("ctrl+d", "detach"), + ("/new", "new session"), + ]); + Self { + state: AttachState { + list_open: selected.is_none(), + selected, + ..Default::default() + }, + composer, + requests, + pending: HashMap::new(), + next_id: 0, + uncertain_delivery: false, + session_list_binding: nori_config::HotkeyConfig::default().open_session_list, + } + } + + pub fn send(&mut self, method: &str, params: Value, pending: Pending) { + if self.state.stopped.is_some() { + return; + } + self.next_id += 1; + let id = self.next_id; + self.pending.insert(id, pending); + if self + .requests + .send(json!({"jsonrpc":"2.0", "id":id, "method":method, "params":params})) + .is_err() + { + self.state + .show_notice("Host connection worker stopped. Detach and try again."); + } + } + + pub fn refresh_list(&mut self) { + if self.state.connected + && !self + .pending + .values() + .any(|pending| matches!(pending, Pending::List)) + { + self.send("_nori/session/list", json!({}), Pending::List); + } + } + + pub fn subscribe_selected(&mut self) { + if let Some(id) = self.state.selected.clone() { + let cursor = self.state.cursors.get(&id).copied().unwrap_or(0); + self.send( + "_nori/session/subscribe", + json!({"session_id":id, "cursors":{id.clone():cursor}}), + Pending::Subscribe { session_id: id }, + ); + } + } + + pub fn connection_event(&mut self, event: ConnectionEvent) -> anyhow::Result<()> { + match event { + ConnectionEvent::Stopped(reason) => { + self.state.connected = false; + self.state.stopped = Some(reason); + self.pending.clear(); + } + ConnectionEvent::Connected => { + self.send("initialize", json!({}), Pending::Initialize); + } + ConnectionEvent::Disconnected(reason) => { + self.state.connected = false; + let uncertain = self + .pending + .values() + .any(|pending| matches!(pending, Pending::New | Pending::Mutation { .. })); + self.uncertain_delivery |= uncertain; + self.pending.clear(); + self.state.show_notice(if uncertain { + "Connection lost. A request may have reached the host; it will not be retried. Check the conversation after reconnecting.".to_string() + } else { + format!("Connection lost. Reconnecting… {reason}") + }); + } + ConnectionEvent::Message(message) => self.message(message)?, + } + Ok(()) + } + + fn message(&mut self, message: Value) -> anyhow::Result<()> { + match message["method"].as_str() { + Some("_nori/session/event") => { + if self.state.replay_error.is_none() + && let Err(error) = self + .state + .apply(serde_json::from_value(message["params"].clone())?) + { + self.state.replay_error = Some(error.to_string()); + } + return Ok(()); + } + Some("_nori/control/changed") => { + let role = message["params"]["role"].as_str().unwrap_or("watcher"); + self.state.role_changed(role); + self.state.show_notice(if self.state.watching { + "Control moved to another terminal. You are now watching; alt+t takes control." + } else { + "You now control the host. Other terminals can keep watching." + }); + return Ok(()); + } + _ => {} + } + let Some(id) = message["id"].as_i64() else { + return Ok(()); + }; + let Some(pending) = self.pending.remove(&id) else { + return Ok(()); + }; + if let Some(error) = message.get("error") { + let text = error["message"] + .as_str() + .unwrap_or("Host request failed") + .to_string(); + if matches!(pending, Pending::Initialize) { + self.state.connected = false; + self.state.stopped = Some(format!( + "Host initialization failed: {text}. Re-run nori attach." + )); + self.pending.clear(); + } + if let Pending::Subscribe { session_id } = &pending { + if self.state.selected.as_ref() != Some(session_id) { + return Ok(()); + } + self.state.replay_error = Some(format!( + "Replay unavailable: {text}. Existing conversation retained." + )); + } + if let Pending::Mutation { draft: Some(draft) } = &pending + && self.composer.is_empty() + { + self.composer.handle_paste(draft.clone()); + } + self.state.show_notice(text); + return Ok(()); + } + let result = &message["result"]; + match pending { + Pending::Initialize => { + self.state + .role_changed(result["control"]["role"].as_str().unwrap_or("watcher")); + self.state.connected = true; + self.state.notice = self.uncertain_delivery.then(|| "Connection restored. A previous request may have reached the host and was not retried; check the conversation before submitting again.".into()); + self.refresh_list(); + self.subscribe_selected(); + } + Pending::List => { + self.state.replace_sessions(result.clone())?; + if let Some(id) = &self.state.selected + && !self.state.sessions.iter().any(|row| &row.session_id == id) + { + self.state.notice = Some(format!( + "Session {id} is not on this host. Choose one from the list." + )); + self.state.list_open = true; + } + } + Pending::New => { + let id = result["session_id"] + .as_str() + .ok_or_else(|| anyhow::anyhow!("Host did not return the new session ID"))?; + self.state.selected = Some(id.into()); + self.state.list_open = false; + self.state.scroll = 0; + self.state.notice = None; + self.state.replay_error = None; + self.subscribe_selected(); + self.refresh_list(); + } + Pending::TakeControl => { + self.state + .role_changed(result["role"].as_str().unwrap_or("watcher")); + } + Pending::Subscribe { .. } | Pending::Mutation { .. } => self.refresh_list(), + } + Ok(()) + } +} diff --git a/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_current_session_id.snap b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_current_session_id.snap new file mode 100644 index 000000000..ed641d376 --- /dev/null +++ b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_current_session_id.snap @@ -0,0 +1,22 @@ +--- +source: tui/src/attach/tests.rs +assertion_line: 372 +expression: rendered +--- + Nori host WATCHING · read-only · alt+t take control + mock-model · abcd1234-session · ready + + + Sessions 1 + + ID AGENT STATUS AGE TITLE + ▏ abcd1234 mock-model ready 2m (current) Review parser ▕ + + + + + + ↑↓ move enter open ctrl+r resume ctrl+f search esc back + + +› Send a prompt diff --git a/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_empty_controller.snap b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_empty_controller.snap new file mode 100644 index 000000000..f7f2e67ff --- /dev/null +++ b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_empty_controller.snap @@ -0,0 +1,21 @@ +--- +source: tui/src/attach/tests.rs +expression: controlling +--- + Nori host CONTROLLING + Sessions · /new starts a session · ctrl+d detaches + + Sessions 0 + + No sessions yet. Type /new and press Enter. + The host keeps running when you detach. + + + + + + + + + +› Send a prompt diff --git a/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_host_restarted.snap b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_host_restarted.snap new file mode 100644 index 000000000..82950bad4 --- /dev/null +++ b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_host_restarted.snap @@ -0,0 +1,22 @@ +--- +source: tui/src/attach/tests.rs +assertion_line: 398 +expression: rendered +--- + Nori host DISCONNECTED · ctrl+d to detach + session · one · + + Preserved history + + + + + + + + + + + Host restarted; sessions were lost. Re-run nori attach. + +› Send a prompt diff --git a/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_host_restarted_with_draft.snap b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_host_restarted_with_draft.snap new file mode 100644 index 000000000..910e60b38 --- /dev/null +++ b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_host_restarted_with_draft.snap @@ -0,0 +1,21 @@ +--- +source: tui/src/attach/tests.rs +assertion_line: 416 +expression: rendered +--- + Nori host DISCONNECTED · ctrl+d to detach + Sessions · /new starts a session · ctrl+d detaches + + Host restarted; sessions were lost. Re-run nori attach. + +› Preserved draft line + Preserved draft line + Preserved draft line + Preserved draft line + Preserved draft line + Preserved draft line + Preserved draft line + Preserved draft line + Preserved draft line + Preserved draft line + Preserved draft line diff --git a/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_host_sessions.snap b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_host_sessions.snap new file mode 100644 index 000000000..ef9a9a3d3 --- /dev/null +++ b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_host_sessions.snap @@ -0,0 +1,21 @@ +--- +source: tui/src/attach/tests.rs +expression: rendered +--- + Nori host CONTROLLING + Sessions · /new starts a session · ctrl+d detaches + + + Sessions 2 + + ID AGENT STATUS AGE TITLE + ▏ session- mock-model ready 2m Review the parser ▕ + session- other-agent waiting on you 1m Update tests + + + + + ↑↓ move enter open ctrl+r resume ctrl+f search esc back + + +› Send a prompt diff --git a/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_permission_controller.snap b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_permission_controller.snap new file mode 100644 index 000000000..8c5f1ee5b --- /dev/null +++ b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_permission_controller.snap @@ -0,0 +1,21 @@ +--- +source: tui/src/attach/tests.rs +expression: screen(&state) +--- + Nori host CONTROLLING + session · one · + + Ready. Send a prompt to begin. + + + + + + + Permission · Write a file + › 1 Allow once + ↑↓ choose · enter answer · number selects an option + + + +› Send a prompt diff --git a/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_permission_watcher.snap b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_permission_watcher.snap new file mode 100644 index 000000000..ddc5ceb78 --- /dev/null +++ b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_permission_watcher.snap @@ -0,0 +1,21 @@ +--- +source: tui/src/attach/tests.rs +expression: screen(&state) +--- + Nori host WATCHING · read-only · alt+t take control + session · one · + + Ready. Send a prompt to begin. + + + + + + + Permission · Write a file + › 1 Allow once + Watching · read-only · alt+t to take control + + + +› Send a prompt diff --git a/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_reconnecting.snap b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_reconnecting.snap new file mode 100644 index 000000000..35ce755c5 --- /dev/null +++ b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_reconnecting.snap @@ -0,0 +1,21 @@ +--- +source: tui/src/attach/tests.rs +expression: reconnecting +--- + Nori host RECONNECTING · sessions continue on the host + Sessions · /new starts a session · ctrl+d detaches + + Sessions 0 + + No sessions yet. Type /new and press Enter. + The host keeps running when you detach. + + + + + + + + + +› Send a prompt diff --git a/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_watcher.snap b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_watcher.snap new file mode 100644 index 000000000..6140e0429 --- /dev/null +++ b/nori-rs/tui/src/attach/snapshots/nori_tui__attach__tests__attached_watcher.snap @@ -0,0 +1,21 @@ +--- +source: tui/src/attach/tests.rs +expression: watching +--- + Nori host WATCHING · read-only · alt+t take control + Sessions · /new starts a session · ctrl+d detaches + + Sessions 0 + + No sessions yet. Type /new and press Enter. + The host keeps running when you detach. + + + + + + + + + +› Send a prompt diff --git a/nori-rs/tui/src/attach/state.rs b/nori-rs/tui/src/attach/state.rs new file mode 100644 index 000000000..a8af1320b --- /dev/null +++ b/nori-rs/tui/src/attach/state.rs @@ -0,0 +1,361 @@ +//! Source-first reduction of host envelopes into presentation owned by this terminal. + +use std::collections::HashMap; + +use nori_protocol::AcpEvent; +use nori_protocol::NoriEvent; +use nori_protocol::SessionEnvelope; +use nori_protocol::SessionEvent; +use nori_protocol::SessionStatus; +use nori_protocol::acp::v1 as acp; +use nori_tui_components::PickerColumn; +use nori_tui_components::PickerItem; +use nori_tui_components::PickerState; +use serde::Deserialize; +use serde_json::Value; +use serde_json::json; + +use crate::presentation::ClientEvent; +use crate::presentation::ClientEventNormalizer; +use crate::presentation::MessageStream; +use crate::presentation::PlanSnapshot; +use crate::presentation::ToolSnapshot; + +pub(super) const READ_ONLY: &str = + "Read-only: take control with alt+t before sending prompts or permission answers."; + +#[derive(Clone, Deserialize)] +pub(super) struct SessionRow { + pub session_id: String, + pub agent: String, + pub status: SessionStatus, + pub title: Option, + #[serde(default)] + pub age_seconds: i64, +} + +pub(super) enum Part { + Message { + stream: MessageStream, + id: Option, + text: String, + }, + Tool(Box), + Plan(PlanSnapshot), + Notice(String), +} + +pub(super) struct Permission { + pub request_id: acp::RequestId, + pub title: String, + pub options: Vec, + pub selected: usize, +} + +#[derive(Default)] +pub(super) struct Conversation { + pub parts: Vec, + pub permissions: Vec, + pub cwd: std::path::PathBuf, + normalizer: ClientEventNormalizer, + message_boundary: bool, +} + +pub(super) struct AttachState { + pub cursors: HashMap, + pub conversations: HashMap, + pub sessions: Vec, + pub picker: PickerState, + pub watching: bool, + pub connected: bool, + pub stopped: Option, + pub selected: Option, + pub list_open: bool, + pub notice: Option, + pub replay_error: Option, + pub scroll: usize, +} + +impl Default for AttachState { + fn default() -> Self { + Self { + cursors: HashMap::new(), + conversations: HashMap::new(), + sessions: Vec::new(), + picker: PickerState::new( + "Sessions", + [ + PickerColumn::fixed("id", "ID", 8).hide_below(65), + PickerColumn::fixed("agent", "AGENT", 14).hide_below(55), + PickerColumn::fixed("status", "STATUS", 16), + PickerColumn::fixed("age", "AGE", 5).hide_below(45), + PickerColumn::flexible("title", "TITLE"), + ], + Vec::new(), + ) + .search_placeholder("Title or agent"), + watching: true, + connected: false, + stopped: None, + selected: None, + list_open: true, + notice: None, + replay_error: None, + scroll: 0, + } + } +} + +impl AttachState { + pub fn replace_sessions(&mut self, value: Value) -> anyhow::Result<()> { + self.sessions = serde_json::from_value(value["sessions"].clone())?; + self.picker.title = format!("Sessions {}", self.sessions.len()); + self.picker.replace_items(self.sessions.iter().map(|row| { + let seconds = row.age_seconds.max(0); + let age = if seconds < 60 { + format!("{seconds}s") + } else if seconds < 3600 { + format!("{}m", seconds / 60) + } else { + format!("{}h", seconds / 3600) + }; + let title = row.title.clone().unwrap_or_else(|| "New session".into()); + let title = if self.selected.as_ref() == Some(&row.session_id) { + format!("(current) {title}") + } else { + title + }; + PickerItem::new(row.session_id.clone(), "title", title) + .cell("id", row.session_id.chars().take(8).collect::()) + .cell("agent", row.agent.clone()) + .cell("status", crate::session_status::status_label(row.status)) + .cell("age", age) + .search_text(format!( + "{} {} {}", + row.title.as_deref().unwrap_or_default(), + row.agent, + row.session_id + )) + })); + Ok(()) + } + + /// Plain text also distinguishes an empty transcript before its cells have + /// been laid out at the current terminal width. + pub fn transcript_text(&self, id: &str) -> String { + self.conversations + .get(id) + .map(|conversation| { + conversation + .parts + .iter() + .map(|part| match part { + Part::Message { text, .. } | Part::Notice(text) => text.clone(), + Part::Tool(tool) => tool.title.clone(), + Part::Plan(plan) => plan + .entries + .iter() + .map(|step| step.step.clone()) + .collect::>() + .join("\n"), + }) + .collect::>() + .join("\n\n") + }) + .unwrap_or_default() + } + + pub fn permission_count(&self, id: &str) -> usize { + self.conversations + .get(id) + .map_or(0, |conversation| conversation.permissions.len()) + } + + pub fn role_label(&self) -> &'static str { + if self.watching { + "WATCHING · read-only · alt+t take control" + } else { + "CONTROLLING" + } + } + + pub fn role_changed(&mut self, role: &str) { + self.watching = role != "controller"; + } + + pub fn require_control(&self) -> anyhow::Result<()> { + anyhow::ensure!(!self.watching, READ_ONLY); + Ok(()) + } + + pub fn prompt(&self, id: &str, text: &str) -> anyhow::Result { + self.require_control()?; + Ok(json!({"session_id":id,"prompt":[{"type":"text","text":text}]})) + } + + pub fn show_notice(&mut self, message: impl Into) { + if self.stopped.is_some() { + return; + } + let message = message.into(); + self.notice = Some(message.clone()); + if let Some(id) = &self.selected { + self.conversations + .entry(id.clone()) + .or_default() + .parts + .push(Part::Notice(message)); + } + } + + pub fn apply(&mut self, envelope: SessionEnvelope) -> anyhow::Result<()> { + let last = self + .cursors + .get(&envelope.conversation_id) + .copied() + .unwrap_or(0); + if envelope.seq <= last { + return Ok(()); + } + anyhow::ensure!( + envelope.seq == last + 1, + "Replay gap for {}: expected event {}, received {}. Existing conversation retained; detach to investigate.", + envelope.conversation_id, + last + 1, + envelope.seq + ); + let conversation = self + .conversations + .entry(envelope.conversation_id.clone()) + .or_default(); + match envelope.event { + SessionEvent::Acp(AcpEvent::Notification( + acp::AgentNotification::SessionNotification(notification), + )) => { + for event in conversation + .normalizer + .push_session_update(¬ification.update) + { + conversation.apply_presentation(event); + } + } + SessionEvent::Acp(AcpEvent::Request { + request_id, + request: acp::AgentRequest::RequestPermissionRequest(request), + }) => { + let title = conversation + .normalizer + .push_permission_request(&request) + .into_iter() + .find_map(|event| { + if let ClientEvent::ApprovalRequest(approval) = event { + Some(approval.title) + } else { + None + } + }) + .unwrap_or_else(|| "Permission requested".into()); + conversation.permissions.push(Permission { + request_id, + title, + options: request.options, + selected: 0, + }); + conversation.message_boundary = true; + } + SessionEvent::Acp(AcpEvent::Response { + response: Err(error), + .. + }) => { + conversation.parts.push(Part::Notice(error.message)); + conversation.message_boundary = true; + } + SessionEvent::Nori(NoriEvent::SessionStarted(started)) => { + conversation.cwd = started.cwd + } + SessionEvent::Nori(NoriEvent::RequestResolved(resolved)) => { + conversation + .permissions + .retain(|permission| permission.request_id != resolved.request_id); + } + SessionEvent::Nori(NoriEvent::SessionEnded(ended)) => { + conversation + .parts + .push(Part::Notice(ended.message.unwrap_or_else(|| { + "Session ended. Use /new to start another session.".into() + }))); + conversation.permissions.clear(); + conversation.message_boundary = true; + } + SessionEvent::Nori(NoriEvent::Notice(notice)) => { + conversation.parts.push(Part::Notice(notice.message)) + } + SessionEvent::Nori(NoriEvent::RequestFailed(failed)) => { + conversation.parts.push(Part::Notice(failed.message)); + conversation.message_boundary = true; + } + SessionEvent::Nori(NoriEvent::SessionPhaseChanged(phase)) => { + if matches!( + phase, + nori_protocol::SessionPhase::Idle + | nori_protocol::SessionPhase::Cancelling { .. } + ) { + conversation.permissions.clear(); + } + conversation.message_boundary = true; + } + SessionEvent::Nori(NoriEvent::ReplayStarted(_)) => { + // A restored transcript replaces presentation; transport replay + // alone does not emit this marker and is deduplicated by seq. + *conversation = Conversation { + cwd: conversation.cwd.clone(), + ..Default::default() + }; + } + SessionEvent::Nori(NoriEvent::ReplayFinished) => conversation.message_boundary = true, + // Unprojected metadata consumes its sequence too, preserving the + // complete wire ordering without inventing presentation events. + _ => {} + } + self.cursors.insert(envelope.conversation_id, envelope.seq); + Ok(()) + } +} + +impl Conversation { + fn apply_presentation(&mut self, event: ClientEvent) { + match event { + ClientEvent::MessageDelta(delta) => { + if !self.message_boundary + && let Some(Part::Message { stream, id, text }) = self.parts.last_mut() + && *stream == delta.stream + && *id == delta.message_id + { + text.push_str(&delta.delta); + } else { + self.parts.push(Part::Message { + stream: delta.stream, + id: delta.message_id, + text: delta.delta, + }); + } + self.message_boundary = false; + } + ClientEvent::ToolSnapshot(snapshot) => { + if let Some(Part::Tool(previous)) = self.parts.iter_mut().find( + |part| matches!(part, Part::Tool(tool) if tool.call_id == snapshot.call_id), + ) { + *previous = Box::new(snapshot); + } else { + self.parts.push(Part::Tool(Box::new(snapshot))); + } + self.message_boundary = true; + } + ClientEvent::PlanSnapshot(plan) => { + self.parts.push(Part::Plan(plan)); + self.message_boundary = true; + } + _ => {} + } + } +} diff --git a/nori-rs/tui/src/attach/tests.rs b/nori-rs/tui/src/attach/tests.rs new file mode 100644 index 000000000..d7dd71a0f --- /dev/null +++ b/nori-rs/tui/src/attach/tests.rs @@ -0,0 +1,431 @@ +use nori_protocol::SessionEnvelope; +use pretty_assertions::assert_eq; +use serde_json::json; + +use super::state::AttachState; + +fn message(session: &str, seq: i64, text: &str) -> SessionEnvelope { + use nori_protocol::acp::v1 as acp; + let chunk = acp::ContentChunk::new(acp::ContentBlock::Text(acp::TextContent::new(text))) + .message_id("answer"); + let notification = acp::SessionNotification::new( + "agent-session", + acp::SessionUpdate::AgentMessageChunk(chunk), + ); + SessionEnvelope { + conversation_id: session.into(), + agent: "test-agent".into(), + seq, + event: nori_protocol::SessionEvent::Acp(nori_protocol::AcpEvent::Notification( + acp::AgentNotification::SessionNotification(notification), + )), + } +} + +#[test] +fn replay_continues_the_conversation_without_duplicate_chunks() { + let mut state = AttachState::default(); + state.apply(message("one", 1, "Hello ")).unwrap(); + state.apply(message("one", 1, "Hello ")).unwrap(); + state.apply(message("one", 2, "world")).unwrap(); + assert_eq!(state.transcript_text("one"), "Hello world"); + assert_eq!(state.cursors.get("one"), Some(&2)); +} + +#[test] +fn replay_gaps_are_visible_and_never_advance_the_cursor() { + let mut state = AttachState::default(); + state.apply(message("one", 1, "Hello")).unwrap(); + assert!(state.apply(message("one", 3, "lost middle")).is_err()); + assert_eq!(state.cursors.get("one"), Some(&1)); +} + +#[test] +fn watcher_cannot_submit_and_handoff_enables_the_same_draft() { + let mut state = AttachState::default(); + state.role_changed("watcher"); + assert!(state.prompt("one", "my draft").is_err()); + state.role_changed("controller"); + assert!(state.prompt("one", "my draft").is_ok()); + assert!( + state.transcript_text("one").is_empty(), + "only the host's canonical echo renders a prompt" + ); +} + +#[test] +fn independent_session_sequences_do_not_drop_each_others_events() { + let mut state = AttachState::default(); + state.apply(message("one", 1, "Alpha")).unwrap(); + state.apply(message("two", 1, "Beta")).unwrap(); + assert_eq!(state.cursors.get("one"), Some(&1)); + assert_eq!(state.cursors.get("two"), Some(&1)); + assert_eq!(state.transcript_text("one"), "Alpha"); + assert_eq!(state.transcript_text("two"), "Beta"); +} + +#[test] +fn unresolved_permission_replays_and_remote_answer_clears_it() { + use nori_protocol::acp::v1 as acp; + let mut state = AttachState::default(); + let request: acp::RequestPermissionRequest = serde_json::from_value(json!({ + "sessionId":"agent-session", "toolCall":{"toolCallId":"tool", "title":"Write a file"}, + "options":[{"optionId":"allow", "name":"Allow once", "kind":"allow_once"}] + })) + .unwrap(); + let request_id = acp::RequestId::Str("permission".into()); + state + .apply(SessionEnvelope { + conversation_id: "one".into(), + agent: "test-agent".into(), + seq: 1, + event: nori_protocol::SessionEvent::Acp(nori_protocol::AcpEvent::Request { + request_id: request_id.clone(), + request: acp::AgentRequest::RequestPermissionRequest(request), + }), + }) + .unwrap(); + assert_eq!(state.permission_count("one"), 1); + state.connected = true; + state.selected = Some("one".into()); + state.list_open = false; + state.role_changed("controller"); + insta::assert_snapshot!("attached_permission_controller", screen(&state)); + state.role_changed("watcher"); + insta::assert_snapshot!("attached_permission_watcher", screen(&state)); + state + .apply(SessionEnvelope { + conversation_id: "one".into(), + agent: "test-agent".into(), + seq: 2, + event: nori_protocol::SessionEvent::Nori(nori_protocol::NoriEvent::RequestResolved( + nori_protocol::RequestResolved { + request_id, + answered_by: "another controller".into(), + }, + )), + }) + .unwrap(); + assert_eq!(state.permission_count("one"), 0); +} + +fn screen(state: &AttachState) -> String { + screen_with_composer(state, &crate::ComposerInput::for_attachment()) +} + +fn screen_with_composer(state: &AttachState, composer: &crate::ComposerInput) -> String { + let area = ratatui::layout::Rect::new(0, 0, 90, 18); + let mut buffer = ratatui::buffer::Buffer::empty(area); + super::render::render(state, composer, area, &mut buffer); + (0..area.height) + .map(|y| { + (0..area.width) + .map(|x| buffer[(x, y)].symbol()) + .collect::() + .trim_end() + .to_string() + }) + .collect::>() + .join("\n") +} + +#[test] +fn attached_screens_identify_control_and_reconnection() { + let mut state = AttachState { + connected: true, + ..Default::default() + }; + state.role_changed("controller"); + let controlling = screen(&state); + assert!(controlling.contains("CONTROLLING"), "{controlling}"); + assert!( + controlling.contains("/new"), + "empty host must offer a way to start" + ); + insta::assert_snapshot!("attached_empty_controller", controlling); + state.role_changed("watcher"); + let watching = screen(&state); + assert!( + watching.contains("WATCHING") && watching.contains("read-only"), + "{watching}" + ); + insta::assert_snapshot!("attached_watcher", watching); + state.connected = false; + let reconnecting = screen(&state); + assert!(reconnecting.contains("RECONNECTING"), "{reconnecting}"); + insta::assert_snapshot!("attached_reconnecting", reconnecting); +} + +#[test] +fn host_session_list_renders_titles_agents_and_status() { + let mut state = AttachState { + connected: true, + ..Default::default() + }; + state.role_changed("controller"); + state.replace_sessions(json!({"sessions":[ + {"session_id":"session-alpha","agent":"mock-model","status":"ready","title":"Review the parser","age_seconds":120}, + {"session_id":"session-beta","agent":"other-agent","status":"waiting_on_you","title":"Update tests","age_seconds":60} + ]})).unwrap(); + let rendered = screen(&state); + assert!( + rendered.contains("Review the parser") && rendered.contains("waiting on you"), + "{rendered}" + ); + insta::assert_snapshot!("attached_host_sessions", rendered); +} + +#[test] +fn attachment_composer_submits_frontend_commands_as_text() { + for text in [ + "/new", + "/new custom-agent", + "/close", + "/resume", + "/cancel", + "/detach", + "/quit", + "/sessions", + ] { + let mut composer = crate::ComposerInput::for_attachment(); + composer.handle_paste(text.into()); + let action = composer.input(crossterm::event::KeyEvent::new( + crossterm::event::KeyCode::Enter, + crossterm::event::KeyModifiers::NONE, + )); + assert!( + matches!(action, crate::ComposerAction::Submitted(actual) if actual == text), + "{text} must reach the attachment frontend" + ); + } +} + +#[test] +fn resumed_transcript_replaces_the_existing_presentation_without_repeating_turns() { + let mut state = AttachState::default(); + state.apply(message("one", 1, "Original answer")).unwrap(); + let marker = |seq, event| SessionEnvelope { + conversation_id: "one".into(), + agent: "test-agent".into(), + seq, + event: nori_protocol::SessionEvent::Nori(event), + }; + state + .apply(marker( + 2, + nori_protocol::NoriEvent::SessionStarted(nori_protocol::SessionStarted { + transcript_id: Some("one".into()), + acp_session_id: "agent-session".into(), + cwd: "/tmp".into(), + transcript_path: None, + history_log_id: 0, + history_entry_count: 0, + config_options: vec![], + }), + )) + .unwrap(); + state + .apply(marker( + 3, + nori_protocol::NoriEvent::ReplayStarted(nori_protocol::ReplayStarted { + source: nori_protocol::ReplaySource::Agent, + }), + )) + .unwrap(); + state + .apply(marker( + 4, + nori_protocol::NoriEvent::ReplayStarted(nori_protocol::ReplayStarted { + source: nori_protocol::ReplaySource::Transcript, + }), + )) + .unwrap(); + state.apply(message("one", 5, "Original answer")).unwrap(); + state + .apply(marker(6, nori_protocol::NoriEvent::ReplayFinished)) + .unwrap(); + state.apply(message("one", 7, "New live answer")).unwrap(); + assert_eq!( + state.transcript_text("one"), + "Original answer\n\nNew live answer" + ); + assert_eq!(state.cursors.get("one"), Some(&7)); +} + +#[test] +fn failed_session_resume_hotkey_keeps_the_selected_host_identity() { + use crossterm::event::KeyCode; + use crossterm::event::KeyEvent; + use crossterm::event::KeyModifiers; + let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); + let mut runtime = super::runtime::Runtime::new(Some("running-other".into()), tx); + runtime.state.connected = true; + runtime.state.role_changed("controller"); + runtime.state.list_open = true; + runtime.state.replace_sessions(json!({"sessions":[{"session_id":"one","agent":"mock-model","status":"failed","title":"Recover this"}]})).unwrap(); + runtime.key(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL)); + let request = rx.try_recv().expect("Ctrl+R sends a host resume request"); + assert_eq!(request["method"], "_nori/session/resume"); + assert_eq!(request["params"]["session_id"], "one"); + runtime.state.list_open = false; + runtime.key(KeyEvent::new(KeyCode::Left, KeyModifiers::NONE)); + assert!( + screen(&runtime.state).contains("Recover this"), + "Left on an empty composer opens the session list" + ); +} + +#[test] +fn ending_or_cancelling_a_turn_removes_its_permission_choices() { + use nori_protocol::acp::v1 as acp; + for phase in [ + nori_protocol::SessionPhase::Idle, + nori_protocol::SessionPhase::Cancelling { + request_id: acp::RequestId::Str("turn".into()), + }, + ] { + let mut state = AttachState::default(); + let request = serde_json::from_value(json!({"sessionId":"agent-session", "toolCall":{"toolCallId":"tool","title":"Write"},"options":[{"optionId":"allow","name":"Allow","kind":"allow_once"}]})).unwrap(); + state + .apply(SessionEnvelope { + conversation_id: "one".into(), + agent: "test".into(), + seq: 1, + event: nori_protocol::SessionEvent::Acp(nori_protocol::AcpEvent::Request { + request_id: acp::RequestId::Str("permission".into()), + request: acp::AgentRequest::RequestPermissionRequest(request), + }), + }) + .unwrap(); + assert_eq!(state.permission_count("one"), 1); + state + .apply(SessionEnvelope { + conversation_id: "one".into(), + agent: "test".into(), + seq: 2, + event: nori_protocol::SessionEvent::Nori( + nori_protocol::NoriEvent::SessionPhaseChanged(phase), + ), + }) + .unwrap(); + assert_eq!(state.permission_count("one"), 0); + } +} + +#[test] +fn old_subscription_failure_does_not_block_the_new_selection() { + let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); + let mut runtime = super::runtime::Runtime::new(Some("expired".into()), tx); + runtime.state.connected = true; + runtime.state.role_changed("controller"); + runtime.subscribe_selected(); + let old = rx.try_recv().unwrap(); + runtime.state.selected = Some("healthy".into()); + runtime.subscribe_selected(); + runtime + .connection_event(super::connection::ConnectionEvent::Message(json!({ + "jsonrpc":"2.0", "id":old["id"], "error":{"code":-32000,"message":"Replay expired"} + }))) + .unwrap(); + assert!( + runtime.state.replay_error.is_none(), + "a previous selection must not block the healthy session" + ); + assert!( + runtime.state.notice.is_none(), + "the error belongs to the old selection" + ); +} + +#[test] +fn session_list_uses_the_configured_binding_instead_of_the_default() { + use crossterm::event::KeyCode; + use crossterm::event::KeyEvent; + use crossterm::event::KeyModifiers; + let (tx, _rx) = tokio::sync::mpsc::unbounded_channel(); + let mut runtime = super::runtime::Runtime::new(Some("one".into()), tx); + runtime.set_session_list_binding(nori_config::HotkeyBinding::from_str("alt+g")); + runtime.key(KeyEvent::new(KeyCode::Char('s'), KeyModifiers::ALT)); + assert!( + !runtime.state.list_open, + "rebound default must not open the list" + ); + runtime.key(KeyEvent::new(KeyCode::Char('g'), KeyModifiers::ALT)); + assert!(runtime.state.list_open, "configured binding opens the list"); +} + +#[test] +fn current_session_row_keeps_short_id_visible() { + let mut state = AttachState { + connected: true, + selected: Some("abcd1234-session".into()), + ..Default::default() + }; + state.replace_sessions(json!({"sessions":[ + {"session_id":"abcd1234-session","agent":"mock-model","status":"ready","title":"Review parser","age_seconds":120} + ]})).unwrap(); + let rendered = screen(&state); + let row = rendered + .lines() + .find(|line| line.contains("Review parser")) + .unwrap(); + assert!(row.contains("abcd1234"), "{rendered}"); + assert!(row.contains("current"), "{rendered}"); + insta::assert_snapshot!("attached_current_session_id", rendered); +} + +#[test] +fn terminal_connection_failure_remains_visible_and_blocks_requests() { + use super::connection::ConnectionEvent; + use super::runtime::Runtime; + use crossterm::event::KeyCode; + use crossterm::event::KeyEvent; + use crossterm::event::KeyModifiers; + let (requests, mut received) = tokio::sync::mpsc::unbounded_channel(); + let mut runtime = Runtime::new(Some("one".into()), requests); + runtime + .state + .apply(message("one", 1, "Preserved history")) + .unwrap(); + runtime + .connection_event(ConnectionEvent::Stopped( + "Host restarted; sessions were lost. Re-run nori attach.".into(), + )) + .unwrap(); + runtime.key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); + runtime.key(KeyEvent::new(KeyCode::Char('t'), KeyModifiers::ALT)); + runtime.composer.handle_paste("My draft".into()); + runtime.key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + runtime.refresh_list(); + runtime.subscribe_selected(); + assert!(received.try_recv().is_err()); + assert_eq!(runtime.state.transcript_text("one"), "Preserved history"); + assert!(!runtime.composer.is_empty()); + let rendered = screen(&runtime.state); + assert!( + rendered.contains("Host restarted") && rendered.contains("nori attach"), + "{rendered}" + ); + assert!( + !rendered.contains("RECONNECTING") && !rendered.contains("sessions continue"), + "{rendered}" + ); + insta::assert_snapshot!("attached_host_restarted", rendered); +} + +#[test] +fn stopped_explanation_remains_visible_above_a_tall_draft() { + let state = AttachState { + stopped: Some("Host restarted; sessions were lost. Re-run nori attach.".into()), + ..Default::default() + }; + let mut composer = crate::ComposerInput::for_attachment(); + composer.handle_paste("Preserved draft line\n".repeat(30)); + let rendered = screen_with_composer(&state, &composer); + assert!( + rendered.contains("Host restarted") && rendered.contains("nori attach"), + "{rendered}" + ); + assert!(!composer.is_empty()); + insta::assert_snapshot!("attached_host_restarted_with_draft", rendered); +} diff --git a/nori-rs/tui/src/bottom_pane/chat_composer/key_handling.rs b/nori-rs/tui/src/bottom_pane/chat_composer/key_handling.rs index 83b10fa27..66fe7b312 100644 --- a/nori-rs/tui/src/bottom_pane/chat_composer/key_handling.rs +++ b/nori-rs/tui/src/bottom_pane/chat_composer/key_handling.rs @@ -826,6 +826,7 @@ impl ChatComposer { // literal text. let first_line = self.textarea.text().lines().next().unwrap_or(""); if let Some((name, rest)) = parse_slash_name(first_line) + && !self.literal_commands && rest.is_empty() && let Some((_n, cmd)) = built_in_slash_commands() .into_iter() @@ -881,7 +882,7 @@ impl ChatComposer { // user can quit without the leading slash. A leading space opts out // (mirroring how a leading space escapes slash commands below), // keeping the words available as literal messages to the agent. - if !input_starts_with_space { + if !input_starts_with_space && !self.literal_commands { if text == "exit" { return (InputResult::Command(SlashCommand::Exit), true); } @@ -890,7 +891,8 @@ impl ChatComposer { } } if let Some((name, _rest)) = parse_slash_name(&text) { - let treat_as_plain_text = input_starts_with_space || name.contains('/'); + let treat_as_plain_text = + self.literal_commands || input_starts_with_space || name.contains('/'); if !treat_as_plain_text { let is_builtin = built_in_slash_commands() .into_iter() diff --git a/nori-rs/tui/src/bottom_pane/chat_composer/mod.rs b/nori-rs/tui/src/bottom_pane/chat_composer/mod.rs index cb1d535ec..b1d119cd8 100644 --- a/nori-rs/tui/src/bottom_pane/chat_composer/mod.rs +++ b/nori-rs/tui/src/bottom_pane/chat_composer/mod.rs @@ -115,6 +115,8 @@ pub(crate) struct ChatComposer { textarea: TextArea, textarea_state: RefCell, input_enabled: bool, + /// Let embedding frontends interpret submitted commands themselves. + literal_commands: bool, active_popup: ActivePopup, app_event_tx: AppEventSender, history: ChatComposerHistory, @@ -194,6 +196,7 @@ impl ChatComposer { textarea: TextArea::new(), textarea_state: RefCell::new(TextAreaState::default()), input_enabled: true, + literal_commands: false, active_popup: ActivePopup::None, app_event_tx, history: ChatComposerHistory::new(), @@ -242,6 +245,11 @@ impl ChatComposer { !self.is_shell_mode && self.textarea.is_empty() } + pub(crate) fn set_literal_commands(&mut self, enabled: bool) { + self.literal_commands = enabled; + self.sync_command_popup(); + } + /// Record the history metadata advertised by `SessionConfiguredEvent` so /// that the composer can navigate cross-session history. pub(crate) fn set_history_metadata(&mut self, log_id: u64, entry_count: usize) { diff --git a/nori-rs/tui/src/bottom_pane/chat_composer/popup_management.rs b/nori-rs/tui/src/bottom_pane/chat_composer/popup_management.rs index 98aa1e851..3c5ce4252 100644 --- a/nori-rs/tui/src/bottom_pane/chat_composer/popup_management.rs +++ b/nori-rs/tui/src/bottom_pane/chat_composer/popup_management.rs @@ -342,6 +342,12 @@ impl ChatComposer { /// textarea. This must be called after every modification that can change /// the text so the popup is shown/updated/hidden as appropriate. pub(super) fn sync_command_popup(&mut self) { + if self.literal_commands { + if matches!(self.active_popup, ActivePopup::Command(_)) { + self.active_popup = ActivePopup::None; + } + return; + } let text = self.textarea.text(); let first_line_end = text.find('\n').unwrap_or(text.len()); let first_line = &text[..first_line_end]; diff --git a/nori-rs/tui/src/lib.rs b/nori-rs/tui/src/lib.rs index 8864ecd1b..6a1d64800 100644 --- a/nori-rs/tui/src/lib.rs +++ b/nori-rs/tui/src/lib.rs @@ -32,6 +32,9 @@ mod app; mod app_backtrack; mod app_event; mod app_event_sender; +mod attach; +pub use attach::AttachOptions; +pub use attach::run_attach; mod bottom_pane; mod chatwidget; mod cli; diff --git a/nori-rs/tui/src/public_widgets/composer_input.rs b/nori-rs/tui/src/public_widgets/composer_input.rs index 2a80c087e..ad4233e22 100644 --- a/nori-rs/tui/src/public_widgets/composer_input.rs +++ b/nori-rs/tui/src/public_widgets/composer_input.rs @@ -32,12 +32,21 @@ pub struct ComposerInput { } impl ComposerInput { + /// Composer for an attached host, whose commands are interpreted by its frontend. + pub fn for_attachment() -> Self { + Self::with_commands("Send a prompt", true) + } /// Create a new composer input with a neutral placeholder. pub fn new() -> Self { + Self::with_commands("Compose new task", false) + } + + fn with_commands(placeholder: &str, literal_commands: bool) -> Self { let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); let sender = AppEventSender::new(tx.clone()); // `enhanced_keys_supported=true` enables Shift+Enter newline hint/behavior. - let inner = ChatComposer::new(true, sender, true, "Compose new task".to_string(), false); + let mut inner = ChatComposer::new(true, sender, true, placeholder.to_string(), false); + inner.set_literal_commands(literal_commands); Self { inner, _tx: tx, rx } } diff --git a/nori-rs/tui/src/remote_control.rs b/nori-rs/tui/src/remote_control.rs index 38c960cb0..44b5b86b8 100644 --- a/nori-rs/tui/src/remote_control.rs +++ b/nori-rs/tui/src/remote_control.rs @@ -504,6 +504,42 @@ mod tests { report.lines().join("\n") } + // Other tests can fork while a listener is open, retaining its socket until + // exec even after this process closes it. Isolate same-port replacement so + // those unrelated children cannot inherit the listener under test. + async fn run_in_isolated_process(test_name: &str) -> bool { + const CHILD_TEST: &str = "NORI_REMOTE_CONTROL_ISOLATED_TEST"; + if std::env::var(CHILD_TEST).ok().as_deref() == Some(test_name) { + return false; + } + + let mut command = tokio::process::Command::new( + std::env::current_exe().expect("locate current test executable"), + ); + command + .args([ + "--exact", + test_name, + "--test-threads=1", + "--nocapture", + "--format=pretty", + ]) + .env(CHILD_TEST, test_name) + .kill_on_drop(true); + let output = tokio::time::timeout(Duration::from_secs(15), command.output()) + .await + .expect("isolated listener test timed out") + .expect("run isolated listener test"); + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed;"), + "isolated test {test_name} must run and pass exactly once: {}\n{stdout}\n{stderr}", + output.status, + ); + true + } + fn addr_from_url(url: &str) -> SocketAddr { url.strip_prefix("ws://") .and_then(|value| value.strip_suffix("/acp")) @@ -817,6 +853,14 @@ Hint: Tailscale is available; use /remote-control on tailnet. #[tokio::test] async fn changing_exposure_can_reuse_the_existing_loopback_port() { + if run_in_isolated_process( + "remote_control::tests::changing_exposure_can_reuse_the_existing_loopback_port", + ) + .await + { + return; + } + let reserved = std::net::TcpListener::bind("0.0.0.0:0").expect("reserve a free port"); let port = reserved.local_addr().expect("reserved address").port(); drop(reserved); @@ -846,6 +890,14 @@ Hint: Tailscale is available; use /remote-control on tailnet. #[tokio::test] async fn failed_same_port_replacement_restores_the_previous_surface() { + if run_in_isolated_process( + "remote_control::tests::failed_same_port_replacement_restores_the_previous_surface", + ) + .await + { + return; + } + let reserved = std::net::TcpListener::bind("0.0.0.0:0").expect("reserve a free port"); let port = reserved.local_addr().expect("reserved address").port(); drop(reserved);