Skip to main content

trusty_code/tui_client/
discovery.rs

1//! Daemon discovery for [`crate::tui_client::CodeEngine`] (issue #3415,
2//! DOC-50 §3.4).
3//!
4//! Why: `tcode tui` needs to find an already-running `tcode serve --http`
5//! daemon without the operator hand-copying a port. DOC-50 §3.4 specifies
6//! the lookup priority — explicit override, then a discovery file, then a
7//! liveness check — but its prose sketched a NEW `~/.trusty-code/daemon.json`
8//! shape; `crate::serve::discovery` documents why this crate follows the
9//! ALREADY-ESTABLISHED sibling convention (`trusty-memory`/`trusty-search`'s
10//! plain-text `http_addr` file) instead. This module is the READ side of
11//! that convention; `crate::serve::discovery`'s `write_http_addr_file` is
12//! the write side, called from `crate::serve::http::run_http`.
13//! What: [`lookup_daemon`] tries, in order, [`DAEMON_URL_ENV`] (an
14//! explicit override — trusted without a liveness check of its own source,
15//! but still ping-verified before use, same as the file-sourced candidate)
16//! then the `http_addr` discovery file; whichever candidate is found is
17//! verified alive via `GET {url}/health` (the SAME route
18//! `crate::serve::methods::health_payload` answers, already the
19//! ecosystem-standard liveness probe per `crate::serve::http`'s docs). It
20//! reports the outcome as a three-way [`Lookup`] — live, found-but-dead
21//! (naming its [`Source`]), or no candidate at all — because a CALLER has to
22//! branch on WHICH source failed: `tcode tui` auto-spawns a daemon when the
23//! discovery file is stale or absent, but must NOT when
24//! [`DAEMON_URL_ENV`] explicitly named an address, since spawning
25//! something at a DIFFERENT address would quietly ignore that instruction
26//! (#4512). A live daemon additionally carries the [`ReportedBinding`] it
27//! published, because "a daemon is answering" is NOT the same question as
28//! "that daemon serves the project I mean to work in" — see
29//! [`ReportedBinding`]. [`discover_daemon_url`] is the attach-only wrapper
30//! over it, collapsing the same three outcomes into a [`DiscoveryError`]
31//! with an actionable message — never a silent `None`/default.
32//! Test: `discovery_tests::*` for the pure candidate-selection logic (env
33//! var precedence, file fallback, "neither present" case), the
34//! [`Lookup`]-to-[`DiscoveryError`] collapse, and [`ReportedBinding`]
35//! parsing; the liveness-ping branch is covered end-to-end in
36//! `tests/tui_client_engine.rs` against a mock daemon (a unit test would need
37//! a real bound socket to ping, which belongs in that hermetic integration
38//! suite, not here).
39
40use std::path::PathBuf;
41use std::time::Duration;
42
43use crate::binding::ProjectBinding;
44
45/// Environment variable that, when set to a non-empty value, names the
46/// daemon URL directly — highest-priority discovery source (DOC-50 §3.4
47/// point 1).
48pub const DAEMON_URL_ENV: &str = "TCODE_DAEMON_URL";
49
50/// How long the liveness ping (`GET {url}/health`) waits before treating the
51/// candidate as dead. Short and fixed — this call happens once, at REPL
52/// startup, and a slow/hung `/health` response is itself a strong "don't use
53/// this daemon" signal.
54const PING_TIMEOUT: Duration = Duration::from_secs(2);
55
56/// Which discovery source produced a candidate URL — carried into
57/// [`Lookup::Dead`] (and from there into [`DiscoveryError::NotAlive`]) so the
58/// error message tells the operator WHERE the stale/wrong pointer came from,
59/// and so `tcode tui`'s auto-spawn can tell an EXPLICIT instruction it must
60/// obey ([`Source::Env`]) from a stale file it may replace ([`Source::File`]).
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub enum Source {
63    /// [`DAEMON_URL_ENV`] named the URL — an explicit operator instruction.
64    Env,
65    /// The `http_addr` discovery file named the URL — a best-effort pointer
66    /// a previous daemon left behind.
67    File,
68}
69
70impl Source {
71    /// Human-readable name for error messages ("from {found_via}").
72    pub fn as_str(self) -> &'static str {
73        match self {
74            Source::Env => "TCODE_DAEMON_URL",
75            Source::File => "discovery file",
76        }
77    }
78}
79
80/// The project binding a live daemon published on `GET /health` (#4512).
81///
82/// Why: a `tcode serve --http` daemon binds exactly ONE `ProjectBinding` at
83/// `crate::serve::build_router` time and keeps it for its whole life. Until
84/// #4512 that binding was invisible to clients, which was harmless while
85/// `tcode tui` refused to run without a hand-started daemon — the operator
86/// who started it knew what it was bound to. Auto-attach removes that
87/// guarantee: a TUI launched in project B finds project A's daemon on the
88/// well-known port and would drive it, so every session, index, and file
89/// operation would silently land in the wrong project. Making the binding
90/// part of the lookup result is what lets a caller refuse.
91/// What: the daemon's bound project root, or an explicit projectless state,
92/// or [`Unreported`](ReportedBinding::Unreported) when `/health` answered but
93/// carried no usable `binding` field — a daemon older than #4512, or one
94/// whose payload could not be parsed. Those two are deliberately the same
95/// variant: both mean "this daemon's project CANNOT be verified", and a
96/// caller must treat an unverifiable daemon the same way regardless of why.
97/// Test: `discovery_tests::reported_binding_parses_every_health_shape`.
98#[derive(Debug, Clone, PartialEq, Eq)]
99pub enum ReportedBinding {
100    /// The daemon reported it serves no project.
101    Projectless,
102    /// The daemon reported this canonical project root.
103    Bound(PathBuf),
104    /// `/health` answered, but with no parseable `binding` field.
105    Unreported,
106}
107
108impl ReportedBinding {
109    /// Read a [`ReportedBinding`] out of a `GET /health` body.
110    ///
111    /// Why/What: reuses `ProjectBinding`'s own `Deserialize` (the
112    /// `{state, root}` wire shape defined once in `crate::binding`) rather
113    /// than re-spelling that shape here, so the reader can never drift from
114    /// the writer. A missing or malformed field is
115    /// [`Unreported`](ReportedBinding::Unreported), never a guess.
116    /// Test: `discovery_tests::reported_binding_parses_every_health_shape`.
117    pub fn from_health(health: &serde_json::Value) -> Self {
118        let Some(raw) = health.get("binding") else {
119            return Self::Unreported;
120        };
121        match serde_json::from_value::<ProjectBinding>(raw.clone()) {
122            Ok(binding) => match binding.root() {
123                Some(root) => Self::Bound(root.to_path_buf()),
124                None => Self::Projectless,
125            },
126            Err(_) => Self::Unreported,
127        }
128    }
129
130    /// How to name this binding in an operator-facing message.
131    ///
132    /// Why: a mismatch error has to print BOTH sides, and "no project" has to
133    /// read as a deliberate state rather than as missing information.
134    /// Test: `discovery_tests::reported_binding_describes_each_state`.
135    pub fn describe(&self) -> String {
136        match self {
137            Self::Projectless => "<projectless>".to_string(),
138            Self::Bound(root) => root.display().to_string(),
139            Self::Unreported => "<unreported — daemon predates #4512>".to_string(),
140        }
141    }
142}
143
144/// The three distinguishable outcomes of one daemon lookup.
145///
146/// Why: [`DiscoveryError`] collapses "found but dead" and "nothing found"
147/// into two error variants that both mean "you can't attach", which is all
148/// an attach-only caller needs. Auto-spawn needs MORE: it must refuse to
149/// spawn when [`Source::Env`] named a dead address (spawning would land at a
150/// different address and ignore the operator's explicit instruction), while
151/// treating a dead or absent discovery file as a green light (#4512). It
152/// also needs the live daemon's [`ReportedBinding`], since attaching to a
153/// daemon bound to a DIFFERENT project is worse than not attaching at all.
154/// Test: `discovery_tests::lookup_collapses_into_discovery_errors`.
155#[derive(Debug, Clone, PartialEq, Eq)]
156pub enum Lookup {
157    /// A candidate answered `GET {url}/health` — attach to it, if `binding`
158    /// is the project the caller wants.
159    Live {
160        url: String,
161        binding: ReportedBinding,
162    },
163    /// A candidate URL was named by `source` but is not responding.
164    Dead { url: String, source: Source },
165    /// Neither source named a candidate URL.
166    Absent,
167}
168
169/// See module docs.
170#[derive(Debug, thiserror::Error, PartialEq, Eq)]
171pub enum DiscoveryError {
172    /// Neither `TCODE_DAEMON_URL` nor the discovery file named a candidate
173    /// daemon URL.
174    #[error(
175        "no tcode daemon found — start one with `tcode serve --http`, or point \
176         `tcode tui` at a running instance with `{DAEMON_URL_ENV}=http://host:port`"
177    )]
178    NotFound,
179
180    /// A candidate URL was found (from `source`) but did not answer
181    /// `GET {url}/health` with a success status within [`PING_TIMEOUT`].
182    #[error(
183        "found a tcode daemon reference at {url} (from {found_via}) but it is not responding \
184         — is it still running? Start one with `tcode serve --http`, or update {DAEMON_URL_ENV} \
185         to point at a live daemon"
186    )]
187    NotAlive {
188        url: String,
189        found_via: &'static str,
190    },
191}
192
193/// Resolve a candidate daemon URL and report whether it is live, per this
194/// module's docs.
195///
196/// Why/What: see module docs — this is the source-aware primitive
197/// [`discover_daemon_url`] and `tcode tui`'s auto-spawn (#4512) are both
198/// built on. `client` is caller-supplied (rather than built internally) so
199/// `CodeEngine` can reuse the SAME pooled `reqwest::Client` for both this
200/// ping and every later `POST /rpc`/SSE call — one connection pool for the
201/// engine's whole lifetime, not one throwaway client per call.
202/// Test: `discovery_tests::env_var_wins_over_file`,
203/// `discovery_tests::env_var_trailing_slash_is_stripped`,
204/// `discovery_tests::blank_env_var_is_ignored` cover candidate selection;
205/// the liveness branch is covered by `tests/tui_client_engine.rs` and (for
206/// the spawn decision it feeds) `cli::daemon_autospawn`'s tests.
207pub async fn lookup_daemon(client: &reqwest::Client) -> Lookup {
208    let Some((url, source)) = candidate_url() else {
209        return Lookup::Absent;
210    };
211    match probe_health(client, &url).await {
212        Some(health) => Lookup::Live {
213            url,
214            binding: ReportedBinding::from_health(&health),
215        },
216        None => Lookup::Dead { url, source },
217    }
218}
219
220/// Resolve and verify a live daemon URL, failing when none can be attached
221/// to — the attach-only view of [`lookup_daemon`].
222///
223/// Why: `CodeEngine::discover` (and every non-TUI caller) only ever wants
224/// "give me a live daemon or an actionable error"; the three-way [`Lookup`]
225/// distinction matters solely to the auto-spawn path.
226/// Test: `discovery_tests::lookup_collapses_into_discovery_errors`;
227/// end-to-end in `tests/tui_client_engine.rs`.
228pub async fn discover_daemon_url(client: &reqwest::Client) -> Result<String, DiscoveryError> {
229    collapse(lookup_daemon(client).await)
230}
231
232/// The pure [`Lookup`] -> [`DiscoveryError`] mapping, split out of
233/// [`discover_daemon_url`] so it is unit testable without a bound socket.
234fn collapse(lookup: Lookup) -> Result<String, DiscoveryError> {
235    match lookup {
236        Lookup::Live { url, .. } => Ok(url),
237        Lookup::Dead { url, source } => Err(DiscoveryError::NotAlive {
238            url,
239            found_via: source.as_str(),
240        }),
241        Lookup::Absent => Err(DiscoveryError::NotFound),
242    }
243}
244
245/// Pick a candidate URL from the env var or the discovery file, per the
246/// documented priority. Pure (no network I/O) so it's directly unit
247/// testable.
248fn candidate_url() -> Option<(String, Source)> {
249    if let Ok(raw) = std::env::var(DAEMON_URL_ENV) {
250        let trimmed = raw.trim();
251        if !trimmed.is_empty() {
252            return Some((trimmed.trim_end_matches('/').to_string(), Source::Env));
253        }
254    }
255    let path = crate::serve::discovery::http_addr_path()?;
256    let addr = crate::serve::discovery::read_http_addr_file(&path)?;
257    Some((format!("http://{addr}"), Source::File))
258}
259
260/// `GET {base_url}/health`, bounded by [`PING_TIMEOUT`] — `Some(body)` iff
261/// it returns a success (2xx) status with a JSON body.
262///
263/// #4512: this used to answer a bare `bool`. The BODY is now needed too, for
264/// the `binding` field the caller checks before attaching; a 2xx whose body
265/// will not parse as JSON still counts as alive (the daemon is answering),
266/// and degrades to `Value::Null`, from which
267/// [`ReportedBinding::from_health`] correctly reports `Unreported`.
268async fn probe_health(client: &reqwest::Client, base_url: &str) -> Option<serde_json::Value> {
269    let url = format!("{base_url}/health");
270    let resp = client.get(&url).timeout(PING_TIMEOUT).send().await.ok()?;
271    if !resp.status().is_success() {
272        return None;
273    }
274    Some(resp.json().await.unwrap_or(serde_json::Value::Null))
275}
276
277#[cfg(test)]
278mod discovery_tests {
279    use super::*;
280
281    /// Serializes every test in this module that mutates `DAEMON_URL_ENV` —
282    /// mirrors `crate::task::mock_llm::MOCK_LLM_ENV_LOCK`'s established
283    /// pattern for env-mutating tests in this crate (a plain `tokio::sync::Mutex`
284    /// guard rather than pulling in `serial_test` for one file).
285    static ENV_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
286
287    /// Both a `TCODE_DAEMON_URL` and a discovery file present: the env var
288    /// must win (DOC-50 §3.4 point 1's explicit priority).
289    #[tokio::test]
290    async fn env_var_wins_over_file() {
291        let _guard = ENV_LOCK.lock().await;
292        // SAFETY: test-only env mutation; serialized by `ENV_LOCK`.
293        unsafe {
294            std::env::set_var(DAEMON_URL_ENV, "http://127.0.0.1:9999");
295        }
296        let (url, source) = candidate_url().expect("candidate");
297        unsafe {
298            std::env::remove_var(DAEMON_URL_ENV);
299        }
300        assert_eq!(url, "http://127.0.0.1:9999");
301        assert_eq!(source, Source::Env);
302    }
303
304    /// A trailing slash on the env var is stripped, so URL-joining callers
305    /// (`{base}/rpc`, `{base}/health`) never produce a doubled `//`.
306    #[tokio::test]
307    async fn env_var_trailing_slash_is_stripped() {
308        let _guard = ENV_LOCK.lock().await;
309        // SAFETY: test-only env mutation; serialized by `ENV_LOCK`.
310        unsafe {
311            std::env::set_var(DAEMON_URL_ENV, "http://127.0.0.1:9999/");
312        }
313        let (url, _source) = candidate_url().expect("candidate");
314        unsafe {
315            std::env::remove_var(DAEMON_URL_ENV);
316        }
317        assert_eq!(url, "http://127.0.0.1:9999");
318    }
319
320    /// An empty/whitespace `TCODE_DAEMON_URL` must be treated as unset, not
321    /// as a (broken) candidate.
322    #[tokio::test]
323    async fn blank_env_var_is_ignored() {
324        let _guard = ENV_LOCK.lock().await;
325        // SAFETY: test-only env mutation; serialized by `ENV_LOCK`.
326        unsafe {
327            std::env::set_var(DAEMON_URL_ENV, "   ");
328        }
329        // With the env var blank, resolution falls through to the discovery
330        // file — assert only that the env var itself did not win.
331        let result = candidate_url();
332        unsafe {
333            std::env::remove_var(DAEMON_URL_ENV);
334        }
335        if let Some((_, source)) = result {
336            assert_ne!(source, Source::Env);
337        }
338    }
339
340    /// `DiscoveryError::NotFound`'s message must name the actionable fix
341    /// (start a daemon, or set the env var) — pinned so a future edit can't
342    /// silently regress it into an unhelpful "not found".
343    #[test]
344    fn not_found_message_is_actionable() {
345        let msg = DiscoveryError::NotFound.to_string();
346        assert!(msg.contains("tcode serve --http"));
347        assert!(msg.contains(DAEMON_URL_ENV));
348    }
349
350    /// Every `Lookup` outcome must collapse to the matching attach-only
351    /// result — pinned because `tcode tui`'s auto-spawn now branches on the
352    /// SAME three outcomes (#4512), and the two views must stay agreed on
353    /// what each one means.
354    #[test]
355    fn lookup_collapses_into_discovery_errors() {
356        assert_eq!(
357            collapse(Lookup::Live {
358                url: "http://127.0.0.1:7882".to_string(),
359                binding: ReportedBinding::Projectless,
360            }),
361            Ok("http://127.0.0.1:7882".to_string())
362        );
363        assert_eq!(
364            collapse(Lookup::Dead {
365                url: "http://127.0.0.1:7882".to_string(),
366                source: Source::Env,
367            }),
368            Err(DiscoveryError::NotAlive {
369                url: "http://127.0.0.1:7882".to_string(),
370                found_via: "TCODE_DAEMON_URL",
371            })
372        );
373        assert_eq!(collapse(Lookup::Absent), Err(DiscoveryError::NotFound));
374    }
375
376    /// Every shape a real `GET /health` body can take must map to the right
377    /// `ReportedBinding` — including the two "cannot verify" shapes, which
378    /// must NOT be mistaken for a projectless daemon (#4512).
379    #[test]
380    fn reported_binding_parses_every_health_shape() {
381        use serde_json::json;
382
383        let bound = json!({
384            "server": "tcode",
385            "binding": {"state": crate::binding::STATE_GIT_REPO, "root": "/tmp/proj"},
386        });
387        assert_eq!(
388            ReportedBinding::from_health(&bound),
389            ReportedBinding::Bound(PathBuf::from("/tmp/proj"))
390        );
391
392        let projectless = json!({
393            "binding": {"state": crate::binding::STATE_PROJECTLESS, "root": null},
394        });
395        assert_eq!(
396            ReportedBinding::from_health(&projectless),
397            ReportedBinding::Projectless
398        );
399
400        // A pre-#4512 daemon: `/health` answers, but with no binding at all.
401        let old = json!({"server": "tcode", "version": "0.2.0", "status": "ok"});
402        assert_eq!(
403            ReportedBinding::from_health(&old),
404            ReportedBinding::Unreported,
405            "a daemon that reports nothing must never read as projectless"
406        );
407
408        // A malformed payload is equally unverifiable, never a guess.
409        let malformed = json!({"binding": {"state": "who knows"}});
410        assert_eq!(
411            ReportedBinding::from_health(&malformed),
412            ReportedBinding::Unreported
413        );
414        assert_eq!(
415            ReportedBinding::from_health(&serde_json::Value::Null),
416            ReportedBinding::Unreported
417        );
418    }
419
420    /// Each state must render an operator-readable name — the mismatch error
421    /// prints both sides, so "no project" must not come out blank.
422    #[test]
423    fn reported_binding_describes_each_state() {
424        assert_eq!(ReportedBinding::Projectless.describe(), "<projectless>");
425        assert_eq!(
426            ReportedBinding::Bound(PathBuf::from("/tmp/proj")).describe(),
427            "/tmp/proj"
428        );
429        assert!(
430            ReportedBinding::Unreported.describe().contains("4512"),
431            "an unverifiable daemon must say why it cannot be checked"
432        );
433    }
434
435    /// `DiscoveryError::NotAlive`'s message must name both the dead URL and
436    /// which source produced it.
437    #[test]
438    fn not_alive_message_names_url_and_source() {
439        let err = DiscoveryError::NotAlive {
440            url: "http://127.0.0.1:7882".to_string(),
441            found_via: Source::File.as_str(),
442        };
443        let msg = err.to_string();
444        assert!(msg.contains("http://127.0.0.1:7882"));
445        assert!(msg.contains("discovery file"));
446    }
447}