Skip to main content

trusty_common/
lib.rs

1//! Shared utility surface for trusty-* projects.
2//!
3//! Why: Port auto-detect, data-directory resolution, tracing init, NO_COLOR
4//! handling, and the OpenRouter chat-completions client appeared in both
5//! trusty-memory and trusty-search with subtle divergence. Centralising keeps
6//! them aligned and gives future trusty-* binaries a one-import surface.
7//!
8//! What: pure utility functions — no global state. Each subsystem is a free
9//! function or a small helper struct.
10//!
11//! Test: `cargo test -p trusty-common` covers port walking, data-dir creation,
12//! and the OpenRouter request shape (without hitting the network).
13//!
14//! # Test isolation: `TRUSTY_DATA_DIR_OVERRIDE`
15//!
16//! macOS's [`dirs::data_dir()`] resolves the application-support directory via
17//! `NSFileManager`, a native Cocoa API that completely ignores the `HOME` and
18//! `XDG_DATA_HOME` environment variables. This makes it impossible to redirect
19//! data-directory access in tests using ordinary env-var tricks, because the
20//! kernel query bypasses the environment entirely.
21//!
22//! To work around this, [`resolve_data_dir`] checks the
23//! [`DATA_DIR_OVERRIDE_ENV`] (`TRUSTY_DATA_DIR_OVERRIDE`) environment variable
24//! before consulting `dirs::data_dir()`. When set, the variable's value is used
25//! as the base directory verbatim, and `dirs::data_dir()` is never called.
26//!
27//! **This escape hatch is intended for testing only.** Do not set it in
28//! production deployments; rely on the OS-standard data directory instead.
29
30use std::net::SocketAddr;
31use std::path::{Path, PathBuf};
32
33pub mod chat;
34pub mod claude_config;
35pub mod project_discovery;
36
37/// macOS LaunchAgent generation and lifecycle management. macOS-only —
38/// the module compiles to nothing on every other platform.
39#[cfg(target_os = "macos")]
40pub mod launchd;
41
42#[cfg(feature = "axum-server")]
43pub mod server;
44
45/// Shared JSON-RPC 2.0 / MCP primitives (formerly the `trusty-mcp-core` crate).
46///
47/// Why: Centralises `Request`/`Response`/`JsonRpcError` envelopes, the
48/// `initialize` response builder, an async stdio dispatch loop, and the
49/// OpenRPC `rpc.discover` helpers so every MCP server in the workspace
50/// imports the same types.
51/// What: Gated behind the `mcp` feature; pulls in no extra dependencies
52/// beyond `serde` / `tokio`, both of which are already required.
53/// Test: `cargo test -p trusty-common --features mcp` runs the module's
54/// own unit tests (envelope round-trips, stdio loop dispatch, OpenRPC
55/// builder shape).
56#[cfg(feature = "mcp")]
57pub mod mcp;
58
59/// General-purpose JSON-RPC client + transports (formerly the library half
60/// of the `trusty-rpc` crate).
61///
62/// Why: Both `trpc` (the CLI) and any future library consumer want one
63/// place that owns the JSON-RPC envelope construction, stdio-subprocess
64/// transport, HTTP transport, and pretty-printers.
65/// What: Gated behind the `rpc` feature; requires `uuid` for request id
66/// generation. The HTTP transport reuses the workspace `reqwest`.
67/// Test: `cargo test -p trusty-common --features rpc` runs the module's
68/// own unit tests (envelope extraction, pretty-print smoke tests).
69#[cfg(feature = "rpc")]
70pub mod rpc;
71
72/// Shared text-embedding abstraction (formerly the `trusty-embedder` crate).
73///
74/// Why: trusty-memory and trusty-search both ship near-identical `Embedder`
75/// traits and `FastEmbedder` implementations; centralising the surface here
76/// keeps them aligned and lets future consumers pick up embedding for free
77/// without a separate published crate.
78/// What: Gated behind the `embedder` feature. Exposes the `Embedder` trait,
79/// `FastEmbedder` (fastembed-rs, all-MiniLM-L6-v2, 384-d) with LRU caching
80/// and ORT warmup, and (under `embedder-test-support`) the `MockEmbedder`
81/// test double.
82/// Test: `cargo test -p trusty-common --features embedder,embedder-test-support`
83/// covers the mock embedder and ONNX-backed `#[ignore]`d integration tests.
84#[cfg(feature = "embedder")]
85pub mod embedder;
86
87/// Symbol-graph engine (formerly the `trusty-symgraph` crate).
88///
89/// Why: All trusty-* tools that touch source code (open-mpm, trusty-search,
90/// trusty-analyze) want the same `EntityType` / `RawEntity` / `EdgeKind`
91/// data shapes and (for orchestrators) the same tree-sitter pipeline. Living
92/// here lets the workspace ship one tree-sitter `links =` slot instead of
93/// juggling two crates that both claim it.
94/// What: Gated behind two features. `symgraph` exposes only the contracts
95/// surface (`EntityType`, `RawEntity`, `EdgeKind`, `fact_hash_str`, tables)
96/// — no tree-sitter, no `links` conflict. `symgraph-parser` additionally
97/// pulls in tree-sitter and the full parse → registry → emit stack.
98/// `symgraph-server` enables the HTTP server frontend.
99/// Test: `cargo test -p trusty-common --features symgraph` exercises the
100/// contracts surface; `cargo test -p trusty-symgraph` covers the parser
101/// path through the thin re-export shim.
102#[cfg(feature = "symgraph")]
103pub mod symgraph;
104
105/// Memory Palace storage engine (formerly the `trusty-memory-core` crate).
106///
107/// Why: Centralises the Memory Palace data model (`Palace` / `Wing` /
108/// `Room` / `Drawer`), storage backends (usearch vector index + SQLite
109/// knowledge graph + chat-session log + payload store), retrieval handle,
110/// and the dream / decay / analytics / git-history surfaces so every
111/// trusty-* binary that talks to a palace reuses the same types. Absorbed
112/// into `trusty-common` (issue #5 phase 2d) so we ship one fewer published
113/// crate.
114/// What: Gated behind the `memory-core` feature because it pulls in heavy
115/// storage deps (`usearch`, `rusqlite`, `r2d2`, `git2`, `kuzu`). Enables
116/// the embedder surface automatically (memory-core → embedder).
117/// Test: `cargo test -p trusty-common --features memory-core` exercises
118/// the full surface.
119#[cfg(feature = "memory-core")]
120pub mod memory_core;
121
122/// Unified monitor TUI for the trusty-search and trusty-memory daemons
123/// (formerly the `trusty-monitor-tui` crate).
124///
125/// Why: operators run both daemons and want one terminal surface that shows
126/// the health of both at a glance. Living here behind the `monitor-tui`
127/// feature flag matches the workspace's "one fewer published crate" direction
128/// (issue #31 companion) and keeps the dashboard logic unit-testable.
129/// What: gated behind the `monitor-tui` feature, which pulls in `ratatui` and
130/// `crossterm`. Exposes `monitor::run` (the entry point the `trusty-monitor`
131/// binary calls) plus the pure `dashboard` / `search_client` / `memory_client`
132/// submodules.
133/// Test: `cargo test -p trusty-common --features monitor-tui` covers the
134/// rendering, layout, and HTTP-client pieces.
135#[cfg(feature = "monitor-tui")]
136pub mod monitor;
137
138pub use chat::{
139    ChatEvent, ChatProvider, LocalModelConfig, OllamaProvider, OpenRouterProvider, ToolCall,
140    ToolDef, auto_detect_local_provider,
141};
142
143use anyhow::{Context, Result, anyhow};
144use serde::{Deserialize, Serialize};
145use tokio::net::TcpListener;
146
147// ─── Port binding ─────────────────────────────────────────────────────────
148
149/// Bind to `addr`; if the port is in use, walk forward up to `max_attempts`
150/// ports and return the first listener that binds.
151///
152/// Why: Running multiple instances of a trusty-* daemon (or restarting before
153/// the kernel releases the prior socket) shouldn't produce a noisy failure —
154/// auto-incrementing gives a friendlier developer experience while still
155/// honouring the user's preferred starting port.
156/// What: returns the first successful `tokio::net::TcpListener`. Callers can
157/// inspect `local_addr()` to discover where it landed and report it however
158/// they prefer — this function does not perform any I/O on stdout/stderr.
159/// `max_attempts == 0` means "try `addr` exactly once".
160/// Test: `auto_port_walks_forward` binds a port, then calls this with the
161/// occupied port and confirms a different free port is returned.
162pub async fn bind_with_auto_port(addr: SocketAddr, max_attempts: u16) -> Result<TcpListener> {
163    use std::io::ErrorKind;
164    let mut current = addr;
165    for attempt in 0..=max_attempts {
166        match TcpListener::bind(current).await {
167            Ok(l) => return Ok(l),
168            Err(e) if e.kind() == ErrorKind::AddrInUse && attempt < max_attempts => {
169                let next_port = current.port().saturating_add(1);
170                if next_port == 0 {
171                    anyhow::bail!("ran out of ports while searching for free slot");
172                }
173                tracing::warn!("port {} in use, trying {}", current.port(), next_port);
174                current.set_port(next_port);
175            }
176            Err(e) => return Err(e.into()),
177        }
178    }
179    anyhow::bail!("could not find free port after {max_attempts} attempts")
180}
181
182// ─── Data directory ───────────────────────────────────────────────────────
183
184/// Environment variable name for the data-directory test escape hatch.
185///
186/// Why: macOS's `dirs::data_dir()` delegates to `NSFileManager`, a native Cocoa
187/// API that ignores `HOME` and `XDG_DATA_HOME`. Setting `HOME` in a test process
188/// does **not** redirect `dirs::data_dir()` on macOS, making path isolation
189/// impossible without a separate bypass. This constant names that bypass.
190///
191/// What: When `TRUSTY_DATA_DIR_OVERRIDE` is set in the environment,
192/// [`resolve_data_dir`] uses its value as the base directory and skips the
193/// `dirs::data_dir()` call entirely. The final path is
194/// `${TRUSTY_DATA_DIR_OVERRIDE}/<app_name>`, identical in structure to the
195/// normal OS-standard path.
196///
197/// **Intended for tests only.** Do not set this variable in production; it
198/// bypasses the OS-standard application-data directory.
199///
200/// Test: All `resolve_data_dir` tests in this module set this var to a
201/// temporary directory so they run identically on macOS, Linux, and Windows.
202pub const DATA_DIR_OVERRIDE_ENV: &str = "TRUSTY_DATA_DIR_OVERRIDE";
203
204/// Resolve `<data_dir>/<app_name>`, creating it if it doesn't exist.
205///
206/// Why: All trusty-* tools want a per-machine, per-app directory under the
207/// OS-standard data dir (`~/Library/Application Support/`, `~/.local/share/`,
208/// `%APPDATA%/`). If `dirs::data_dir()` is unavailable (rare — locked-down
209/// containers), falls back to `~/.<app_name>` so the tool still works.
210///
211/// The [`DATA_DIR_OVERRIDE_ENV`] (`TRUSTY_DATA_DIR_OVERRIDE`) environment
212/// variable provides a test escape hatch: when set, `dirs::data_dir()` is
213/// **never called** and the variable's value is used as the base directory
214/// instead. This is necessary because macOS's `dirs::data_dir()` calls
215/// `NSFileManager` — a native Cocoa API that resolves the application-support
216/// directory through the system rather than through the process environment —
217/// so setting `HOME` or `XDG_DATA_HOME` in a test process does not redirect
218/// it. `TRUSTY_DATA_DIR_OVERRIDE` is the only reliable cross-platform way to
219/// isolate test data paths. **It is intended for tests only; do not set it in
220/// production.**
221///
222/// What: returns the absolute path `${base}/<app_name>` (created if absent).
223/// Resolution order:
224/// 1. `$TRUSTY_DATA_DIR_OVERRIDE/<app_name>` — when the env var is set.
225/// 2. `$(dirs::data_dir())/<app_name>` — normal OS-standard path.
226/// 3. `~/.<app_name>` — fallback when `dirs::data_dir()` returns `None`.
227///
228/// Test: `resolve_data_dir_creates_directory` pins a temporary directory via
229/// `TRUSTY_DATA_DIR_OVERRIDE` and asserts that the returned path is created
230/// under it, exercising both the override path and directory-creation logic.
231pub fn resolve_data_dir(app_name: &str) -> Result<PathBuf> {
232    let base = if let Ok(override_dir) = std::env::var(DATA_DIR_OVERRIDE_ENV) {
233        PathBuf::from(override_dir)
234    } else {
235        dirs::data_dir()
236            .or_else(|| dirs::home_dir().map(|h| h.join(format!(".{app_name}"))))
237            .context("could not resolve data directory or home directory")?
238    };
239    let dir = if base.ends_with(format!(".{app_name}")) {
240        base
241    } else {
242        base.join(app_name)
243    };
244    std::fs::create_dir_all(&dir)
245        .with_context(|| format!("create data directory {}", dir.display()))?;
246    Ok(dir)
247}
248
249// ─── Daemon address file ──────────────────────────────────────────────────
250
251/// Filename used inside each app's data directory to record the daemon's
252/// bound HTTP address. Kept as a module-level constant so writers and readers
253/// can't drift.
254const DAEMON_ADDR_FILENAME: &str = "http_addr";
255
256/// Write the daemon's bound HTTP address to the app's data directory.
257///
258/// Why: Both trusty-search and trusty-memory persist their bound `host:port`
259/// to disk so MCP clients (and follow-up CLI invocations) can discover where
260/// the daemon ended up after auto-port-walking. Centralising the path layout
261/// keeps the two projects in sync and prevents a third trusty-* daemon from
262/// inventing yet another location.
263/// What: writes `addr` verbatim (no trailing newline) to
264/// `{resolve_data_dir(app_name)}/http_addr`, creating the directory if it
265/// doesn't yet exist. Atomic-overwrite semantics aren't required — the file
266/// is rewritten on every daemon start.
267/// Test: `daemon_addr_round_trips` writes then reads under a stubbed HOME and
268/// confirms equality.
269pub fn write_daemon_addr(app_name: &str, addr: &str) -> Result<()> {
270    let dir = resolve_data_dir(app_name)?;
271    let path = dir.join(DAEMON_ADDR_FILENAME);
272    std::fs::write(&path, addr).with_context(|| format!("write daemon addr to {}", path.display()))
273}
274
275/// Read the daemon's HTTP address from the app's data directory.
276///
277/// Why: CLI commands and MCP clients need to discover the running daemon's
278/// bound port. Returning `Option` lets callers distinguish "daemon never
279/// started" (file absent) from "filesystem error" (permission denied, etc.)
280/// without resorting to string matching on error messages.
281/// What: reads `{resolve_data_dir(app_name)}/http_addr`, trims surrounding
282/// whitespace, and returns `Some(addr)`. Returns `Ok(None)` iff the file
283/// does not exist; any other I/O error propagates as `Err`.
284/// Test: `daemon_addr_round_trips` and `read_daemon_addr_missing_returns_none`.
285pub fn read_daemon_addr(app_name: &str) -> Result<Option<String>> {
286    let dir = resolve_data_dir(app_name)?;
287    let path = dir.join(DAEMON_ADDR_FILENAME);
288    match std::fs::read_to_string(&path) {
289        Ok(s) => Ok(Some(s.trim().to_string())),
290        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
291        Err(e) => Err(anyhow::Error::new(e))
292            .with_context(|| format!("read daemon addr from {}", path.display())),
293    }
294}
295
296// ─── CLI initialisation ───────────────────────────────────────────────────
297
298/// Initialise the global tracing subscriber.
299///
300/// Why: Every trusty-* binary wants the same verbosity ladder and the same
301/// `RUST_LOG` override semantics. Defining it once removes the boilerplate
302/// from every `main.rs`.
303/// What: `verbose_count` maps `0 → warn`, `1 → info`, `2 → debug`, `3+ →
304/// trace`. If `RUST_LOG` is set in the environment it wins. Logs go to
305/// stderr so stdout stays clean for MCP JSON-RPC.
306/// Test: side-effecting (global subscriber) — covered by integration with
307/// `cargo run -- -v status` in downstream crates.
308pub fn init_tracing(verbose_count: u8) {
309    let default_filter = match verbose_count {
310        0 => "warn",
311        1 => "info",
312        2 => "debug",
313        _ => "trace",
314    };
315    let filter = tracing_subscriber::EnvFilter::try_from_default_env()
316        .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new(default_filter));
317    // try_init so callers that pre-install a subscriber don't panic.
318    let _ = tracing_subscriber::fmt()
319        .with_env_filter(filter)
320        .with_writer(std::io::stderr)
321        .with_target(false)
322        .try_init();
323}
324
325/// Disable coloured terminal output when requested or when stdout is not a TTY.
326///
327/// Why: Pipe-friendly output is mandatory for scripting (`trusty-search list
328/// | jq …`). `NO_COLOR` / `TERM=dumb` are the canonical signals; passing
329/// `--no-color` should override too.
330/// What: calls `colored::control::set_override(false)` when the caller asks
331/// for it or when the standard heuristics indicate no colour.
332/// Test: side-effecting global; trivially covered by manual `NO_COLOR=1 cargo
333/// run -- list`.
334pub fn maybe_disable_color(no_color: bool) {
335    let env_says_no =
336        std::env::var("NO_COLOR").is_ok() || std::env::var("TERM").as_deref() == Ok("dumb");
337    if no_color || env_says_no {
338        colored::control::set_override(false);
339    }
340}
341
342// ─── OpenRouter ───────────────────────────────────────────────────────────
343
344const OPENROUTER_URL: &str = "https://openrouter.ai/api/v1/chat/completions";
345const HTTP_REFERER: &str = "https://github.com/bobmatnyc/trusty-common";
346const X_TITLE: &str = "trusty-common";
347const OPENROUTER_CONNECT_TIMEOUT_SECS: u64 = 10;
348const OPENROUTER_REQUEST_TIMEOUT_SECS: u64 = 120; // chat completions can take 60–90s
349
350/// OpenAI-compatible chat message.
351///
352/// Why: Both trusty-memory's `chat` subcommand and trusty-search's `/chat`
353/// endpoint speak the OpenRouter format. Sharing the struct keeps them in
354/// step (and lets callers compose chat histories without re-defining types).
355/// Tool-use additions (`tool_call_id`, `tool_calls`) follow the OpenAI
356/// function-calling shape: assistant messages set `tool_calls` when the model
357/// requests tool invocations; subsequent `role: "tool"` messages echo the
358/// matching `tool_call_id` with the tool's result in `content`.
359/// What: `role` is one of `"system" | "user" | "assistant" | "tool"`.
360/// `content` is the message text. `tool_call_id` is the id of the tool call
361/// this message is replying to (only set when `role == "tool"`). `tool_calls`
362/// is the raw OpenAI `tool_calls` array on an assistant message that asked
363/// to invoke tools — kept as `serde_json::Value` so we don't drop any fields
364/// the upstream may add.
365/// Test: serde round-trip in `chat_message_round_trips`.
366#[derive(Debug, Clone, Serialize, Deserialize)]
367pub struct ChatMessage {
368    pub role: String,
369    pub content: String,
370    #[serde(skip_serializing_if = "Option::is_none", default)]
371    pub tool_call_id: Option<String>,
372    #[serde(skip_serializing_if = "Option::is_none", default)]
373    pub tool_calls: Option<Vec<serde_json::Value>>,
374}
375
376#[derive(Debug, Serialize)]
377struct ChatRequest<'a> {
378    model: &'a str,
379    messages: &'a [ChatMessage],
380    stream: bool,
381}
382
383#[derive(Debug, Deserialize)]
384struct ChatResponse {
385    choices: Vec<Choice>,
386}
387
388#[derive(Debug, Deserialize)]
389struct Choice {
390    message: ResponseMessage,
391}
392
393#[derive(Debug, Deserialize)]
394struct ResponseMessage {
395    #[serde(default)]
396    content: String,
397}
398
399/// Send a chat completion request to OpenRouter and return the assistant's
400/// message content.
401///
402/// Why: A one-shot, non-streaming chat call is the common-case helper — used
403/// by trusty-memory's `chat` CLI and trusty-search's `/chat` endpoint.
404/// What: POSTs `{model, messages, stream: false}` to OpenRouter with bearer
405/// auth, decodes the response, and returns `choices[0].message.content`.
406/// Errors propagate as anyhow with HTTP status context.
407/// Test: error paths covered by `openrouter_propagates_http_errors` (uses a
408/// blackhole base URL — no real call).
409#[deprecated(since = "0.3.1", note = "Use OpenRouterProvider::chat_stream instead")]
410pub async fn openrouter_chat(
411    api_key: &str,
412    model: &str,
413    messages: Vec<ChatMessage>,
414) -> Result<String> {
415    if api_key.is_empty() {
416        return Err(anyhow!("openrouter api key is empty"));
417    }
418    let client = reqwest::Client::builder()
419        .connect_timeout(std::time::Duration::from_secs(
420            OPENROUTER_CONNECT_TIMEOUT_SECS,
421        ))
422        .timeout(std::time::Duration::from_secs(
423            OPENROUTER_REQUEST_TIMEOUT_SECS,
424        ))
425        .build()
426        .context("build reqwest client for openrouter_chat")?;
427    let body = ChatRequest {
428        model,
429        messages: &messages,
430        stream: false,
431    };
432    let resp = client
433        .post(OPENROUTER_URL)
434        .bearer_auth(api_key)
435        .header("HTTP-Referer", HTTP_REFERER)
436        .header("X-Title", X_TITLE)
437        .json(&body)
438        .send()
439        .await
440        .context("POST openrouter chat completions")?;
441    let status = resp.status();
442    if !status.is_success() {
443        let text = resp.text().await.unwrap_or_default();
444        return Err(anyhow!("openrouter HTTP {status}: {text}"));
445    }
446    let payload: ChatResponse = resp.json().await.context("decode openrouter response")?;
447    payload
448        .choices
449        .into_iter()
450        .next()
451        .map(|c| c.message.content)
452        .ok_or_else(|| anyhow!("openrouter returned no choices"))
453}
454
455/// Stream chat-completion deltas from OpenRouter through a tokio mpsc channel.
456///
457/// Why: `chat` UIs want incremental tokens for a responsive feel; the
458/// streaming endpoint emits SSE `data:` frames with delta content.
459/// What: POSTs the request with `stream: true`, parses each SSE `data:` line
460/// as a JSON object, extracts `choices[0].delta.content`, and sends each
461/// non-empty chunk to `tx`. The function returns when the stream terminates
462/// (either by `[DONE]` sentinel or by upstream EOF).
463/// Test: integration-only (no offline mock); covered manually via the
464/// trusty-search `/chat` endpoint that re-uses this helper.
465#[deprecated(since = "0.3.1", note = "Use OpenRouterProvider::chat_stream instead")]
466pub async fn openrouter_chat_stream(
467    api_key: &str,
468    model: &str,
469    messages: Vec<ChatMessage>,
470    tx: tokio::sync::mpsc::Sender<String>,
471) -> Result<()> {
472    use futures_util::StreamExt;
473
474    if api_key.is_empty() {
475        return Err(anyhow!("openrouter api key is empty"));
476    }
477    let client = reqwest::Client::builder()
478        .connect_timeout(std::time::Duration::from_secs(
479            OPENROUTER_CONNECT_TIMEOUT_SECS,
480        ))
481        .timeout(std::time::Duration::from_secs(
482            OPENROUTER_REQUEST_TIMEOUT_SECS,
483        ))
484        .build()
485        .context("build reqwest client for openrouter_chat_stream")?;
486    let body = ChatRequest {
487        model,
488        messages: &messages,
489        stream: true,
490    };
491    let resp = client
492        .post(OPENROUTER_URL)
493        .bearer_auth(api_key)
494        .header("HTTP-Referer", HTTP_REFERER)
495        .header("X-Title", X_TITLE)
496        .json(&body)
497        .send()
498        .await
499        .context("POST openrouter chat completions (stream)")?;
500    let status = resp.status();
501    if !status.is_success() {
502        let text = resp.text().await.unwrap_or_default();
503        return Err(anyhow!("openrouter HTTP {status}: {text}"));
504    }
505
506    let mut buf = String::new();
507    let mut stream = resp.bytes_stream();
508    while let Some(chunk) = stream.next().await {
509        let bytes = chunk.context("read openrouter stream chunk")?;
510        let text = match std::str::from_utf8(&bytes) {
511            Ok(s) => s,
512            Err(_) => continue,
513        };
514        buf.push_str(text);
515
516        while let Some(idx) = buf.find('\n') {
517            let line: String = buf.drain(..=idx).collect();
518            let line = line.trim();
519            let Some(payload) = line.strip_prefix("data:").map(str::trim) else {
520                continue;
521            };
522            if payload.is_empty() || payload == "[DONE]" {
523                continue;
524            }
525            let v: serde_json::Value = match serde_json::from_str(payload) {
526                Ok(v) => v,
527                Err(_) => continue,
528            };
529            if let Some(delta) = v
530                .get("choices")
531                .and_then(|c| c.get(0))
532                .and_then(|c| c.get("delta"))
533                .and_then(|d| d.get("content"))
534                .and_then(|c| c.as_str())
535                && !delta.is_empty()
536                && tx.send(delta.to_string()).await.is_err()
537            {
538                // Receiver dropped — caller has lost interest.
539                return Ok(());
540            }
541        }
542    }
543    Ok(())
544}
545
546// ─── Misc helpers ─────────────────────────────────────────────────────────
547
548/// Check whether a path exists and is a directory.
549///
550/// Why: tiny but commonly-needed shim — clearer at call sites than
551/// `path.exists() && path.is_dir()`.
552/// What: returns `true` iff the path exists and metadata reports a directory.
553/// Test: `is_dir_recognises_directories`.
554pub fn is_dir(path: &Path) -> bool {
555    path.metadata().map(|m| m.is_dir()).unwrap_or(false)
556}
557
558#[cfg(test)]
559mod tests {
560    use super::*;
561    use std::sync::Mutex;
562
563    /// Serialises tests that mutate the `TRUSTY_DATA_DIR_OVERRIDE` env var so
564    /// they don't race when `cargo test` runs them in parallel threads.
565    static ENV_LOCK: Mutex<()> = Mutex::new(());
566
567    #[tokio::test]
568    async fn auto_port_walks_forward() {
569        // Bind to an OS-chosen port, then ask auto-port to start there.
570        let occupied = TcpListener::bind("127.0.0.1:0").await.unwrap();
571        let port = occupied.local_addr().unwrap().port();
572        let addr: SocketAddr = format!("127.0.0.1:{port}").parse().unwrap();
573        let next = bind_with_auto_port(addr, 8).await.unwrap();
574        let got = next.local_addr().unwrap().port();
575        assert_ne!(got, port, "expected walk-forward to a different port");
576    }
577
578    #[tokio::test]
579    async fn auto_port_zero_attempts_still_binds_free() {
580        let addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
581        let l = bind_with_auto_port(addr, 0).await.unwrap();
582        assert!(l.local_addr().unwrap().port() > 0);
583    }
584
585    #[test]
586    fn resolve_data_dir_creates_directory() {
587        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
588        // Use the override env var so we deterministically control the base
589        // directory cross-platform (macOS's dirs::data_dir ignores HOME).
590        let tmp = tempfile_like_dir();
591        // SAFETY: env mutation; tests in this module run serially via
592        // #[test] threading isolation only when MUTEX-guarded — we accept
593        // the residual risk since the override var is unique to these tests.
594        unsafe {
595            std::env::set_var(DATA_DIR_OVERRIDE_ENV, &tmp);
596        }
597        let dir = resolve_data_dir("trusty-test-xyz").unwrap();
598        assert!(
599            dir.exists(),
600            "data dir should be created at {}",
601            dir.display()
602        );
603        assert!(dir.is_dir());
604        assert!(
605            dir.starts_with(&tmp),
606            "data dir {} should live under override {}",
607            dir.display(),
608            tmp.display()
609        );
610        unsafe {
611            std::env::remove_var(DATA_DIR_OVERRIDE_ENV);
612        }
613    }
614
615    #[test]
616    fn daemon_addr_round_trips() {
617        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
618        let tmp = tempfile_like_dir();
619        // SAFETY: env mutation; see note in resolve_data_dir_creates_directory.
620        unsafe {
621            std::env::set_var(DATA_DIR_OVERRIDE_ENV, &tmp);
622        }
623        let app = format!(
624            "trusty-test-daemon-{}-{}",
625            std::process::id(),
626            std::time::SystemTime::now()
627                .duration_since(std::time::UNIX_EPOCH)
628                .map(|d| d.as_nanos())
629                .unwrap_or(0)
630        );
631        write_daemon_addr(&app, "127.0.0.1:12345").unwrap();
632        let got = read_daemon_addr(&app).unwrap();
633        unsafe {
634            std::env::remove_var(DATA_DIR_OVERRIDE_ENV);
635        }
636        assert_eq!(got.as_deref(), Some("127.0.0.1:12345"));
637    }
638
639    #[test]
640    fn read_daemon_addr_missing_returns_none() {
641        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
642        let tmp = tempfile_like_dir();
643        // SAFETY: env mutation; see note in resolve_data_dir_creates_directory.
644        unsafe {
645            std::env::set_var(DATA_DIR_OVERRIDE_ENV, &tmp);
646        }
647        let app = format!(
648            "trusty-test-daemon-missing-{}-{}",
649            std::process::id(),
650            std::time::SystemTime::now()
651                .duration_since(std::time::UNIX_EPOCH)
652                .map(|d| d.as_nanos())
653                .unwrap_or(0)
654        );
655        let got = read_daemon_addr(&app).unwrap();
656        unsafe {
657            std::env::remove_var(DATA_DIR_OVERRIDE_ENV);
658        }
659        assert!(got.is_none(), "expected None when file absent, got {got:?}");
660    }
661
662    #[test]
663    fn is_dir_recognises_directories() {
664        let tmp = tempfile_like_dir();
665        assert!(is_dir(&tmp));
666        assert!(!is_dir(&tmp.join("nope")));
667    }
668
669    #[test]
670    fn chat_message_round_trips() {
671        let m = ChatMessage {
672            role: "user".into(),
673            content: "hello".into(),
674            tool_call_id: None,
675            tool_calls: None,
676        };
677        let s = serde_json::to_string(&m).unwrap();
678        let back: ChatMessage = serde_json::from_str(&s).unwrap();
679        assert_eq!(back.role, "user");
680        assert_eq!(back.content, "hello");
681    }
682
683    #[tokio::test]
684    #[allow(deprecated)]
685    async fn openrouter_chat_rejects_empty_key() {
686        let err = openrouter_chat("", "x", vec![]).await.unwrap_err();
687        assert!(err.to_string().contains("api key"));
688    }
689
690    // Test-only helper: makes a unique scratch dir without pulling in tempfile
691    // as a dev-dep (keeps the dependency surface minimal).
692    fn tempfile_like_dir() -> PathBuf {
693        let pid = std::process::id();
694        let nanos = std::time::SystemTime::now()
695            .duration_since(std::time::UNIX_EPOCH)
696            .map(|d| d.as_nanos())
697            .unwrap_or(0);
698        let p = std::env::temp_dir().join(format!("trusty-common-test-{pid}-{nanos}"));
699        std::fs::create_dir_all(&p).unwrap();
700        p
701    }
702}