Skip to main content

blyte_cli/
surfaces_cmd.rs

1use std::fmt::Write as _;
2use std::io::Write;
3use std::path::Path;
4
5use crate::session::{Entry, EntryBody};
6use crate::surface_dir::{is_running, list_records_for_root};
7use crate::surface_registry::{find_by_name, first_line, live_entries, RegistryEntry};
8
9/// A stopped surface belonging to a folder.
10///
11/// `last_used` is in Unix seconds: the `ts` of the last complete entry in
12/// `entries.jsonl`, or the record's `started_at` when that file is absent or
13/// has no entries (a surface that was started and never used was last used
14/// when it started).
15#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
16pub struct StoppedSurface {
17    pub id: String,
18    pub name: String,
19    pub last_used: u64,
20    pub last_message: Option<String>,
21}
22
23fn scan_entries_summary(path: &Path) -> Result<(Option<u64>, Option<String>), String> {
24    let bytes = match std::fs::read(path) {
25        Ok(b) => b,
26        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok((None, None)),
27        Err(e) => return Err(format!("failed to read {}: {e}", path.display())),
28    };
29
30    let mut last_ts: Option<u64> = None;
31    let mut last_user_text: Option<String> = None;
32    let mut pos = 0usize;
33    let mut line_no = 0usize;
34    while pos < bytes.len() {
35        line_no += 1;
36        let start = pos;
37        let end = match bytes[pos..].iter().position(|&b| b == b'\n') {
38            Some(rel) => pos + rel + 1,
39            None => bytes.len(),
40        };
41        let is_last_without_newline = end == bytes.len() && !bytes[start..end].ends_with(b"\n");
42        let line_slice = &bytes[start..end];
43        let parsed = std::str::from_utf8(line_slice)
44            .map_err(|e| e.to_string())
45            .and_then(|s| serde_json::from_str::<Entry>(s).map_err(|e| e.to_string()));
46        match parsed {
47            Ok(entry) => {
48                last_ts = Some(entry.ts);
49                if let EntryBody::UserMessage { text, .. } = entry.body {
50                    last_user_text = Some(text);
51                }
52            }
53            Err(reason) => {
54                if !is_last_without_newline {
55                    return Err(format!(
56                        "invalid entry in {} at line {}: {}",
57                        path.display(),
58                        line_no,
59                        reason
60                    ));
61                }
62            }
63        }
64        pos = end;
65    }
66
67    let last_message = last_user_text.and_then(|text| {
68        let line = first_line(&text);
69        if line.is_empty() {
70            None
71        } else {
72            Some(line)
73        }
74    });
75
76    Ok((last_ts, last_message))
77}
78
79fn stopped_surfaces_for_root(root: &Path, state_dir: &Path) -> Result<Vec<StoppedSurface>, String> {
80    let records = list_records_for_root(root, Some(state_dir))?;
81    let mut stopped = Vec::new();
82    for located in records {
83        if is_running(&located.record) {
84            continue;
85        }
86        let entries_path = located.dir.join("entries.jsonl");
87        let (last_ts, last_message) = scan_entries_summary(&entries_path)?;
88        let last_used = last_ts.unwrap_or(located.record.started_at);
89        stopped.push(StoppedSurface {
90            id: located.record.id,
91            name: located.record.name,
92            last_used,
93            last_message,
94        });
95    }
96    stopped.sort_by(|a, b| b.last_used.cmp(&a.last_used).then_with(|| a.id.cmp(&b.id)));
97    Ok(stopped)
98}
99
100/// Collect stopped surfaces belonging to `folder`, newest first by `last_used`, then by `id`.
101pub fn stopped_surfaces(folder: &Path, state_dir: &Path) -> Result<Vec<StoppedSurface>, String> {
102    let root = crate::serve::resolve_folder(folder)?;
103    stopped_surfaces_for_root(&root, state_dir)
104}
105
106fn format_utc_minute(ts: u64) -> String {
107    let days = (ts / 86_400) as i64;
108    let secs_of_day = ts % 86_400;
109    let hour = secs_of_day / 3_600;
110    let min = (secs_of_day % 3_600) / 60;
111
112    let z = days + 719_468;
113    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
114    let doe = (z - era * 146_097) as u64;
115    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
116    let y = yoe as i64 + era * 400;
117    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
118    let mp = (5 * doy + 2) / 153;
119    let d = doy - (153 * mp + 2) / 5 + 1;
120    let m = if mp < 10 { mp + 3 } else { mp - 9 };
121    let year = if m <= 2 { y + 1 } else { y };
122
123    format!("{year:04}-{m:02}-{d:02} {hour:02}:{min:02}")
124}
125
126pub fn format_stopped_surfaces_table(entries: &[StoppedSurface], folder: &Path) -> String {
127    if entries.is_empty() {
128        return format!("no stopped surfaces in {}\n", folder.display());
129    }
130
131    let rows: Vec<(&str, &str, String, String)> = entries
132        .iter()
133        .map(|entry| {
134            let last_used = format_utc_minute(entry.last_used);
135            let message = match &entry.last_message {
136                Some(msg) => msg.chars().take(60).collect(),
137                None => "-".to_string(),
138            };
139            (entry.name.as_str(), entry.id.as_str(), last_used, message)
140        })
141        .collect();
142
143    let name_w = rows
144        .iter()
145        .map(|row| row.0.chars().count())
146        .max()
147        .unwrap_or(0)
148        .max("NAME".len());
149    let id_w = rows
150        .iter()
151        .map(|row| row.1.chars().count())
152        .max()
153        .unwrap_or(0)
154        .max("ID".len());
155    let used_w = rows
156        .iter()
157        .map(|row| row.2.chars().count())
158        .max()
159        .unwrap_or(0)
160        .max("LAST USED".len());
161
162    let mut out = String::new();
163    let _ = writeln!(
164        out,
165        "{:<name_w$}  {:<id_w$}  {:<used_w$}  LAST MESSAGE",
166        "NAME", "ID", "LAST USED"
167    );
168    for (name, id, last_used, message) in rows {
169        let _ = writeln!(
170            out,
171            "{name:<name_w$}  {id:<id_w$}  {last_used:<used_w$}  {message}"
172        );
173    }
174    let _ = writeln!(out);
175    let _ = writeln!(out, "resume with: blyte --resume <name or id>");
176    out
177}
178
179pub fn run_stopped_surfaces(
180    folder: &Path,
181    state_dir: &Path,
182    json: bool,
183    out: &mut dyn Write,
184    err: &mut dyn Write,
185) -> i32 {
186    let root = match crate::serve::resolve_folder(folder) {
187        Ok(root) => root,
188        Err(e) => {
189            let _ = writeln!(err, "blyte: {e}");
190            return 1;
191        }
192    };
193    let entries = match stopped_surfaces_for_root(&root, state_dir) {
194        Ok(entries) => entries,
195        Err(e) => {
196            let _ = writeln!(err, "blyte: {e}");
197            return 1;
198        }
199    };
200
201    if json {
202        match serde_json::to_string_pretty(&entries) {
203            Ok(text) => {
204                let _ = writeln!(out, "{text}");
205                return 0;
206            }
207            Err(e) => {
208                let _ = writeln!(err, "blyte: failed to serialize surfaces: {e}");
209                return 1;
210            }
211        }
212    }
213
214    let _ = write!(out, "{}", format_stopped_surfaces_table(&entries, &root));
215    0
216}
217
218fn repository_name(root: &Path) -> String {
219    root.file_name()
220        .map(|name| name.to_string_lossy().into_owned())
221        .unwrap_or_else(|| root.display().to_string())
222}
223
224pub fn format_surfaces_table(entries: &[RegistryEntry], current_id: Option<&str>) -> String {
225    if entries.is_empty() {
226        return "no surfaces are running\n".to_string();
227    }
228
229    let rows: Vec<(String, String, &str, &str)> = entries
230        .iter()
231        .map(|entry| {
232            let name = if current_id == Some(entry.id.as_str()) {
233                format!("{} (this surface)", entry.name)
234            } else {
235                entry.name.clone()
236            };
237            (
238                name,
239                repository_name(&entry.root),
240                entry.branch.as_deref().unwrap_or("-"),
241                entry.doing.as_str(),
242            )
243        })
244        .collect();
245
246    let name_w = rows
247        .iter()
248        .map(|row| row.0.chars().count())
249        .max()
250        .unwrap_or(0)
251        .max("NAME".len());
252    let repo_w = rows
253        .iter()
254        .map(|row| row.1.chars().count())
255        .max()
256        .unwrap_or(0)
257        .max("REPOSITORY".len());
258    let branch_w = rows
259        .iter()
260        .map(|row| row.2.chars().count())
261        .max()
262        .unwrap_or(0)
263        .max("BRANCH".len());
264
265    let mut out = String::new();
266    let _ = writeln!(
267        out,
268        "{:<name_w$}  {:<repo_w$}  {:<branch_w$}  DOING",
269        "NAME", "REPOSITORY", "BRANCH"
270    );
271    for (name, repo, branch, doing) in rows {
272        let _ = writeln!(
273            out,
274            "{name:<name_w$}  {repo:<repo_w$}  {branch:<branch_w$}  {doing}"
275        );
276    }
277    out
278}
279
280pub fn run_surfaces(dir: &Path, json: bool, out: &mut dyn Write, err: &mut dyn Write) -> i32 {
281    let entries = match live_entries(dir) {
282        Ok(entries) => entries,
283        Err(e) => {
284            let _ = writeln!(err, "blyte: {e}");
285            return 1;
286        }
287    };
288
289    if json {
290        match serde_json::to_string_pretty(&entries) {
291            Ok(text) => {
292                let _ = writeln!(out, "{text}");
293                return 0;
294            }
295            Err(e) => {
296                let _ = writeln!(err, "blyte: failed to serialize surfaces: {e}");
297                return 1;
298            }
299        }
300    }
301
302    let _ = write!(out, "{}", format_surfaces_table(&entries, None));
303    0
304}
305
306pub fn surface_url(entry: &RegistryEntry) -> Result<String, String> {
307    let token_path = blyte_agent::sandbox::surface_token_path_for_id(&entry.id)?;
308    let raw_token = std::fs::read_to_string(&token_path).map_err(|_| {
309        format!(
310            "surface {} has no usable token at {}",
311            entry.name,
312            token_path.display()
313        )
314    })?;
315    let token = raw_token.trim();
316    if token.is_empty() || token.contains(['\n', '\r']) {
317        return Err(format!(
318            "surface {} has no usable token at {}",
319            entry.name,
320            token_path.display()
321        ));
322    }
323    Ok(format!("http://127.0.0.1:{}/#token={token}", entry.port))
324}
325
326pub fn surfaces_payload(
327    registry_dir: &Path,
328    current_id: &str,
329    stopped: &[StoppedSurface],
330) -> Result<serde_json::Value, String> {
331    let mut entries = live_entries(registry_dir)?;
332    entries.sort_by(|a, b| {
333        a.name
334            .cmp(&b.name)
335            .then_with(|| a.started_at.cmp(&b.started_at))
336    });
337    if !entries.iter().any(|entry| entry.id == current_id) {
338        return Err(format!(
339            "current surface {current_id} is not in the surface registry"
340        ));
341    }
342    let surfaces: Vec<serde_json::Value> = entries
343        .iter()
344        .map(|entry| {
345            let (url, error) = match surface_url(entry) {
346                Ok(url) => (Some(url), None),
347                Err(err) => (None, Some(err)),
348            };
349            serde_json::json!({
350                "id": entry.id,
351                "name": entry.name,
352                "root": entry.root.to_string_lossy(),
353                "branch": entry.branch,
354                "doing": entry.doing,
355                "current": entry.id == current_id,
356                "url": url,
357                "error": error,
358            })
359        })
360        .collect();
361    Ok(serde_json::json!({ "surfaces": surfaces, "stopped": stopped }))
362}
363
364pub fn run_open(
365    dir: &Path,
366    name: &str,
367    opener: &dyn Fn(&str),
368    out: &mut dyn Write,
369    err: &mut dyn Write,
370) -> i32 {
371    let entry = match find_by_name(dir, name) {
372        Ok(entry) => entry,
373        Err(e) => {
374            let _ = writeln!(err, "blyte: {e}");
375            return 1;
376        }
377    };
378
379    let url = match surface_url(&entry) {
380        Ok(url) => url,
381        Err(e) => {
382            let _ = writeln!(err, "blyte: {e}");
383            return 1;
384        }
385    };
386
387    opener(&url);
388    let _ = writeln!(out, "blyte: opened surface {}", entry.name);
389    0
390}