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