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
126#[derive(Debug, Clone, PartialEq, Eq)]
127pub struct UnreadableRecord {
128 pub path: PathBuf,
129 pub reason: String,
130}
131
132#[derive(Debug, Clone, Default, PartialEq, Eq)]
133pub struct RegistryEntries {
134 pub entries: Vec<RegistryEntry>,
135 pub unreadable: Vec<UnreadableRecord>,
136}
137
138pub fn report_unreadable(unreadable: &[UnreadableRecord], err: &mut dyn Write) {
139 for record in unreadable {
140 let _ = writeln!(
141 err,
142 "blyte: skipped surface record {}: {}",
143 record.path.display(),
144 record.reason
145 );
146 }
147 if !unreadable.is_empty() {
148 let _ = err.flush();
149 }
150}
151
152pub fn read_entries(dir: &Path) -> Result<RegistryEntries, String> {
153 let read_dir = match std::fs::read_dir(dir) {
154 Ok(rd) => rd,
155 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(RegistryEntries::default()),
156 Err(e) => return Err(format!("failed to read {}: {e}", dir.display())),
157 };
158 let mut entries = Vec::new();
159 let mut unreadable = Vec::new();
160 for item in read_dir {
161 let item = item.map_err(|e| format!("failed to read {}: {e}", dir.display()))?;
162 let path = item.path();
163 let file_name = item.file_name();
164 let lossy = file_name.to_string_lossy();
165 if !lossy.ends_with(".json") {
166 continue;
167 }
168 let Some(name_str) = file_name.to_str() else {
169 return Err(format!("invalid registry entry path: {}", path.display()));
170 };
171 let Some(stem) = name_str.strip_suffix(".json") else {
172 continue;
173 };
174 let bytes = match std::fs::read(&path) {
177 Ok(bytes) => bytes,
178 Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
179 Err(e) => return Err(format!("failed to read {}: {e}", path.display())),
180 };
181 let entry: RegistryEntry = match serde_json::from_slice(&bytes) {
182 Ok(entry) => entry,
183 Err(e) => {
184 unreadable.push(UnreadableRecord {
185 path,
186 reason: e.to_string(),
187 });
188 continue;
189 }
190 };
191 if entry.id != stem {
192 unreadable.push(UnreadableRecord {
193 path,
194 reason: format!("has id {}, expected {stem}", entry.id),
195 });
196 continue;
197 }
198 entries.push(entry);
199 }
200 entries.sort_by(|a, b| {
201 a.started_at
202 .cmp(&b.started_at)
203 .then_with(|| a.id.cmp(&b.id))
204 });
205 unreadable.sort_by(|a, b| a.path.cmp(&b.path));
206 Ok(RegistryEntries {
207 entries,
208 unreadable,
209 })
210}
211
212pub fn live_entries(dir: &Path) -> Result<RegistryEntries, String> {
213 let read = read_entries(dir)?;
214 let mut live = Vec::with_capacity(read.entries.len());
215 for entry in read.entries {
216 match probe(entry.pid, entry.port, &entry.id) {
217 Liveness::Running | Liveness::Unknown => live.push(entry),
218 Liveness::NotRunning => remove_entry(dir, &entry.id)?,
219 }
220 }
221 Ok(RegistryEntries {
222 entries: live,
223 unreadable: read.unreadable,
224 })
225}
226
227pub fn find_by_name(dir: &Path, name: &str) -> Result<RegistryEntry, String> {
228 let listing = live_entries(dir)?;
229 let mut matches: Vec<RegistryEntry> = listing
230 .entries
231 .into_iter()
232 .filter(|entry| entry.name == name || entry.id == name)
233 .collect();
234 match matches.len() {
235 0 => {
236 if listing.unreadable.is_empty() {
237 Err(format!("no running surface named {name}"))
238 } else {
239 let paths: Vec<String> = listing
240 .unreadable
241 .iter()
242 .map(|record| record.path.display().to_string())
243 .collect();
244 let label = if paths.len() == 1 {
245 "skipped unreadable surface record"
246 } else {
247 "skipped unreadable surface records"
248 };
249 Err(format!(
250 "no running surface named {name} ({label}: {})",
251 paths.join(", ")
252 ))
253 }
254 }
255 1 => Ok(matches.remove(0)),
256 _ => {
257 let ids: Vec<&str> = matches.iter().map(|e| e.id.as_str()).collect();
258 Err(format!(
259 "more than one running surface is named {name}; use an id: {}",
260 ids.join(", ")
261 ))
262 }
263 }
264}
265
266pub fn first_line(text: &str) -> String {
267 for line in text.lines() {
268 let trimmed = line.trim();
269 if !trimmed.is_empty() {
270 return trimmed.chars().take(120).collect();
271 }
272 }
273 String::new()
274}