Skip to main content

blyte_cli/
surfaces_cmd.rs

1use std::collections::BTreeSet;
2use std::fmt::Write as _;
3use std::io::{ErrorKind, Read, Write};
4use std::net::{SocketAddr, TcpStream};
5use std::path::{Path, PathBuf};
6use std::time::{Duration, Instant};
7
8use crate::serve::TOKEN_HEADER;
9use crate::session::{Entry, EntryBody};
10use crate::surface_dir::{is_running, list_records_for_root};
11use crate::surface_registry::{find_by_name, first_line, live_entries, RegistryEntry};
12
13const OPEN_CODE_TIMEOUT: Duration = Duration::from_secs(5);
14const MAX_OPEN_CODE_RESPONSE_BYTES: usize = 64 * 1024;
15
16/// A stopped surface belonging to a folder.
17///
18/// `last_used` is in Unix seconds: the `ts` of the last complete entry in
19/// `entries.jsonl`, or the record's `started_at` when that file is absent or
20/// has no entries (a surface that was started and never used was last used
21/// when it started).
22#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
23pub struct StoppedSurface {
24    pub id: String,
25    pub name: String,
26    pub last_used: u64,
27    pub last_message: Option<String>,
28}
29
30fn scan_entries_summary(path: &Path) -> Result<(Option<u64>, Option<String>), String> {
31    let bytes = match std::fs::read(path) {
32        Ok(b) => b,
33        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok((None, None)),
34        Err(e) => return Err(format!("failed to read {}: {e}", path.display())),
35    };
36
37    let mut last_ts: Option<u64> = None;
38    let mut last_user_text: Option<String> = None;
39    let mut pos = 0usize;
40    let mut line_no = 0usize;
41    while pos < bytes.len() {
42        line_no += 1;
43        let start = pos;
44        let end = match bytes[pos..].iter().position(|&b| b == b'\n') {
45            Some(rel) => pos + rel + 1,
46            None => bytes.len(),
47        };
48        let is_last_without_newline = end == bytes.len() && !bytes[start..end].ends_with(b"\n");
49        let line_slice = &bytes[start..end];
50        let parsed = std::str::from_utf8(line_slice)
51            .map_err(|e| e.to_string())
52            .and_then(|s| serde_json::from_str::<Entry>(s).map_err(|e| e.to_string()));
53        match parsed {
54            Ok(entry) => {
55                last_ts = Some(entry.ts);
56                if let EntryBody::UserMessage { text, .. } = entry.body {
57                    last_user_text = Some(text);
58                }
59            }
60            Err(reason) => {
61                if !is_last_without_newline {
62                    return Err(format!(
63                        "invalid entry in {} at line {}: {}",
64                        path.display(),
65                        line_no,
66                        reason
67                    ));
68                }
69            }
70        }
71        pos = end;
72    }
73
74    let last_message = last_user_text.and_then(|text| {
75        let line = first_line(&text);
76        if line.is_empty() {
77            None
78        } else {
79            Some(line)
80        }
81    });
82
83    Ok((last_ts, last_message))
84}
85
86fn stopped_surfaces_for_root(root: &Path, state_dir: &Path) -> Result<Vec<StoppedSurface>, String> {
87    let records = list_records_for_root(root, Some(state_dir))?;
88    let mut stopped = Vec::new();
89    for located in records {
90        if is_running(&located.record) {
91            continue;
92        }
93        let entries_path = located.dir.join("entries.jsonl");
94        let (last_ts, last_message) = scan_entries_summary(&entries_path)?;
95        let last_used = last_ts.unwrap_or(located.record.started_at);
96        stopped.push(StoppedSurface {
97            id: located.record.id,
98            name: located.record.name,
99            last_used,
100            last_message,
101        });
102    }
103    stopped.sort_by(|a, b| b.last_used.cmp(&a.last_used).then_with(|| a.id.cmp(&b.id)));
104    Ok(stopped)
105}
106
107/// Collect stopped surfaces belonging to `folder`, newest first by `last_used`, then by `id`.
108pub fn stopped_surfaces(folder: &Path, state_dir: &Path) -> Result<Vec<StoppedSurface>, String> {
109    let root = crate::serve::resolve_folder(folder)?;
110    stopped_surfaces_for_root(&root, state_dir)
111}
112
113fn format_utc_minute(ts: u64) -> String {
114    let days = (ts / 86_400) as i64;
115    let secs_of_day = ts % 86_400;
116    let hour = secs_of_day / 3_600;
117    let min = (secs_of_day % 3_600) / 60;
118
119    let z = days + 719_468;
120    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
121    let doe = (z - era * 146_097) as u64;
122    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
123    let y = yoe as i64 + era * 400;
124    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
125    let mp = (5 * doy + 2) / 153;
126    let d = doy - (153 * mp + 2) / 5 + 1;
127    let m = if mp < 10 { mp + 3 } else { mp - 9 };
128    let year = if m <= 2 { y + 1 } else { y };
129
130    format!("{year:04}-{m:02}-{d:02} {hour:02}:{min:02}")
131}
132
133pub fn format_stopped_surfaces_table(entries: &[StoppedSurface], folder: &Path) -> String {
134    if entries.is_empty() {
135        return format!("no stopped surfaces in {}\n", folder.display());
136    }
137
138    let rows: Vec<(&str, &str, String, String)> = entries
139        .iter()
140        .map(|entry| {
141            let last_used = format_utc_minute(entry.last_used);
142            let message = match &entry.last_message {
143                Some(msg) => msg.chars().take(60).collect(),
144                None => "-".to_string(),
145            };
146            (entry.name.as_str(), entry.id.as_str(), last_used, message)
147        })
148        .collect();
149
150    let name_w = rows
151        .iter()
152        .map(|row| row.0.chars().count())
153        .max()
154        .unwrap_or(0)
155        .max("NAME".len());
156    let id_w = rows
157        .iter()
158        .map(|row| row.1.chars().count())
159        .max()
160        .unwrap_or(0)
161        .max("ID".len());
162    let used_w = rows
163        .iter()
164        .map(|row| row.2.chars().count())
165        .max()
166        .unwrap_or(0)
167        .max("LAST USED".len());
168
169    let mut out = String::new();
170    let _ = writeln!(
171        out,
172        "{:<name_w$}  {:<id_w$}  {:<used_w$}  LAST MESSAGE",
173        "NAME", "ID", "LAST USED"
174    );
175    for (name, id, last_used, message) in rows {
176        let _ = writeln!(
177            out,
178            "{name:<name_w$}  {id:<id_w$}  {last_used:<used_w$}  {message}"
179        );
180    }
181    let _ = writeln!(out);
182    let _ = writeln!(out, "resume with: blyte --resume <name or id>");
183    out
184}
185
186pub fn run_stopped_surfaces(
187    folder: &Path,
188    state_dir: &Path,
189    json: bool,
190    out: &mut dyn Write,
191    err: &mut dyn Write,
192) -> i32 {
193    let root = match crate::serve::resolve_folder(folder) {
194        Ok(root) => root,
195        Err(e) => {
196            let _ = writeln!(err, "blyte: {e}");
197            return 1;
198        }
199    };
200    let entries = match stopped_surfaces_for_root(&root, state_dir) {
201        Ok(entries) => entries,
202        Err(e) => {
203            let _ = writeln!(err, "blyte: {e}");
204            return 1;
205        }
206    };
207
208    if json {
209        match serde_json::to_string_pretty(&entries) {
210            Ok(text) => {
211                let _ = writeln!(out, "{text}");
212                return 0;
213            }
214            Err(e) => {
215                let _ = writeln!(err, "blyte: failed to serialize surfaces: {e}");
216                return 1;
217            }
218        }
219    }
220
221    let _ = write!(out, "{}", format_stopped_surfaces_table(&entries, &root));
222    0
223}
224
225fn repository_name(root: &Path) -> String {
226    root.file_name()
227        .map(|name| name.to_string_lossy().into_owned())
228        .unwrap_or_else(|| root.display().to_string())
229}
230
231pub fn format_surfaces_table(entries: &[RegistryEntry], current_id: Option<&str>) -> String {
232    if entries.is_empty() {
233        return "no surfaces are running\n".to_string();
234    }
235
236    let rows: Vec<(String, String, &str, &str, &str)> = entries
237        .iter()
238        .map(|entry| {
239            let name = if current_id == Some(entry.id.as_str()) {
240                format!("{} (this surface)", entry.name)
241            } else {
242                entry.name.clone()
243            };
244            (
245                name,
246                repository_name(&entry.root),
247                entry.branch.as_deref().unwrap_or("-"),
248                entry.state.display_label(),
249                entry.doing.as_str(),
250            )
251        })
252        .collect();
253
254    let name_w = rows
255        .iter()
256        .map(|row| row.0.chars().count())
257        .max()
258        .unwrap_or(0)
259        .max("NAME".len());
260    let repo_w = rows
261        .iter()
262        .map(|row| row.1.chars().count())
263        .max()
264        .unwrap_or(0)
265        .max("REPOSITORY".len());
266    let branch_w = rows
267        .iter()
268        .map(|row| row.2.chars().count())
269        .max()
270        .unwrap_or(0)
271        .max("BRANCH".len());
272    let state_w = rows
273        .iter()
274        .map(|row| row.3.chars().count())
275        .max()
276        .unwrap_or(0)
277        .max("STATE".len());
278
279    let mut out = String::new();
280    let _ = writeln!(
281        out,
282        "{:<name_w$}  {:<repo_w$}  {:<branch_w$}  {:<state_w$}  DOING",
283        "NAME", "REPOSITORY", "BRANCH", "STATE"
284    );
285    for (name, repo, branch, state, doing) in rows {
286        let _ = writeln!(
287            out,
288            "{name:<name_w$}  {repo:<repo_w$}  {branch:<branch_w$}  {state:<state_w$}  {doing}"
289        );
290    }
291    out
292}
293
294pub fn run_surfaces(dir: &Path, json: bool, out: &mut dyn Write, err: &mut dyn Write) -> i32 {
295    let entries = match live_entries(dir) {
296        Ok(entries) => entries,
297        Err(e) => {
298            let _ = writeln!(err, "blyte: {e}");
299            return 1;
300        }
301    };
302
303    if json {
304        match serde_json::to_string_pretty(&entries) {
305            Ok(text) => {
306                let _ = writeln!(out, "{text}");
307                return 0;
308            }
309            Err(e) => {
310                let _ = writeln!(err, "blyte: failed to serialize surfaces: {e}");
311                return 1;
312            }
313        }
314    }
315
316    let _ = write!(out, "{}", format_surfaces_table(&entries, None));
317    0
318}
319
320fn read_surface_token(entry: &RegistryEntry) -> Result<String, String> {
321    let token_path = blyte_agent::sandbox::surface_token_path_for_id(&entry.id)?;
322    let raw_token = std::fs::read_to_string(&token_path).map_err(|_| {
323        format!(
324            "surface {} has no usable token at {}",
325            entry.name,
326            token_path.display()
327        )
328    })?;
329    let token = raw_token.trim();
330    if token.is_empty() || token.contains(['\n', '\r']) {
331        return Err(format!(
332            "surface {} has no usable token at {}",
333            entry.name,
334            token_path.display()
335        ));
336    }
337    Ok(token.to_string())
338}
339
340pub fn surface_url(entry: &RegistryEntry) -> Result<String, String> {
341    let token = read_surface_token(entry)?;
342    Ok(format!("http://127.0.0.1:{}/#token={token}", entry.port))
343}
344
345fn parse_http_status(head: &str) -> Result<u16, String> {
346    let status_line = head.lines().next().unwrap_or("").trim_end_matches('\r');
347    let mut parts = status_line.split_whitespace();
348    let version = parts
349        .next()
350        .ok_or_else(|| "empty HTTP response".to_string())?;
351    if !version.starts_with("HTTP/") {
352        return Err("invalid HTTP response".to_string());
353    }
354    let code_str = parts
355        .next()
356        .ok_or_else(|| "missing HTTP status code".to_string())?;
357    code_str
358        .parse::<u16>()
359        .map_err(|_| "invalid HTTP status code".to_string())
360}
361
362pub fn request_open_code(entry: &RegistryEntry, token: &str) -> Result<String, String> {
363    request_open_code_at(&entry.name, entry.port, token)
364}
365
366pub fn request_open_code_at(name: &str, port: u16, token: &str) -> Result<String, String> {
367    let deadline = Instant::now() + OPEN_CODE_TIMEOUT;
368    let addr = SocketAddr::from(([127, 0, 0, 1], port));
369    let mut stream = TcpStream::connect_timeout(&addr, OPEN_CODE_TIMEOUT).map_err(|e| {
370        if e.kind() == ErrorKind::ConnectionRefused {
371            format!("surface {name} refused the connection on port {port}")
372        } else {
373            format!("cannot connect to surface {name} on port {port}: {e}")
374        }
375    })?;
376
377    let remaining = deadline.saturating_duration_since(Instant::now());
378    if remaining.is_zero() {
379        return Err(format!("surface {name} timed out on port {port}"));
380    }
381    let _ = stream.set_write_timeout(Some(remaining));
382
383    let req = format!(
384        "POST /api/session/open-codes HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n{TOKEN_HEADER}: {token}\r\nContent-Type: application/json\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{{}}"
385    );
386    stream
387        .write_all(req.as_bytes())
388        .map_err(|e| format!("failed to request an open code from surface {name}: {e}"))?;
389
390    let mut raw = Vec::new();
391    let mut chunk = [0u8; 4096];
392    loop {
393        if raw.len() >= MAX_OPEN_CODE_RESPONSE_BYTES {
394            return Err(format!(
395                "surface {name} gave an answer blyte does not understand"
396            ));
397        }
398        let remaining = deadline.saturating_duration_since(Instant::now());
399        if remaining.is_zero() {
400            return Err(format!("surface {name} timed out on port {port}"));
401        }
402        let _ = stream.set_read_timeout(Some(remaining));
403        let max_read = (MAX_OPEN_CODE_RESPONSE_BYTES - raw.len()).min(chunk.len());
404        match stream.read(&mut chunk[..max_read]) {
405            Ok(0) => break,
406            Ok(n) => raw.extend_from_slice(&chunk[..n]),
407            Err(e) if e.kind() == ErrorKind::Interrupted => continue,
408            Err(e) if e.kind() == ErrorKind::TimedOut || e.kind() == ErrorKind::WouldBlock => {
409                return Err(format!("surface {name} timed out on port {port}"));
410            }
411            Err(e) => {
412                return Err(format!("failed to read answer from surface {name}: {e}"));
413            }
414        }
415    }
416
417    let text = std::str::from_utf8(&raw)
418        .map_err(|_| format!("surface {name} gave an answer blyte does not understand"))?;
419    let (head, resp_body) = text
420        .split_once("\r\n\r\n")
421        .ok_or_else(|| format!("surface {name} gave an answer blyte does not understand"))?;
422    let status = parse_http_status(head)
423        .map_err(|_| format!("surface {name} gave an answer blyte does not understand"))?;
424    if status != 200 {
425        return Err(format!(
426            "surface {name} could not create an open code (HTTP {status})"
427        ));
428    }
429    let parsed: serde_json::Value = serde_json::from_str(resp_body)
430        .map_err(|_| format!("surface {name} gave an answer blyte does not understand"))?;
431    let code = parsed
432        .get("code")
433        .and_then(|v| v.as_str())
434        .map(str::trim)
435        .filter(|s| !s.is_empty())
436        .ok_or_else(|| format!("surface {name} gave an answer blyte does not understand"))?;
437    Ok(code.to_string())
438}
439
440fn known_folders(state_dir: &Path, entries: &[RegistryEntry]) -> Result<Vec<String>, String> {
441    let mut folders = BTreeSet::new();
442    let repos_path = state_dir.join("repos");
443    match std::fs::read_to_string(&repos_path) {
444        Ok(content) => {
445            for line in content.lines() {
446                let trimmed = line.trim();
447                if trimmed.is_empty() {
448                    continue;
449                }
450                let path = PathBuf::from(trimmed);
451                if path.is_dir() {
452                    folders.insert(trimmed.to_string());
453                }
454            }
455        }
456        Err(e) if e.kind() == ErrorKind::NotFound => {}
457        Err(e) => {
458            return Err(format!("failed to read {}: {e}", repos_path.display()));
459        }
460    }
461    for entry in entries {
462        folders.insert(entry.root.to_string_lossy().into_owned());
463    }
464    Ok(folders.into_iter().collect())
465}
466
467pub fn surfaces_payload(
468    registry_dir: &Path,
469    state_dir: &Path,
470    current_id: &str,
471    stopped: &[StoppedSurface],
472) -> Result<serde_json::Value, String> {
473    let mut entries = live_entries(registry_dir)?;
474    entries.sort_by(|a, b| {
475        a.name
476            .cmp(&b.name)
477            .then_with(|| a.started_at.cmp(&b.started_at))
478    });
479    if !entries.iter().any(|entry| entry.id == current_id) {
480        return Err(format!(
481            "current surface {current_id} is not in the surface registry"
482        ));
483    }
484    let folders = known_folders(state_dir, &entries)?;
485    let surfaces: Vec<serde_json::Value> = entries
486        .iter()
487        .map(|entry| {
488            let (url, error) = match surface_url(entry) {
489                Ok(url) => (Some(url), None),
490                Err(err) => (None, Some(err)),
491            };
492            serde_json::json!({
493                "id": entry.id,
494                "name": entry.name,
495                "root": entry.root.to_string_lossy(),
496                "branch": entry.branch,
497                "doing": entry.doing,
498                "state": entry.state,
499                "current": entry.id == current_id,
500                "url": url,
501                "error": error,
502            })
503        })
504        .collect();
505    Ok(serde_json::json!({ "surfaces": surfaces, "stopped": stopped, "folders": folders }))
506}
507
508pub fn run_open(
509    dir: &Path,
510    name: &str,
511    opener: &dyn Fn(&str),
512    out: &mut dyn Write,
513    err: &mut dyn Write,
514) -> i32 {
515    let entry = match find_by_name(dir, name) {
516        Ok(entry) => entry,
517        Err(e) => {
518            let _ = writeln!(err, "blyte: {e}");
519            return 1;
520        }
521    };
522
523    let token = match read_surface_token(&entry) {
524        Ok(token) => token,
525        Err(e) => {
526            let _ = writeln!(err, "blyte: {e}");
527            return 1;
528        }
529    };
530
531    let code = match request_open_code(&entry, &token) {
532        Ok(code) => code,
533        Err(e) => {
534            let _ = writeln!(err, "blyte: {e}");
535            return 1;
536        }
537    };
538
539    let url = format!("http://127.0.0.1:{}/#open={code}", entry.port);
540    opener(&url);
541    let _ = writeln!(out, "blyte: opened surface {}", entry.name);
542    0
543}