Skip to main content

trusty_console/
lib.rs

1//! trusty-console library entry point.
2//!
3//! Why: Expose the console daemon's startup sequence as a public `run()`
4//! function so bundled shim binaries inside host crates (trusty-search,
5//! trusty-memory, trusty-analyze, trusty-review, trusty-mpm) can call
6//! `trusty_console::run()` without duplicating any logic. This mirrors the
7//! exact pattern used by trusty-embedderd (bundled into trusty-search via
8//! issue #187) and trusty-bm25-daemon (bundled into trusty-memory via PR #190).
9//! What: Re-exports all public submodules and provides `run_from(argv)` as the
10//! canonical library entry point that parses an explicit argv vector and
11//! dispatches to subcommands; `run()` is a thin wrapper passing the process's
12//! global argv.
13//! Test: `cargo test -p trusty-console` exercises the CLI parsing tests defined
14//! in the submodules.
15
16// docs.rs builds a release's documentation once, from the uploaded tarball,
17// so a broken intra-doc link is baked into that version forever and only a new
18// release can correct it. Deny keeps this crate at zero rather than letting the
19// ratchet in `scripts/check_rustdoc_links.sh` absorb a new one.
20#![deny(rustdoc::broken_intra_doc_links)]
21
22use std::sync::Arc;
23use std::time::Duration;
24
25use anyhow::{Context, Result};
26use clap::{Parser, Subcommand};
27use tracing::info;
28use trusty_common::{init_tracing, shutdown_signal, write_daemon_addr};
29
30/// Default console HTTP bind address (used for both serve and `port` reporting).
31///
32/// Why: A single constant keeps the serve default and the `port` verb's
33/// fallback in lock-step so `trusty-installer` (`tctl`) never discovers a port
34/// the console would not actually bind to.
35/// What: `127.0.0.1:7788` — the canonical localhost console address.
36/// Test: `test_resolve_reported_addr_default` asserts the `port` verb falls
37/// back to this value's host/port when no discovery file is present.
38pub const DEFAULT_HTTP: &str = "127.0.0.1:7788";
39
40/// Default console port, parsed once from [`DEFAULT_HTTP`].
41///
42/// Why: The `port` verb reports this when no running console has written a
43/// discovery file yet.
44/// What: `7788`.
45/// Test: covered by the `port` verb tests below.
46pub const DEFAULT_PORT: u16 = 7788;
47
48pub mod bind;
49// #6285: the console's own SPA, split out of `server` at the 500-SLOC cap.
50pub mod connector;
51pub mod console_ui;
52pub mod detect;
53pub mod mcp_handle;
54pub mod metrics_poller;
55pub mod poller;
56pub mod proxy;
57pub mod routes;
58// #6285: the console's client to trusty-search, which no longer serves HTTP.
59pub mod search_uds;
60pub mod server;
61pub mod service;
62// #6155: the trusty-search SPA, mounted under /tools/search/.
63pub mod tools_ui;
64pub mod webhook;
65
66/// How often the background sweep re-attempts pending webhook deliveries.
67///
68/// The sweep is the *recovery* mechanism, not the detection one — a stuck
69/// delivery is detected by `GET /api/console/metrics/webhooks`, which scans the
70/// spool on the request and therefore stays honest even if this loop dies.
71const WEBHOOK_RETRY_INTERVAL: Duration = Duration::from_secs(60);
72pub(crate) mod url_util;
73
74// ─── CLI ─────────────────────────────────────────────────────────────────────
75
76/// trusty-console: web dashboard for trusty services.
77///
78/// Why: Provides a single entry point for all console subcommands so future
79/// phases (status, doctor, open) can be added without breaking existing usage.
80/// What: Parses top-level arguments and delegates to subcommand handlers.
81/// Test: `cargo run -p trusty-console -- serve --help` must succeed.
82#[derive(Debug, Parser)]
83#[command(
84    name = "trusty-console",
85    version,
86    about = "Web dashboard for trusty services"
87)]
88pub struct Cli {
89    #[command(subcommand)]
90    pub command: Commands,
91}
92
93/// Available subcommands.
94///
95/// Why: `serve` runs the dashboard; `port` is a non-serving contract verb that
96/// reports the console's bound (or default) port so orchestrators like
97/// `trusty-installer` (`tctl`) can discover/launch the console without parsing logs.
98/// What: Clap enum; each variant carries its own args.
99/// Test: Subcommand selection tested via `Cli::parse_from`.
100#[derive(Debug, Subcommand)]
101pub enum Commands {
102    /// Start the HTTP server and serve the console dashboard.
103    Serve(ServeArgs),
104    /// Report the console's bound (or default) HTTP port and exit.
105    Port(PortArgs),
106    /// Manage inference provider configuration (API keys) — the universal
107    /// `config keys set/list/test/unset` surface shared by every trusty-*
108    /// binary (epic #2400 Wave 1, #2405).
109    Config(trusty_common::inference::config::ConfigCommand),
110    /// Manage the macOS launchd LaunchAgent for the console daemon (#2557).
111    ///
112    /// `install` writes `~/Library/LaunchAgents/com.trusty.trusty-console.plist`
113    /// (running `trusty-console serve`) and bootstraps it; `uninstall` unloads
114    /// and removes it; `status` / `logs` inspect the running agent. macOS-only.
115    /// `tctl install` / `tctl start` call `install` on the operator's behalf.
116    Service {
117        #[command(subcommand)]
118        action: service::ServiceAction,
119    },
120}
121
122/// Arguments for `trusty-console port`.
123///
124/// Why: `trusty-installer` (`tctl`) (the orchestrator, issue #1316) discovers
125/// the console URL by spawning `trusty-console port --json` and parsing the
126/// `{addr,port}` envelope (see trusty-installer `os_env.rs`). The verb must
127/// exist and be machine-readable for that discovery to work after the console is
128/// de-bundled from the host crates (#1318).
129/// What: A single `--json` flag selecting JSON output (default is a single
130/// human-readable port line).
131/// Test: `test_port_args_json_flag` / `test_port_args_default` below.
132#[derive(Debug, Parser)]
133pub struct PortArgs {
134    /// Emit a JSON envelope `{"addr":"<host>","port":<u16>}` instead of a bare
135    /// port number. Consumed by `trusty-installer` (`tctl`) console discovery.
136    #[arg(long, default_value_t = false)]
137    pub json: bool,
138}
139
140/// Arguments for `trusty-console serve`.
141///
142/// Why: The bind address must be configurable so users can change the port when
143/// 7788 is taken; `--open` is a convenience for developers; `--poll-interval`
144/// lets operators tune the background health-poll frequency; `--tailscale`
145/// enables durable tailnet exposure without requiring `--http 0.0.0.0`.
146/// What: Optional `--http` (default `127.0.0.1:7788`), `--open`,
147/// `--poll-interval`, and `--tailscale` flags.
148/// Env overrides: `TRUSTY_CONSOLE_BIND` sets the default bind mode so a
149/// supervised/relaunched daemon stays tailnet-reachable without extra flags.
150/// Test: Default address tested in `test_serve_args_defaults` below.
151#[derive(Debug, Parser)]
152pub struct ServeArgs {
153    /// Address to listen on (default: 127.0.0.1:7788).
154    ///
155    /// Takes precedence over --tailscale and TRUSTY_CONSOLE_BIND when set to a
156    /// non-default value.
157    #[arg(long, default_value = "127.0.0.1:7788")]
158    pub http: String,
159
160    /// Expose the console on both 127.0.0.1 and the machine's Tailscale IPv4,
161    /// enabling tailnet clients to reach the console without LAN exposure.
162    ///
163    /// The Tailscale IP is detected via `tailscale ip -4`. If Tailscale is not
164    /// running, prints a warning and falls back to localhost-only.
165    ///
166    /// Can also be set persistently via the TRUSTY_CONSOLE_BIND=tailscale env
167    /// var so a supervised/relaunched console stays tailnet-reachable without
168    /// manually passing this flag.
169    #[arg(long, default_value_t = false)]
170    pub tailscale: bool,
171
172    /// Open the console in the default browser after starting.
173    #[arg(long, default_value_t = false)]
174    pub open: bool,
175
176    /// Background poll interval in seconds (default: 15).
177    ///
178    /// Controls BOTH the health poller (`poller::start`) AND the metrics
179    /// poller (`metrics_poller::start`). Increasing this value reduces the
180    /// frequency of both the HTTP health checks against each connector AND
181    /// the stdio MCP `console_metrics` tool calls against trusty-analyze.
182    #[arg(long, default_value_t = 15u64)]
183    pub poll_interval: u64,
184}
185
186// ─── public entry point ────────────────────────────────────────────────────
187
188/// Library entry point for the trusty-console daemon, using the process argv.
189///
190/// Why: The standalone `trusty-console` crate is now the SOLE producer of the
191/// `trusty-console` binary (#1318 — de-bundled from the 5 host crates). The
192/// thin `main.rs` calls this, which simply forwards the process's global argv
193/// to `run_from`.
194/// What: Collects `std::env::args()` and delegates to [`run_from`].
195/// Test: Indirectly via the `run_from` tests below and the binary smoke test.
196pub async fn run() -> Result<()> {
197    run_from(std::env::args().collect()).await
198}
199
200/// Library entry point parameterised on an explicit argv vector.
201///
202/// Why: Decoupling argument parsing from the process's global argv (#1318)
203/// lets callers (tests, future embedders) drive the console deterministically
204/// without mutating `std::env`. Previously `run()` called `Cli::parse()`,
205/// which read global argv and could not be exercised in isolation.
206/// What: Initialises tracing, parses `argv` via `Cli::parse_from`, and
207/// dispatches to the matching subcommand handler. `argv[0]` is the program
208/// name (clap convention). Returns `Ok(())` after clean shutdown.
209/// Test: `test_run_from_port_json_outputs_envelope` drives this directly with
210/// a synthetic argv; integration via `cargo test -p trusty-console`.
211pub async fn run_from(argv: Vec<String>) -> Result<()> {
212    init_tracing(1);
213
214    let cli = Cli::parse_from(argv);
215
216    match cli.command {
217        Commands::Serve(args) => run_serve(args).await,
218        Commands::Port(args) => run_port(args),
219        Commands::Config(cmd) => cmd.run().await,
220        // `service` drives macOS launchd synchronously; no async work needed.
221        Commands::Service { action } => service::run_service_action(&action),
222    }
223}
224
225/// Resolve the console's reportable HTTP address (host, port).
226///
227/// Why: The `port` verb must report the LIVE port of a running console when
228/// one exists, falling back to the default otherwise — so `trusty-installer`
229/// (`tctl`) discovery (issue #1316) points at the real dashboard, not a guess.
230/// What: Reads the `trusty-console` discovery file via
231/// `trusty_common::read_daemon_addr`; on a parseable `host:port` returns that
232/// pair, else falls back to ([`DEFAULT_HTTP`] host, [`DEFAULT_PORT`]). Never
233/// errors — discovery failures degrade to the default.
234/// Test: `test_resolve_reported_addr_default` (no file → default).
235pub fn resolve_reported_addr() -> (String, u16) {
236    if let Ok(Some(recorded)) = trusty_common::read_daemon_addr("trusty-console")
237        && let Ok(sa) = recorded.parse::<std::net::SocketAddr>()
238    {
239        return (sa.ip().to_string(), sa.port());
240    }
241    let default_host = DEFAULT_HTTP
242        .rsplit_once(':')
243        .map(|(h, _)| h.to_owned())
244        .unwrap_or_else(|| "127.0.0.1".to_owned());
245    (default_host, DEFAULT_PORT)
246}
247
248/// Run the `port` subcommand: print the console's bound/default port and exit.
249///
250/// Why: `trusty-installer` (`tctl`) console discovery spawns
251/// `trusty-console port --json` and parses a `{addr,port}` envelope
252/// (trusty-installer `os_env.rs`). This verb is the contract that makes that
253/// discovery work; without it the call exits non-zero and console discovery is
254/// silently broken (the latent bug fixed by #1318).
255/// What: Resolves the reportable address; with `--json` prints
256/// `{"addr":"<host>","port":<u16>}` to stdout, otherwise prints the bare port.
257/// Returns `Ok(())`.
258/// Test: `test_run_from_port_json_outputs_envelope`,
259/// `test_port_envelope_is_valid_json`.
260pub fn run_port(args: PortArgs) -> Result<()> {
261    let (addr, port) = resolve_reported_addr();
262    if args.json {
263        let envelope = serde_json::json!({ "addr": addr, "port": port });
264        println!("{envelope}");
265    } else {
266        println!("{port}");
267    }
268    Ok(())
269}
270
271/// Run the `serve` subcommand.
272///
273/// Why: Separating the serve logic from `run()` keeps `run()` thin and allows
274/// this function to be called from integration tests.
275/// What: Resolves bind addresses (respecting `--tailscale`, `--http`, and
276/// `TRUSTY_CONSOLE_BIND`), builds the router, binds TCP listener(s), writes
277/// the discovery file, starts the background health-poll task, optionally opens
278/// a browser, then serves until SIGTERM/SIGINT with graceful shutdown.
279/// Additional addresses beyond the primary get their own spawned `axum::serve`
280/// task that runs concurrently until the shared shutdown signal fires.
281/// Test: Server integration tests in `server.rs` cover the router directly
282/// without exercising this function (to avoid real TCP binding in unit tests).
283pub async fn run_serve(args: ServeArgs) -> Result<()> {
284    // ── resolve bind mode ───────────────────────────────────────────────────
285    let mode = bind::BindMode::from_env_and_flags(&args.http, DEFAULT_HTTP, args.tailscale);
286    let port = bind::port_from_addr(&args.http, DEFAULT_PORT);
287    let addrs = bind::resolve_bind_addrs(&mode, port, bind::detect_tailscale_ipv4);
288
289    // ── service setup ───────────────────────────────────────────────────────
290    let connectors = detect::all_connectors();
291    let state = server::AppState::new(connectors);
292
293    // Kick off an eager first poll so the cache is warm before the first
294    // HTTP request arrives.
295    {
296        let cache = state.poller_cache().clone();
297        let c = state.connectors();
298        cache.poll_once(c).await;
299    }
300
301    // Start the background poller that refreshes the cache on the configured
302    // interval.
303    poller::start(
304        state.poller_cache().clone(),
305        state.connectors(),
306        Duration::from_secs(args.poll_interval),
307    );
308
309    // ── metrics MCP poll (trusty-analyze) ───────────────────────────────────
310    // The analyze handle is stored in AppState so on-demand routes
311    // (/api/console/metrics/analyze/indexes, /api/console/metrics/analyze/visualize)
312    // share the same child process. Here we hand a clone of that Arc to the
313    // background metrics poller so both paths reuse one stdio connection.
314    //
315    // Why "mcp" not "serve --mcp":
316    // `serve --mcp` starts BOTH the HTTP daemon and an MCP stdio loop; it
317    // requires trusty-search to be reachable at startup and tries to open the
318    // redb facts store (which may already be locked by the running daemon).
319    // `mcp` only runs a pure stdio bridge pointing at the running HTTP daemon;
320    // if the HTTP daemon is not yet up, `ensure_mcp_daemon_up` in analyze's
321    // `mcp` subcommand starts it automatically. This is the correct invocation
322    // for a lightweight stdio-only console_metrics child.
323    metrics_poller::start(
324        state.analyze_handle(),
325        state.metrics_cache().clone(),
326        Duration::from_secs(args.poll_interval),
327    );
328
329    // ── metrics MCP poll (trusty-memory) ────────────────────────────────────
330    // trusty-memory's stdio MCP mode is `serve --stdio` (see main.rs).
331    // The bridge forwards all JSON-RPC calls to the running HTTP daemon and
332    // auto-starts it if absent. On machines without trusty-memory the handle
333    // marks it Absent immediately; the cache stays None;
334    // /api/console/metrics/memory returns 503 (graceful degradation).
335    //
336    // The handle comes from AppState::mcp_handles so the services route and
337    // the metrics poller share the same McpServiceHandle (and thus the same
338    // tools/list probe result — once the probe marks the handle Degraded,
339    // that state is visible to both paths without a second probe).
340    {
341        let handles = state.mcp_handles();
342        if let Some(h) = handles.get("trusty-memory") {
343            metrics_poller::start(
344                Arc::clone(h),
345                state.memory_metrics_cache().clone(),
346                Duration::from_secs(args.poll_interval),
347            );
348        } else {
349            tracing::warn!(
350                service = "trusty-memory",
351                "run_serve: no MCP handle registered for trusty-memory — \
352                 metrics poller will not start for this service"
353            );
354        }
355    }
356
357    // ── metrics MCP poll (trusty-search) ────────────────────────────────────
358    // trusty-search's stdio MCP mode is `serve` (see serve_stdio in main.rs).
359    // On machines without trusty-search the handle marks it Absent immediately;
360    // the cache stays None; /api/console/metrics/search returns 503.
361    //
362    // Same shared-handle pattern as trusty-memory above.
363    {
364        let handles = state.mcp_handles();
365        if let Some(h) = handles.get("trusty-search") {
366            metrics_poller::start(
367                Arc::clone(h),
368                state.search_metrics_cache().clone(),
369                Duration::from_secs(args.poll_interval),
370            );
371        } else {
372            tracing::warn!(
373                service = "trusty-search",
374                "run_serve: no MCP handle registered for trusty-search — \
375                 metrics poller will not start for this service"
376            );
377        }
378    }
379
380    // ── metrics MCP poll (trusty-review) ────────────────────────────────────
381    // trusty-review's stdio MCP mode is `serve --stdio` (see commands/serve.rs).
382    // When in stdio mode, trusty-review does NOT start an HTTP daemon — it runs
383    // a pure MCP JSON-RPC loop over stdin/stdout, connected to the LLM directly.
384    // This is the correct invocation for the console's lightweight metrics poll.
385    // On machines without trusty-review the handle marks it Absent immediately;
386    // the cache stays None; /api/console/metrics/review returns 503.
387    //
388    // Same shared-handle pattern as trusty-memory and trusty-search above.
389    {
390        let handles = state.mcp_handles();
391        if let Some(h) = handles.get("trusty-review") {
392            metrics_poller::start(
393                Arc::clone(h),
394                state.review_metrics_cache().clone(),
395                Duration::from_secs(args.poll_interval),
396            );
397        } else {
398            tracing::warn!(
399                service = "trusty-review",
400                "run_serve: no MCP handle registered for trusty-review — \
401                 metrics poller will not start for this service"
402            );
403        }
404    }
405
406    // ── metrics MCP poll (trusty-mpm) ───────────────────────────────────────
407    // trusty-mpm's stdio MCP mode is `serve --stdio` (the #1221 bridge that
408    // auto-starts the durable daemon and forwards JSON-RPC to its loopback
409    // POST /rpc). The console_metrics poll keeps the coarse session-fleet +
410    // supervisor health cache warm for /api/console/metrics/mpm; the Sessions
411    // tab itself polls /api/console/sessions live at a faster cadence (#1222).
412    // On machines without trusty-mpm the handle marks it Absent immediately; the
413    // cache stays None; /api/console/metrics/mpm returns 503 (graceful).
414    {
415        let handles = state.mcp_handles();
416        if let Some(h) = handles.get("trusty-mpm") {
417            metrics_poller::start(
418                Arc::clone(h),
419                state.mpm_metrics_cache().clone(),
420                Duration::from_secs(args.poll_interval),
421            );
422        } else {
423            tracing::warn!(
424                service = "trusty-mpm",
425                "run_serve: no MCP handle registered for trusty-mpm — \
426                 metrics poller will not start for this service"
427            );
428        }
429    }
430
431    // #3269: trust the console's own non-loopback bind address(es) (e.g. the
432    // Tailscale CGNAT address in `--tailscale` mode) as write-origin
433    // self-origins, so the console's own write UI served from that address is
434    // not 403'd by the same-origin guard. Loopback stays trusted unconditionally
435    // regardless of bind mode.
436    let self_origins = routes::origin_guard::SelfOrigins::from_bind_addrs(&addrs);
437
438    // ── webhook ingress (#5089 step 3, ADR-0034) ────────────────────────────
439    // `?` on purpose: a console that cannot open its spool must not start and
440    // serve `/api/webhooks/{source}` anyway, because a delivery it cannot
441    // durably record is a delivery it must refuse — and an unmounted route
442    // would 404 instead of 5xx, which GitHub logs and no one reads.
443    let ingress = webhook::WebhookIngress::from_env()
444        .context("open the webhook spool under the console data directory")?;
445    info!(
446        spool = %ingress.spool().root().display(),
447        "webhook ingress ready at POST /api/webhooks/{{source}}"
448    );
449    webhook::start_retry_sweep(ingress.clone(), WEBHOOK_RETRY_INTERVAL);
450    let router = server::build_router_with_webhooks(state.clone(), self_origins, ingress);
451
452    // ── bind primary listener ───────────────────────────────────────────────
453    let primary_addr = *addrs.first().context("bind address list is empty")?;
454    let primary_listener = bind::bind_listener(primary_addr).await?;
455    let primary_local = primary_listener.local_addr().context("get local addr")?;
456    let addr_string = primary_local.to_string();
457    info!("trusty-console listening on http://{primary_local}");
458
459    // ── bind additional listeners (Tailscale mode: secondary addr) ──────────
460    for &extra_addr in addrs.get(1..).unwrap_or(&[]) {
461        let extra_listener = bind::bind_listener(extra_addr).await?;
462        let extra_local = extra_listener
463            .local_addr()
464            .context("get extra local addr")?;
465        info!("trusty-console also listening on http://{extra_local}");
466        eprintln!("trusty-console (tailnet): http://{extra_local}");
467        let r = router.clone();
468        tokio::spawn(async move {
469            if let Err(e) = axum::serve(extra_listener, r)
470                .with_graceful_shutdown(trusty_common::shutdown_signal())
471                .await
472            {
473                tracing::warn!("extra listener {extra_local} exited: {e}");
474            }
475        });
476    }
477
478    // ── write discovery file (primary address) ──────────────────────────────
479    // Best-effort: log a warning on failure but do not abort the serve.
480    if let Err(e) = write_daemon_addr("trusty-console", &addr_string) {
481        tracing::warn!("could not write trusty-console discovery file: {e}");
482    }
483
484    let console_url = format!("http://{primary_local}");
485    eprintln!("trusty-console: {console_url}");
486
487    if args.open {
488        // Best-effort browser open; ignore errors.
489        let _ = open::that(&console_url);
490    }
491
492    axum::serve(primary_listener, router)
493        .with_graceful_shutdown(shutdown_signal())
494        .await
495        .context("server error")?;
496
497    // Best-effort removal of the discovery file on clean shutdown.
498    // Only remove the file if it still points to our address; another
499    // instance may have already written a new one.
500    //
501    // RESIDUAL RACE: the read → compare → delete sequence is not atomic. A
502    // second instance could write a new address between our read and our
503    // remove_file, causing us to delete a file we should not. The window is
504    // tiny (milliseconds) and the consequence is cosmetic (a stale `port`
505    // invocation returns the default rather than the live address). No
506    // behavior change is required — this comment documents the known race.
507    if let Ok(Some(recorded)) = trusty_common::read_daemon_addr("trusty-console")
508        && recorded == addr_string
509        && let Ok(dir) = trusty_common::resolve_data_dir("trusty-console")
510    {
511        let _ = std::fs::remove_file(dir.join("http_addr"));
512    }
513
514    Ok(())
515}
516
517// ─── tests ───────────────────────────────────────────────────────────────────
518
519#[cfg(test)]
520mod tests {
521    use super::*;
522
523    /// Serialises tests that mutate the `TRUSTY_DATA_DIR_OVERRIDE` env var.
524    ///
525    /// Why: `std::env::set_var`/`remove_var` are process-global; parallel test
526    /// threads racing on them cause flaky failures. A module-level mutex makes
527    /// the override-set / call / override-clear sequence atomic per test.
528    /// What: a `()` mutex acquired at the top of each env-mutating test.
529    /// Test: used by the `port` verb tests below.
530    static DATA_DIR_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
531
532    /// Why: default http address must be 127.0.0.1:7788 and tailscale off.
533    /// What: parses `serve` with no flags and checks all defaults.
534    /// Test: this test itself.
535    #[test]
536    fn test_serve_args_defaults() {
537        let cli = Cli::parse_from(["trusty-console", "serve"]);
538        match cli.command {
539            Commands::Serve(args) => {
540                assert_eq!(args.http, "127.0.0.1:7788");
541                assert!(!args.open);
542                assert!(!args.tailscale);
543                assert_eq!(args.poll_interval, 15);
544            }
545            other => panic!("expected Serve, got {other:?}"),
546        }
547    }
548
549    /// Why: --tailscale flag must be parsed correctly.
550    /// What: parses `serve --tailscale`; asserts tailscale=true.
551    /// Test: this test itself.
552    #[test]
553    fn test_serve_args_tailscale_flag() {
554        let cli = Cli::parse_from(["trusty-console", "serve", "--tailscale"]);
555        match cli.command {
556            Commands::Serve(args) => {
557                assert!(args.tailscale);
558                assert_eq!(args.http, "127.0.0.1:7788");
559            }
560            other => panic!("expected Serve, got {other:?}"),
561        }
562    }
563
564    /// Why: custom --http flag must override the default.
565    /// What: parses `serve --http 0.0.0.0:9000`.
566    /// Test: this test itself.
567    #[test]
568    fn test_serve_args_custom_http() {
569        let cli = Cli::parse_from(["trusty-console", "serve", "--http", "0.0.0.0:9000"]);
570        match cli.command {
571            Commands::Serve(args) => {
572                assert_eq!(args.http, "0.0.0.0:9000");
573            }
574            other => panic!("expected Serve, got {other:?}"),
575        }
576    }
577
578    /// Why: --poll-interval must override the default.
579    /// What: parses `serve --poll-interval 30`.
580    /// Test: this test itself.
581    #[test]
582    fn test_serve_args_custom_poll_interval() {
583        let cli = Cli::parse_from(["trusty-console", "serve", "--poll-interval", "30"]);
584        match cli.command {
585            Commands::Serve(args) => {
586                assert_eq!(args.poll_interval, 30);
587            }
588            other => panic!("expected Serve, got {other:?}"),
589        }
590    }
591
592    /// Why: the `port` subcommand must parse with a default (non-JSON) form so
593    /// the bare-port output path is reachable.
594    /// What: parses `port` and asserts `--json` defaults to false.
595    /// Test: this test itself.
596    #[test]
597    fn test_port_args_default() {
598        let cli = Cli::parse_from(["trusty-console", "port"]);
599        match cli.command {
600            Commands::Port(args) => assert!(!args.json),
601            other => panic!("expected Port, got {other:?}"),
602        }
603    }
604
605    /// Why: `trusty-installer` (`tctl`) invokes `trusty-console port --json`; the flag must parse.
606    /// What: parses `port --json` and asserts `json == true`.
607    /// Test: this test itself.
608    #[test]
609    fn test_port_args_json_flag() {
610        let cli = Cli::parse_from(["trusty-console", "port", "--json"]);
611        match cli.command {
612            Commands::Port(args) => assert!(args.json),
613            other => panic!("expected Port, got {other:?}"),
614        }
615    }
616
617    /// Why: when no console has written a discovery file, the reported port
618    /// must fall back to the canonical default so `trusty-installer` (`tctl`)
619    /// still gets a usable address.
620    /// What: calls `resolve_reported_addr` under an isolated data dir (no
621    /// discovery file present) and asserts the default host/port.
622    /// Test: this test itself; uses the data-dir override env to avoid reading
623    /// a real running console's file.
624    #[test]
625    fn test_resolve_reported_addr_default() {
626        let _guard = DATA_DIR_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
627        let tmp = std::env::temp_dir().join(format!(
628            "trusty-console-port-test-{}-{}",
629            std::process::id(),
630            std::time::SystemTime::now()
631                .duration_since(std::time::UNIX_EPOCH)
632                .map(|d| d.as_nanos())
633                .unwrap_or(0)
634        ));
635        std::fs::create_dir_all(&tmp).expect("create temp data dir");
636        // SAFETY: guarded by data_dir_test_lock to serialise env mutation.
637        unsafe {
638            std::env::set_var(trusty_common::DATA_DIR_OVERRIDE_ENV, &tmp);
639        }
640        let (addr, port) = resolve_reported_addr();
641        unsafe {
642            std::env::remove_var(trusty_common::DATA_DIR_OVERRIDE_ENV);
643        }
644        assert_eq!(addr, "127.0.0.1");
645        assert_eq!(port, DEFAULT_PORT);
646    }
647
648    /// Why: the JSON envelope emitted by `run_port` must be valid JSON with the
649    /// `addr` and `port` keys that `trusty-installer` (`tctl`) `parse_console_port` consumes.
650    /// What: builds the same envelope `run_port` prints and round-trips it
651    /// through serde to assert structure.
652    /// Test: this test itself.
653    #[test]
654    fn test_port_envelope_is_valid_json() {
655        let envelope = serde_json::json!({ "addr": "127.0.0.1", "port": DEFAULT_PORT });
656        let s = envelope.to_string();
657        let v: serde_json::Value = serde_json::from_str(&s).expect("valid json");
658        assert_eq!(v.get("addr").and_then(|a| a.as_str()), Some("127.0.0.1"));
659        assert_eq!(
660            v.get("port").and_then(|p| p.as_u64()),
661            Some(DEFAULT_PORT as u64)
662        );
663    }
664
665    /// Why: the #1318 decoupling requires that an explicit argv parses to the
666    /// `Port` command and that the `port` handler runs without touching the
667    /// process's global argv. This exercises that parse → dispatch path.
668    /// What: parses `["trusty-console","port","--json"]` via `Cli::parse_from`
669    /// (the same call `run_from` makes) and runs `run_port` synchronously under
670    /// an isolated data dir; asserts the dispatch matches `Port` and the
671    /// handler returns Ok. Kept synchronous so the env-override mutex is never
672    /// held across an `await` (clippy::await_holding_lock).
673    /// Test: this test itself.
674    #[test]
675    fn test_run_from_port_json_outputs_envelope() {
676        let _guard = DATA_DIR_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
677        let tmp = std::env::temp_dir().join(format!(
678            "trusty-console-runfrom-test-{}-{}",
679            std::process::id(),
680            std::time::SystemTime::now()
681                .duration_since(std::time::UNIX_EPOCH)
682                .map(|d| d.as_nanos())
683                .unwrap_or(0)
684        ));
685        std::fs::create_dir_all(&tmp).expect("create temp data dir");
686        // SAFETY: guarded by DATA_DIR_ENV_LOCK to serialise env mutation.
687        unsafe {
688            std::env::set_var(trusty_common::DATA_DIR_OVERRIDE_ENV, &tmp);
689        }
690        let argv = [
691            "trusty-console".to_owned(),
692            "port".to_owned(),
693            "--json".to_owned(),
694        ];
695        let cli = Cli::parse_from(argv);
696        let result = match cli.command {
697            Commands::Port(args) => {
698                assert!(args.json, "argv --json should parse to json=true");
699                run_port(args)
700            }
701            other => panic!("expected Port, got {other:?}"),
702        };
703        unsafe {
704            std::env::remove_var(trusty_common::DATA_DIR_OVERRIDE_ENV);
705        }
706        assert!(result.is_ok(), "run_port(port --json) should succeed");
707    }
708}