Skip to main content

trusty_code/serve/
uds.rs

1//! The `tcode` daemon's Unix-socket transport — the one every client but the
2//! GUI webview now dials (#6637, ADR-0032).
3//!
4//! Why: a loopback TCP port is reachable by any process on the machine,
5//! including a page running in the operator's browser, which is what forced
6//! the bearer-token and origin-guard stack #6491 added. A `0600` socket inside
7//! a `0700` directory, with a peer-uid check on every accept, is an OS
8//! boundary instead of a convention, so none of that machinery is ported here
9//! — [`trusty_common::uds::server`]'s module docs state why re-adding it would
10//! guard nothing. The owner ruling of 2026-09-08 makes UDS this daemon's
11//! native transport: `tcode tui` dials the socket directly, and the HTTP the
12//! GUI webview needs moves into `trusty-code-gui` in PR 2.
13//!
14//! What: [`run_daemon`] is the persistent daemon's whole body. It binds the
15//! socket FIRST and treats a bind failure as fatal — a daemon that silently
16//! served HTTP only would leave every socket client reporting "no daemon"
17//! while one is plainly running — then builds the router ONCE and serves it
18//! over both transports, so a session created over the socket is the same
19//! session the GUI's HTTP call sees.
20//!
21//! The method surface is mounted, not restated. Exactly one of the 34
22//! registered JSON-RPC methods (`session.attach`) uses
23//! `crate::jsonrpc::ConnectionContext::notify`, and a UDS connection is one
24//! frame in and one frame out, so it cannot push. The other 33 ignore the
25//! context entirely, which is what lets [`JsonRpcFallback`] carry the whole
26//! table through [`trusty_common::uds::server::RpcRouter::fallback`] rather
27//! than re-registering each name — registering the same table twice is the
28//! silent-drift risk this workspace's common-entry-point rule exists to stop.
29//! `session.attach`'s live half is served instead by
30//! [`crate::session::events_stream`], and the workstream fan-out by
31//! [`crate::workstreams::events_stream`]; both are registered as STREAM
32//! methods, which the router checks before the fallback, so the names win over
33//! the pass-through.
34//!
35//! **HTTP is a transient here, not an end state.** It stays bound only because
36//! `trusty-code-gui`'s webview still `fetch`es it; PR 2 moves that bridge into
37//! the GUI crate and this daemon binds the socket alone.
38//!
39//! Test: `uds_tests`.
40
41use std::path::{Path, PathBuf};
42use std::sync::Arc;
43
44use anyhow::{Context, Result};
45use async_trait::async_trait;
46use serde_json::Value;
47use tracing::info;
48use trusty_common::uds::server::{RpcError, RpcFallback, RpcRouter, RpcServeOptions, serve_until};
49use trusty_common::uds::{bind_singleton_hardened, server::RpcStreamItems};
50use trusty_mcp::Request;
51
52use crate::binding::ProjectBinding;
53use crate::jsonrpc::Router;
54use crate::session::SessionRegistry;
55use crate::session::events_stream::{self, SessionEventsParams};
56use crate::workstreams::SharedWorkstreamStore;
57use crate::workstreams::events_stream::{self as workstream_events, WorkstreamEventsParams};
58
59/// The application name whose data directory holds the daemon's socket.
60///
61/// Why named rather than inlined: [`trusty_common::daemon_addr::daemon_socket_path`]
62/// is the single answer to "where does this daemon answer", and a server and a
63/// client that disagree about the path produce a daemon that is up and a probe
64/// that reports it down. Both ends resolve it from this constant.
65pub const SOCKET_APP_NAME: &str = "trusty-code";
66
67/// The socket `tcode serve` binds and every client dials.
68///
69/// # Errors
70///
71/// Whatever `resolve_data_dir` returns — the data directory could not be
72/// resolved or created.
73///
74/// Test: `uds_tests::socket_path_sits_in_the_daemon_data_dir`.
75pub fn socket_path() -> Result<PathBuf> {
76    trusty_common::daemon_addr::daemon_socket_path(SOCKET_APP_NAME)
77        .context("tcode serve: resolve the daemon socket path")
78}
79
80/// The socket a daemon serving `project` binds when the shared socket is held
81/// by a daemon serving a different project (#4600).
82///
83/// Why: one shared socket per user meant a second project could not run at
84/// all — its TUI refused the first project's daemon (correctly, #4512) and had
85/// nowhere else to start its own. A per-project sibling gives each project a
86/// home while the first daemon keeps the shared path `trusty-code-gui` dials.
87/// What: `<shared dir>/<shared stem>-<key>.sock`, where `key` is the first 12
88/// hex digits of SHA-256 over the canonical project root, or `projectless`.
89/// Deterministic, so every client and the daemon itself derive the same path
90/// with nothing recorded on disk. A collision is not trusted: clients still
91/// check the binding the daemon reports before attaching. 12 digits keep the
92/// path inside macOS' 104-byte `sun_path` under a temp data directory.
93/// Test: `uds_tests::project_socket_path_is_per_project_and_stable`.
94pub fn project_socket_path(shared: &Path, project: Option<&Path>) -> PathBuf {
95    use sha2::{Digest, Sha256};
96    let key = match project {
97        Some(root) => {
98            let digest = Sha256::digest(root.as_os_str().as_encoded_bytes());
99            digest[..6].iter().map(|b| format!("{b:02x}")).collect()
100        }
101        None => "projectless".to_string(),
102    };
103    let stem = shared
104        .file_stem()
105        .map(|s| s.to_string_lossy().into_owned())
106        .unwrap_or_else(|| SOCKET_APP_NAME.to_string());
107    shared.with_file_name(format!("{stem}-{key}.sock"))
108}
109
110/// Mounts [`crate::jsonrpc::Router`] as the socket router's catch-all.
111///
112/// Why: see the module docs — the dispatcher already owns the method surface,
113/// and registering those 33 names a second time here is the drift this avoids.
114/// What: rebuilds the [`Request`] envelope the dispatcher takes and hands back
115/// either half of its [`trusty_mcp::Response`]. The id is `0` on the way in
116/// and discarded on the way out — [`RpcRouter`] stamps the caller's real id
117/// onto the response frame, so the one supplied here would only be
118/// overwritten. The context is the same throwaway
119/// `crate::serve::rest::throwaway_ctx` builds, because a one-frame-in,
120/// one-frame-out connection has nowhere to push a notification to; the one
121/// handler that would try is served as a stream instead.
122/// Test: `uds_tests::fallback_dispatches_every_jsonrpc_router_method`,
123/// `uds_tests::fallback_reports_an_unknown_method`.
124pub struct JsonRpcFallback {
125    router: Arc<Router>,
126}
127
128#[async_trait]
129impl RpcFallback for JsonRpcFallback {
130    async fn call(&self, method: &str, params: Value) -> Result<Value, RpcError> {
131        let request = Request {
132            jsonrpc: Some("2.0".to_string()),
133            id: Some(serde_json::json!(0)),
134            method: method.to_string(),
135            params: Some(params),
136        };
137        let response = self
138            .router
139            .dispatch(request, &crate::serve::rest::throwaway_ctx())
140            .await;
141        match (response.result, response.error) {
142            (Some(result), _) => Ok(result),
143            (None, Some(error)) => Err(RpcError::new(i64::from(error.code), error.message)),
144            // The dispatcher's own contract is that exactly one of the two is
145            // present. Saying so beats answering `null` as a success.
146            (None, None) => Err(RpcError::internal(format!(
147                "dispatcher answered {method} with neither result nor error"
148            ))),
149        }
150    }
151}
152
153/// Assemble the socket router: two stream methods plus the whole JSON-RPC
154/// table behind them.
155///
156/// Why: kept separate from [`run_daemon_on`] so a test can dispatch against it
157/// without binding a socket.
158/// What: registers [`crate::session::events_stream::METHOD`] and
159/// [`crate::workstreams::events_stream::METHOD`] with
160/// [`RpcRouter::typed_stream`], then mounts [`JsonRpcFallback`]. Neither
161/// stream is marked with `RpcRouter::mark_liveness`: an open tail is real work
162/// and must hold the connection, not be discounted as a monitor's poll.
163/// Test: `uds_tests::stream_names_win_over_the_fallback`.
164pub fn build_rpc_router(
165    router: Arc<Router>,
166    sessions: Arc<SessionRegistry>,
167    workstreams: SharedWorkstreamStore,
168) -> RpcRouter {
169    RpcRouter::new()
170        .typed_stream(events_stream::METHOD, move |params: SessionEventsParams| {
171            let sessions = sessions.clone();
172            async move { events_stream::open(sessions, params).await }
173        })
174        .typed_stream(
175            workstream_events::METHOD,
176            move |params: WorkstreamEventsParams| {
177                let workstreams = workstreams.clone();
178                async move { open_workstream(workstreams, params).await }
179            },
180        )
181        .fallback(JsonRpcFallback { router })
182}
183
184/// Named rather than inlined so the closure above stays a one-liner and the
185/// return type is written once.
186async fn open_workstream(
187    workstreams: SharedWorkstreamStore,
188    params: WorkstreamEventsParams,
189) -> Result<RpcStreamItems, RpcError> {
190    workstream_events::open(workstreams, params).await
191}
192
193/// Run the persistent `tcode` daemon: bind the socket, optionally bind HTTP,
194/// and serve both until SIGTERM/SIGINT.
195///
196/// Why/What: see module docs. `http_port` is `Some` for as long as
197/// `trusty-code-gui`'s webview still dials the TCP listener; PR 2 makes it
198/// `None` and deletes the parameter.
199///
200/// # Errors
201///
202/// The socket could not be bound or hardened (fatal — there is deliberately no
203/// HTTP-only degrade), the router could not be assembled, or the HTTP listener
204/// failed.
205///
206/// Test: `uds_tests::run_uds_socket_bind_failure_is_fatal`,
207/// `uds_tests::session_events_stream_stays_open_under_idle_window`.
208pub async fn run_daemon(binding: ProjectBinding, http_port: Option<u16>) -> Result<()> {
209    let socket = socket_path()?;
210    run_daemon_on(
211        binding,
212        &socket,
213        None,
214        http_port,
215        trusty_common::shutdown_signal(),
216    )
217    .await
218}
219
220/// [`run_daemon`] on this binding's own socket, [`project_socket_path`],
221/// instead of the shared one (#4600, `tcode serve --project-socket`).
222///
223/// Why: `tcode tui` starts a daemon here when the shared socket already serves
224/// another project. The daemon derives the path from its own binding rather
225/// than taking a path argument, so it can only ever land on the path a client
226/// of the same project will probe, and never hardens an arbitrary directory.
227///
228/// # Errors
229///
230/// As [`run_daemon`].
231///
232/// Test: `uds_tests::project_socket_path_is_per_project_and_stable` (the path);
233/// `tests/cli_e2e.rs::tui_starts_its_own_daemon_beside_another_projects` (the
234/// real daemon binding it).
235pub async fn run_project_daemon(binding: ProjectBinding, http_port: Option<u16>) -> Result<()> {
236    let socket = project_socket_path(&socket_path()?, binding.root());
237    run_daemon_on(
238        binding,
239        &socket,
240        None,
241        http_port,
242        trusty_common::shutdown_signal(),
243    )
244    .await
245}
246
247/// [`run_daemon`] with the socket path, the workstream data directory and the
248/// shutdown trigger injected.
249///
250/// Why: the same seam [`crate::serve::build_router_at`] has, and `pub` for
251/// the same reason [`crate::serve::http::build_axum_router`] is — an
252/// integration test outside this crate needs it to stand a real daemon up on a
253/// throwaway socket. Why: — a test drives
254/// the real bind/serve/unlink machinery against a tempdir socket and its own
255/// shutdown signal, without touching the operator's data directory or waiting
256/// on a real one.
257/// What: `data_dir` of `None` is production — `crate::serve::build_router`,
258/// which resolves the real `~/.trusty-code` and starts the log-drain
259/// scheduler. `Some(dir)` routes through `build_router_at` instead, which does
260/// neither.
261pub async fn run_daemon_on(
262    binding: ProjectBinding,
263    socket: &Path,
264    data_dir: Option<&Path>,
265    http_port: Option<u16>,
266    shutdown: impl std::future::Future<Output = ()> + Send,
267) -> Result<()> {
268    // Bound FIRST, and fatally: a daemon that could not take the socket must
269    // not come up serving HTTP alone, because every socket client would then
270    // report "no daemon" against a process that is plainly running.
271    // `bind_singleton_hardened` (not `bind_hardened`) because this daemon is
272    // restart-prone and has to take over the socket file a killed predecessor
273    // left behind; a LIVE owner is still refused.
274    let listener = bind_singleton_hardened(socket).await.with_context(|| {
275        format!(
276            "tcode serve: bind the daemon socket at {}",
277            socket.display()
278        )
279    })?;
280
281    info!(
282        binding = binding.state(),
283        project = binding.label().unwrap_or_else(|| "<projectless>".into()),
284        socket = %socket.display(),
285        "tcode serve: starting"
286    );
287    eprintln!("tcode serve: listening on {}", socket.display());
288
289    // #4512: `GET /health` reports this binding, so keep a handle before
290    // `build_router` consumes it.
291    let published_binding = Arc::new(binding.clone());
292    let (router, sessions, workstreams) = match data_dir {
293        Some(dir) => super::build_router_at(binding, dir).await?,
294        None => super::build_router(binding).await?,
295    };
296    let router = Arc::new(router);
297    let rpc_router = Arc::new(build_rpc_router(
298        router.clone(),
299        sessions.clone(),
300        workstreams.clone(),
301    ));
302
303    let serve_socket = async {
304        serve_until(&listener, rpc_router, RpcServeOptions::default(), shutdown).await;
305        // Unlink BEFORE dropping the listener — `RpcServer::run` records why:
306        // with the order reversed a successor that rebinds in the gap has its
307        // fresh socket deleted by this process.
308        if let Err(e) = std::fs::remove_file(socket) {
309            tracing::debug!(socket = %socket.display(), error = %e, "socket already gone");
310        }
311        drop(listener);
312        Ok::<(), anyhow::Error>(())
313    };
314
315    match http_port {
316        Some(port) => {
317            let serve_http = super::http::run_http(
318                router,
319                sessions.clone(),
320                workstreams,
321                port,
322                published_binding,
323            );
324            tokio::try_join!(serve_socket, serve_http)?;
325        }
326        None => serve_socket.await?,
327    }
328
329    sessions.shutdown_executions(super::SHUTDOWN_GRACE).await;
330    info!("tcode serve: stopped");
331    Ok(())
332}
333
334#[cfg(test)]
335#[path = "uds_tests.rs"]
336mod uds_tests;