Skip to main content

lean_ctx/dashboard/
mod.rs

1use std::sync::Arc;
2use subtle::ConstantTimeEq;
3use tokio::io::{AsyncReadExt, AsyncWriteExt};
4use tokio::net::TcpListener;
5
6const DEFAULT_PORT: u16 = 3333;
7const DEFAULT_HOST: &str = "127.0.0.1";
8const DASHBOARD_HTML: &str = include_str!("dashboard.html");
9
10const COCKPIT_INDEX_HTML: &str = include_str!("static/index.html");
11const COCKPIT_STYLE_CSS: &str = include_str!("static/style.css");
12const COCKPIT_LIB_API_JS: &str = include_str!("static/lib/api.js");
13const COCKPIT_LIB_FORMAT_JS: &str = include_str!("static/lib/format.js");
14const COCKPIT_LIB_ROUTER_JS: &str = include_str!("static/lib/router.js");
15const COCKPIT_LIB_CHARTS_JS: &str = include_str!("static/lib/charts.js");
16const COCKPIT_LIB_SHARED_JS: &str = include_str!("static/lib/shared.js");
17const COCKPIT_COMPONENT_NAV_JS: &str = include_str!("static/components/cockpit-nav.js");
18const COCKPIT_COMPONENT_CONTEXT_JS: &str = include_str!("static/components/cockpit-context.js");
19const COCKPIT_COMPONENT_OVERVIEW_JS: &str = include_str!("static/components/cockpit-overview.js");
20const COCKPIT_COMPONENT_LIVE_JS: &str = include_str!("static/components/cockpit-live.js");
21const COCKPIT_COMPONENT_KNOWLEDGE_JS: &str = include_str!("static/components/cockpit-knowledge.js");
22const COCKPIT_COMPONENT_AGENTS_JS: &str = include_str!("static/components/cockpit-agents.js");
23const COCKPIT_COMPONENT_MEMORY_JS: &str = include_str!("static/components/cockpit-memory.js");
24const COCKPIT_COMPONENT_SEARCH_JS: &str = include_str!("static/components/cockpit-search.js");
25const COCKPIT_COMPONENT_COMPRESSION_JS: &str =
26    include_str!("static/components/cockpit-compression.js");
27const COCKPIT_COMPONENT_GRAPH_JS: &str = include_str!("static/components/cockpit-graph.js");
28const COCKPIT_COMPONENT_HEALTH_JS: &str = include_str!("static/components/cockpit-health.js");
29const COCKPIT_COMPONENT_REMAINING_JS: &str = include_str!("static/components/cockpit-remaining.js");
30
31pub mod routes;
32
33pub async fn start(port: Option<u16>, host: Option<String>) {
34    let port = port.unwrap_or_else(|| {
35        std::env::var("LEAN_CTX_PORT")
36            .ok()
37            .and_then(|p| p.parse().ok())
38            .unwrap_or(DEFAULT_PORT)
39    });
40
41    let host = host.unwrap_or_else(|| {
42        std::env::var("LEAN_CTX_HOST")
43            .ok()
44            .unwrap_or_else(|| DEFAULT_HOST.to_string())
45    });
46
47    let addr = format!("{host}:{port}");
48    let is_local = host == "127.0.0.1" || host == "localhost" || host == "::1";
49
50    // Avoid accidental multiple dashboard instances (common source of "it hangs").
51    // Only safe to auto-detect for local dashboards without auth.
52    if is_local && dashboard_responding(&host, port) {
53        println!("\n  lean-ctx dashboard already running → http://{host}:{port}");
54        println!("  Tip: use Ctrl+C in the existing terminal to stop it.\n");
55        if let Some(t) = load_saved_token() {
56            open_browser(&format!("http://localhost:{port}/?token={t}"));
57        } else {
58            open_browser(&format!("http://localhost:{port}"));
59        }
60        return;
61    }
62
63    // Always enable auth (even on loopback) to prevent cross-origin reads of /api/*
64    // from a malicious website (CORS is not a reliable boundary for localhost services).
65    let t = generate_token();
66    save_token(&t);
67    let token = Some(Arc::new(t));
68
69    if let Some(t) = token.as_ref() {
70        if is_local {
71            println!("  Auth: enabled (local)");
72            println!("  Browser URL:  http://localhost:{port}/?token={t}");
73        } else {
74            eprintln!(
75                "  \x1b[33m⚠\x1b[0m Binding to {host} — authentication enabled.\n  \
76                 Bearer token: \x1b[1;32m{t}\x1b[0m\n  \
77                 Browser URL:  http://<your-ip>:{port}/?token={t}"
78            );
79        }
80    }
81
82    let listener = match TcpListener::bind(&addr).await {
83        Ok(l) => l,
84        Err(e) => {
85            eprintln!("Failed to bind to {addr}: {e}");
86            std::process::exit(1);
87        }
88    };
89
90    let stats_path = crate::core::data_dir::lean_ctx_data_dir().map_or_else(
91        |_| "~/.lean-ctx/stats.json".to_string(),
92        |d| d.join("stats.json").display().to_string(),
93    );
94
95    if host == "0.0.0.0" {
96        println!("\n  lean-ctx dashboard → http://0.0.0.0:{port} (all interfaces)");
97        println!("  Local access:  http://localhost:{port}");
98    } else {
99        println!("\n  lean-ctx dashboard → http://{host}:{port}");
100    }
101    println!("  Stats file: {stats_path}");
102    println!("  Press Ctrl+C to stop\n");
103
104    if is_local {
105        if let Some(t) = token.as_ref() {
106            open_browser(&format!("http://localhost:{port}/?token={t}"));
107        } else {
108            open_browser(&format!("http://localhost:{port}"));
109        }
110    }
111    if crate::shell::is_container() && is_local {
112        println!("  Tip (Docker): bind 0.0.0.0 + publish port:");
113        println!("    lean-ctx dashboard --host=0.0.0.0 --port={port}");
114        println!("    docker run ... -p {port}:{port} ...");
115        println!();
116    }
117
118    loop {
119        if let Ok((stream, _)) = listener.accept().await {
120            let token_ref = token.clone();
121            tokio::spawn(handle_request(stream, token_ref));
122        }
123    }
124}
125
126fn generate_token() -> String {
127    let mut bytes = [0u8; 32];
128    getrandom::fill(&mut bytes).expect("CSPRNG unavailable — cannot generate secure token");
129    format!("lctx_{}", hex_lower(&bytes))
130}
131
132fn save_token(token: &str) {
133    if let Ok(dir) = crate::core::data_dir::lean_ctx_data_dir() {
134        let _ = std::fs::create_dir_all(&dir);
135        let path = dir.join("dashboard.token");
136        #[cfg(unix)]
137        {
138            use std::io::Write;
139            use std::os::unix::fs::OpenOptionsExt;
140            let Ok(mut f) = std::fs::OpenOptions::new()
141                .write(true)
142                .create(true)
143                .truncate(true)
144                .mode(0o600)
145                .open(&path)
146            else {
147                return;
148            };
149            let _ = f.write_all(token.as_bytes());
150        }
151        #[cfg(not(unix))]
152        {
153            let _ = std::fs::write(&path, token);
154        }
155    }
156}
157
158fn load_saved_token() -> Option<String> {
159    let dir = crate::core::data_dir::lean_ctx_data_dir().ok()?;
160    let path = dir.join("dashboard.token");
161    std::fs::read_to_string(path)
162        .ok()
163        .map(|s| s.trim().to_string())
164}
165
166/// Adds `nonce="..."` to all inline `<script>` tags (those without a `src=` attribute).
167/// External scripts (`<script src="...">`) are left untouched.
168pub fn add_nonce_to_inline_scripts(html: &str, nonce: &str) -> String {
169    let mut result = String::with_capacity(html.len() + 128);
170    let mut remaining = html;
171    while let Some(pos) = remaining.find("<script") {
172        result.push_str(&remaining[..pos]);
173        let tag_start = &remaining[pos..];
174        let tag_end = tag_start.find('>').unwrap_or(tag_start.len());
175        let tag = &tag_start[..=tag_end];
176        if tag.contains("src=") || tag.contains("nonce=") {
177            result.push_str(tag);
178        } else {
179            result.push_str(&tag.replacen("<script", &format!("<script nonce=\"{nonce}\""), 1));
180        }
181        remaining = &tag_start[tag_end + 1..];
182    }
183    result.push_str(remaining);
184    result
185}
186
187fn hex_lower(bytes: &[u8]) -> String {
188    const HEX: &[u8; 16] = b"0123456789abcdef";
189    let mut out = String::with_capacity(bytes.len() * 2);
190    for &b in bytes {
191        out.push(HEX[(b >> 4) as usize] as char);
192        out.push(HEX[(b & 0x0f) as usize] as char);
193    }
194    out
195}
196
197fn open_browser(url: &str) {
198    #[cfg(target_os = "macos")]
199    {
200        let _ = std::process::Command::new("open").arg(url).spawn();
201    }
202
203    #[cfg(target_os = "linux")]
204    {
205        let _ = std::process::Command::new("xdg-open")
206            .arg(url)
207            .stderr(std::process::Stdio::null())
208            .spawn();
209    }
210
211    #[cfg(target_os = "windows")]
212    {
213        let _ = std::process::Command::new("cmd")
214            .args(["/C", "start", url])
215            .spawn();
216    }
217}
218
219fn dashboard_responding(host: &str, port: u16) -> bool {
220    use std::io::{Read, Write};
221    use std::net::TcpStream;
222    use std::time::Duration;
223
224    let addr = format!("{host}:{port}");
225    let Ok(mut s) = TcpStream::connect_timeout(
226        &addr
227            .parse()
228            .unwrap_or_else(|_| std::net::SocketAddr::from(([127, 0, 0, 1], port))),
229        Duration::from_millis(150),
230    ) else {
231        return false;
232    };
233    let _ = s.set_read_timeout(Some(Duration::from_millis(150)));
234    let _ = s.set_write_timeout(Some(Duration::from_millis(150)));
235
236    let auth_header = load_saved_token()
237        .map(|t| format!("Authorization: Bearer {t}\r\n"))
238        .unwrap_or_default();
239
240    let req = format!(
241        "GET /api/version HTTP/1.1\r\nHost: localhost\r\n{auth_header}Connection: close\r\n\r\n"
242    );
243    if s.write_all(req.as_bytes()).is_err() {
244        return false;
245    }
246    let mut buf = [0u8; 256];
247    let Ok(n) = s.read(&mut buf) else {
248        return false;
249    };
250    let head = String::from_utf8_lossy(&buf[..n]);
251    head.starts_with("HTTP/1.1 200") || head.starts_with("HTTP/1.0 200")
252}
253
254const MAX_HTTP_MESSAGE: usize = 2 * 1024 * 1024;
255
256fn header_line_value<'a>(header_section: &'a str, name: &str) -> Option<&'a str> {
257    for line in header_section.lines() {
258        let Some((k, v)) = line.split_once(':') else {
259            continue;
260        };
261        if k.trim().eq_ignore_ascii_case(name) {
262            return Some(v.trim());
263        }
264    }
265    None
266}
267
268/// Loopback dashboards often use `localhost` vs `127.0.0.1` interchangeably in `Origin`.
269fn host_loopback_aliases(host: &str) -> Vec<String> {
270    let mut v = vec![host.to_string()];
271    if let Some(port) = host.strip_prefix("127.0.0.1:") {
272        v.push(format!("localhost:{port}"));
273    }
274    if let Some(port) = host.strip_prefix("localhost:") {
275        v.push(format!("127.0.0.1:{port}"));
276    }
277    if let Some(port) = host.strip_prefix("[::1]:") {
278        v.push(format!("127.0.0.1:{port}"));
279        v.push(format!("localhost:{port}"));
280    }
281    v
282}
283
284fn origin_matches_dashboard_host(origin: &str, host: &str) -> bool {
285    let origin = origin.trim_end_matches('/');
286    for h in host_loopback_aliases(host) {
287        if origin.eq_ignore_ascii_case(&format!("http://{h}"))
288            || origin.eq_ignore_ascii_case(&format!("https://{h}"))
289        {
290            return true;
291        }
292    }
293    false
294}
295
296/// Defense-in-depth for browser POSTs: reject cross-site `Origin` on mutating `/api/*` calls.
297/// Non-browser clients (no `Origin`) remain allowed when Bearer auth succeeds.
298fn csrf_origin_ok(header_section: &str, method: &str, path: &str) -> bool {
299    let uc = method.to_ascii_uppercase();
300    if !matches!(uc.as_str(), "POST" | "PUT" | "PATCH" | "DELETE") {
301        return true;
302    }
303    if !path.starts_with("/api/") {
304        return true;
305    }
306    let Some(origin) = header_line_value(header_section, "Origin") else {
307        return true;
308    };
309    if origin.is_empty() || origin.eq_ignore_ascii_case("null") {
310        return true;
311    }
312    let Some(host) = header_line_value(header_section, "Host") else {
313        return false;
314    };
315    origin_matches_dashboard_host(origin, host)
316}
317
318fn find_headers_end(buf: &[u8]) -> Option<usize> {
319    buf.windows(4).position(|w| w == b"\r\n\r\n")
320}
321
322fn parse_content_length_header(header_section: &[u8]) -> Option<usize> {
323    let text = String::from_utf8_lossy(header_section);
324    for line in text.lines() {
325        let Some((k, v)) = line.split_once(':') else {
326            continue;
327        };
328        if k.trim().eq_ignore_ascii_case("content-length") {
329            return v.trim().parse::<usize>().ok();
330        }
331    }
332    Some(0)
333}
334
335async fn read_http_message(stream: &mut tokio::net::TcpStream) -> Option<Vec<u8>> {
336    let mut buf = Vec::new();
337    let mut tmp = [0u8; 8192];
338    loop {
339        if let Some(end) = find_headers_end(&buf) {
340            let cl = parse_content_length_header(&buf[..end])?;
341            let total = end + 4 + cl;
342            if total > MAX_HTTP_MESSAGE {
343                return None;
344            }
345            if buf.len() >= total {
346                buf.truncate(total);
347                return Some(buf);
348            }
349        } else if buf.len() > 65_536 {
350            return None;
351        }
352
353        let n = stream.read(&mut tmp).await.ok()?;
354        if n == 0 {
355            return None;
356        }
357        buf.extend_from_slice(&tmp[..n]);
358        if buf.len() > MAX_HTTP_MESSAGE {
359            return None;
360        }
361    }
362}
363
364async fn handle_request(mut stream: tokio::net::TcpStream, token: Option<Arc<String>>) {
365    let is_loopback = stream.peer_addr().is_ok_and(|a| a.ip().is_loopback());
366
367    let Some(buf) = read_http_message(&mut stream).await else {
368        return;
369    };
370    let Some(header_end) = find_headers_end(&buf) else {
371        return;
372    };
373    let header_text = String::from_utf8_lossy(&buf[..header_end]).to_string();
374    let body_start = header_end + 4;
375    let Some(content_len) = parse_content_length_header(&buf[..header_end]) else {
376        return;
377    };
378    if buf.len() < body_start + content_len {
379        return;
380    }
381    let body_str = std::str::from_utf8(&buf[body_start..body_start + content_len])
382        .unwrap_or("")
383        .to_string();
384
385    let first = header_text.lines().next().unwrap_or("");
386    let mut parts = first.split_whitespace();
387    let method = parts.next().unwrap_or("GET").to_string();
388    let raw_path = parts.next().unwrap_or("/").to_string();
389
390    let (path, query_token) = if let Some(idx) = raw_path.find('?') {
391        let p = &raw_path[..idx];
392        let qs = &raw_path[idx + 1..];
393        let tok = qs
394            .split('&')
395            .find_map(|pair| pair.strip_prefix("token="))
396            .map(std::string::ToString::to_string);
397        (p.to_string(), tok)
398    } else {
399        (raw_path.clone(), None)
400    };
401
402    let query_str = raw_path
403        .find('?')
404        .map_or(String::new(), |i| raw_path[i + 1..].to_string());
405
406    let is_api = path.starts_with("/api/");
407    let requires_auth = is_api || path == "/metrics";
408
409    if let Some(ref expected) = token {
410        let has_header_auth = check_auth(&header_text, expected);
411
412        if requires_auth && !has_header_auth {
413            let body = r#"{"error":"unauthorized"}"#;
414            let response = format!(
415                "HTTP/1.1 401 Unauthorized\r\n\
416                 Content-Type: application/json\r\n\
417                 Content-Length: {}\r\n\
418                 WWW-Authenticate: Bearer\r\n\
419                 Connection: close\r\n\
420                 \r\n\
421                 {body}",
422                body.len()
423            );
424            let _ = stream.write_all(response.as_bytes()).await;
425            return;
426        }
427
428        if !csrf_origin_ok(&header_text, method.as_str(), path.as_str()) {
429            let body = r#"{"error":"forbidden"}"#;
430            let response = format!(
431                "HTTP/1.1 403 Forbidden\r\n\
432                 Content-Type: application/json\r\n\
433                 Content-Length: {}\r\n\
434                 Connection: close\r\n\
435                 \r\n\
436                 {body}",
437                body.len()
438            );
439            let _ = stream.write_all(response.as_bytes()).await;
440            return;
441        }
442    }
443
444    let path = path.as_str();
445    let query_str = query_str.as_str();
446    let method = method.as_str();
447
448    let compute = std::panic::catch_unwind(|| {
449        routes::route_response(
450            path,
451            query_str,
452            query_token.as_ref(),
453            token.as_ref(),
454            is_loopback,
455            method,
456            &body_str,
457        )
458    });
459    let (status, content_type, mut body) = match compute {
460        Ok(v) => v,
461        Err(_) => (
462            "500 Internal Server Error",
463            "application/json",
464            r#"{"error":"dashboard route panicked"}"#.to_string(),
465        ),
466    };
467
468    let cache_header = if content_type.starts_with("application/json") {
469        "Cache-Control: no-cache, no-store, must-revalidate\r\nPragma: no-cache\r\n"
470    } else if content_type.starts_with("application/javascript")
471        || content_type.starts_with("text/css")
472    {
473        "Cache-Control: no-cache, must-revalidate\r\n"
474    } else {
475        ""
476    };
477
478    let nonce = {
479        let mut nb = [0u8; 16];
480        getrandom::fill(&mut nb).expect("CSPRNG unavailable — cannot generate CSP nonce");
481        hex_lower(&nb)
482    };
483    if content_type.contains("text/html") {
484        body = add_nonce_to_inline_scripts(&body, &nonce);
485    }
486    let security_headers = format!(
487        "X-Content-Type-Options: nosniff\r\n\
488         X-Frame-Options: DENY\r\n\
489         Referrer-Policy: no-referrer\r\n\
490         Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-{nonce}' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data:; connect-src 'self'\r\n"
491    );
492
493    let response = format!(
494        "HTTP/1.1 {status}\r\n\
495         Content-Type: {content_type}\r\n\
496         Content-Length: {}\r\n\
497         {cache_header}\
498         {security_headers}\
499         Connection: close\r\n\
500         \r\n\
501         {body}",
502        body.len()
503    );
504
505    let _ = stream.write_all(response.as_bytes()).await;
506}
507
508fn check_auth(request: &str, expected_token: &str) -> bool {
509    for line in request.lines() {
510        let lower = line.to_lowercase();
511        if lower.starts_with("authorization:") {
512            let value = line["authorization:".len()..].trim();
513            if let Some(token) = value
514                .strip_prefix("Bearer ")
515                .or_else(|| value.strip_prefix("bearer "))
516            {
517                return constant_time_eq(token.trim().as_bytes(), expected_token.as_bytes());
518            }
519        }
520    }
521    false
522}
523
524fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
525    if a.len() != b.len() {
526        return false;
527    }
528    bool::from(a.ct_eq(b))
529}
530
531#[cfg(test)]
532mod tests {
533    use super::routes::helpers::normalize_dashboard_demo_path;
534    use super::*;
535    use tempfile::tempdir;
536
537    static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
538
539    #[test]
540    fn check_auth_with_valid_bearer() {
541        let req = "GET /api/stats HTTP/1.1\r\nAuthorization: Bearer lctx_abc123\r\n\r\n";
542        assert!(check_auth(req, "lctx_abc123"));
543    }
544
545    #[test]
546    fn check_auth_with_invalid_bearer() {
547        let req = "GET /api/stats HTTP/1.1\r\nAuthorization: Bearer wrong_token\r\n\r\n";
548        assert!(!check_auth(req, "lctx_abc123"));
549    }
550
551    #[test]
552    fn check_auth_missing_header() {
553        let req = "GET /api/stats HTTP/1.1\r\nHost: localhost\r\n\r\n";
554        assert!(!check_auth(req, "lctx_abc123"));
555    }
556
557    #[test]
558    fn check_auth_lowercase_bearer() {
559        let req = "GET /api/stats HTTP/1.1\r\nauthorization: bearer lctx_abc123\r\n\r\n";
560        assert!(check_auth(req, "lctx_abc123"));
561    }
562
563    #[test]
564    fn query_token_parsing() {
565        let raw_path = "/index.html?token=lctx_abc123&other=val";
566        let idx = raw_path.find('?').unwrap();
567        let qs = &raw_path[idx + 1..];
568        let tok = qs.split('&').find_map(|pair| pair.strip_prefix("token="));
569        assert_eq!(tok, Some("lctx_abc123"));
570    }
571
572    #[test]
573    fn api_path_detection() {
574        assert!("/api/stats".starts_with("/api/"));
575        assert!("/api/version".starts_with("/api/"));
576        assert!(!"/".starts_with("/api/"));
577        assert!(!"/index.html".starts_with("/api/"));
578        assert!(!"/favicon.ico".starts_with("/api/"));
579    }
580
581    #[test]
582    fn normalize_dashboard_demo_path_strips_rooted_relative_windows_path() {
583        let normalized = normalize_dashboard_demo_path(r"\backend\list_tables.js");
584        assert_eq!(
585            normalized,
586            format!("backend{}list_tables.js", std::path::MAIN_SEPARATOR)
587        );
588    }
589
590    #[test]
591    fn normalize_dashboard_demo_path_preserves_absolute_windows_path() {
592        let input = r"C:\repo\backend\list_tables.js";
593        assert_eq!(normalize_dashboard_demo_path(input), input);
594    }
595
596    #[test]
597    fn normalize_dashboard_demo_path_preserves_unc_path() {
598        let input = r"\\server\share\backend\list_tables.js";
599        assert_eq!(normalize_dashboard_demo_path(input), input);
600    }
601
602    #[test]
603    fn normalize_dashboard_demo_path_strips_dot_slash_prefix() {
604        assert_eq!(
605            normalize_dashboard_demo_path("./src/main.rs"),
606            "src/main.rs"
607        );
608        assert_eq!(
609            normalize_dashboard_demo_path(r".\src\main.rs"),
610            format!("src{}main.rs", std::path::MAIN_SEPARATOR)
611        );
612    }
613
614    #[test]
615    fn api_profile_returns_json() {
616        let (_status, _ct, body) =
617            routes::route_response("/api/profile", "", None, None, false, "GET", "");
618        let v: serde_json::Value = serde_json::from_str(&body).expect("valid JSON");
619        assert!(v.get("active_name").is_some(), "missing active_name");
620        assert!(
621            v.pointer("/profile/profile/name")
622                .and_then(|n| n.as_str())
623                .is_some(),
624            "missing profile.profile.name"
625        );
626        assert!(v.get("available").and_then(|a| a.as_array()).is_some());
627    }
628
629    #[test]
630    fn api_episodes_returns_json() {
631        let (_status, _ct, body) =
632            routes::route_response("/api/episodes", "", None, None, false, "GET", "");
633        let v: serde_json::Value = serde_json::from_str(&body).expect("valid JSON");
634        assert!(v.get("project_hash").is_some());
635        assert!(v.get("stats").is_some());
636        assert!(v.get("recent").and_then(|a| a.as_array()).is_some());
637    }
638
639    #[test]
640    fn api_procedures_returns_json() {
641        let (_status, _ct, body) =
642            routes::route_response("/api/procedures", "", None, None, false, "GET", "");
643        let v: serde_json::Value = serde_json::from_str(&body).expect("valid JSON");
644        assert!(v.get("project_hash").is_some());
645        assert!(v.get("procedures").and_then(|a| a.as_array()).is_some());
646        assert!(v.get("suggestions").and_then(|a| a.as_array()).is_some());
647    }
648
649    #[test]
650    fn api_compression_demo_heals_moved_file_paths() {
651        let _g = ENV_LOCK.lock().expect("env lock");
652        let td = tempdir().expect("tempdir");
653        let root = td.path();
654        std::fs::create_dir_all(root.join("src").join("moved")).expect("mkdir");
655        std::fs::write(
656            root.join("src").join("moved").join("foo.rs"),
657            "pub fn foo() { println!(\"hi\"); }\n",
658        )
659        .expect("write foo.rs");
660
661        let root_s = root.to_string_lossy().to_string();
662        std::env::set_var("LEAN_CTX_DASHBOARD_PROJECT", &root_s);
663
664        let (_status, _ct, body) = routes::route_response(
665            "/api/compression-demo",
666            "path=src/foo.rs",
667            None,
668            None,
669            false,
670            "GET",
671            "",
672        );
673        let v: serde_json::Value = serde_json::from_str(&body).expect("valid JSON");
674        assert!(v.get("error").is_none(), "unexpected error: {body}");
675        assert_eq!(
676            v.get("resolved_from").and_then(|x| x.as_str()),
677            Some("src/moved/foo.rs")
678        );
679
680        std::env::remove_var("LEAN_CTX_DASHBOARD_PROJECT");
681        if let Some(dir) = crate::core::graph_index::ProjectIndex::index_dir(&root_s) {
682            let _ = std::fs::remove_dir_all(dir);
683        }
684    }
685}