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