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