1use std::collections::BTreeSet;
2use std::fmt::Write as _;
3use std::io::{BufRead, 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 UnreadableRecord,
14};
15
16const OPEN_CODE_TIMEOUT: Duration = Duration::from_secs(5);
17const RELOAD_WAIT_TIMEOUT: Duration = Duration::from_secs(20);
18const RELOAD_POLL_INTERVAL: Duration = Duration::from_millis(100);
19const STOP_WAIT_TIMEOUT: Duration = Duration::from_secs(10);
20const STOP_POLL_INTERVAL: Duration = Duration::from_millis(50);
21const MAX_OPEN_CODE_RESPONSE_BYTES: usize = 64 * 1024;
22const RUNS_WINDOW_DAYS: u64 = 14;
23const PICKER_MAX_STOPPED: usize = 5;
24
25#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
32pub struct StoppedSurface {
33 pub id: String,
34 pub name: String,
35 pub last_used: u64,
36 pub last_message: Option<String>,
37}
38
39#[derive(Debug, Clone, Default, PartialEq, Eq)]
40pub struct StoppedListing {
41 pub surfaces: Vec<StoppedSurface>,
42 pub unreadable: Vec<UnreadableRecord>,
43}
44
45fn scan_entries_summary(path: &Path) -> Result<(Option<u64>, Option<String>), String> {
46 let bytes = match std::fs::read(path) {
47 Ok(b) => b,
48 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok((None, None)),
49 Err(e) => return Err(e.to_string()),
50 };
51
52 let mut last_ts: Option<u64> = None;
53 let mut last_user_text: Option<String> = None;
54 let mut pos = 0usize;
55 let mut line_no = 0usize;
56 while pos < bytes.len() {
57 line_no += 1;
58 let start = pos;
59 let end = match bytes[pos..].iter().position(|&b| b == b'\n') {
60 Some(rel) => pos + rel + 1,
61 None => bytes.len(),
62 };
63 let is_last_without_newline = end == bytes.len() && !bytes[start..end].ends_with(b"\n");
64 let line_slice = &bytes[start..end];
65 let parsed = std::str::from_utf8(line_slice)
66 .map_err(|e| e.to_string())
67 .and_then(|s| serde_json::from_str::<Entry>(s).map_err(|e| e.to_string()));
68 match parsed {
69 Ok(entry) => {
70 last_ts = Some(entry.ts);
71 if let EntryBody::UserMessage { text, .. } = entry.body {
72 last_user_text = Some(text);
73 }
74 }
75 Err(reason) => {
76 if !is_last_without_newline {
77 return Err(format!("invalid entry at line {line_no}: {reason}"));
78 }
79 }
80 }
81 pos = end;
82 }
83
84 let last_message = last_user_text.and_then(|text| {
85 let line = first_line(&text);
86 if line.is_empty() {
87 None
88 } else {
89 Some(line)
90 }
91 });
92
93 Ok((last_ts, last_message))
94}
95
96fn stopped_surfaces_for_root(root: &Path, state_dir: &Path) -> Result<StoppedListing, String> {
97 let listing = list_records_for_root(root, Some(state_dir))?;
98 let mut surfaces = Vec::new();
99 let mut unreadable = listing.unreadable;
100 for located in listing.records {
101 if is_running(&located.record) {
102 continue;
103 }
104 let entries_path = located.dir.join("entries.jsonl");
105 let (last_ts, last_message) = match scan_entries_summary(&entries_path) {
106 Ok(summary) => summary,
107 Err(reason) => {
108 unreadable.push(UnreadableRecord {
109 path: entries_path,
110 reason,
111 });
112 continue;
113 }
114 };
115 let last_used = last_ts.unwrap_or(located.record.started_at);
116 surfaces.push(StoppedSurface {
117 id: located.record.id,
118 name: located.record.name,
119 last_used,
120 last_message,
121 });
122 }
123 surfaces.sort_by(|a, b| b.last_used.cmp(&a.last_used).then_with(|| a.id.cmp(&b.id)));
124 unreadable.sort_by(|a, b| a.path.cmp(&b.path));
125 Ok(StoppedListing {
126 surfaces,
127 unreadable,
128 })
129}
130
131pub fn stopped_surfaces(folder: &Path, state_dir: &Path) -> Result<StoppedListing, String> {
133 let root = crate::serve::resolve_folder(folder)?;
134 stopped_surfaces_for_root(&root, state_dir)
135}
136
137fn format_utc_minute(ts: u64) -> String {
138 let days = (ts / 86_400) as i64;
139 let secs_of_day = ts % 86_400;
140 let hour = secs_of_day / 3_600;
141 let min = (secs_of_day % 3_600) / 60;
142
143 let z = days + 719_468;
144 let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
145 let doe = (z - era * 146_097) as u64;
146 let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
147 let y = yoe as i64 + era * 400;
148 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
149 let mp = (5 * doy + 2) / 153;
150 let d = doy - (153 * mp + 2) / 5 + 1;
151 let m = if mp < 10 { mp + 3 } else { mp - 9 };
152 let year = if m <= 2 { y + 1 } else { y };
153
154 format!("{year:04}-{m:02}-{d:02} {hour:02}:{min:02}")
155}
156
157pub fn format_stopped_surfaces_table(entries: &[StoppedSurface], folder: &Path) -> String {
158 if entries.is_empty() {
159 return format!("no stopped surfaces in {}\n", folder.display());
160 }
161
162 let rows: Vec<(&str, &str, String, String)> = entries
163 .iter()
164 .map(|entry| {
165 let last_used = format_utc_minute(entry.last_used);
166 let message = match &entry.last_message {
167 Some(msg) => msg.chars().take(60).collect(),
168 None => "-".to_string(),
169 };
170 (entry.name.as_str(), entry.id.as_str(), last_used, message)
171 })
172 .collect();
173
174 let name_w = rows
175 .iter()
176 .map(|row| row.0.chars().count())
177 .max()
178 .unwrap_or(0)
179 .max("NAME".len());
180 let id_w = rows
181 .iter()
182 .map(|row| row.1.chars().count())
183 .max()
184 .unwrap_or(0)
185 .max("ID".len());
186 let used_w = rows
187 .iter()
188 .map(|row| row.2.chars().count())
189 .max()
190 .unwrap_or(0)
191 .max("LAST USED".len());
192
193 let mut out = String::new();
194 let _ = writeln!(
195 out,
196 "{:<name_w$} {:<id_w$} {:<used_w$} LAST MESSAGE",
197 "NAME", "ID", "LAST USED"
198 );
199 for (name, id, last_used, message) in rows {
200 let _ = writeln!(
201 out,
202 "{name:<name_w$} {id:<id_w$} {last_used:<used_w$} {message}"
203 );
204 }
205 let _ = writeln!(out);
206 let _ = writeln!(out, "resume with: blyte --resume <name or id>");
207 out
208}
209
210pub fn run_stopped_surfaces(
211 folder: &Path,
212 state_dir: &Path,
213 json: bool,
214 out: &mut dyn Write,
215 err: &mut dyn Write,
216) -> i32 {
217 let root = match crate::serve::resolve_folder(folder) {
218 Ok(root) => root,
219 Err(e) => {
220 let _ = writeln!(err, "blyte: {e}");
221 return 1;
222 }
223 };
224 let listing = match stopped_surfaces_for_root(&root, state_dir) {
225 Ok(listing) => listing,
226 Err(e) => {
227 let _ = writeln!(err, "blyte: {e}");
228 return 1;
229 }
230 };
231 report_unreadable(&listing.unreadable, err);
232
233 if json {
234 match serde_json::to_string_pretty(&listing.surfaces) {
235 Ok(text) => {
236 let _ = writeln!(out, "{text}");
237 return 0;
238 }
239 Err(e) => {
240 let _ = writeln!(err, "blyte: failed to serialize surfaces: {e}");
241 return 1;
242 }
243 }
244 }
245
246 let _ = write!(
247 out,
248 "{}",
249 format_stopped_surfaces_table(&listing.surfaces, &root)
250 );
251 0
252}
253
254fn repository_name(root: &Path) -> String {
255 root.file_name()
256 .map(|name| name.to_string_lossy().into_owned())
257 .unwrap_or_else(|| root.display().to_string())
258}
259
260fn count_running_runs_at(root: &Path, now: SystemTime) -> Result<usize, String> {
261 let now = now
262 .duration_since(UNIX_EPOCH)
263 .map_err(|e| format!("system clock is before UNIX_EPOCH: {e}"))?
264 .as_secs();
265 crate::live_runs::collect(root, now, RUNS_WINDOW_DAYS).map(|live| live.running.len())
266}
267
268pub fn count_running_runs(root: &Path) -> Result<usize, String> {
269 count_running_runs_at(root, SystemTime::now())
270}
271
272fn format_surface_state(entry: &RegistryEntry) -> String {
273 if entry.state != SurfaceState::Idle {
274 return entry.state.display_label().to_string();
275 }
276 match count_running_runs(&entry.root) {
277 Ok(0) => entry.state.display_label().to_string(),
278 Ok(1) => "idle (1 run working)".to_string(),
279 Ok(n) => format!("idle ({n} runs working)"),
280 Err(err) => format!("idle (runs unknown: {err})"),
281 }
282}
283
284fn format_surface_version(entry: &RegistryEntry) -> String {
285 match entry.runtime.is_stale() {
286 Ok(false) => entry.runtime.version.clone(),
287 Ok(true) => format!("{} (stale)", entry.runtime.version),
288 Err(err) => format!("{} (stale unknown: {err})", entry.runtime.version),
289 }
290}
291
292#[derive(serde::Serialize)]
293struct SurfaceJsonEntry<'a> {
294 #[serde(flatten)]
295 entry: &'a RegistryEntry,
296 stale: Option<bool>,
297 #[serde(skip_serializing_if = "Option::is_none")]
298 stale_error: Option<String>,
299 runs_working: Option<usize>,
300 #[serde(skip_serializing_if = "Option::is_none")]
301 runs_error: Option<String>,
302}
303
304pub fn format_surfaces_table(entries: &[RegistryEntry], current_id: Option<&str>) -> String {
305 if entries.is_empty() {
306 return "no surfaces are running\n".to_string();
307 }
308
309 let rows: Vec<(String, String, &str, String, String, &str)> = entries
310 .iter()
311 .map(|entry| {
312 let name = if current_id == Some(entry.id.as_str()) {
313 format!("{} (this surface)", entry.name)
314 } else {
315 entry.name.clone()
316 };
317 (
318 name,
319 repository_name(&entry.root),
320 entry.branch.as_deref().unwrap_or("-"),
321 format_surface_version(entry),
322 format_surface_state(entry),
323 entry.doing.as_str(),
324 )
325 })
326 .collect();
327
328 let name_w = rows
329 .iter()
330 .map(|row| row.0.chars().count())
331 .max()
332 .unwrap_or(0)
333 .max("NAME".len());
334 let repo_w = rows
335 .iter()
336 .map(|row| row.1.chars().count())
337 .max()
338 .unwrap_or(0)
339 .max("REPOSITORY".len());
340 let branch_w = rows
341 .iter()
342 .map(|row| row.2.chars().count())
343 .max()
344 .unwrap_or(0)
345 .max("BRANCH".len());
346 let version_w = rows
347 .iter()
348 .map(|row| row.3.chars().count())
349 .max()
350 .unwrap_or(0)
351 .max("VERSION".len());
352 let state_w = rows
353 .iter()
354 .map(|row| row.4.chars().count())
355 .max()
356 .unwrap_or(0)
357 .max("STATE".len());
358
359 let mut out = String::new();
360 let _ = writeln!(
361 out,
362 "{:<name_w$} {:<repo_w$} {:<branch_w$} {:<version_w$} {:<state_w$} DOING",
363 "NAME", "REPOSITORY", "BRANCH", "VERSION", "STATE"
364 );
365 for (name, repo, branch, version, state, doing) in rows {
366 let _ = writeln!(
367 out,
368 "{name:<name_w$} {repo:<repo_w$} {branch:<branch_w$} {version:<version_w$} {state:<state_w$} {doing}"
369 );
370 }
371 out
372}
373
374pub fn run_surfaces(dir: &Path, json: bool, out: &mut dyn Write, err: &mut dyn Write) -> i32 {
375 let listing = match live_entries(dir) {
376 Ok(listing) => listing,
377 Err(e) => {
378 let _ = writeln!(err, "blyte: {e}");
379 return 1;
380 }
381 };
382 report_unreadable(&listing.unreadable, err);
383
384 if json {
385 let payload: Vec<SurfaceJsonEntry<'_>> = listing
386 .entries
387 .iter()
388 .map(|entry| {
389 let (stale, stale_error) = match entry.runtime.is_stale() {
390 Ok(stale) => (Some(stale), None),
391 Err(stale_err) => (None, Some(stale_err)),
392 };
393 let (runs_working, runs_error) = match count_running_runs(&entry.root) {
394 Ok(count) => (Some(count), None),
395 Err(runs_err) => (None, Some(runs_err)),
396 };
397 SurfaceJsonEntry {
398 entry,
399 stale,
400 stale_error,
401 runs_working,
402 runs_error,
403 }
404 })
405 .collect();
406 match serde_json::to_string_pretty(&payload) {
407 Ok(text) => {
408 let _ = writeln!(out, "{text}");
409 return 0;
410 }
411 Err(e) => {
412 let _ = writeln!(err, "blyte: failed to serialize surfaces: {e}");
413 return 1;
414 }
415 }
416 }
417
418 let _ = write!(out, "{}", format_surfaces_table(&listing.entries, None));
419 0
420}
421
422fn read_surface_token(entry: &RegistryEntry) -> Result<String, String> {
423 let token_path = blyte_agent::sandbox::surface_token_path_for_id(&entry.id)?;
424 let raw_token = std::fs::read_to_string(&token_path).map_err(|_| {
425 format!(
426 "surface {} has no usable token at {}",
427 entry.name,
428 token_path.display()
429 )
430 })?;
431 let token = raw_token.trim();
432 if token.is_empty() || token.contains(['\n', '\r']) {
433 return Err(format!(
434 "surface {} has no usable token at {}",
435 entry.name,
436 token_path.display()
437 ));
438 }
439 Ok(token.to_string())
440}
441
442pub fn surface_url(entry: &RegistryEntry) -> Result<String, String> {
443 let token = read_surface_token(entry)?;
444 Ok(format!("http://127.0.0.1:{}/#token={token}", entry.port))
445}
446
447fn parse_http_status(head: &str) -> Result<u16, String> {
448 let status_line = head.lines().next().unwrap_or("").trim_end_matches('\r');
449 let mut parts = status_line.split_whitespace();
450 let version = parts
451 .next()
452 .ok_or_else(|| "empty HTTP response".to_string())?;
453 if !version.starts_with("HTTP/") {
454 return Err("invalid HTTP response".to_string());
455 }
456 let code_str = parts
457 .next()
458 .ok_or_else(|| "missing HTTP status code".to_string())?;
459 code_str
460 .parse::<u16>()
461 .map_err(|_| "invalid HTTP status code".to_string())
462}
463
464pub fn request_open_code(entry: &RegistryEntry, token: &str) -> Result<String, String> {
465 request_open_code_at(&entry.name, entry.port, token)
466}
467
468pub fn request_open_code_at(name: &str, port: u16, token: &str) -> Result<String, String> {
469 let deadline = Instant::now() + OPEN_CODE_TIMEOUT;
470 let addr = SocketAddr::from(([127, 0, 0, 1], port));
471 let mut stream = TcpStream::connect_timeout(&addr, OPEN_CODE_TIMEOUT).map_err(|e| {
472 if e.kind() == ErrorKind::ConnectionRefused {
473 format!("surface {name} refused the connection on port {port}")
474 } else {
475 format!("cannot connect to surface {name} on port {port}: {e}")
476 }
477 })?;
478
479 let remaining = deadline.saturating_duration_since(Instant::now());
480 if remaining.is_zero() {
481 return Err(format!("surface {name} timed out on port {port}"));
482 }
483 let _ = stream.set_write_timeout(Some(remaining));
484
485 let req = format!(
486 "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{{}}"
487 );
488 stream
489 .write_all(req.as_bytes())
490 .map_err(|e| format!("failed to request an open code from surface {name}: {e}"))?;
491
492 let mut raw = Vec::new();
493 let mut chunk = [0u8; 4096];
494 loop {
495 if raw.len() >= MAX_OPEN_CODE_RESPONSE_BYTES {
496 return Err(format!(
497 "surface {name} gave an answer blyte does not understand"
498 ));
499 }
500 let remaining = deadline.saturating_duration_since(Instant::now());
501 if remaining.is_zero() {
502 return Err(format!("surface {name} timed out on port {port}"));
503 }
504 let _ = stream.set_read_timeout(Some(remaining));
505 let max_read = (MAX_OPEN_CODE_RESPONSE_BYTES - raw.len()).min(chunk.len());
506 match stream.read(&mut chunk[..max_read]) {
507 Ok(0) => break,
508 Ok(n) => raw.extend_from_slice(&chunk[..n]),
509 Err(e) if e.kind() == ErrorKind::Interrupted => continue,
510 Err(e) if e.kind() == ErrorKind::TimedOut || e.kind() == ErrorKind::WouldBlock => {
511 return Err(format!("surface {name} timed out on port {port}"));
512 }
513 Err(e) => {
514 return Err(format!("failed to read answer from surface {name}: {e}"));
515 }
516 }
517 }
518
519 let text = std::str::from_utf8(&raw)
520 .map_err(|_| format!("surface {name} gave an answer blyte does not understand"))?;
521 let (head, resp_body) = text
522 .split_once("\r\n\r\n")
523 .ok_or_else(|| format!("surface {name} gave an answer blyte does not understand"))?;
524 let status = parse_http_status(head)
525 .map_err(|_| format!("surface {name} gave an answer blyte does not understand"))?;
526 if status != 200 {
527 return Err(format!(
528 "surface {name} could not create an open code (HTTP {status})"
529 ));
530 }
531 let parsed: serde_json::Value = serde_json::from_str(resp_body)
532 .map_err(|_| format!("surface {name} gave an answer blyte does not understand"))?;
533 let code = parsed
534 .get("code")
535 .and_then(|v| v.as_str())
536 .map(str::trim)
537 .filter(|s| !s.is_empty())
538 .ok_or_else(|| format!("surface {name} gave an answer blyte does not understand"))?;
539 Ok(code.to_string())
540}
541
542fn known_folders(state_dir: &Path, entries: &[RegistryEntry]) -> Result<Vec<String>, String> {
543 let mut folders = BTreeSet::new();
544 let repos_path = state_dir.join("repos");
545 match std::fs::read_to_string(&repos_path) {
546 Ok(content) => {
547 for line in content.lines() {
548 let trimmed = line.trim();
549 if trimmed.is_empty() {
550 continue;
551 }
552 let path = PathBuf::from(trimmed);
553 if path.is_dir() {
554 folders.insert(trimmed.to_string());
555 }
556 }
557 }
558 Err(e) if e.kind() == ErrorKind::NotFound => {}
559 Err(e) => {
560 return Err(format!("failed to read {}: {e}", repos_path.display()));
561 }
562 }
563 for entry in entries {
564 folders.insert(entry.root.to_string_lossy().into_owned());
565 }
566 Ok(folders.into_iter().collect())
567}
568
569pub fn surfaces_payload(
570 registry_dir: &Path,
571 state_dir: &Path,
572 current_id: &str,
573 stopped: &[StoppedSurface],
574) -> Result<serde_json::Value, String> {
575 let listing = live_entries(registry_dir)?;
576 let mut entries = listing.entries;
577 entries.sort_by(|a, b| {
578 a.name
579 .cmp(&b.name)
580 .then_with(|| a.started_at.cmp(&b.started_at))
581 });
582 if !entries.iter().any(|entry| entry.id == current_id) {
583 return Err(format!(
584 "current surface {current_id} is not in the surface registry"
585 ));
586 }
587 let folders = known_folders(state_dir, &entries)?;
588 let surfaces: Vec<serde_json::Value> = entries
589 .iter()
590 .map(|entry| {
591 let (url, error) = match surface_url(entry) {
592 Ok(url) => (Some(url), None),
593 Err(err) => (None, Some(err)),
594 };
595 let (stale, stale_error) = match entry.runtime.is_stale() {
596 Ok(stale) => (Some(stale), None),
597 Err(err) => (None, Some(err)),
598 };
599 serde_json::json!({
600 "id": entry.id,
601 "name": entry.name,
602 "root": entry.root.to_string_lossy(),
603 "branch": entry.branch,
604 "doing": entry.doing,
605 "state": entry.state,
606 "version": entry.runtime.version,
607 "boot_id": entry.runtime.boot_id,
608 "stale": stale,
609 "stale_error": stale_error,
610 "current": entry.id == current_id,
611 "url": url,
612 "error": error,
613 })
614 })
615 .collect();
616 let unreadable: Vec<serde_json::Value> = listing
617 .unreadable
618 .iter()
619 .map(|record| {
620 serde_json::json!({
621 "path": record.path.to_string_lossy(),
622 "reason": record.reason,
623 })
624 })
625 .collect();
626 Ok(serde_json::json!({
627 "surfaces": surfaces,
628 "stopped": stopped,
629 "folders": folders,
630 "unreadable": unreadable,
631 }))
632}
633
634pub fn run_open(
635 dir: &Path,
636 name: &str,
637 opener: &dyn Fn(&str),
638 out: &mut dyn Write,
639 err: &mut dyn Write,
640) -> i32 {
641 let entry = match find_by_name(dir, name) {
642 Ok(entry) => entry,
643 Err(e) => {
644 let _ = writeln!(err, "blyte: {e}");
645 return 1;
646 }
647 };
648
649 let token = match read_surface_token(&entry) {
650 Ok(token) => token,
651 Err(e) => {
652 let _ = writeln!(err, "blyte: {e}");
653 return 1;
654 }
655 };
656
657 let code = match request_open_code(&entry, &token) {
658 Ok(code) => code,
659 Err(e) => {
660 let _ = writeln!(err, "blyte: {e}");
661 return 1;
662 }
663 };
664
665 let url = format!("http://127.0.0.1:{}/#open={code}", entry.port);
666 opener(&url);
667 let _ = writeln!(out, "blyte: opened surface {}", entry.name);
668 0
669}
670
671fn http_json_request(
672 name: &str,
673 port: u16,
674 method: &str,
675 path: &str,
676 token: &str,
677 body: Option<&str>,
678 timeout: Duration,
679) -> Result<(u16, String), String> {
680 let deadline = Instant::now() + timeout;
681 let addr = SocketAddr::from(([127, 0, 0, 1], port));
682 let mut stream = TcpStream::connect_timeout(&addr, timeout).map_err(|e| {
683 if e.kind() == ErrorKind::ConnectionRefused {
684 format!("surface {name} refused the connection on port {port}")
685 } else {
686 format!("cannot connect to surface {name} on port {port}: {e}")
687 }
688 })?;
689
690 let remaining = deadline.saturating_duration_since(Instant::now());
691 if remaining.is_zero() {
692 return Err(format!("surface {name} timed out on port {port}"));
693 }
694 let _ = stream.set_write_timeout(Some(remaining));
695
696 let req = match body {
697 Some(payload) => format!(
698 "{method} {path} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n{TOKEN_HEADER}: {token}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{payload}",
699 payload.len()
700 ),
701 None => format!(
702 "{method} {path} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n{TOKEN_HEADER}: {token}\r\nConnection: close\r\n\r\n"
703 ),
704 };
705 stream
706 .write_all(req.as_bytes())
707 .map_err(|e| format!("failed to contact surface {name}: {e}"))?;
708
709 let mut raw = Vec::new();
710 let mut chunk = [0u8; 4096];
711 loop {
712 if raw.len() >= MAX_OPEN_CODE_RESPONSE_BYTES {
713 return Err(format!(
714 "surface {name} gave an answer blyte does not understand"
715 ));
716 }
717 let remaining = deadline.saturating_duration_since(Instant::now());
718 if remaining.is_zero() {
719 return Err(format!("surface {name} timed out on port {port}"));
720 }
721 let _ = stream.set_read_timeout(Some(remaining));
722 let max_read = (MAX_OPEN_CODE_RESPONSE_BYTES - raw.len()).min(chunk.len());
723 match stream.read(&mut chunk[..max_read]) {
724 Ok(0) => break,
725 Ok(n) => raw.extend_from_slice(&chunk[..n]),
726 Err(e) if e.kind() == ErrorKind::Interrupted => continue,
727 Err(e) if e.kind() == ErrorKind::TimedOut || e.kind() == ErrorKind::WouldBlock => {
728 return Err(format!("surface {name} timed out on port {port}"));
729 }
730 Err(e) => {
731 return Err(format!("failed to read answer from surface {name}: {e}"));
732 }
733 }
734 }
735
736 let text = std::str::from_utf8(&raw)
737 .map_err(|_| format!("surface {name} gave an answer blyte does not understand"))?;
738 let (head, resp_body) = text
739 .split_once("\r\n\r\n")
740 .ok_or_else(|| format!("surface {name} gave an answer blyte does not understand"))?;
741 let status = parse_http_status(head)
742 .map_err(|_| format!("surface {name} gave an answer blyte does not understand"))?;
743 Ok((status, resp_body.to_string()))
744}
745
746pub fn request_reload(entry: &RegistryEntry, token: &str) -> Result<(), String> {
747 let (status, resp_body) = http_json_request(
748 &entry.name,
749 entry.port,
750 "POST",
751 "/api/reload",
752 token,
753 Some("{}"),
754 OPEN_CODE_TIMEOUT,
755 )?;
756 if status != 200 {
757 let detail = serde_json::from_str::<serde_json::Value>(&resp_body)
758 .ok()
759 .and_then(|v| v.get("error").and_then(|e| e.as_str()).map(str::to_string));
760 return match detail {
761 Some(msg) if !msg.trim().is_empty() => Err(format!(
762 "surface {} failed to reload (HTTP {status}): {msg}",
763 entry.name
764 )),
765 _ => Err(format!(
766 "surface {} failed to reload (HTTP {status})",
767 entry.name
768 )),
769 };
770 }
771 let parsed: serde_json::Value = serde_json::from_str(&resp_body).map_err(|_| {
772 format!(
773 "surface {} gave an answer blyte does not understand",
774 entry.name
775 )
776 })?;
777 if parsed.get("reloading").and_then(|v| v.as_bool()) != Some(true) {
778 return Err(format!(
779 "surface {} gave an answer blyte does not understand",
780 entry.name
781 ));
782 }
783 Ok(())
784}
785
786fn wait_for_reloaded_surface(
787 entry: &RegistryEntry,
788 token: &str,
789 timeout: Duration,
790) -> Result<(String, String), String> {
791 let deadline = Instant::now() + timeout;
792 let mut last_error: Option<String> = None;
793 while Instant::now() < deadline {
794 let remaining = deadline.saturating_duration_since(Instant::now());
795 let step_timeout = remaining.min(Duration::from_secs(2));
796 match http_json_request(
797 &entry.name,
798 entry.port,
799 "GET",
800 "/api/session",
801 token,
802 None,
803 step_timeout,
804 ) {
805 Ok((200, body)) => {
806 if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&body) {
807 if let (Some(boot_id), Some(version)) = (
808 parsed
809 .get("boot_id")
810 .and_then(|v| v.as_str())
811 .map(str::trim),
812 parsed
813 .get("version")
814 .and_then(|v| v.as_str())
815 .map(str::trim),
816 ) {
817 if !boot_id.is_empty() && boot_id != entry.runtime.boot_id {
818 return Ok((version.to_string(), boot_id.to_string()));
819 }
820 }
821 }
822 }
823 Ok((status, _)) => {
824 last_error = Some(format!("HTTP {status} while waiting for reload"));
825 }
826 Err(e) => {
827 last_error = Some(e);
828 }
829 }
830 std::thread::sleep(RELOAD_POLL_INTERVAL);
831 }
832 match last_error {
833 Some(e) => Err(format!(
834 "surface {} did not come back after reload within {}s ({e})",
835 entry.name,
836 timeout.as_secs()
837 )),
838 None => Err(format!(
839 "surface {} did not report a new boot_id after reload within {}s",
840 entry.name,
841 timeout.as_secs()
842 )),
843 }
844}
845
846fn select_surface_targets(
847 dir: &Path,
848 cwd: &Path,
849 target: Option<&str>,
850 all: bool,
851 err: &mut dyn Write,
852) -> Result<Vec<RegistryEntry>, String> {
853 let listing = live_entries(dir)?;
854 report_unreadable(&listing.unreadable, err);
855 let mut entries = listing.entries;
856 entries.sort_by(|a, b| {
857 a.name
858 .cmp(&b.name)
859 .then_with(|| a.started_at.cmp(&b.started_at))
860 });
861
862 if all {
863 return Ok(entries);
864 }
865
866 if let Some(name_or_id) = target {
867 let matches: Vec<RegistryEntry> = entries
868 .iter()
869 .filter(|e| e.id == name_or_id || e.name == name_or_id)
870 .cloned()
871 .collect();
872 return match matches.len() {
873 0 => {
874 if entries.is_empty() {
875 Err(format!(
876 "no running surface named {name_or_id} (no surfaces are running)"
877 ))
878 } else {
879 let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
880 Err(format!(
881 "no running surface named {name_or_id}; running surfaces: {}",
882 names.join(", ")
883 ))
884 }
885 }
886 1 => Ok(matches),
887 _ => {
888 let ids: Vec<&str> = matches.iter().map(|e| e.id.as_str()).collect();
889 Err(format!(
890 "more than one running surface is named {name_or_id}; specify by id: {}",
891 ids.join(", ")
892 ))
893 }
894 };
895 }
896
897 let root = crate::serve::resolve_folder(cwd)?;
898 let matches: Vec<RegistryEntry> = entries.into_iter().filter(|e| e.root == root).collect();
899 match matches.len() {
900 0 => Err(format!("no running surface for {}", root.display())),
901 1 => Ok(matches),
902 _ => {
903 let names: Vec<String> = matches
904 .iter()
905 .map(|e| format!("{} ({})", e.name, e.id))
906 .collect();
907 Err(format!(
908 "multiple surfaces are running for {}; specify one by name or id: {}",
909 root.display(),
910 names.join(", ")
911 ))
912 }
913 }
914}
915
916pub fn run_reload(
917 dir: &Path,
918 cwd: &Path,
919 target: Option<&str>,
920 all: bool,
921 out: &mut dyn Write,
922 err: &mut dyn Write,
923) -> i32 {
924 let targets = match select_surface_targets(dir, cwd, target, all, err) {
925 Ok(targets) => targets,
926 Err(e) => {
927 let _ = writeln!(err, "blyte: {e}");
928 return 1;
929 }
930 };
931
932 if targets.is_empty() {
933 let _ = writeln!(out, "blyte: no surfaces are running");
934 return 0;
935 }
936
937 let mut had_error = false;
938 let mut pending: Vec<(RegistryEntry, String)> = Vec::new();
939 for entry in targets {
940 let token = match read_surface_token(&entry) {
941 Ok(token) => token,
942 Err(e) => {
943 let _ = writeln!(err, "blyte: {e}");
944 had_error = true;
945 continue;
946 }
947 };
948 if let Err(e) = request_reload(&entry, &token) {
949 let _ = writeln!(err, "blyte: {e}");
950 had_error = true;
951 continue;
952 }
953 pending.push((entry, token));
954 }
955
956 for (entry, token) in pending {
957 match wait_for_reloaded_surface(&entry, &token, RELOAD_WAIT_TIMEOUT) {
958 Ok((new_version, _new_boot_id)) => {
959 if !new_version.is_empty() && new_version != entry.runtime.version {
960 let _ = writeln!(
961 out,
962 "blyte: reloaded surface {} ({} -> {})",
963 entry.name, entry.runtime.version, new_version
964 );
965 } else {
966 let version_label = if new_version.is_empty() {
967 entry.runtime.version.as_str()
968 } else {
969 new_version.as_str()
970 };
971 let _ = writeln!(
972 out,
973 "blyte: reloaded surface {} ({version_label})",
974 entry.name
975 );
976 }
977 }
978 Err(e) => {
979 let _ = writeln!(err, "blyte: {e}");
980 had_error = true;
981 }
982 }
983 }
984
985 if had_error {
986 1
987 } else {
988 0
989 }
990}
991
992pub fn request_stop(entry: &RegistryEntry, token: &str, force: bool) -> Result<(), String> {
993 let payload = if force { "{\"force\":true}" } else { "{}" };
994 let (status, resp_body) = http_json_request(
995 &entry.name,
996 entry.port,
997 "POST",
998 "/api/stop",
999 token,
1000 Some(payload),
1001 OPEN_CODE_TIMEOUT,
1002 )?;
1003 if status != 200 && status != 202 {
1004 let detail = serde_json::from_str::<serde_json::Value>(&resp_body)
1005 .ok()
1006 .and_then(|v| v.get("error").and_then(|e| e.as_str()).map(str::to_string));
1007 return match detail {
1008 Some(msg) if !msg.trim().is_empty() => Err(format!(
1009 "surface {} failed to stop (HTTP {status}): {msg}",
1010 entry.name
1011 )),
1012 _ => Err(format!(
1013 "surface {} failed to stop (HTTP {status})",
1014 entry.name
1015 )),
1016 };
1017 }
1018 let parsed: serde_json::Value = serde_json::from_str(&resp_body).map_err(|_| {
1019 format!(
1020 "surface {} gave an answer blyte does not understand",
1021 entry.name
1022 )
1023 })?;
1024 if parsed.get("stopping").and_then(|v| v.as_bool()) != Some(true) {
1025 return Err(format!(
1026 "surface {} gave an answer blyte does not understand",
1027 entry.name
1028 ));
1029 }
1030 Ok(())
1031}
1032
1033fn wait_for_surface_stopped(
1034 dir: &Path,
1035 entry: &RegistryEntry,
1036 timeout: Duration,
1037) -> Result<(), String> {
1038 let deadline = Instant::now() + timeout;
1039 let addr = SocketAddr::from(([127, 0, 0, 1], entry.port));
1040 let reg_path = crate::surface_registry::entry_path(dir, &entry.id);
1041 while Instant::now() < deadline {
1042 let port_closed = TcpStream::connect_timeout(&addr, Duration::from_millis(150)).is_err();
1043 if port_closed {
1044 if !reg_path.exists() {
1045 return Ok(());
1046 }
1047 if !crate::surface_dir::pid_exists(entry.pid) {
1048 crate::surface_registry::remove_entry(dir, &entry.id)?;
1049 return Ok(());
1050 }
1051 }
1052 std::thread::sleep(STOP_POLL_INTERVAL);
1053 }
1054 Err(format!(
1055 "surface {} did not stop within {}s",
1056 entry.name,
1057 timeout.as_secs()
1058 ))
1059}
1060
1061pub fn stop_surface_entry(
1062 dir: &Path,
1063 entry: &RegistryEntry,
1064 force: bool,
1065 out: &mut dyn Write,
1066 err: &mut dyn Write,
1067) -> i32 {
1068 let token = match read_surface_token(entry) {
1069 Ok(token) => token,
1070 Err(e) => {
1071 let _ = writeln!(err, "blyte: {e}");
1072 return 1;
1073 }
1074 };
1075 if let Err(e) = request_stop(entry, &token, force) {
1076 let _ = writeln!(err, "blyte: {e}");
1077 return 1;
1078 }
1079 if let Err(e) = wait_for_surface_stopped(dir, entry, STOP_WAIT_TIMEOUT) {
1080 let _ = writeln!(err, "blyte: {e}");
1081 return 1;
1082 }
1083 let _ = writeln!(
1084 out,
1085 "blyte: stopped surface {} ({}); resume with: blyte --resume {}",
1086 entry.name, entry.id, entry.name
1087 );
1088 0
1089}
1090
1091pub fn run_stop(
1092 dir: &Path,
1093 cwd: &Path,
1094 target: Option<&str>,
1095 all: bool,
1096 force: bool,
1097 out: &mut dyn Write,
1098 err: &mut dyn Write,
1099) -> i32 {
1100 let targets = match select_surface_targets(dir, cwd, target, all, err) {
1101 Ok(targets) => targets,
1102 Err(e) => {
1103 let _ = writeln!(err, "blyte: {e}");
1104 return 1;
1105 }
1106 };
1107
1108 if targets.is_empty() {
1109 if all {
1110 let _ = writeln!(out, "blyte: no surfaces are running");
1111 return 0;
1112 }
1113 let _ = writeln!(err, "blyte: no running surface matched");
1114 return 1;
1115 }
1116
1117 let mut had_error = false;
1118 let mut pending: Vec<RegistryEntry> = Vec::new();
1119 for entry in targets {
1120 let token = match read_surface_token(&entry) {
1121 Ok(token) => token,
1122 Err(e) => {
1123 let _ = writeln!(err, "blyte: {e}");
1124 had_error = true;
1125 continue;
1126 }
1127 };
1128 if let Err(e) = request_stop(&entry, &token, force) {
1129 let _ = writeln!(err, "blyte: {e}");
1130 had_error = true;
1131 continue;
1132 }
1133 pending.push(entry);
1134 }
1135
1136 for entry in pending {
1137 match wait_for_surface_stopped(dir, &entry, STOP_WAIT_TIMEOUT) {
1138 Ok(()) => {
1139 let _ = writeln!(
1140 out,
1141 "blyte: stopped surface {} ({}); resume with: blyte --resume {}",
1142 entry.name, entry.id, entry.name
1143 );
1144 }
1145 Err(e) => {
1146 let _ = writeln!(err, "blyte: {e}");
1147 had_error = true;
1148 }
1149 }
1150 }
1151
1152 if had_error {
1153 1
1154 } else {
1155 0
1156 }
1157}
1158
1159pub fn open_running_entry(
1160 entry: &RegistryEntry,
1161 no_open: bool,
1162 opener: &dyn Fn(&str),
1163 out: &mut dyn Write,
1164 err: &mut dyn Write,
1165) -> i32 {
1166 let token = match read_surface_token(entry) {
1167 Ok(token) => token,
1168 Err(e) => {
1169 let _ = writeln!(err, "blyte: {e}");
1170 return 1;
1171 }
1172 };
1173
1174 if no_open {
1175 let _ = writeln!(
1176 out,
1177 "blyte: surface {} at http://127.0.0.1:{}/#token={token}",
1178 entry.name, entry.port
1179 );
1180 return 0;
1181 }
1182
1183 let code = match request_open_code(entry, &token) {
1184 Ok(code) => code,
1185 Err(e) => {
1186 let _ = writeln!(err, "blyte: {e}");
1187 return 1;
1188 }
1189 };
1190
1191 let url = format!("http://127.0.0.1:{}/#open={code}", entry.port);
1192 opener(&url);
1193 let _ = writeln!(out, "blyte: opened surface {}", entry.name);
1194 0
1195}
1196
1197fn running_surfaces_listing_for_folder(
1198 dir: &Path,
1199 folder: &Path,
1200) -> Result<(Vec<RegistryEntry>, Vec<UnreadableRecord>), String> {
1201 let root = crate::serve::resolve_folder(folder)?;
1202 let listing = live_entries(dir)?;
1203 let mut matches: Vec<RegistryEntry> = listing
1204 .entries
1205 .into_iter()
1206 .filter(|e| e.root == root)
1207 .collect();
1208 matches.sort_by(|a, b| {
1209 b.started_at
1210 .cmp(&a.started_at)
1211 .then_with(|| a.name.cmp(&b.name))
1212 });
1213 Ok((matches, listing.unreadable))
1214}
1215
1216pub fn running_surfaces_for_folder(
1217 dir: &Path,
1218 folder: &Path,
1219) -> Result<Vec<RegistryEntry>, String> {
1220 running_surfaces_listing_for_folder(dir, folder).map(|(entries, _)| entries)
1221}
1222
1223pub type PickerCandidates = (
1224 Vec<RegistryEntry>,
1225 Vec<StoppedSurface>,
1226 Vec<UnreadableRecord>,
1227);
1228
1229pub fn load_picker_candidates(
1230 reg_dir: &Path,
1231 state_dir: &Path,
1232 folder: &Path,
1233) -> Result<PickerCandidates, String> {
1234 let (running, mut unreadable) =
1235 running_surfaces_listing_for_folder(reg_dir, folder).map_err(|e| {
1236 format!(
1237 "failed to load running surfaces from {}: {e}",
1238 reg_dir.display()
1239 )
1240 })?;
1241 let stopped = if running.is_empty() {
1242 let listing = stopped_surfaces(folder, state_dir).map_err(|e| {
1243 format!(
1244 "failed to load stopped surfaces for {} (state dir {}): {e}",
1245 folder.display(),
1246 state_dir.display()
1247 )
1248 })?;
1249 unreadable.extend(listing.unreadable);
1250 listing.surfaces
1251 } else {
1252 Vec::new()
1253 };
1254 Ok((running, stopped, unreadable))
1255}
1256
1257#[derive(Debug, Clone, PartialEq, Eq)]
1258pub enum LaunchAction {
1259 OpenRunning(RegistryEntry),
1260 Resume(String),
1261 StartNew,
1262 StopRunning(RegistryEntry),
1263 Cancel,
1264}
1265
1266pub fn should_run_picker(is_tty: bool, resume: Option<&str>, foreground: bool, new: bool) -> bool {
1267 is_tty && resume.is_none() && !new && !foreground
1268}
1269
1270pub fn pick_launch_action(
1271 running: &[RegistryEntry],
1272 stopped: &[StoppedSurface],
1273 input: &mut dyn BufRead,
1274 out: &mut dyn Write,
1275) -> Result<LaunchAction, String> {
1276 if !running.is_empty() {
1277 if running.len() == 1 {
1278 let entry = &running[0];
1279 writeln!(
1280 out,
1281 "Surface `{}` is already running for this folder (port {}).",
1282 entry.name, entry.port
1283 )
1284 .map_err(|e| e.to_string())?;
1285 writeln!(out, " [1] Open running surface `{}` (default)", entry.name)
1286 .map_err(|e| e.to_string())?;
1287 writeln!(out, " [n] Start a new surface").map_err(|e| e.to_string())?;
1288 writeln!(out, " [s] Stop running surface `{}`", entry.name)
1289 .map_err(|e| e.to_string())?;
1290 writeln!(out, " [q] Cancel").map_err(|e| e.to_string())?;
1291 } else {
1292 writeln!(
1293 out,
1294 "Multiple surfaces are already running for this folder:"
1295 )
1296 .map_err(|e| e.to_string())?;
1297 for (idx, entry) in running.iter().enumerate() {
1298 let suffix = if idx == 0 { " (default)" } else { "" };
1299 writeln!(
1300 out,
1301 " [{}] Open `{}` ({}, port {}){}",
1302 idx + 1,
1303 entry.name,
1304 entry.id,
1305 entry.port,
1306 suffix
1307 )
1308 .map_err(|e| e.to_string())?;
1309 }
1310 writeln!(out, " [n] Start a new surface").map_err(|e| e.to_string())?;
1311 writeln!(
1312 out,
1313 " [s] Stop `{}` (or `s <num>` to stop another)",
1314 running[0].name
1315 )
1316 .map_err(|e| e.to_string())?;
1317 writeln!(out, " [q] Cancel").map_err(|e| e.to_string())?;
1318 }
1319
1320 loop {
1321 write!(out, "Choice [1]: ").map_err(|e| e.to_string())?;
1322 out.flush().map_err(|e| e.to_string())?;
1323 let mut line = String::new();
1324 let n = input.read_line(&mut line).map_err(|e| e.to_string())?;
1325 if n == 0 {
1326 return Ok(LaunchAction::Cancel);
1327 }
1328 let choice = line.trim().to_ascii_lowercase();
1329 if choice.is_empty() || choice == "o" || choice == "open" {
1330 return Ok(LaunchAction::OpenRunning(running[0].clone()));
1331 }
1332 if choice == "n" || choice == "new" {
1333 return Ok(LaunchAction::StartNew);
1334 }
1335 if choice == "q" || choice == "quit" {
1336 return Ok(LaunchAction::Cancel);
1337 }
1338 if choice == "s" || choice == "stop" {
1339 return Ok(LaunchAction::StopRunning(running[0].clone()));
1340 }
1341 if let Some(rest) = choice
1342 .strip_prefix("s ")
1343 .or_else(|| choice.strip_prefix("stop "))
1344 {
1345 if let Ok(idx) = rest.trim().parse::<usize>() {
1346 if idx >= 1 && idx <= running.len() {
1347 return Ok(LaunchAction::StopRunning(running[idx - 1].clone()));
1348 }
1349 }
1350 }
1351 if let Ok(idx) = choice.parse::<usize>() {
1352 if idx >= 1 && idx <= running.len() {
1353 return Ok(LaunchAction::OpenRunning(running[idx - 1].clone()));
1354 }
1355 }
1356 writeln!(
1357 out,
1358 "Invalid choice. Enter 1..{}, n, s, or q.",
1359 running.len()
1360 )
1361 .map_err(|e| e.to_string())?;
1362 }
1363 }
1364
1365 if !stopped.is_empty() {
1366 let shown = &stopped[..stopped.len().min(PICKER_MAX_STOPPED)];
1367 writeln!(out, "Recent stopped surfaces for this folder:").map_err(|e| e.to_string())?;
1368 for (idx, entry) in shown.iter().enumerate() {
1369 let suffix = if idx == 0 { " (default)" } else { "" };
1370 let preview = match &entry.last_message {
1371 Some(msg) => {
1372 let snippet: String = msg.chars().take(40).collect();
1373 format!(" - {snippet}")
1374 }
1375 None => String::new(),
1376 };
1377 writeln!(
1378 out,
1379 " [{}] Resume `{}` ({}){}{}",
1380 idx + 1,
1381 entry.name,
1382 entry.id,
1383 preview,
1384 suffix
1385 )
1386 .map_err(|e| e.to_string())?;
1387 }
1388 writeln!(out, " [n] Start a fresh surface").map_err(|e| e.to_string())?;
1389 writeln!(out, " [q] Cancel").map_err(|e| e.to_string())?;
1390
1391 loop {
1392 write!(out, "Choice [1]: ").map_err(|e| e.to_string())?;
1393 out.flush().map_err(|e| e.to_string())?;
1394 let mut line = String::new();
1395 let n = input.read_line(&mut line).map_err(|e| e.to_string())?;
1396 if n == 0 {
1397 return Ok(LaunchAction::Cancel);
1398 }
1399 let choice = line.trim().to_ascii_lowercase();
1400 if choice.is_empty() || choice == "r" || choice == "resume" {
1401 return Ok(LaunchAction::Resume(shown[0].id.clone()));
1402 }
1403 if choice == "n" || choice == "new" {
1404 return Ok(LaunchAction::StartNew);
1405 }
1406 if choice == "q" || choice == "quit" {
1407 return Ok(LaunchAction::Cancel);
1408 }
1409 if let Ok(idx) = choice.parse::<usize>() {
1410 if idx >= 1 && idx <= shown.len() {
1411 return Ok(LaunchAction::Resume(shown[idx - 1].id.clone()));
1412 }
1413 }
1414 writeln!(out, "Invalid choice. Enter 1..{}, n, or q.", shown.len())
1415 .map_err(|e| e.to_string())?;
1416 }
1417 }
1418
1419 Ok(LaunchAction::StartNew)
1420}
1421
1422#[cfg(test)]
1423mod tests {
1424 use super::{count_running_runs_at, wait_for_surface_stopped};
1425 use crate::surface_registry::{entry_path, write_entry, RegistryEntry, SurfaceState};
1426 use crate::surface_version::SurfaceRuntimeInfo;
1427 use std::net::TcpListener;
1428 use std::path::Path;
1429 use std::time::{Duration, Instant, UNIX_EPOCH};
1430
1431 fn unused_port() -> u16 {
1432 TcpListener::bind("127.0.0.1:0")
1433 .expect("bind ephemeral port")
1434 .local_addr()
1435 .expect("local addr")
1436 .port()
1437 }
1438
1439 fn test_entry(dir: &Path, id: &str, name: &str, pid: u32, port: u16) -> RegistryEntry {
1440 let fake_bin = dir.join("blyte-bin");
1441 if !fake_bin.exists() {
1442 std::fs::write(&fake_bin, b"#!/bin/sh\n").expect("write fake bin");
1443 }
1444 let runtime =
1445 SurfaceRuntimeInfo::from_binary("0.83.1", &fake_bin, "boot-wait").expect("runtime");
1446 RegistryEntry {
1447 id: id.to_string(),
1448 name: name.to_string(),
1449 root: dir.to_path_buf(),
1450 branch: Some("main".to_string()),
1451 pid,
1452 port,
1453 started_at: 1_700_000_000,
1454 doing: "idle".to_string(),
1455 state: SurfaceState::Idle,
1456 runtime,
1457 }
1458 }
1459
1460 #[test]
1461 fn count_running_runs_at_rejects_pre_epoch_time() {
1462 let tmp = tempfile::tempdir().expect("tempdir");
1463 std::fs::create_dir_all(tmp.path().join(".git")).expect("create .git");
1464 let pre_epoch = UNIX_EPOCH
1465 .checked_sub(Duration::from_secs(1))
1466 .expect("pre-epoch SystemTime");
1467
1468 let err = count_running_runs_at(tmp.path(), pre_epoch)
1469 .expect_err("expected error for system clock before UNIX_EPOCH");
1470 assert!(
1471 err.contains("UNIX_EPOCH"),
1472 "error should name UNIX_EPOCH: {err}"
1473 );
1474 }
1475
1476 #[test]
1477 fn wait_for_surface_stopped_polls_until_registry_removed_while_pid_alive() {
1478 let tmp = tempfile::tempdir().expect("tempdir");
1479 let reg_dir = tmp.path().join("surfaces");
1480 let entry = test_entry(
1481 tmp.path(),
1482 "s00000000000000a1",
1483 "slow-cleanup",
1484 std::process::id(),
1485 unused_port(),
1486 );
1487 write_entry(®_dir, &entry).expect("write entry");
1488 let reg_path = entry_path(®_dir, &entry.id);
1489 assert!(reg_path.exists());
1490
1491 let remover_path = reg_path.clone();
1492 let handle = std::thread::spawn(move || {
1493 std::thread::sleep(Duration::from_millis(160));
1494 std::fs::remove_file(&remover_path).expect("remove registry entry");
1495 });
1496
1497 let started = Instant::now();
1498 wait_for_surface_stopped(®_dir, &entry, Duration::from_secs(2))
1499 .expect("wait should succeed once registry entry is removed");
1500 let elapsed = started.elapsed();
1501 handle.join().expect("join remover thread");
1502 assert!(
1503 elapsed >= Duration::from_millis(120),
1504 "returned too early before cleanup finished: {elapsed:?}"
1505 );
1506 assert!(!reg_path.exists());
1507 }
1508
1509 #[test]
1510 fn wait_for_surface_stopped_times_out_and_keeps_registry_when_pid_still_alive() {
1511 let tmp = tempfile::tempdir().expect("tempdir");
1512 let reg_dir = tmp.path().join("surfaces");
1513 let entry = test_entry(
1514 tmp.path(),
1515 "s00000000000000a2",
1516 "stuck-cleanup",
1517 std::process::id(),
1518 unused_port(),
1519 );
1520 write_entry(®_dir, &entry).expect("write entry");
1521 let reg_path = entry_path(®_dir, &entry.id);
1522
1523 let err = wait_for_surface_stopped(®_dir, &entry, Duration::from_millis(180))
1524 .expect_err("expected timeout while pid is alive and registry exists");
1525 assert!(err.contains("stuck-cleanup"), "got: {err}");
1526 assert!(err.contains("did not stop"), "got: {err}");
1527 assert!(
1528 reg_path.exists(),
1529 "wait_for_surface_stopped must not delete registry while pid is still alive"
1530 );
1531 }
1532
1533 #[cfg(unix)]
1534 #[test]
1535 fn wait_for_surface_stopped_cleans_up_stale_registry_after_pid_exits() {
1536 let tmp = tempfile::tempdir().expect("tempdir");
1537 let reg_dir = tmp.path().join("surfaces");
1538 let mut child = std::process::Command::new("/bin/sh")
1539 .args(["-c", "exit 0"])
1540 .spawn()
1541 .expect("spawn short-lived process");
1542 let dead_pid = child.id();
1543 let status = child.wait().expect("reap short-lived process");
1544 assert!(status.success());
1545
1546 let entry = test_entry(
1547 tmp.path(),
1548 "s00000000000000a3",
1549 "crashed-surface",
1550 dead_pid,
1551 unused_port(),
1552 );
1553 write_entry(®_dir, &entry).expect("write entry");
1554 let reg_path = entry_path(®_dir, &entry.id);
1555 assert!(reg_path.exists());
1556
1557 wait_for_surface_stopped(®_dir, &entry, Duration::from_secs(2))
1558 .expect("dead pid with closed port should clean up stale registry entry");
1559 assert!(!reg_path.exists());
1560 }
1561}