1use std::io::Write;
2use std::path::{Path, PathBuf};
3use std::sync::atomic::{AtomicU64, Ordering};
4
5use blyte_agent::sandbox::validate_surface_id;
6use serde::{Deserialize, Serialize};
7
8use crate::surface_dir::{probe, validate_surface_name, Liveness};
9
10static TMP_COUNTER: AtomicU64 = AtomicU64::new(0);
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
13#[serde(rename_all = "lowercase")]
14pub enum SurfaceState {
15 Idle,
16 Working,
17 Approval,
18 Replied,
19}
20
21impl SurfaceState {
22 pub fn as_str(&self) -> &'static str {
23 match self {
24 Self::Idle => "idle",
25 Self::Working => "working",
26 Self::Approval => "approval",
27 Self::Replied => "replied",
28 }
29 }
30
31 pub fn display_label(&self) -> &'static str {
32 match self {
33 Self::Idle => "idle",
34 Self::Working => "working",
35 Self::Approval => "waiting on you (approval)",
36 Self::Replied => "waiting on you (replied)",
37 }
38 }
39}
40
41#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
42pub struct RegistryEntry {
43 pub id: String,
44 pub name: String,
45 pub root: PathBuf,
46 pub branch: Option<String>,
47 pub pid: u32,
48 pub port: u16,
49 pub started_at: u64,
50 pub doing: String,
51 pub state: SurfaceState,
52}
53
54pub fn state_dir() -> Result<PathBuf, String> {
55 crate::registry::state_dir().ok_or_else(|| {
56 "cannot find the blyte state directory: set BLYTE_STATE_DIR, XDG_STATE_HOME or HOME"
57 .to_string()
58 })
59}
60
61pub fn registry_dir() -> Result<PathBuf, String> {
62 state_dir().map(|dir| dir.join("surfaces"))
63}
64
65pub fn entry_path(dir: &Path, id: &str) -> PathBuf {
66 dir.join(format!("{id}.json"))
67}
68
69pub fn write_entry(dir: &Path, entry: &RegistryEntry) -> Result<(), String> {
70 validate_surface_id(&entry.id)?;
71 validate_surface_name(&entry.name)?;
72 std::fs::create_dir_all(dir).map_err(|e| format!("failed to create {}: {e}", dir.display()))?;
73 let dest = entry_path(dir, &entry.id);
74 let mut json = serde_json::to_string_pretty(entry)
75 .map_err(|e| format!("failed to serialize {}: {e}", dest.display()))?;
76 json.push('\n');
77 let seq = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
78 let tmp = dir.join(format!(".{}.tmp.{}.{seq}", entry.id, std::process::id()));
79 let mut opts = std::fs::OpenOptions::new();
80 opts.write(true).create_new(true);
81 #[cfg(unix)]
82 {
83 use std::os::unix::fs::OpenOptionsExt;
84 opts.mode(0o600);
85 }
86 let mut file = opts
87 .open(&tmp)
88 .map_err(|e| format!("failed to create {}: {e}", tmp.display()))?;
89 if let Err(e) = file.write_all(json.as_bytes()) {
90 drop(file);
91 let _ = std::fs::remove_file(&tmp);
92 return Err(format!("failed to write {}: {e}", tmp.display()));
93 }
94 drop(file);
95 #[cfg(unix)]
96 {
97 use std::os::unix::fs::PermissionsExt;
98 if let Err(e) = std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o600)) {
99 let _ = std::fs::remove_file(&tmp);
100 return Err(format!(
101 "failed to set permissions on {}: {e}",
102 tmp.display()
103 ));
104 }
105 }
106 if let Err(e) = std::fs::rename(&tmp, &dest) {
107 let _ = std::fs::remove_file(&tmp);
108 return Err(format!(
109 "failed to rename {} to {}: {e}",
110 tmp.display(),
111 dest.display()
112 ));
113 }
114 Ok(())
115}
116
117pub fn remove_entry(dir: &Path, id: &str) -> Result<(), String> {
118 let path = entry_path(dir, id);
119 match std::fs::remove_file(&path) {
120 Ok(()) => Ok(()),
121 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
122 Err(e) => Err(format!("failed to remove {}: {e}", path.display())),
123 }
124}
125
126pub fn read_entries(dir: &Path) -> Result<Vec<RegistryEntry>, String> {
127 let read_dir = match std::fs::read_dir(dir) {
128 Ok(rd) => rd,
129 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
130 Err(e) => return Err(format!("failed to read {}: {e}", dir.display())),
131 };
132 let mut entries = Vec::new();
133 for item in read_dir {
134 let item = item.map_err(|e| format!("failed to read {}: {e}", dir.display()))?;
135 let path = item.path();
136 let file_name = item.file_name();
137 let lossy = file_name.to_string_lossy();
138 if !lossy.ends_with(".json") {
139 continue;
140 }
141 let Some(name_str) = file_name.to_str() else {
142 return Err(format!("invalid registry entry path: {}", path.display()));
143 };
144 let Some(stem) = name_str.strip_suffix(".json") else {
145 continue;
146 };
147 let text = match std::fs::read_to_string(&path) {
150 Ok(text) => text,
151 Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
152 Err(e) => return Err(format!("failed to read {}: {e}", path.display())),
153 };
154 let entry: RegistryEntry = serde_json::from_str(&text)
155 .map_err(|e| format!("failed to parse {}: {e}", path.display()))?;
156 if entry.id != stem {
157 return Err(format!(
158 "surface registry entry {} has id {}, expected {stem}",
159 path.display(),
160 entry.id
161 ));
162 }
163 entries.push(entry);
164 }
165 entries.sort_by(|a, b| {
166 a.started_at
167 .cmp(&b.started_at)
168 .then_with(|| a.id.cmp(&b.id))
169 });
170 Ok(entries)
171}
172
173pub fn live_entries(dir: &Path) -> Result<Vec<RegistryEntry>, String> {
174 let entries = read_entries(dir)?;
175 let mut live = Vec::with_capacity(entries.len());
176 for entry in entries {
177 match probe(entry.pid, entry.port, &entry.id) {
178 Liveness::Running | Liveness::Unknown => live.push(entry),
179 Liveness::NotRunning => remove_entry(dir, &entry.id)?,
180 }
181 }
182 Ok(live)
183}
184
185pub fn find_by_name(dir: &Path, name: &str) -> Result<RegistryEntry, String> {
186 let entries = live_entries(dir)?;
187 let mut matches: Vec<RegistryEntry> = entries
188 .into_iter()
189 .filter(|entry| entry.name == name || entry.id == name)
190 .collect();
191 match matches.len() {
192 0 => Err(format!("no running surface named {name}")),
193 1 => Ok(matches.remove(0)),
194 _ => {
195 let ids: Vec<&str> = matches.iter().map(|e| e.id.as_str()).collect();
196 Err(format!(
197 "more than one running surface is named {name}; use an id: {}",
198 ids.join(", ")
199 ))
200 }
201 }
202}
203
204pub fn first_line(text: &str) -> String {
205 for line in text.lines() {
206 let trimmed = line.trim();
207 if !trimmed.is_empty() {
208 return trimmed.chars().take(120).collect();
209 }
210 }
211 String::new()
212}