Skip to main content

blyte_cli/
serve.rs

1use serde::Serialize;
2use std::collections::{BTreeSet, HashSet, VecDeque};
3use std::io::{Read, Write};
4use std::net::TcpListener;
5#[cfg(unix)]
6use std::os::unix::fs::OpenOptionsExt;
7use std::path::{Path, PathBuf};
8use std::process::Command;
9use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
10use std::sync::{Arc, Mutex};
11use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
12
13use crate::cli::SurfaceArgs;
14use crate::http::{Request, Response};
15use crate::open_window::OpenIn;
16use crate::queue_actions::{Action, Hold};
17use crate::repl::ReplConfig;
18use crate::requests::{Publisher, RealPublisher, RequestActionError, RequestsState};
19use crate::session::{
20    AgentRunner, AnswerError, ApprovalAnswer, Attachment, EntryBody, PeerDelivery, PromptRunner,
21    Session,
22};
23use crate::surface_dir::SurfaceRecord;
24
25pub const TOKEN_HEADER: &str = "X-Blyte-Token";
26pub const MESSAGE_HEADER: &str = "X-Blyte-Message-Credential";
27pub const RECONCILE_SAFETY_NET_INTERVAL: Duration = Duration::from_secs(30);
28pub const OPEN_CODE_TTL_SECS: u64 = 60;
29pub const MAX_OPEN_CODES: usize = 16;
30
31const INDEX_HTML: &str = include_str!("../assets/surface/index.html");
32const MAX_WAIT_MS: u64 = 25_000;
33const RECONCILE_POLL_WAIT: Duration = Duration::from_millis(50);
34const TOKEN_BYTES: usize = 32;
35const MAX_PEER_TEXT_BYTES: usize = 16_384;
36const MAX_PEER_REPO_CHARS: usize = 200;
37
38static SESSION_COUNTER: AtomicU64 = AtomicU64::new(1);
39
40struct OpenCodeEntry {
41    code: String,
42    created_at: u64,
43}
44
45#[derive(Default)]
46pub struct OpenCodes {
47    entries: Mutex<VecDeque<OpenCodeEntry>>,
48}
49
50impl OpenCodes {
51    pub fn new() -> Self {
52        Self {
53            entries: Mutex::new(VecDeque::new()),
54        }
55    }
56
57    pub fn issue(&self, now: u64) -> Result<String, String> {
58        let code = generate_token()?;
59        let mut entries = self
60            .entries
61            .lock()
62            .map_err(|e| format!("open codes lock poisoned: {e}"))?;
63        while entries.len() >= MAX_OPEN_CODES {
64            entries.pop_front();
65        }
66        entries.push_back(OpenCodeEntry {
67            code: code.clone(),
68            created_at: now,
69        });
70        Ok(code)
71    }
72
73    pub fn redeem(&self, provided: &str, now: u64) -> Result<bool, String> {
74        if provided.is_empty() {
75            return Ok(false);
76        }
77        let mut entries = self
78            .entries
79            .lock()
80            .map_err(|e| format!("open codes lock poisoned: {e}"))?;
81        let mut matched_idx = None;
82        for (idx, entry) in entries.iter().enumerate() {
83            if constant_time_eq(provided.as_bytes(), entry.code.as_bytes()) {
84                matched_idx = Some(idx);
85            }
86        }
87        let Some(idx) = matched_idx else {
88            entries.retain(|e| now.saturating_sub(e.created_at) <= OPEN_CODE_TTL_SECS);
89            return Ok(false);
90        };
91        let entry = entries.remove(idx).unwrap();
92        entries.retain(|e| now.saturating_sub(e.created_at) <= OPEN_CODE_TTL_SECS);
93        Ok(now.saturating_sub(entry.created_at) <= OPEN_CODE_TTL_SECS)
94    }
95}
96
97pub struct Surface {
98    pub surface_id: String,
99    pub surface_name: String,
100    pub root: PathBuf,
101    pub repo: String,
102    pub session: Session,
103    pub session_id: String,
104    pub started_at: u64,
105    pub days: u64,
106    pub token: String,
107    pub message_credential: String,
108    pub open_codes: OpenCodes,
109    pub requests: Arc<RequestsState>,
110    pub publisher: Arc<dyn Publisher>,
111    pub reconcile_lock: Mutex<()>,
112    pub reconcile_requested: AtomicBool,
113}
114
115pub fn generate_token() -> Result<String, String> {
116    let mut bytes = [0u8; TOKEN_BYTES];
117    let mut file = std::fs::File::open("/dev/urandom")
118        .map_err(|e| format!("failed to open /dev/urandom: {e}"))?;
119    file.read_exact(&mut bytes)
120        .map_err(|e| format!("failed to read /dev/urandom: {e}"))?;
121    const HEX: &[u8; 16] = b"0123456789abcdef";
122    let mut out = String::with_capacity(bytes.len() * 2);
123    for byte in bytes {
124        out.push(HEX[(byte >> 4) as usize] as char);
125        out.push(HEX[(byte & 0x0f) as usize] as char);
126    }
127    Ok(out)
128}
129
130pub fn constant_time_eq(provided: &[u8], expected: &[u8]) -> bool {
131    let mut diff = provided.len() ^ expected.len();
132    for (i, &exp) in expected.iter().enumerate() {
133        let prov = provided.get(i).copied().unwrap_or(0);
134        diff |= usize::from(prov ^ exp);
135    }
136    std::hint::black_box(diff) == 0
137}
138
139fn has_valid_token(surface: &Surface, req: &Request) -> bool {
140    if surface.token.is_empty() {
141        return false;
142    }
143    let mut values = req.header_values(TOKEN_HEADER);
144    let Some(provided) = values.next() else {
145        return false;
146    };
147    if values.next().is_some() {
148        return false;
149    }
150    constant_time_eq(provided.as_bytes(), surface.token.as_bytes())
151}
152
153fn has_valid_message_credential(surface: &Surface, req: &Request) -> bool {
154    if surface.message_credential.is_empty() {
155        return false;
156    }
157    let mut values = req.header_values(MESSAGE_HEADER);
158    let Some(provided) = values.next() else {
159        return false;
160    };
161    if values.next().is_some() {
162        return false;
163    }
164    constant_time_eq(provided.as_bytes(), surface.message_credential.as_bytes())
165}
166
167#[derive(Serialize)]
168struct RunWithHold<'a> {
169    #[serde(flatten)]
170    run: &'a crate::replay::Run,
171    hold: Option<Hold>,
172    combined: bool,
173    #[serde(skip_serializing_if = "std::ops::Not::not")]
174    in_place: bool,
175    #[serde(skip_serializing_if = "std::ops::Not::not")]
176    undone: bool,
177}
178
179#[derive(Serialize)]
180struct LiveRunsResponse<'a> {
181    generated_at: u64,
182    repo: &'a str,
183    running: &'a [crate::live_runs::RunningRun],
184    runs: Vec<RunWithHold<'a>>,
185    skipped: &'a [crate::replay::Skipped],
186}
187
188fn json_error(status: u16, msg: impl Into<String>) -> Response {
189    Response::json(status, &serde_json::json!({ "error": msg.into() }))
190}
191
192fn method_not_allowed(req: &Request) -> Response {
193    json_error(
194        405,
195        format!("method {} not allowed for {}", req.method, req.path),
196    )
197}
198
199fn is_valid_run_id(id: &str) -> bool {
200    !id.is_empty()
201        && id != "."
202        && id != ".."
203        && id
204            .bytes()
205            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
206}
207
208fn parse_json_object(body: &[u8]) -> Result<serde_json::Map<String, serde_json::Value>, Response> {
209    let val: serde_json::Value = serde_json::from_slice(body)
210        .map_err(|e| json_error(400, format!("invalid JSON body: {e}")))?;
211    val.as_object()
212        .cloned()
213        .ok_or_else(|| json_error(400, "request body must be a JSON object"))
214}
215
216fn handle_surfaces(surface: &Surface) -> Response {
217    let state_dir = match crate::surface_registry::state_dir() {
218        Ok(dir) => dir,
219        Err(e) => return json_error(500, e),
220    };
221    let registry_dir = state_dir.join("surfaces");
222    let stopped = match crate::surfaces_cmd::stopped_surfaces(&surface.root, &state_dir) {
223        Ok(stopped) => stopped,
224        Err(e) => return json_error(500, e),
225    };
226    match crate::surfaces_cmd::surfaces_payload(
227        &registry_dir,
228        &state_dir,
229        &surface.surface_id,
230        &stopped,
231    ) {
232        Ok(payload) => Response::json(200, &payload),
233        Err(e) => json_error(500, e),
234    }
235}
236
237fn handle_post_start_surface(req: &Request) -> Response {
238    let obj = match parse_json_object(&req.body) {
239        Ok(o) => o,
240        Err(resp) => return resp,
241    };
242    let Some(folder) = obj.get("folder").and_then(|v| v.as_str()) else {
243        return json_error(400, "missing or invalid field folder");
244    };
245    let state_dir = match crate::surface_registry::state_dir() {
246        Ok(dir) => dir,
247        Err(e) => return json_error(500, e),
248    };
249    match crate::surface_start::start_surface_in(folder, &state_dir) {
250        Ok(started) => Response::json(
251            200,
252            &serde_json::json!({
253                "name": started.name,
254                "url": started.url,
255            }),
256        ),
257        Err(crate::surface_start::StartError::BadRequest(msg)) => json_error(400, msg),
258        Err(crate::surface_start::StartError::Internal(msg)) => json_error(500, msg),
259    }
260}
261
262type StopTrigger = Arc<dyn Fn() + Send + Sync>;
263
264fn handle_post_stop(stop_trigger: Option<&StopTrigger>) -> Response {
265    if let Some(trigger) = stop_trigger {
266        let trigger = Arc::clone(trigger);
267        std::thread::spawn(move || {
268            std::thread::sleep(Duration::from_millis(50));
269            trigger();
270        });
271    }
272    Response::json(202, &serde_json::json!({ "stopping": true }))
273}
274
275fn health_response(surface: &Surface) -> Response {
276    Response::json(
277        200,
278        &serde_json::json!({
279            "surface_id": surface.surface_id,
280            "surface_name": surface.surface_name,
281            "session_id": surface.session_id,
282        }),
283    )
284}
285
286fn session_response(surface: &Surface) -> Response {
287    let info = surface.session.info();
288    let repository = match is_repository(&surface.root) {
289        Ok(v) => v,
290        Err(e) => return json_error(500, e),
291    };
292    Response::json(
293        200,
294        &serde_json::json!({
295            "session_id": surface.session_id,
296            "surface_name": surface.surface_name,
297            "repo": surface.repo,
298            "repository": repository,
299            "started_at": surface.started_at,
300            "model": info.model,
301            "effort": info.effort,
302            "effort_supported": info.effort_supported,
303            "busy": info.busy,
304            "queued": info.queued,
305            "last_seq": info.last_seq,
306            "state": info.state,
307        }),
308    )
309}
310
311fn handle_events(surface: &Surface, req: &Request) -> Response {
312    let after_raw = match req.query_value("after") {
313        Some(v) => v,
314        None => return json_error(400, "missing required query parameter: after"),
315    };
316    let after = match after_raw.parse::<u64>() {
317        Ok(v) => v,
318        Err(_) => {
319            return json_error(
320                400,
321                format!("query parameter after must be a non-negative integer, got '{after_raw}'"),
322            );
323        }
324    };
325    let wait_ms = match req.query_value("wait_ms") {
326        None => 0,
327        Some(raw) => match raw.parse::<u64>() {
328            Ok(v) if v <= MAX_WAIT_MS => v,
329            Ok(v) => {
330                return json_error(
331                    400,
332                    format!("query parameter wait_ms must be at most {MAX_WAIT_MS}, got {v}"),
333                );
334            }
335            Err(_) => {
336                return json_error(
337                    400,
338                    format!("query parameter wait_ms must be a non-negative integer, got '{raw}'"),
339                );
340            }
341        },
342    };
343    let entries = surface
344        .session
345        .entries_after(after, Duration::from_millis(wait_ms));
346    let last_seq = surface.session.info().last_seq;
347    Response::json(
348        200,
349        &serde_json::json!({
350            "entries": entries,
351            "last_seq": last_seq,
352        }),
353    )
354}
355
356fn handle_post_message(surface: &Surface, req: &Request) -> Response {
357    let obj = match parse_json_object(&req.body) {
358        Ok(o) => o,
359        Err(resp) => return resp,
360    };
361    let attachment_ids: Vec<String> = match obj.get("attachments") {
362        None | Some(serde_json::Value::Null) => Vec::new(),
363        Some(serde_json::Value::Array(arr)) => {
364            let mut ids = Vec::with_capacity(arr.len());
365            for item in arr {
366                match item.as_str() {
367                    Some(s) => ids.push(s.to_string()),
368                    None => {
369                        return json_error(400, "field attachments must be an array of strings");
370                    }
371                }
372            }
373            ids
374        }
375        Some(_) => return json_error(400, "field attachments must be an array of strings"),
376    };
377    let text = match obj.get("text") {
378        Some(serde_json::Value::String(s)) => s.clone(),
379        Some(serde_json::Value::Null) | None if !attachment_ids.is_empty() => String::new(),
380        Some(_) => return json_error(400, "field text must be a string"),
381        None => return json_error(400, "missing required field: text"),
382    };
383    let report_ids: Vec<String> = match obj.get("reports") {
384        None | Some(serde_json::Value::Null) => Vec::new(),
385        Some(serde_json::Value::Array(arr)) => {
386            let mut ids = Vec::with_capacity(arr.len());
387            for item in arr {
388                match item.as_str() {
389                    Some(s) => ids.push(s.to_string()),
390                    None => return json_error(400, "field reports must be an array of strings"),
391                }
392            }
393            ids
394        }
395        Some(_) => return json_error(400, "field reports must be an array of strings"),
396    };
397    let pastes: Vec<crate::session::Paste> = match obj.get("pastes") {
398        None | Some(serde_json::Value::Null) => Vec::new(),
399        Some(serde_json::Value::Array(arr)) => {
400            let mut out = Vec::with_capacity(arr.len());
401            for item in arr {
402                match serde_json::from_value::<crate::session::Paste>(item.clone()) {
403                    Ok(p) => out.push(p),
404                    Err(e) => return json_error(400, format!("invalid paste entry: {e}")),
405                }
406            }
407            out
408        }
409        Some(_) => return json_error(400, "field pastes must be an array"),
410    };
411
412    let mut report_attachments = Vec::with_capacity(report_ids.len());
413    for id in report_ids {
414        let path = surface.root.join(".wt").join(format!("{id}.report.md"));
415        if !is_valid_run_id(&id) {
416            return json_error(
417                400,
418                format!("invalid report run id '{id}' (path: {})", path.display()),
419            );
420        }
421        match std::fs::read_to_string(&path) {
422            Ok(body) => report_attachments.push(Attachment {
423                run: id,
424                text: body,
425            }),
426            Err(e) => {
427                return json_error(
428                    400,
429                    format!(
430                        "cannot read report for run '{id}' at {}: {e}",
431                        path.display()
432                    ),
433                );
434            }
435        }
436    }
437
438    let mut file_attachments = Vec::with_capacity(attachment_ids.len());
439    if !attachment_ids.is_empty() {
440        let Some(record_dir) = surface.session.attachments_root() else {
441            return json_error(500, "attachments directory is not configured");
442        };
443        for id in attachment_ids {
444            match crate::attachments::load_with_path(&record_dir, &id) {
445                Ok((meta, path, _)) => {
446                    file_attachments.push(crate::session::QueuedAttachment { meta, path })
447                }
448                Err(e) => return json_error(400, e),
449            }
450        }
451    }
452
453    match surface.session.submit_with_attachments(
454        &text,
455        report_attachments,
456        file_attachments,
457        pastes,
458    ) {
459        Ok(seq) => Response::json(200, &serde_json::json!({ "seq": seq })),
460        Err(e) => json_error(400, e),
461    }
462}
463
464fn handle_post_attachment(surface: &Surface, req: &Request) -> Response {
465    let Some(raw_name) = req
466        .query_value("name")
467        .map(str::trim)
468        .filter(|s| !s.is_empty())
469    else {
470        return json_error(400, "missing required query parameter: name");
471    };
472    if req.body.len() > crate::attachments::MAX_ATTACHMENT_BYTES {
473        return Response::text(
474            413,
475            &format!("{raw_name} is larger than the 10 MiB limit for one file"),
476        );
477    }
478    if req.body.is_empty() {
479        return json_error(400, format!("{raw_name} is empty"));
480    }
481    let Some(record_dir) = surface.session.attachments_root() else {
482        return json_error(500, "attachments directory is not configured");
483    };
484    match crate::attachments::store(&record_dir, raw_name, &req.body) {
485        Ok(meta) => match serde_json::to_value(&meta) {
486            Ok(v) => Response::json(200, &v),
487            Err(e) => json_error(500, format!("failed to serialise attachment metadata: {e}")),
488        },
489        Err(e) => json_error(400, e),
490    }
491}
492
493fn handle_get_attachment(surface: &Surface, id: &str) -> Response {
494    let Some(record_dir) = surface.session.attachments_root() else {
495        return json_error(500, "attachments directory is not configured");
496    };
497    match crate::attachments::load(&record_dir, id) {
498        Ok((_meta, bytes)) => {
499            let content_type =
500                crate::attachments::detect_image(&bytes).unwrap_or("application/octet-stream");
501            Response::bytes(200, content_type, bytes)
502        }
503        Err(e) => json_error(404, e),
504    }
505}
506
507fn handle_post_peer_message(surface: &Surface, req: &Request) -> Response {
508    let obj = match parse_json_object(&req.body) {
509        Ok(o) => o,
510        Err(resp) => return resp,
511    };
512    for key in obj.keys() {
513        if !matches!(key.as_str(), "from_name" | "from_repository" | "text") {
514            return json_error(400, format!("unexpected field: {key}"));
515        }
516    }
517    let from_name = match obj.get("from_name") {
518        Some(serde_json::Value::String(s)) => s.clone(),
519        Some(_) => return json_error(400, "field from_name must be a string"),
520        None => return json_error(400, "missing required field: from_name"),
521    };
522    if let Err(e) = crate::surface_dir::validate_surface_name(&from_name) {
523        return json_error(400, format!("invalid from_name: {e}"));
524    }
525    let from_repository = match obj.get("from_repository") {
526        Some(serde_json::Value::String(s)) => s.clone(),
527        Some(_) => return json_error(400, "field from_repository must be a string"),
528        None => return json_error(400, "missing required field: from_repository"),
529    };
530    let repo_chars = from_repository.chars().count();
531    if repo_chars == 0 || repo_chars > MAX_PEER_REPO_CHARS {
532        return json_error(
533            400,
534            format!("field from_repository must be 1 to {MAX_PEER_REPO_CHARS} characters"),
535        );
536    }
537    if from_repository.chars().any(char::is_control) {
538        return json_error(
539            400,
540            "field from_repository must not contain control characters",
541        );
542    }
543    let text = match obj.get("text") {
544        Some(serde_json::Value::String(s)) => s.clone(),
545        Some(_) => return json_error(400, "field text must be a string"),
546        None => return json_error(400, "missing required field: text"),
547    };
548    if text.trim().is_empty() {
549        return json_error(400, "field text must not be blank");
550    }
551    if text.len() > MAX_PEER_TEXT_BYTES {
552        return json_error(
553            400,
554            format!("field text must be at most {MAX_PEER_TEXT_BYTES} bytes"),
555        );
556    }
557
558    match surface
559        .session
560        .submit_peer(&from_name, &from_repository, &text)
561    {
562        Ok(PeerDelivery::Delivered) => {
563            Response::json(200, &serde_json::json!({ "status": "delivered" }))
564        }
565        Ok(PeerDelivery::Held) => Response::json(200, &serde_json::json!({ "status": "held" })),
566        Err(e) => json_error(400, e),
567    }
568}
569
570fn handle_models() -> Response {
571    let discovered = blyte_provider::discover_all_models();
572    let mut models = Vec::new();
573    let mut unavailable = Vec::new();
574    let mut error_parts = Vec::new();
575
576    for (provider, result) in discovered {
577        match result {
578            Ok(list) => {
579                for m in list {
580                    let effort_supported = crate::session::model_supports_effort(&m.id);
581                    models.push(serde_json::json!({
582                        "id": m.id,
583                        "effort_supported": effort_supported,
584                    }));
585                }
586            }
587            Err(e) => {
588                let err_text = e.to_string();
589                error_parts.push(format!("{provider}: {err_text}"));
590                unavailable.push(serde_json::json!({
591                    "provider": provider,
592                    "error": err_text,
593                }));
594            }
595        }
596    }
597
598    if models.is_empty() {
599        let msg = if error_parts.is_empty() {
600            "no models listed by any provider".to_string()
601        } else {
602            format!("no models available: {}", error_parts.join("; "))
603        };
604        return json_error(502, msg);
605    }
606
607    Response::json(
608        200,
609        &serde_json::json!({
610            "models": models,
611            "unavailable": unavailable,
612        }),
613    )
614}
615
616fn handle_post_model(surface: &Surface, req: &Request) -> Response {
617    let obj = match parse_json_object(&req.body) {
618        Ok(o) => o,
619        Err(resp) => return resp,
620    };
621    let model = match obj.get("model") {
622        Some(serde_json::Value::String(s)) => s.clone(),
623        Some(_) => return json_error(400, "field model must be a string"),
624        None => return json_error(400, "missing required field: model"),
625    };
626    if model.trim().is_empty() {
627        return json_error(400, "field model must not be empty");
628    }
629    if let Err(e) = blyte_provider::resolve_provider(Some(&model)) {
630        return json_error(400, e.to_string());
631    }
632    if let Err(e) = surface.session.set_model(&model) {
633        return json_error(400, e);
634    }
635    session_response(surface)
636}
637
638fn handle_post_effort(surface: &Surface, req: &Request) -> Response {
639    let obj = match parse_json_object(&req.body) {
640        Ok(o) => o,
641        Err(resp) => return resp,
642    };
643    let effort = match obj.get("effort") {
644        Some(serde_json::Value::Null) => None,
645        Some(serde_json::Value::String(s)) => Some(s.clone()),
646        Some(_) => return json_error(400, "field effort must be a string or null"),
647        None => return json_error(400, "missing required field: effort"),
648    };
649    if let Err(e) = surface.session.set_effort(effort.as_deref()) {
650        return json_error(400, e);
651    }
652    session_response(surface)
653}
654
655fn handle_post_seen(surface: &Surface) -> Response {
656    surface.session.mark_seen();
657    Response::text(204, "")
658}
659
660fn handle_post_approval(surface: &Surface, id: &str, req: &Request) -> Response {
661    let obj = match parse_json_object(&req.body) {
662        Ok(o) => o,
663        Err(resp) => return resp,
664    };
665    if obj.len() != 1 {
666        return json_error(400, "request body must contain only field answer");
667    }
668    let answer = match obj.get("answer") {
669        Some(serde_json::Value::String(s)) if s == "yes" => ApprovalAnswer::Yes,
670        Some(serde_json::Value::String(s)) if s == "no" => ApprovalAnswer::No,
671        Some(serde_json::Value::String(other)) => {
672            return json_error(
673                400,
674                format!("field answer must be \"yes\" or \"no\", got '{other}'"),
675            );
676        }
677        Some(_) => return json_error(400, "field answer must be \"yes\" or \"no\""),
678        None => return json_error(400, "missing required field: answer"),
679    };
680    match surface.session.answer_approval(id, answer) {
681        Ok(seq) => Response::json(
682            200,
683            &serde_json::json!({
684                "id": id,
685                "answer": answer.as_str(),
686                "seq": seq,
687            }),
688        ),
689        Err(AnswerError::NotFound) => json_error(404, format!("unknown approval id: {id}")),
690        Err(AnswerError::AlreadyAnswered) => {
691            json_error(409, format!("approval {id} has already been answered"))
692        }
693    }
694}
695
696pub fn reconcile_runs(
697    surface: &Surface,
698    now: u64,
699) -> Result<(crate::live_runs::LiveRuns, Vec<String>), String> {
700    let _guard = surface
701        .reconcile_lock
702        .lock()
703        .unwrap_or_else(|e| e.into_inner());
704    if !is_repository(&surface.root)? {
705        let records_dir = crate::dispatch_in_place::records_dir_for(&surface.root)?;
706        let owned = crate::requests::owned_run_ids_in(&records_dir, &surface.surface_id)?;
707        let mut live =
708            crate::live_runs::collect_in_place(&surface.root, &records_dir, now, surface.days)?;
709        live.running.retain(|run| owned.contains(&run.id));
710        live.runs.retain(|run| owned.contains(&run.id));
711
712        let mut errors = Vec::new();
713        if let Err(e) = crate::run_results::report_finished_runs_in(surface, &records_dir) {
714            errors.push(format!("run report failed: {e}"));
715        }
716        return Ok((live, errors));
717    }
718    let owned = crate::requests::owned_run_ids(surface)?;
719    let mut live = crate::live_runs::collect(&surface.root, now, surface.days)?;
720    let mut any_written = false;
721    for run in &live.runs {
722        if !owned.contains(&run.id) || run.checks_recorded {
723            continue;
724        }
725        if crate::queue_actions::ensure_checks(&surface.root, &run.id)? {
726            any_written = true;
727        }
728    }
729    if any_written {
730        live = crate::live_runs::collect(&surface.root, now, surface.days)?;
731    }
732    live.running.retain(|run| owned.contains(&run.id));
733    live.runs.retain(|run| owned.contains(&run.id));
734
735    let mut errors = Vec::new();
736    if let Err(e) = crate::run_results::report_finished_runs(surface) {
737        errors.push(format!("run report failed: {e}"));
738    }
739
740    let mut triggered = BTreeSet::new();
741    for run in &live.runs {
742        if run.research {
743            continue;
744        }
745        if let Some(ref req_id) = run.request {
746            if triggered.insert(req_id.clone()) {
747                if let Err(e) = crate::requests::maybe_combine(surface, req_id) {
748                    errors.push(format!("combine trigger failed for {req_id}: {e}"));
749                }
750            }
751        }
752    }
753
754    Ok((live, errors))
755}
756
757fn handle_runs(surface: &Surface, now: u64) -> Response {
758    let is_repo = match is_repository(&surface.root) {
759        Ok(v) => v,
760        Err(e) => return json_error(500, e),
761    };
762    let (live, errors) = match reconcile_runs(surface, now) {
763        Ok(res) => res,
764        Err(e) => return json_error(500, e),
765    };
766    for msg in errors {
767        surface.session.record_error(&msg);
768    }
769
770    let mut runs_with_hold = Vec::with_capacity(live.runs.len());
771    if is_repo {
772        let run_refs: Vec<(&str, Option<&str>)> = live
773            .runs
774            .iter()
775            .map(|run| (run.id.as_str(), run.request.as_deref()))
776            .collect();
777        let combined_ids = match crate::requests::combined_run_ids(&surface.root, &run_refs) {
778            Ok(ids) => ids,
779            Err(e) => return json_error(500, e),
780        };
781
782        for run in &live.runs {
783            let hold = match crate::queue_actions::read_hold(&surface.root, &run.id) {
784                Ok(h) => h,
785                Err(e) => return json_error(500, e),
786            };
787            let combined = combined_ids.contains(&run.id);
788            runs_with_hold.push(RunWithHold {
789                run,
790                hold,
791                combined,
792                in_place: false,
793                undone: false,
794            });
795        }
796    } else {
797        let records_dir = match crate::dispatch_in_place::records_dir_for(&surface.root) {
798            Ok(dir) => dir,
799            Err(e) => return json_error(500, e),
800        };
801        for run in &live.runs {
802            let hold = match crate::queue_actions::read_hold_in(&records_dir, &run.id) {
803                Ok(h) => h,
804                Err(e) => return json_error(500, e),
805            };
806            let undone = crate::in_place_review::is_undone(&records_dir, &run.id);
807            runs_with_hold.push(RunWithHold {
808                run,
809                hold,
810                combined: false,
811                in_place: true,
812                undone,
813            });
814        }
815    }
816
817    let payload = LiveRunsResponse {
818        generated_at: live.generated_at,
819        repo: &live.repo,
820        running: &live.running,
821        runs: runs_with_hold,
822        skipped: &live.skipped,
823    };
824    match serde_json::to_value(&payload) {
825        Ok(val) => Response::json(200, &val),
826        Err(e) => json_error(500, format!("failed to serialize runs: {e}")),
827    }
828}
829
830fn handle_runs_changed(surface: &Surface) -> Response {
831    surface.reconcile_requested.store(true, Ordering::Release);
832    Response::json(202, &serde_json::json!({}))
833}
834
835const NOT_A_GIT_REPO_ERROR: &str = "this folder is not a git repository";
836
837fn require_repository(root: &Path) -> Result<(), Response> {
838    match is_repository(root) {
839        Ok(true) => Ok(()),
840        Ok(false) => Err(json_error(409, NOT_A_GIT_REPO_ERROR)),
841        Err(e) => Err(json_error(500, e)),
842    }
843}
844
845fn handle_run_diff(surface: &Surface, id: &str) -> Response {
846    let is_repo = match is_repository(&surface.root) {
847        Ok(v) => v,
848        Err(e) => return json_error(500, e),
849    };
850    if !is_valid_run_id(id) {
851        return json_error(404, format!("unknown run: {id}"));
852    }
853    if !is_repo {
854        let records_dir = match crate::dispatch_in_place::records_dir_for(&surface.root) {
855            Ok(dir) => dir,
856            Err(e) => return json_error(500, e),
857        };
858        let start = records_dir.join(format!("{id}.start.json"));
859        let summary = records_dir.join(format!("{id}.json"));
860        let report_json = records_dir.join(format!("{id}.report.json"));
861        let report_md = records_dir.join(format!("{id}.report.md"));
862        if !start.exists() && !summary.exists() && !report_json.exists() && !report_md.exists() {
863            return json_error(404, format!("unknown run: {id}"));
864        }
865        if let Err(err) = crate::requests::run_owner_check_in(&records_dir, &surface.surface_id, id)
866        {
867            return request_action_error_response(err);
868        }
869        return match crate::in_place_review::diff_for_run(&records_dir, id) {
870            Ok(body) => Response::text(200, &body),
871            Err(e) => {
872                if !summary.exists() || e.contains("No such file") || e.contains("missing manifest")
873                {
874                    json_error(404, e)
875                } else {
876                    json_error(500, e)
877                }
878            }
879        };
880    }
881    let wt_dir = surface.root.join(".wt");
882    let wt = wt_dir.join(id);
883    let start = wt_dir.join(format!("{id}.start.json"));
884    let summary = wt_dir.join(format!("{id}.json"));
885    let report_json = wt_dir.join(format!("{id}.report.json"));
886    let report_md = wt_dir.join(format!("{id}.report.md"));
887    if !wt.exists()
888        && !start.exists()
889        && !summary.exists()
890        && !report_json.exists()
891        && !report_md.exists()
892    {
893        return json_error(404, format!("unknown run: {id}"));
894    }
895    if let Err(err) = crate::requests::run_owner_check(surface, id) {
896        return request_action_error_response(err);
897    }
898    match crate::queue_actions::compute_review(&surface.root, id, true) {
899        Ok(data) => {
900            let body = if !data.wt_exists {
901                "(worktree removed)\n".to_string()
902            } else if data.diff_out.is_empty() {
903                String::new()
904            } else {
905                format!("{}\n", data.diff_out)
906            };
907            Response::text(200, &body)
908        }
909        Err(e) => {
910            if !wt.is_dir() || !wt.join(".git").exists() {
911                json_error(404, e)
912            } else {
913                json_error(500, e)
914            }
915        }
916    }
917}
918
919fn handle_run_undo(surface: &Surface, id: &str) -> Response {
920    let is_repo = match is_repository(&surface.root) {
921        Ok(v) => v,
922        Err(e) => return json_error(500, e),
923    };
924    if is_repo {
925        return json_error(
926            409,
927            "undo is for runs in a folder that is not a git repository",
928        );
929    }
930    if !is_valid_run_id(id) {
931        return json_error(404, format!("unknown run: {id}"));
932    }
933    let records_dir = match crate::dispatch_in_place::records_dir_for(&surface.root) {
934        Ok(dir) => dir,
935        Err(e) => return json_error(500, e),
936    };
937    let run_exists = records_dir.join(format!("{id}.start.json")).exists()
938        || records_dir.join(format!("{id}.json")).exists()
939        || records_dir.join(format!("{id}.report.json")).exists()
940        || records_dir.join(format!("{id}.report.md")).exists();
941    if run_exists {
942        if let Err(err) = crate::requests::run_owner_check_in(&records_dir, &surface.surface_id, id)
943        {
944            return request_action_error_response(err);
945        }
946    }
947    match crate::in_place_review::undo_in(&surface.root, id) {
948        Ok(lines) => Response::json(200, &serde_json::json!({ "lines": lines })),
949        Err(msg) => json_error(409, msg),
950    }
951}
952
953fn parse_action(raw: &str) -> Result<Action, String> {
954    match raw {
955        "accept" => Ok(Action::Accept),
956        "send_back" => Ok(Action::SendBack),
957        "redo" => Ok(Action::Redo),
958        "hold" => Ok(Action::Hold),
959        "mark_read" => Ok(Action::MarkRead),
960        other => Err(format!(
961            "unknown action '{other}'; must be one of accept, send_back, redo, hold, mark_read"
962        )),
963    }
964}
965
966fn handle_run_decision(surface: &Surface, id: &str, req: &Request, now: u64) -> Response {
967    let is_repo = match is_repository(&surface.root) {
968        Ok(v) => v,
969        Err(e) => return json_error(500, e),
970    };
971    let obj = match parse_json_object(&req.body) {
972        Ok(o) => o,
973        Err(resp) => return resp,
974    };
975    let action_str = match obj.get("action") {
976        Some(serde_json::Value::String(s)) => s.clone(),
977        Some(_) => return json_error(400, "field action must be a string"),
978        None => return json_error(400, "missing required field: action"),
979    };
980    let action = match parse_action(&action_str) {
981        Ok(a) => a,
982        Err(e) => return json_error(400, e),
983    };
984    let note = match obj.get("note") {
985        None | Some(serde_json::Value::Null) => None,
986        Some(serde_json::Value::String(s)) => Some(s.clone()),
987        Some(_) => return json_error(400, "field note must be a string or null"),
988    };
989
990    let decision = if is_repo {
991        let wt_dir = surface.root.join(".wt");
992        let run_exists = is_valid_run_id(id)
993            && (wt_dir.join(id).exists()
994                || wt_dir.join(format!("{id}.start.json")).exists()
995                || wt_dir.join(format!("{id}.json")).exists()
996                || wt_dir.join(format!("{id}.report.json")).exists()
997                || wt_dir.join(format!("{id}.report.md")).exists());
998        if run_exists {
999            if let Err(err) = crate::requests::run_owner_check(surface, id) {
1000                return request_action_error_response(err);
1001            }
1002        }
1003        match crate::queue_actions::decide(&surface.root, id, action, note.as_deref(), now) {
1004            Ok(d) => d,
1005            Err(e) => return json_error(400, e),
1006        }
1007    } else {
1008        let records_dir = match crate::dispatch_in_place::records_dir_for(&surface.root) {
1009            Ok(dir) => dir,
1010            Err(e) => return json_error(500, e),
1011        };
1012        let run_exists = is_valid_run_id(id)
1013            && (records_dir.join(format!("{id}.start.json")).exists()
1014                || records_dir.join(format!("{id}.json")).exists()
1015                || records_dir.join(format!("{id}.report.json")).exists()
1016                || records_dir.join(format!("{id}.report.md")).exists());
1017        if run_exists {
1018            if let Err(err) =
1019                crate::requests::run_owner_check_in(&records_dir, &surface.surface_id, id)
1020            {
1021                return request_action_error_response(err);
1022            }
1023        }
1024        match crate::queue_actions::decide_in_place(&records_dir, id, action, note.as_deref(), now)
1025        {
1026            Ok(d) => d,
1027            Err(e) => return json_error(400, e),
1028        }
1029    };
1030    let seq = match surface.session.record_decision(
1031        &decision.run,
1032        &action_str,
1033        decision.note.as_deref(),
1034        decision.conversation_message.as_deref(),
1035    ) {
1036        Ok(s) => s,
1037        Err(e) => return json_error(500, e),
1038    };
1039    if is_repo && action == Action::Accept {
1040        match crate::requests::run_request_id(&surface.root, &decision.run) {
1041            Ok(Some(req_id)) => {
1042                if let Err(e) = crate::requests::maybe_combine(surface, &req_id) {
1043                    surface
1044                        .session
1045                        .record_error(&format!("combine trigger failed for {req_id}: {e}"));
1046                }
1047            }
1048            Ok(None) => {}
1049            Err(e) => return json_error(500, e),
1050        }
1051    }
1052    Response::json(
1053        200,
1054        &serde_json::json!({
1055            "decision": {
1056                "run": decision.run,
1057                "action": action_str,
1058                "note": decision.note,
1059                "conversation_message": decision.conversation_message,
1060            },
1061            "seq": seq,
1062        }),
1063    )
1064}
1065
1066fn handle_map(surface: &Surface) -> Response {
1067    match crate::map::build(&surface.root, &surface.repo) {
1068        Ok(data) => match serde_json::to_value(&data) {
1069            Ok(val) => Response::json(200, &val),
1070            Err(e) => json_error(500, format!("failed to serialize map: {e}")),
1071        },
1072        Err(e) => json_error(422, e),
1073    }
1074}
1075
1076fn handle_requests(surface: &Surface) -> Response {
1077    match is_repository(&surface.root) {
1078        Ok(true) => {}
1079        Ok(false) => return Response::json(200, &serde_json::json!([])),
1080        Err(e) => return json_error(500, e),
1081    }
1082    match crate::requests::list_requests(surface) {
1083        Ok(list) => match serde_json::to_value(&list) {
1084            Ok(val) => Response::json(200, &val),
1085            Err(e) => json_error(500, format!("failed to serialize requests: {e}")),
1086        },
1087        Err(e) => json_error(500, e),
1088    }
1089}
1090
1091fn request_action_error_response(err: RequestActionError) -> Response {
1092    match err {
1093        RequestActionError::BadRequest(msg) => json_error(400, msg),
1094        RequestActionError::NotOwned(msg) => json_error(403, msg),
1095        RequestActionError::Conflict(msg) => json_error(409, msg),
1096        RequestActionError::Internal(msg) => json_error(500, msg),
1097    }
1098}
1099
1100fn handle_request_push(surface: &Surface, id: &str) -> Response {
1101    if let Err(resp) = require_repository(&surface.root) {
1102        return resp;
1103    }
1104    match crate::requests::push_request(surface, id) {
1105        Ok(()) => Response::json(200, &serde_json::json!({ "pushed": true })),
1106        Err(err) => request_action_error_response(err),
1107    }
1108}
1109
1110fn handle_request_pull_request(surface: &Surface, id: &str, req: &Request) -> Response {
1111    if let Err(resp) = require_repository(&surface.root) {
1112        return resp;
1113    }
1114    if let Err(e) = crate::dispatch::validate_request_id(id) {
1115        return json_error(400, e);
1116    }
1117    let obj = match parse_json_object(&req.body) {
1118        Ok(o) => o,
1119        Err(resp) => return resp,
1120    };
1121    let title = match obj.get("title") {
1122        Some(serde_json::Value::String(s)) if !s.trim().is_empty() => s.clone(),
1123        Some(serde_json::Value::String(_)) => {
1124            return json_error(400, "field title must not be empty");
1125        }
1126        Some(_) => return json_error(400, "field title must be a string"),
1127        None => return json_error(400, "missing required field: title"),
1128    };
1129    let body = match obj.get("body") {
1130        None | Some(serde_json::Value::Null) => String::new(),
1131        Some(serde_json::Value::String(s)) => s.clone(),
1132        Some(_) => return json_error(400, "field body must be a string"),
1133    };
1134    match crate::requests::open_request_pull_request(surface, id, &title, &body) {
1135        Ok(url) => Response::json(200, &serde_json::json!({ "url": url })),
1136        Err(err) => request_action_error_response(err),
1137    }
1138}
1139
1140#[derive(Clone, Copy)]
1141enum ApiGetHandler {
1142    Session,
1143    Events,
1144    Models,
1145    Runs,
1146    Requests,
1147    Map,
1148    RunDiff,
1149}
1150
1151const API_GET_ROUTES: &[(&str, ApiGetHandler)] = &[
1152    ("/api/session", ApiGetHandler::Session),
1153    ("/api/session/events", ApiGetHandler::Events),
1154    ("/api/models", ApiGetHandler::Models),
1155    ("/api/runs", ApiGetHandler::Runs),
1156    ("/api/requests", ApiGetHandler::Requests),
1157    ("/api/map", ApiGetHandler::Map),
1158    ("/api/runs/{id}/diff", ApiGetHandler::RunDiff),
1159];
1160
1161pub fn authenticated_api_get_routes() -> Vec<&'static str> {
1162    API_GET_ROUTES.iter().map(|(pattern, _)| *pattern).collect()
1163}
1164
1165fn match_api_get_route<'a>(pattern: &str, path: &'a str) -> Option<Option<&'a str>> {
1166    if let Some((prefix, suffix)) = pattern.split_once("{id}") {
1167        let rest = path.strip_prefix(prefix)?;
1168        let id = rest.strip_suffix(suffix)?;
1169        if !id.is_empty() && !id.contains('/') {
1170            return Some(Some(id));
1171        }
1172        None
1173    } else if pattern == path {
1174        Some(None)
1175    } else {
1176        None
1177    }
1178}
1179
1180fn handle_post_open_code(surface: &Surface, now: u64) -> Response {
1181    match surface.open_codes.issue(now) {
1182        Ok(code) => Response::json(200, &serde_json::json!({ "code": code })),
1183        Err(e) => json_error(500, e),
1184    }
1185}
1186
1187fn handle_post_open(surface: &Surface, req: &Request, now: u64) -> Response {
1188    let forbidden = Response {
1189        status: 403,
1190        content_type: "application/json",
1191        body: b"{}".to_vec(),
1192    };
1193    let Ok(value) = serde_json::from_slice::<serde_json::Value>(&req.body) else {
1194        return forbidden;
1195    };
1196    let Some(code) = value.get("code").and_then(|v| v.as_str()) else {
1197        return forbidden;
1198    };
1199    match surface.open_codes.redeem(code, now) {
1200        Ok(true) => Response::json(200, &serde_json::json!({ "token": surface.token })),
1201        Ok(false) => forbidden,
1202        Err(e) => json_error(500, e),
1203    }
1204}
1205
1206pub fn route(surface: &Surface, req: &Request, now: u64) -> Response {
1207    route_inner(surface, req, now, None)
1208}
1209
1210fn route_inner(
1211    surface: &Surface,
1212    req: &Request,
1213    now: u64,
1214    stop_trigger: Option<&StopTrigger>,
1215) -> Response {
1216    if req.path == "/api/peer/messages" && req.method == "POST" {
1217        if !has_valid_message_credential(surface, req) {
1218            return json_error(403, "missing or invalid message credential");
1219        }
1220        return handle_post_peer_message(surface, req);
1221    }
1222
1223    let is_health_get = req.path == "/api/health" && req.method == "GET";
1224    let is_open_post = req.path == "/api/open" && req.method == "POST";
1225    if (req.path.starts_with("/api/") || req.method == "POST")
1226        && !is_health_get
1227        && !is_open_post
1228        && !has_valid_token(surface, req)
1229    {
1230        return json_error(
1231            403,
1232            "missing or invalid surface token; open the page from the URL blyte printed",
1233        );
1234    }
1235
1236    if let Some((status, content_type, body)) = crate::dashboard::shared_asset(&req.path) {
1237        if req.method != "GET" {
1238            return method_not_allowed(req);
1239        }
1240        return Response {
1241            status,
1242            content_type,
1243            body,
1244        };
1245    }
1246
1247    if req.path == "/" || req.path == "/index.html" {
1248        if req.method != "GET" {
1249            return method_not_allowed(req);
1250        }
1251        return Response::html(INDEX_HTML.as_bytes().to_vec());
1252    }
1253
1254    if req.path == "/api/health" {
1255        if req.method != "GET" {
1256            return method_not_allowed(req);
1257        }
1258        return health_response(surface);
1259    }
1260
1261    for &(pattern, handler) in API_GET_ROUTES {
1262        if let Some(id) = match_api_get_route(pattern, &req.path) {
1263            if req.method != "GET" {
1264                return method_not_allowed(req);
1265            }
1266            return match handler {
1267                ApiGetHandler::Session => session_response(surface),
1268                ApiGetHandler::Events => handle_events(surface, req),
1269                ApiGetHandler::Models => handle_models(),
1270                ApiGetHandler::Runs => handle_runs(surface, now),
1271                ApiGetHandler::Requests => handle_requests(surface),
1272                ApiGetHandler::Map => handle_map(surface),
1273                ApiGetHandler::RunDiff => handle_run_diff(surface, id.unwrap_or("")),
1274            };
1275        }
1276    }
1277
1278    match req.path.as_str() {
1279        "/api/open" => {
1280            if req.method != "POST" {
1281                return method_not_allowed(req);
1282            }
1283            handle_post_open(surface, req, now)
1284        }
1285        "/api/surfaces" => {
1286            if req.method != "GET" {
1287                return method_not_allowed(req);
1288            }
1289            handle_surfaces(surface)
1290        }
1291        "/api/surfaces/start" => {
1292            if req.method != "POST" {
1293                return method_not_allowed(req);
1294            }
1295            handle_post_start_surface(req)
1296        }
1297        "/api/session/stop" => {
1298            if req.method != "POST" {
1299                return method_not_allowed(req);
1300            }
1301            handle_post_stop(stop_trigger)
1302        }
1303        "/api/session/open-codes" => {
1304            if req.method != "POST" {
1305                return method_not_allowed(req);
1306            }
1307            handle_post_open_code(surface, now)
1308        }
1309        "/api/session/messages" => {
1310            if req.method != "POST" {
1311                return method_not_allowed(req);
1312            }
1313            handle_post_message(surface, req)
1314        }
1315        "/api/session/attachments" => {
1316            if req.method != "POST" {
1317                return method_not_allowed(req);
1318            }
1319            handle_post_attachment(surface, req)
1320        }
1321        "/api/session/model" => {
1322            if req.method != "POST" {
1323                return method_not_allowed(req);
1324            }
1325            handle_post_model(surface, req)
1326        }
1327        "/api/session/effort" => {
1328            if req.method != "POST" {
1329                return method_not_allowed(req);
1330            }
1331            handle_post_effort(surface, req)
1332        }
1333        "/api/session/seen" => {
1334            if req.method != "POST" {
1335                return method_not_allowed(req);
1336            }
1337            handle_post_seen(surface)
1338        }
1339        "/api/runs/changed" => {
1340            if req.method != "POST" {
1341                return method_not_allowed(req);
1342            }
1343            handle_runs_changed(surface)
1344        }
1345        path => {
1346            if let Some(id) = path.strip_prefix("/api/session/attachments/") {
1347                if !id.is_empty() && !id.contains('/') {
1348                    if req.method != "GET" {
1349                        return method_not_allowed(req);
1350                    }
1351                    return handle_get_attachment(surface, id);
1352                }
1353            }
1354            if let Some(id) = path.strip_prefix("/api/session/approvals/") {
1355                if !id.is_empty() && !id.contains('/') {
1356                    if req.method != "POST" {
1357                        return method_not_allowed(req);
1358                    }
1359                    return handle_post_approval(surface, id, req);
1360                }
1361            }
1362            if let Some(rest) = path.strip_prefix("/api/runs/") {
1363                if let Some(id) = rest.strip_suffix("/decision") {
1364                    if !id.is_empty() && !id.contains('/') {
1365                        if req.method != "POST" {
1366                            return method_not_allowed(req);
1367                        }
1368                        return handle_run_decision(surface, id, req, now);
1369                    }
1370                }
1371                if let Some(id) = rest.strip_suffix("/undo") {
1372                    if !id.is_empty() && !id.contains('/') {
1373                        if req.method != "POST" {
1374                            return method_not_allowed(req);
1375                        }
1376                        return handle_run_undo(surface, id);
1377                    }
1378                }
1379            }
1380            if let Some(rest) = path.strip_prefix("/api/requests/") {
1381                if let Some(id) = rest.strip_suffix("/push") {
1382                    if req.method != "POST" {
1383                        return method_not_allowed(req);
1384                    }
1385                    return handle_request_push(surface, id);
1386                }
1387                if let Some(id) = rest.strip_suffix("/pull-request") {
1388                    if req.method != "POST" {
1389                        return method_not_allowed(req);
1390                    }
1391                    return handle_request_pull_request(surface, id, req);
1392                }
1393            }
1394            json_error(404, format!("not found: {}", req.path))
1395        }
1396    }
1397}
1398
1399enum GitToplevel {
1400    Repository(PathBuf),
1401    NotARepository,
1402}
1403
1404fn find_git_toplevel(dir: &Path) -> Result<GitToplevel, String> {
1405    let out = Command::new("git")
1406        .args(["rev-parse", "--show-toplevel"])
1407        .env("LC_ALL", "C")
1408        .current_dir(dir)
1409        .output()
1410        .map_err(|e| format!("failed to run git rev-parse --show-toplevel: {e}"))?;
1411    if !out.status.success() {
1412        let stderr = String::from_utf8_lossy(&out.stderr);
1413        if stderr.contains("not a git repository (or any") {
1414            return Ok(GitToplevel::NotARepository);
1415        }
1416        let detail = stderr.trim();
1417        if detail.is_empty() {
1418            return Err(format!("not inside a git repository ({})", dir.display()));
1419        }
1420        return Err(format!(
1421            "not inside a git repository ({}): {detail}",
1422            dir.display()
1423        ));
1424    }
1425    let path_str = String::from_utf8_lossy(&out.stdout).trim().to_string();
1426    if path_str.is_empty() {
1427        return Err(format!("not inside a git repository ({})", dir.display()));
1428    }
1429    Ok(GitToplevel::Repository(PathBuf::from(path_str)))
1430}
1431
1432pub(crate) fn is_repository(root: &Path) -> Result<bool, String> {
1433    match find_git_toplevel(root)? {
1434        GitToplevel::Repository(_) => Ok(true),
1435        GitToplevel::NotARepository => Ok(false),
1436    }
1437}
1438
1439fn resolve_denied_path(denied: &Path) -> Result<PathBuf, String> {
1440    let mut probe = denied;
1441    let mut tail = Vec::new();
1442    loop {
1443        match probe.canonicalize() {
1444            Ok(mut resolved) => {
1445                for part in tail.into_iter().rev() {
1446                    resolved.push(part);
1447                }
1448                return Ok(resolved);
1449            }
1450            Err(e)
1451                if matches!(
1452                    e.kind(),
1453                    std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
1454                ) =>
1455            {
1456                let Some(name) = probe.file_name() else {
1457                    return Err(format!("cannot canonicalize {}: {e}", denied.display()));
1458                };
1459                let Some(parent) = probe.parent() else {
1460                    return Err(format!("cannot canonicalize {}: {e}", denied.display()));
1461                };
1462                tail.push(name.to_os_string());
1463                probe = parent;
1464            }
1465            Err(e) => {
1466                return Err(format!("cannot canonicalize {}: {e}", denied.display()));
1467            }
1468        }
1469    }
1470}
1471
1472pub fn check_linux_non_repo_root(root: &Path, home: &Path) -> Result<(), String> {
1473    let root_canon = root
1474        .canonicalize()
1475        .map_err(|e| format!("cannot canonicalize {}: {e}", root.display()))?;
1476    let home_canon = home
1477        .canonicalize()
1478        .map_err(|e| format!("cannot canonicalize home directory {}: {e}", home.display()))?;
1479    for denied in blyte_agent::sandbox::read_denied(&home_canon) {
1480        let denied_canon = resolve_denied_path(&denied)?;
1481        if denied.starts_with(&root_canon) || denied_canon.starts_with(&root_canon) {
1482            return Err(format!(
1483                "on Linux a surface cannot start in {}: it contains {}, which the sandbox could not keep unreadable; start it in a subfolder",
1484                root_canon.display(),
1485                denied.display()
1486            ));
1487        }
1488    }
1489    if home_canon.starts_with(&root_canon) {
1490        return Err(format!(
1491            "on Linux a surface cannot start in {}: it contains {}, which the sandbox could not keep unreadable; start it in a subfolder",
1492            root_canon.display(),
1493            home_canon.display()
1494        ));
1495    }
1496    Ok(())
1497}
1498
1499pub fn check_linux_non_repo_root_for_env(
1500    root: &Path,
1501    home: Option<&std::ffi::OsStr>,
1502) -> Result<(), String> {
1503    let home = home.filter(|h| !h.is_empty()).ok_or_else(|| {
1504        format!(
1505            "cannot check whether {} contains protected paths on Linux: HOME is not set",
1506            root.display()
1507        )
1508    })?;
1509    check_linux_non_repo_root(root, Path::new(home))
1510}
1511
1512fn resolve_main_checkout(worktree_root: &Path) -> Result<PathBuf, String> {
1513    let out = Command::new("git")
1514        .args([
1515            "rev-parse",
1516            "--path-format=absolute",
1517            "--git-dir",
1518            "--git-common-dir",
1519        ])
1520        .current_dir(worktree_root)
1521        .output()
1522        .map_err(|_| {
1523            format!(
1524                "cannot find the main checkout of {}",
1525                worktree_root.display()
1526            )
1527        })?;
1528    if !out.status.success() {
1529        return Err(format!(
1530            "cannot find the main checkout of {}",
1531            worktree_root.display()
1532        ));
1533    }
1534    let text = String::from_utf8_lossy(&out.stdout);
1535    let mut lines = text.lines();
1536    let (Some(git_dir), Some(common_dir)) = (lines.next(), lines.next()) else {
1537        return Err(format!(
1538            "cannot find the main checkout of {}",
1539            worktree_root.display()
1540        ));
1541    };
1542    let git_dir_path = PathBuf::from(git_dir.trim());
1543    let common_dir_path = PathBuf::from(common_dir.trim());
1544    let git_dir_canon = git_dir_path
1545        .canonicalize()
1546        .map_err(|e| format!("cannot canonicalize {}: {e}", git_dir_path.display()))?;
1547    let common_dir_canon = common_dir_path
1548        .canonicalize()
1549        .map_err(|e| format!("cannot canonicalize {}: {e}", common_dir_path.display()))?;
1550    if git_dir_canon == common_dir_canon {
1551        return worktree_root
1552            .canonicalize()
1553            .map_err(|e| format!("cannot canonicalize {}: {e}", worktree_root.display()));
1554    }
1555    let main = crate::config::main_checkout(worktree_root).ok_or_else(|| {
1556        format!(
1557            "cannot find the main checkout of {}",
1558            worktree_root.display()
1559        )
1560    })?;
1561    main.canonicalize()
1562        .map_err(|e| format!("cannot canonicalize {}: {e}", main.display()))
1563}
1564
1565pub(crate) fn resolve_folder(folder: &Path) -> Result<PathBuf, String> {
1566    match find_git_toplevel(folder)? {
1567        GitToplevel::Repository(worktree_root) => resolve_main_checkout(&worktree_root),
1568        GitToplevel::NotARepository => folder
1569            .canonicalize()
1570            .map_err(|e| format!("cannot canonicalize {}: {e}", folder.display())),
1571    }
1572}
1573
1574fn current_branch(main_checkout: &Path) -> Result<Option<String>, String> {
1575    match find_git_toplevel(main_checkout)? {
1576        GitToplevel::NotARepository => return Ok(None),
1577        GitToplevel::Repository(_) => {}
1578    }
1579    if let Ok(out) = Command::new("git")
1580        .args(["rev-parse", "--abbrev-ref", "HEAD"])
1581        .current_dir(main_checkout)
1582        .output()
1583    {
1584        if out.status.success() {
1585            let branch = String::from_utf8_lossy(&out.stdout).trim().to_string();
1586            if !branch.is_empty() {
1587                return Ok(Some(branch));
1588            }
1589        }
1590    }
1591    if let Ok(out) = Command::new("git")
1592        .args(["symbolic-ref", "--short", "HEAD"])
1593        .current_dir(main_checkout)
1594        .output()
1595    {
1596        if out.status.success() {
1597            let branch = String::from_utf8_lossy(&out.stdout).trim().to_string();
1598            if !branch.is_empty() {
1599                return Ok(Some(branch));
1600            }
1601        }
1602    }
1603    Err(format!(
1604        "cannot read the current branch of {}",
1605        main_checkout.display()
1606    ))
1607}
1608
1609fn repo_name_for(root: &Path) -> Result<String, String> {
1610    root.file_name()
1611        .and_then(|s| s.to_str())
1612        .filter(|s| !s.is_empty())
1613        .map(String::from)
1614        .ok_or_else(|| format!("cannot determine repository name for {}", root.display()))
1615}
1616
1617fn now_duration() -> Result<Duration, String> {
1618    SystemTime::now()
1619        .duration_since(UNIX_EPOCH)
1620        .map_err(|e| format!("system clock is before Unix epoch: {e}"))
1621}
1622
1623fn new_session_id(nanos: u128) -> String {
1624    let seq = SESSION_COUNTER.fetch_add(1, Ordering::Relaxed);
1625    format!("surface-{}-{nanos}-{seq}", std::process::id())
1626}
1627
1628pub fn open_browser_in(open_in: OpenIn, url: &str) {
1629    crate::open_window::open_url(open_in, url);
1630}
1631
1632pub fn open_browser(url: &str) {
1633    open_browser_in(OpenIn::App, url);
1634}
1635
1636fn resolve_initial_model(config: &ReplConfig) -> String {
1637    if let Some(m) = config.model.as_deref().filter(|s| !s.trim().is_empty()) {
1638        return m.to_string();
1639    }
1640    if let Ok(m) = std::env::var("BLYTE_MODEL") {
1641        if !m.trim().is_empty() {
1642            return m;
1643        }
1644    }
1645    if let Ok(p) = blyte_provider::resolve_provider(None) {
1646        return p.model_id();
1647    }
1648    "gemini-3.8-flash-high".to_string()
1649}
1650
1651static SIGNAL_STOP: AtomicBool = AtomicBool::new(false);
1652static SIGNAL_INTERRUPT: AtomicBool = AtomicBool::new(false);
1653
1654#[cfg(unix)]
1655extern "C" fn handle_shutdown_signal(_: libc::c_int) {
1656    SIGNAL_STOP.store(true, Ordering::Relaxed);
1657}
1658
1659#[cfg(unix)]
1660extern "C" fn handle_interrupt_signal(_: libc::c_int) {
1661    SIGNAL_INTERRUPT.store(true, Ordering::Relaxed);
1662}
1663
1664fn ensure_token_dir(dir: &Path) -> Result<(), String> {
1665    #[cfg(unix)]
1666    {
1667        use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
1668        if let Some(parent) = dir.parent() {
1669            std::fs::create_dir_all(parent)
1670                .map_err(|e| format!("cannot create {}: {e}", parent.display()))?;
1671        }
1672        let mut builder = std::fs::DirBuilder::new();
1673        builder.mode(0o700);
1674        match builder.create(dir) {
1675            Ok(()) => {}
1676            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
1677                std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
1678                    .map_err(|e| format!("cannot set permissions on {}: {e}", dir.display()))?;
1679            }
1680            Err(e) => return Err(format!("cannot create {}: {e}", dir.display())),
1681        }
1682        Ok(())
1683    }
1684    #[cfg(not(unix))]
1685    {
1686        std::fs::create_dir_all(dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))
1687    }
1688}
1689
1690fn write_token_file(token_file_path: &Path, token: &str) -> Result<(), String> {
1691    let token_dir = token_file_path
1692        .parent()
1693        .ok_or_else(|| format!("invalid token path {}", token_file_path.display()))?;
1694    ensure_token_dir(token_dir)?;
1695    let seq = SESSION_COUNTER.fetch_add(1, Ordering::Relaxed);
1696    let tmp_path = token_dir.join(format!(".surface.token.{}.{seq}.tmp", std::process::id()));
1697    let mut opts = std::fs::OpenOptions::new();
1698    opts.write(true).create_new(true);
1699    #[cfg(unix)]
1700    {
1701        opts.mode(0o600);
1702    }
1703    let mut file = opts
1704        .open(&tmp_path)
1705        .map_err(|e| format!("cannot create {}: {e}", token_file_path.display()))?;
1706    if let Err(e) = writeln!(file, "{token}") {
1707        let _ = std::fs::remove_file(&tmp_path);
1708        return Err(format!("cannot write {}: {e}", token_file_path.display()));
1709    }
1710    drop(file);
1711    if let Err(e) = std::fs::rename(&tmp_path, token_file_path) {
1712        let _ = std::fs::remove_file(&tmp_path);
1713        return Err(format!("cannot write {}: {e}", token_file_path.display()));
1714    }
1715    Ok(())
1716}
1717
1718struct TokenFileGuard {
1719    path: PathBuf,
1720}
1721
1722impl Drop for TokenFileGuard {
1723    fn drop(&mut self) {
1724        let _ = std::fs::remove_file(&self.path);
1725    }
1726}
1727
1728struct RegistryEntryGuard {
1729    dir: PathBuf,
1730    id: String,
1731}
1732
1733impl Drop for RegistryEntryGuard {
1734    fn drop(&mut self) {
1735        let _ = crate::surface_registry::remove_entry(&self.dir, &self.id);
1736    }
1737}
1738
1739struct PrivateTmpDirGuard {
1740    path: PathBuf,
1741}
1742
1743impl Drop for PrivateTmpDirGuard {
1744    fn drop(&mut self) {
1745        let _ = std::fs::remove_dir_all(&self.path);
1746    }
1747}
1748
1749struct PublishToolGuard;
1750
1751impl PublishToolGuard {
1752    fn install(surface: Arc<Surface>) -> Self {
1753        blyte_agent::tools::set_publish_tool(Some(Arc::new(
1754            crate::requests::SurfacePublishTool::new(surface),
1755        )));
1756        Self
1757    }
1758}
1759
1760impl Drop for PublishToolGuard {
1761    fn drop(&mut self) {
1762        blyte_agent::tools::set_publish_tool(None);
1763    }
1764}
1765
1766struct LandToolGuard;
1767
1768impl LandToolGuard {
1769    fn install(surface: Arc<Surface>) -> Self {
1770        blyte_agent::tools::set_land_tool(Some(Arc::new(crate::land::SurfaceLandTool::new(
1771            surface,
1772        ))));
1773        Self
1774    }
1775}
1776
1777impl Drop for LandToolGuard {
1778    fn drop(&mut self) {
1779        blyte_agent::tools::set_land_tool(None);
1780    }
1781}
1782
1783pub struct FrontEndContext {
1784    pub surface: Arc<Surface>,
1785    pub take_interrupt: Arc<dyn Fn() -> bool + Send + Sync>,
1786}
1787
1788pub type FrontEnd = Box<dyn FnOnce(FrontEndContext) -> i32 + Send>;
1789
1790struct FrontEndSpec {
1791    front: FrontEnd,
1792    take_interrupt: Arc<dyn Fn() -> bool + Send + Sync>,
1793}
1794
1795#[derive(Clone, Copy)]
1796enum FrontEndOutcome {
1797    Exited(i32),
1798    Panicked,
1799}
1800
1801struct StopControl<S> {
1802    should_stop: S,
1803    trigger: StopTrigger,
1804}
1805
1806fn atomic_stop_control(stop: Arc<AtomicBool>) -> StopControl<impl Fn() -> bool> {
1807    let stop_trigger_flag = Arc::clone(&stop);
1808    StopControl {
1809        should_stop: move || stop.load(Ordering::Acquire),
1810        trigger: Arc::new(move || stop_trigger_flag.store(true, Ordering::Release)),
1811    }
1812}
1813
1814pub fn run(args: &SurfaceArgs, config: ReplConfig) -> i32 {
1815    SIGNAL_STOP.store(false, Ordering::Relaxed);
1816    #[cfg(unix)]
1817    unsafe {
1818        libc::signal(
1819            libc::SIGINT,
1820            handle_shutdown_signal as *const () as libc::sighandler_t,
1821        );
1822        libc::signal(
1823            libc::SIGTERM,
1824            handle_shutdown_signal as *const () as libc::sighandler_t,
1825        );
1826    }
1827    let open_in = args.open_in;
1828    let mut opener = |url: &str| open_browser_in(open_in, url);
1829    let stop_control = StopControl {
1830        should_stop: || SIGNAL_STOP.load(Ordering::Acquire),
1831        trigger: Arc::new(|| SIGNAL_STOP.store(true, Ordering::Release)),
1832    };
1833    run_inner(
1834        args,
1835        config,
1836        &mut std::io::stdout(),
1837        &mut std::io::stderr(),
1838        &mut opener,
1839        stop_control,
1840        None,
1841        None,
1842    )
1843}
1844
1845pub fn run_terminal(args: &SurfaceArgs, config: ReplConfig) -> i32 {
1846    run_with_front_end(
1847        args,
1848        config,
1849        Box::new(|ctx| {
1850            let stdin = std::io::stdin();
1851            let input_is_terminal = std::io::IsTerminal::is_terminal(&stdin);
1852            let mut stdout = std::io::stdout();
1853            let root = ctx.surface.root.clone();
1854            let options = crate::terminal_front::TerminalOptions {
1855                input_is_terminal,
1856                settle: Duration::from_secs(3),
1857                take_interrupt: ctx.take_interrupt,
1858                runs_working: Arc::new(move || crate::surfaces_cmd::count_running_runs(&root)),
1859            };
1860            crate::terminal_front::run_terminal_front(
1861                &ctx.surface.session,
1862                Box::new(std::io::BufReader::new(stdin)),
1863                &mut stdout,
1864                options,
1865            )
1866        }),
1867    )
1868}
1869
1870pub fn run_with_front_end(args: &SurfaceArgs, config: ReplConfig, front: FrontEnd) -> i32 {
1871    SIGNAL_STOP.store(false, Ordering::Relaxed);
1872    SIGNAL_INTERRUPT.store(false, Ordering::Relaxed);
1873    #[cfg(unix)]
1874    unsafe {
1875        libc::signal(
1876            libc::SIGINT,
1877            handle_interrupt_signal as *const () as libc::sighandler_t,
1878        );
1879        libc::signal(
1880            libc::SIGTERM,
1881            handle_shutdown_signal as *const () as libc::sighandler_t,
1882        );
1883    }
1884    let mut opener = |_: &str| {};
1885    let stop_control = StopControl {
1886        should_stop: || SIGNAL_STOP.load(Ordering::Acquire),
1887        trigger: Arc::new(|| SIGNAL_STOP.store(true, Ordering::Release)),
1888    };
1889    let take_interrupt: Arc<dyn Fn() -> bool + Send + Sync> =
1890        Arc::new(|| SIGNAL_INTERRUPT.swap(false, Ordering::AcqRel));
1891    run_inner(
1892        args,
1893        config,
1894        &mut std::io::stdout(),
1895        &mut std::io::stderr(),
1896        &mut opener,
1897        stop_control,
1898        None,
1899        Some(FrontEndSpec {
1900            front,
1901            take_interrupt,
1902        }),
1903    )
1904}
1905
1906pub fn run_with_io(
1907    args: &SurfaceArgs,
1908    config: ReplConfig,
1909    out: &mut dyn Write,
1910    err: &mut dyn Write,
1911) -> i32 {
1912    let open_in = args.open_in;
1913    let mut opener = |url: &str| open_browser_in(open_in, url);
1914    let stop = Arc::new(AtomicBool::new(false));
1915    run_inner(
1916        args,
1917        config,
1918        out,
1919        err,
1920        &mut opener,
1921        atomic_stop_control(stop),
1922        None,
1923        None,
1924    )
1925}
1926
1927pub fn run_with_hooks(
1928    args: &SurfaceArgs,
1929    config: ReplConfig,
1930    out: &mut dyn Write,
1931    err: &mut dyn Write,
1932    opener: &mut dyn FnMut(&str),
1933    stop: Arc<AtomicBool>,
1934) -> i32 {
1935    run_inner(
1936        args,
1937        config,
1938        out,
1939        err,
1940        opener,
1941        atomic_stop_control(stop),
1942        None,
1943        None,
1944    )
1945}
1946
1947pub type RunnerFactory = Box<
1948    dyn FnOnce(
1949        &ReplConfig,
1950        Arc<dyn blyte_agent::approval::Approver>,
1951    ) -> Result<(Box<dyn PromptRunner>, Option<PathBuf>), String>,
1952>;
1953
1954pub fn run_with_runner(
1955    args: &SurfaceArgs,
1956    config: ReplConfig,
1957    out: &mut dyn Write,
1958    err: &mut dyn Write,
1959    opener: &mut dyn FnMut(&str),
1960    stop: Arc<AtomicBool>,
1961    runner: Box<dyn PromptRunner>,
1962) -> i32 {
1963    run_inner(
1964        args,
1965        config,
1966        out,
1967        err,
1968        opener,
1969        atomic_stop_control(stop),
1970        Some(Box::new(|_, _| Ok((runner, None)))),
1971        None,
1972    )
1973}
1974
1975#[allow(clippy::too_many_arguments)]
1976pub fn run_with_front_end_and_runner(
1977    args: &SurfaceArgs,
1978    config: ReplConfig,
1979    out: &mut dyn Write,
1980    err: &mut dyn Write,
1981    stop: Arc<AtomicBool>,
1982    take_interrupt: Arc<dyn Fn() -> bool + Send + Sync>,
1983    runner: Box<dyn PromptRunner>,
1984    front: FrontEnd,
1985) -> i32 {
1986    let mut opener = |_: &str| {};
1987    run_inner(
1988        args,
1989        config,
1990        out,
1991        err,
1992        &mut opener,
1993        atomic_stop_control(stop),
1994        Some(Box::new(|_, _| Ok((runner, None)))),
1995        Some(FrontEndSpec {
1996            front,
1997            take_interrupt,
1998        }),
1999    )
2000}
2001
2002pub fn run_with_runner_factory(
2003    args: &SurfaceArgs,
2004    config: ReplConfig,
2005    out: &mut dyn Write,
2006    err: &mut dyn Write,
2007    opener: &mut dyn FnMut(&str),
2008    stop: Arc<AtomicBool>,
2009    factory: RunnerFactory,
2010) -> i32 {
2011    run_inner(
2012        args,
2013        config,
2014        out,
2015        err,
2016        opener,
2017        atomic_stop_control(stop),
2018        Some(factory),
2019        None,
2020    )
2021}
2022
2023struct ReconcileTimerGuard {
2024    stop: Arc<AtomicBool>,
2025    handle: Option<std::thread::JoinHandle<()>>,
2026}
2027
2028impl Drop for ReconcileTimerGuard {
2029    fn drop(&mut self) {
2030        self.stop.store(true, Ordering::Release);
2031        if let Some(handle) = self.handle.take() {
2032            let _ = handle.join();
2033        }
2034    }
2035}
2036
2037fn spawn_reconcile_timer(surface: Arc<Surface>) -> ReconcileTimerGuard {
2038    let stop = Arc::new(AtomicBool::new(false));
2039    let thread_stop = Arc::clone(&stop);
2040    let handle = std::thread::spawn(move || {
2041        let mut after = surface.session.info().last_seq;
2042        let mut next_tick = Instant::now();
2043        let mut seen_errors: HashSet<String> = HashSet::new();
2044        while !thread_stop.load(Ordering::Acquire) {
2045            let wait = if surface.reconcile_requested.load(Ordering::Acquire) {
2046                Duration::ZERO
2047            } else {
2048                next_tick
2049                    .saturating_duration_since(Instant::now())
2050                    .min(RECONCILE_POLL_WAIT)
2051            };
2052            let entries = surface.session.entries_after(after, wait);
2053            let mut went_idle = false;
2054            for entry in entries {
2055                after = entry.seq;
2056                if matches!(entry.body, EntryBody::Idle { .. }) {
2057                    went_idle = true;
2058                }
2059            }
2060            if thread_stop.load(Ordering::Acquire) {
2061                break;
2062            }
2063            let requested = surface.reconcile_requested.swap(false, Ordering::AcqRel);
2064            if went_idle || requested || Instant::now() >= next_tick {
2065                match now_duration().and_then(|d| reconcile_runs(&surface, d.as_secs())) {
2066                    Ok((_, errors)) => {
2067                        for msg in errors {
2068                            if seen_errors.insert(msg.clone()) {
2069                                surface.session.record_error(&msg);
2070                                eprintln!("blyte: {msg}");
2071                            }
2072                        }
2073                    }
2074                    Err(e) => {
2075                        if seen_errors.insert(e.clone()) {
2076                            eprintln!("blyte: {e}");
2077                        }
2078                    }
2079                }
2080                next_tick = Instant::now() + RECONCILE_SAFETY_NET_INTERVAL;
2081            }
2082        }
2083    });
2084    ReconcileTimerGuard {
2085        stop,
2086        handle: Some(handle),
2087    }
2088}
2089
2090#[allow(clippy::too_many_arguments)]
2091fn run_inner<S>(
2092    args: &SurfaceArgs,
2093    mut config: ReplConfig,
2094    out: &mut dyn Write,
2095    err: &mut dyn Write,
2096    opener: &mut dyn FnMut(&str),
2097    stop_control: StopControl<S>,
2098    custom_runner: Option<RunnerFactory>,
2099    front_end: Option<FrontEndSpec>,
2100) -> i32
2101where
2102    S: Fn() -> bool,
2103{
2104    let StopControl {
2105        should_stop,
2106        trigger: stop_trigger,
2107    } = stop_control;
2108    let (main_checkout, is_repo) = match find_git_toplevel(&config.repo_root) {
2109        Ok(GitToplevel::Repository(worktree_root)) => {
2110            let main = match resolve_main_checkout(&worktree_root) {
2111                Ok(m) => m,
2112                Err(e) => {
2113                    let _ = writeln!(err, "blyte: {e}");
2114                    return 1;
2115                }
2116            };
2117            let same_checkout = match (worktree_root.canonicalize(), main.canonicalize()) {
2118                (Ok(a), Ok(b)) => a == b,
2119                _ => worktree_root == main,
2120            };
2121            if !same_checkout {
2122                let _ = writeln!(
2123                    err,
2124                    "blyte: started in a linked worktree ({}); this surface works in the main checkout {}",
2125                    worktree_root.display(),
2126                    main.display()
2127                );
2128                let _ = err.flush();
2129            }
2130            (main, true)
2131        }
2132        Ok(GitToplevel::NotARepository) => {
2133            let canonical = match config.repo_root.canonicalize() {
2134                Ok(c) => c,
2135                Err(e) => {
2136                    let _ = writeln!(
2137                        err,
2138                        "blyte: cannot canonicalize {}: {e}",
2139                        config.repo_root.display()
2140                    );
2141                    return 1;
2142                }
2143            };
2144            (canonical, false)
2145        }
2146        Err(e) => {
2147            let _ = writeln!(err, "blyte: {e}");
2148            return 1;
2149        }
2150    };
2151
2152    let repo = match repo_name_for(&main_checkout) {
2153        Ok(r) => r,
2154        Err(e) => {
2155            let _ = writeln!(err, "blyte: {e}");
2156            return 1;
2157        }
2158    };
2159
2160    #[cfg(target_os = "linux")]
2161    if !is_repo {
2162        if let Err(e) =
2163            check_linux_non_repo_root_for_env(&main_checkout, std::env::var_os("HOME").as_deref())
2164        {
2165            let _ = writeln!(err, "blyte: {e}");
2166            return 1;
2167        }
2168    }
2169
2170    let state_dir = match crate::surface_registry::state_dir() {
2171        Ok(d) => d,
2172        Err(e) => {
2173            let _ = writeln!(err, "blyte: {e}");
2174            return 1;
2175        }
2176    };
2177    let registry_dir = state_dir.join("surfaces");
2178
2179    let all_records =
2180        match crate::surface_dir::list_records_for_root(&main_checkout, Some(&state_dir)) {
2181            Ok(r) => r,
2182            Err(e) => {
2183                let _ = writeln!(err, "blyte: {e}");
2184                return 1;
2185            }
2186        };
2187    let mut running = Vec::new();
2188    let mut stopped = Vec::new();
2189    for located in all_records {
2190        if crate::surface_dir::is_running(&located.record) {
2191            running.push(located);
2192        } else {
2193            stopped.push(located);
2194        }
2195    }
2196
2197    let live_registry = match crate::surface_registry::live_entries(&registry_dir) {
2198        Ok(listing) => {
2199            crate::surface_registry::report_unreadable(&listing.unreadable, err);
2200            listing.entries
2201        }
2202        Err(e) => {
2203            let _ = writeln!(err, "blyte: {e}");
2204            return 1;
2205        }
2206    };
2207    let mut running_names: Vec<String> = running.iter().map(|r| r.record.name.clone()).collect();
2208    for entry in &live_registry {
2209        if !running_names.iter().any(|n| n == &entry.name) {
2210            running_names.push(entry.name.clone());
2211        }
2212    }
2213
2214    let (surface_id, surface_name, surface_record_dir) = if let Some(ref target) = args.resume {
2215        if let Some(located) = running
2216            .iter()
2217            .find(|r| r.record.id == *target || r.record.name == *target)
2218        {
2219            let _ = writeln!(
2220                err,
2221                "blyte: surface {target} is already running (port {})",
2222                located.record.port
2223            );
2224            return 1;
2225        }
2226        let stopped_matches: Vec<&crate::surface_dir::LocatedRecord> = stopped
2227            .iter()
2228            .filter(|r| r.record.id == *target || r.record.name == *target)
2229            .collect();
2230        if stopped_matches.is_empty() {
2231            let _ = writeln!(
2232                err,
2233                "blyte: no stopped surface named {target} in {}",
2234                main_checkout.display()
2235            );
2236            return 1;
2237        }
2238        if stopped_matches.len() > 1 {
2239            let ids: Vec<&str> = stopped_matches
2240                .iter()
2241                .map(|r| r.record.id.as_str())
2242                .collect();
2243            let _ = writeln!(
2244                err,
2245                "blyte: more than one stopped surface is named {target}; resume by id: {}",
2246                ids.join(", ")
2247            );
2248            return 1;
2249        }
2250        let located = stopped_matches[0];
2251        if running_names.iter().any(|n| n == &located.record.name) {
2252            let _ = writeln!(
2253                err,
2254                "blyte: a running surface is already named {}; stop it or resume by another name",
2255                located.record.name
2256            );
2257            return 1;
2258        }
2259        (
2260            located.record.id.clone(),
2261            located.record.name.clone(),
2262            located.dir.clone(),
2263        )
2264    } else {
2265        let id = match crate::surface_dir::new_surface_id() {
2266            Ok(id) => id,
2267            Err(e) => {
2268                let _ = writeln!(err, "blyte: {e}");
2269                return 1;
2270            }
2271        };
2272        let name = match crate::surface_dir::pick_name(&repo, args.name.as_deref(), &running_names)
2273        {
2274            Ok(name) => name,
2275            Err(e) => {
2276                let _ = writeln!(err, "blyte: {e}");
2277                return 1;
2278            }
2279        };
2280        let record_dir = if is_repo {
2281            crate::surface_dir::surface_dir(&main_checkout, &id)
2282        } else {
2283            let store = match crate::surface_dir::folder_store(&state_dir, &main_checkout) {
2284                Ok(store) => store,
2285                Err(e) => {
2286                    let _ = writeln!(err, "blyte: {e}");
2287                    return 1;
2288                }
2289            };
2290            store.join("surfaces").join(&id)
2291        };
2292        (id, name, record_dir)
2293    };
2294
2295    let branch = match current_branch(&main_checkout) {
2296        Ok(b) => b,
2297        Err(e) => {
2298            let _ = writeln!(err, "blyte: {e}");
2299            return 1;
2300        }
2301    };
2302
2303    if !config.converse {
2304        config.converse = true;
2305        if config.max_turns == 25 || config.max_turns == 60 {
2306            config.max_turns = 1000;
2307        }
2308        if config.fold_budget.is_none() {
2309            config.fold_budget = Some(100_000);
2310        }
2311    }
2312    config.repo_root = main_checkout.clone();
2313
2314    let is_resume = args.resume.is_some();
2315    let model = resolve_initial_model(&config);
2316    let conversation_path = match crate::conversation_store::conversation_path_for_id(&surface_id) {
2317        Ok(p) => p,
2318        Err(e) => {
2319            let _ = writeln!(err, "blyte: {e}");
2320            let _ = err.flush();
2321            return 1;
2322        }
2323    };
2324    let (mut conversation_store, mut loaded_conversation) = if is_resume {
2325        match crate::conversation_store::ConversationStore::load(conversation_path) {
2326            Ok(pair) => pair,
2327            Err(e) => {
2328                let _ = writeln!(err, "blyte: {e}");
2329                let _ = err.flush();
2330                return 1;
2331            }
2332        }
2333    } else {
2334        match crate::conversation_store::ConversationStore::new_for_fresh(conversation_path) {
2335            Ok(store) => (store, None),
2336            Err(e) => {
2337                let _ = writeln!(err, "blyte: {e}");
2338                let _ = err.flush();
2339                return 1;
2340            }
2341        }
2342    };
2343    let (resume_memory, needs_digest_rewrite) = match loaded_conversation.as_mut() {
2344        Some(loaded) if !loaded.messages.is_empty() => {
2345            if crate::conversation_store::digest_for_provider_in_memory(loaded, &model) {
2346                (crate::session::ResumeMemoryState::Summarized, true)
2347            } else {
2348                (crate::session::ResumeMemoryState::Loaded, false)
2349            }
2350        }
2351        _ => (crate::session::ResumeMemoryState::NotLoaded, false),
2352    };
2353
2354    let started_dur = match now_duration() {
2355        Ok(d) => d,
2356        Err(e) => {
2357            let _ = writeln!(err, "blyte: {e}");
2358            return 1;
2359        }
2360    };
2361    let started_at = started_dur.as_secs();
2362    let session_id = new_session_id(started_dur.as_nanos());
2363    if std::env::var("BLYTE_SESSION")
2364        .map(|v| v.is_empty())
2365        .unwrap_or(true)
2366    {
2367        std::env::set_var("BLYTE_SESSION", &session_id);
2368    }
2369
2370    let token = match generate_token() {
2371        Ok(t) => t,
2372        Err(e) => {
2373            let _ = writeln!(err, "blyte: {e}");
2374            return 1;
2375        }
2376    };
2377    let message_credential = match generate_token() {
2378        Ok(t) => t,
2379        Err(e) => {
2380            let _ = writeln!(err, "blyte: {e}");
2381            return 1;
2382        }
2383    };
2384
2385    let bind_addr = format!("127.0.0.1:{}", args.port);
2386    let listener = match TcpListener::bind(&bind_addr) {
2387        Ok(l) => l,
2388        Err(e) => {
2389            let _ = writeln!(err, "blyte: failed to bind {bind_addr}: {e}");
2390            return 1;
2391        }
2392    };
2393    let actual_port = match listener.local_addr() {
2394        Ok(a) => a.port(),
2395        Err(e) => {
2396            let _ = writeln!(err, "blyte: failed to read listener address: {e}");
2397            return 1;
2398        }
2399    };
2400
2401    let token_file_path = match blyte_agent::sandbox::surface_token_path_for_id(&surface_id) {
2402        Ok(p) => p,
2403        Err(e) => {
2404            let _ = writeln!(err, "blyte: {e}");
2405            return 1;
2406        }
2407    };
2408    if let Err(e) = write_token_file(&token_file_path, &token) {
2409        let _ = writeln!(err, "blyte: {e}");
2410        return 1;
2411    }
2412    let _token_guard = TokenFileGuard {
2413        path: token_file_path,
2414    };
2415
2416    let message_file_path = match blyte_agent::sandbox::surface_message_path_for_id(&surface_id) {
2417        Ok(p) => p,
2418        Err(e) => {
2419            let _ = writeln!(err, "blyte: {e}");
2420            return 1;
2421        }
2422    };
2423    if let Err(e) = write_token_file(&message_file_path, &message_credential) {
2424        let _ = writeln!(err, "blyte: {e}");
2425        return 1;
2426    }
2427    let _message_guard = TokenFileGuard {
2428        path: message_file_path,
2429    };
2430
2431    let mut starting_dir_guard = if is_resume {
2432        StartingDirGuard { dir: None }
2433    } else {
2434        if let Err(e) = crate::surface_dir::prepare_starting_dir(&surface_record_dir) {
2435            let _ = writeln!(err, "blyte: {e}");
2436            return 1;
2437        }
2438        StartingDirGuard {
2439            dir: Some(surface_record_dir.clone()),
2440        }
2441    };
2442    let attachments_dir = match prepare_attachments_dir(&surface_record_dir) {
2443        Ok(p) => p,
2444        Err(e) => {
2445            let _ = writeln!(err, "blyte: {e}");
2446            return 1;
2447        }
2448    };
2449    let mut read_roots = blyte_agent::tools::read_roots();
2450    if !read_roots.iter().any(|p| p == &attachments_dir) {
2451        read_roots.push(attachments_dir.clone());
2452        blyte_agent::tools::set_read_roots(read_roots);
2453    }
2454    if !config.allow_read.iter().any(|p| p == &attachments_dir) {
2455        config.allow_read.push(attachments_dir);
2456    }
2457    blyte_agent::tools::set_peer_tools(Some(Arc::new(crate::tell::SurfacePeerTools {
2458        registry_dir: registry_dir.clone(),
2459        surface_id: surface_id.clone(),
2460        surface_name: surface_name.clone(),
2461        repository: repo.clone(),
2462    })));
2463    let entries_log_path = surface_record_dir.join("entries.jsonl");
2464    blyte_agent::tools::set_blyte_surface(Some(surface_id.clone()));
2465    let mut _private_tmp_guard: Option<PrivateTmpDirGuard> = None;
2466    let session = match Session::try_start_with_log_and_resume_io(
2467        model,
2468        Some(entries_log_path),
2469        resume_memory,
2470        err,
2471        |approver| match custom_runner {
2472            Some(factory) => {
2473                let (runner, tmpdir) = factory(&config, approver)?;
2474                _private_tmp_guard = tmpdir.map(|path| PrivateTmpDirGuard { path });
2475                if needs_digest_rewrite {
2476                    if let Some(ref loaded) = loaded_conversation {
2477                        conversation_store.rewrite(
2478                            loaded.model.as_deref(),
2479                            loaded.goal.as_deref(),
2480                            &loaded.messages,
2481                        )?;
2482                    }
2483                }
2484                Ok(runner)
2485            }
2486            None => {
2487                let rewrite_payload = if needs_digest_rewrite {
2488                    loaded_conversation.clone()
2489                } else {
2490                    None
2491                };
2492                let mut runner = AgentRunner::try_new_with_conversation(
2493                    &config,
2494                    approver,
2495                    None,
2496                    loaded_conversation,
2497                )?;
2498                _private_tmp_guard = runner.private_tmpdir().map(|path| PrivateTmpDirGuard {
2499                    path: path.to_path_buf(),
2500                });
2501                if let Some(ref loaded) = rewrite_payload {
2502                    conversation_store.rewrite(
2503                        loaded.model.as_deref(),
2504                        loaded.goal.as_deref(),
2505                        &loaded.messages,
2506                    )?;
2507                }
2508                runner.set_conversation_store(conversation_store);
2509                Ok(Box::new(runner) as Box<dyn crate::session::PromptRunner>)
2510            }
2511        },
2512    ) {
2513        Ok(s) => s,
2514        Err(e) => {
2515            let _ = writeln!(err, "blyte: {e}");
2516            let _ = err.flush();
2517            return 1;
2518        }
2519    };
2520    let record = SurfaceRecord {
2521        id: surface_id.clone(),
2522        name: surface_name.clone(),
2523        pid: std::process::id(),
2524        port: actual_port,
2525        session_id: session_id.clone(),
2526        started_at,
2527    };
2528    if let Err(e) = crate::surface_dir::write_record_in(&surface_record_dir, &record) {
2529        let _ = writeln!(err, "blyte: {e}");
2530        return 1;
2531    }
2532    starting_dir_guard.disarm();
2533    let registry_entry = crate::surface_registry::RegistryEntry {
2534        id: surface_id.clone(),
2535        name: surface_name.clone(),
2536        root: main_checkout.clone(),
2537        branch,
2538        pid: std::process::id(),
2539        port: actual_port,
2540        started_at,
2541        doing: "idle".to_string(),
2542        state: crate::surface_registry::SurfaceState::Idle,
2543    };
2544    if let Err(e) = crate::surface_registry::write_entry(&registry_dir, &registry_entry) {
2545        let _ = writeln!(err, "blyte: {e}");
2546        return 1;
2547    }
2548    let _registry_guard = RegistryEntryGuard {
2549        dir: registry_dir.clone(),
2550        id: surface_id.clone(),
2551    };
2552    let hook_dir = registry_dir.clone();
2553    let hook_entry = registry_entry.clone();
2554    session.set_activity_hook(Box::new(move |prompt, state| {
2555        let doing = match prompt {
2556            Some(text) => {
2557                let line = crate::surface_registry::first_line(text);
2558                if line.is_empty() {
2559                    "working".to_string()
2560                } else {
2561                    line
2562                }
2563            }
2564            None => "idle".to_string(),
2565        };
2566        // The whole entry is written, not only the changed field: another process removes an
2567        // entry whose surface did not answer its health check in time, and this puts it back.
2568        let branch = match current_branch(&hook_entry.root) {
2569            Ok(b) => b,
2570            Err(e) => {
2571                eprintln!("blyte: {e}");
2572                return;
2573            }
2574        };
2575        let entry = crate::surface_registry::RegistryEntry {
2576            branch,
2577            doing,
2578            state,
2579            ..hook_entry.clone()
2580        };
2581        if let Err(e) = crate::surface_registry::write_entry(&hook_dir, &entry) {
2582            eprintln!("blyte: {e}");
2583        }
2584    }));
2585
2586    if !is_repo {
2587        let _ = writeln!(
2588            err,
2589            "blyte: {} is not a git repository: runs edit this folder in place; combining and publishing are off",
2590            main_checkout.display()
2591        );
2592        let _ = err.flush();
2593    }
2594
2595    let open_codes = OpenCodes::new();
2596    let url = format!("http://127.0.0.1:{actual_port}/#token={token}");
2597    let _ = writeln!(out, "blyte: surface {surface_name} at {url}");
2598    let _ = out.flush();
2599    if !args.no_open && front_end.is_none() {
2600        match issue_initial_open_code(&open_codes, now_duration()) {
2601            Ok(code) => {
2602                let open_url = format!("http://127.0.0.1:{actual_port}/#open={code}");
2603                opener(&open_url);
2604            }
2605            Err(e) => {
2606                let _ = writeln!(err, "blyte: failed to create open code: {e}");
2607                let _ = err.flush();
2608            }
2609        }
2610    }
2611
2612    let stop_surface_name = surface_name.clone();
2613
2614    let surface = Arc::new(Surface {
2615        surface_id,
2616        surface_name,
2617        root: main_checkout,
2618        repo,
2619        session,
2620        session_id,
2621        started_at,
2622        days: args.days,
2623        token,
2624        message_credential,
2625        open_codes,
2626        requests: Arc::new(RequestsState::new()),
2627        publisher: Arc::new(RealPublisher),
2628        reconcile_lock: Mutex::new(()),
2629        reconcile_requested: AtomicBool::new(false),
2630    });
2631
2632    let timer_guard = spawn_reconcile_timer(Arc::clone(&surface));
2633    let _publish_tool_guard = PublishToolGuard::install(Arc::clone(&surface));
2634    let _land_tool_guard = LandToolGuard::install(Arc::clone(&surface));
2635
2636    let front_outcome = front_end.map(|spec| {
2637        let outcome = Arc::new(Mutex::new(None));
2638        let outcome_bg = Arc::clone(&outcome);
2639        let surface_bg = Arc::clone(&surface);
2640        let stop_trigger_bg = Arc::clone(&stop_trigger);
2641        std::thread::spawn(move || {
2642            let ctx = FrontEndContext {
2643                surface: surface_bg,
2644                take_interrupt: spec.take_interrupt,
2645            };
2646            let result =
2647                std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || (spec.front)(ctx)));
2648            let value = match result {
2649                Ok(code) => FrontEndOutcome::Exited(code),
2650                Err(_) => FrontEndOutcome::Panicked,
2651            };
2652            *outcome_bg.lock().unwrap_or_else(|e| e.into_inner()) = Some(value);
2653            stop_trigger_bg();
2654        });
2655        outcome
2656    });
2657
2658    let serve_result =
2659        crate::http::serve_until(listener, should_stop, move |req| match now_duration() {
2660            Ok(d) => route_inner(&surface, req, d.as_secs(), Some(&stop_trigger)),
2661            Err(e) => json_error(500, e),
2662        });
2663
2664    drop(_land_tool_guard);
2665    drop(_publish_tool_guard);
2666    drop(timer_guard);
2667
2668    match serve_result {
2669        Ok(()) => {
2670            let _ = writeln!(
2671                out,
2672                "blyte: stopped surface {stop_surface_name}; resume with: blyte --resume {stop_surface_name}"
2673            );
2674            let _ = out.flush();
2675            match front_outcome
2676                .as_ref()
2677                .and_then(|o| *o.lock().unwrap_or_else(|e| e.into_inner()))
2678            {
2679                Some(FrontEndOutcome::Exited(code)) => code,
2680                Some(FrontEndOutcome::Panicked) => {
2681                    let _ = writeln!(err, "blyte: the front end stopped unexpectedly");
2682                    let _ = err.flush();
2683                    1
2684                }
2685                None => 0,
2686            }
2687        }
2688        Err(e) => {
2689            let _ = writeln!(err, "blyte: server error: {e}");
2690            1
2691        }
2692    }
2693}
2694
2695fn issue_initial_open_code(
2696    open_codes: &OpenCodes,
2697    now: Result<Duration, String>,
2698) -> Result<String, String> {
2699    let now_secs = now?.as_secs();
2700    open_codes.issue(now_secs)
2701}
2702
2703fn canonicalize_attachments_dir(attachments_dir: &Path) -> Result<PathBuf, String> {
2704    std::fs::canonicalize(attachments_dir).map_err(|e| {
2705        format!(
2706            "failed to canonicalize attachments directory {}: {e}",
2707            attachments_dir.display()
2708        )
2709    })
2710}
2711
2712fn prepare_attachments_dir(surface_record_dir: &Path) -> Result<PathBuf, String> {
2713    let attachments_dir = crate::attachments::attachments_dir(surface_record_dir);
2714    std::fs::create_dir_all(&attachments_dir)
2715        .map_err(|e| format!("failed to create {}: {e}", attachments_dir.display()))?;
2716    canonicalize_attachments_dir(&attachments_dir)
2717}
2718
2719struct StartingDirGuard {
2720    dir: Option<PathBuf>,
2721}
2722
2723impl StartingDirGuard {
2724    fn disarm(&mut self) {
2725        self.dir = None;
2726    }
2727}
2728
2729impl Drop for StartingDirGuard {
2730    fn drop(&mut self) {
2731        if let Some(ref dir) = self.dir {
2732            crate::surface_dir::cleanup_starting_dir(dir);
2733        }
2734    }
2735}
2736
2737#[cfg(test)]
2738mod tests {
2739    use super::*;
2740
2741    #[test]
2742    fn canonicalize_attachments_dir_errors_when_missing() {
2743        let dir = tempfile::tempdir().unwrap();
2744        let missing = dir.path().join("does-not-exist").join("attachments");
2745        let err = canonicalize_attachments_dir(&missing).unwrap_err();
2746        assert!(
2747            err.contains(&missing.display().to_string()),
2748            "expected error to name missing path, got: {err}"
2749        );
2750        assert!(err.contains("canonicalize"), "unexpected error: {err}");
2751    }
2752
2753    #[cfg(unix)]
2754    #[test]
2755    fn canonicalize_attachments_dir_errors_on_dangling_symlink() {
2756        let dir = tempfile::tempdir().unwrap();
2757        let dangling = dir.path().join("attachments");
2758        std::os::unix::fs::symlink(dir.path().join("missing-target"), &dangling).unwrap();
2759        let err = canonicalize_attachments_dir(&dangling).unwrap_err();
2760        assert!(
2761            err.contains(&dangling.display().to_string()),
2762            "expected error to name symlink path, got: {err}"
2763        );
2764        assert!(err.contains("canonicalize"), "unexpected error: {err}");
2765    }
2766
2767    #[test]
2768    fn prepare_attachments_dir_errors_when_attachments_path_is_a_file() {
2769        let dir = tempfile::tempdir().unwrap();
2770        let blocker = crate::attachments::attachments_dir(dir.path());
2771        std::fs::write(&blocker, b"not a dir").unwrap();
2772        let err = prepare_attachments_dir(dir.path()).unwrap_err();
2773        assert!(
2774            err.contains(&blocker.display().to_string()),
2775            "expected error to name path, got: {err}"
2776        );
2777    }
2778
2779    fn poisoned_open_codes() -> OpenCodes {
2780        let codes = OpenCodes::new();
2781        let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2782            let _guard = codes.entries.lock().unwrap();
2783            panic!("poison");
2784        }));
2785        codes
2786    }
2787
2788    #[test]
2789    fn open_codes_issue_errors_when_lock_poisoned() {
2790        let codes = poisoned_open_codes();
2791        let err = codes.issue(100).unwrap_err();
2792        assert!(err.contains("open codes"), "unexpected error: {err}");
2793        assert!(err.contains("poison"), "unexpected error: {err}");
2794    }
2795
2796    #[test]
2797    fn open_codes_redeem_errors_when_lock_poisoned() {
2798        let codes = poisoned_open_codes();
2799        let err = codes.redeem("some-code", 100).unwrap_err();
2800        assert!(err.contains("open codes"), "unexpected error: {err}");
2801        assert!(err.contains("poison"), "unexpected error: {err}");
2802    }
2803
2804    #[test]
2805    fn issue_initial_open_code_errors_when_clock_fails() {
2806        let codes = OpenCodes::new();
2807        let err = issue_initial_open_code(
2808            &codes,
2809            Err("system clock is before Unix epoch: test".to_string()),
2810        )
2811        .unwrap_err();
2812        assert!(err.contains("system clock"), "unexpected error: {err}");
2813        assert!(codes.entries.lock().unwrap().is_empty());
2814
2815        let code = issue_initial_open_code(&codes, Ok(Duration::from_secs(500))).unwrap();
2816        assert!(codes.redeem(&code, 500).unwrap());
2817    }
2818}