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