Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 43 additions & 15 deletions native/host/src/agents/design.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ use crate::files::kicad::canonical as kc;
use serde_json::{json, Value};
use std::sync::Arc;

/// Bound on synchronous post-save / turn-end `commit_design` so a stalled `repo_lock` or git command never hangs `SaveDocument` / `kicad_edit` for 300 s or delays releasing document locks.
pub const DESIGN_COMMIT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);

fn fail(m: &str) -> (bool, Value) { (false, json!({"error":m})) }
/// (agents/world.rs `cwd` reads the same key by its text: a fold input reaches nothing outside its inputs)
pub fn main_key(th: &str) -> String { format!("kicad.main.{th}") }
Expand Down Expand Up @@ -297,12 +300,34 @@ impl Agents {
let abs = if p.starts_with('/') { p } else { format!("{r}/{p}") };
kc::is_document(&abs).then_some(abs)
}
async fn finish_design_record(&self, th: &str, root: &str, skip: &[String], rec: Result<kc::Recorded, String>) {
match rec {
Ok(r) if r.commit.is_empty() => {}
Ok(r) => {
crate::settings::telemetry_usage::bump(crate::settings::telemetry_usage::BOARDS_CREATED, r.new_boards);
// a STEP written this turn is meshed now, in the background, so its first showing reads it from the cache
let steps: Vec<String> = r.files.iter().filter(|p| crate::files::kicad::solidread::is_step(p)).map(|p| format!("{root}/{p}")).collect();
if !steps.is_empty() { let home = self.hub.cfg.home.clone(); tokio::task::spawn_blocking(move || { let tools = crate::files::kicad::stepglb::machine(&home); for p in steps { crate::files::kicad::solidread::warm(&p, &tools); } }); }
let n = r.files.len();
let pushed = if r.pushed.is_empty() { String::new() } else if r.pushed.starts_with("not pushed") { format!("; {}", r.pushed) } else { format!(", pushed to {}", r.pushed) };
let left = if skip.is_empty() { String::new() } else { format!(" (left for its writer: {})", skip.iter().map(|d| d.rsplit('/').next().unwrap_or(d)).collect::<Vec<_>>().join(", ")) };
let files = r.files.iter().take(6).cloned().collect::<Vec<_>>().join(", ");
let line = if r.reference.is_empty() { format!("Committed {n} design file{} to main as {}{pushed}{left}: {files}", if n == 1 { "" } else { "s" }, r.commit) }
else { format!("Recorded {n} design file{} on {} as {} (your branch is untouched; commit when you choose){left}: {files}", if n == 1 { "" } else { "s" }, r.reference, r.commit) };
self.say(th, "info", "git", line).await
}
Err(e) => self.say(th, "warn", "git", format!("Design files not committed to main: {e}")).await,
}
}
/// Commit the design files changed in the thread's main checkout straight to main (and push
/// when it has an upstream and `git.auto_push` is on: settings/autopush.rs), leaving any document another thread holds for that thread.
/// `why`: "turn" (a turn's end) or "save" (a SaveDocument). Each commit is a line in the thread.
pub async fn design_record(self: &Arc<Self>, th: &str, why: &str) { self.design_record_note(th, why, "").await }
/// The same, `note` a line of the commit's body (a save that also upgraded the file's format says so: savegate.rs).
pub async fn design_record_note(self: &Arc<Self>, th: &str, why: &str, note: &str) {
self.design_record_note_within(th, why, note, DESIGN_COMMIT_TIMEOUT).await
}
pub(crate) async fn design_record_note_within(self: &Arc<Self>, th: &str, why: &str, note: &str, limit: std::time::Duration) {
if crate::copy::on() { return }
let root = self.main_root(th).await; if root.is_empty() || !kc::hardware(&root) { return }
let (title, mine, push, off) = { let w = self.world().await; (w.threads.get(th).map(|t| t.title.clone()).unwrap_or_default(), w.setting(&main_key(th)) == "on", crate::settings::autopush::on(w.setting(crate::settings::autopush::KEY)), crate::settings::offbranch::on(w.setting(crate::settings::offbranch::KEY))) };
Expand All @@ -317,22 +342,25 @@ impl Agents {
let skip: Vec<String> = [f.pcb, f.sch].into_iter().filter(|d| !d.is_empty() && held.contains(&kc::doc_lock(d))).collect();
// #1188: the subject says what changed (kc::describe); the thread it came from is the body, never the subject
let body = design_body(th, &title, why, note);
match kc::commit_design(&root, &body, &skip, push, off).await {
Ok(r) if r.commit.is_empty() => {}
Ok(r) => {
crate::settings::telemetry_usage::bump(crate::settings::telemetry_usage::BOARDS_CREATED, r.new_boards);
// a STEP written this turn is meshed now, in the background, so its first showing reads it from the cache
let steps: Vec<String> = r.files.iter().filter(|p| crate::files::kicad::solidread::is_step(p)).map(|p| format!("{root}/{p}")).collect();
if !steps.is_empty() { let home = self.hub.cfg.home.clone(); tokio::task::spawn_blocking(move || { let tools = crate::files::kicad::stepglb::machine(&home); for p in steps { crate::files::kicad::solidread::warm(&p, &tools); } }); }
let n = r.files.len();
let pushed = if r.pushed.is_empty() { String::new() } else if r.pushed.starts_with("not pushed") { format!("; {}", r.pushed) } else { format!(", pushed to {}", r.pushed) };
let left = if skip.is_empty() { String::new() } else { format!(" (left for its writer: {})", skip.iter().map(|d| d.rsplit('/').next().unwrap_or(d)).collect::<Vec<_>>().join(", ")) };
let files = r.files.iter().take(6).cloned().collect::<Vec<_>>().join(", ");
let line = if r.reference.is_empty() { format!("Committed {n} design file{} to main as {}{pushed}{left}: {files}", if n == 1 { "" } else { "s" }, r.commit) }
else { format!("Recorded {n} design file{} on {} as {} (your branch is untouched; commit when you choose){left}: {files}", if n == 1 { "" } else { "s" }, r.reference, r.commit) };
self.say(th, "info", "git", line).await
let (done_tx, done_rx) = tokio::sync::oneshot::channel::<()>();
let me = self.clone();
let th_s = th.to_string();
tokio::spawn(async move {
let rec = kc::commit_design(&root, &body, &skip, push, off).await;
me.finish_design_record(&th_s, &root, &skip, rec).await;
let _ = done_tx.send(());
});
match tokio::time::timeout(limit, done_rx).await {
Ok(Ok(())) => {}
Ok(Err(_)) => {
self.say(th, "warn", "git", "Design files not committed to main: commit task stopped unexpectedly.".into()).await;
}
Err(_) => {
let secs = limit.as_secs_f64();
let secs_str = if secs >= 1.0 && secs.fract() == 0.0 { format!("{} s", secs as u64) } else { format!("{secs:.2} s") };
let prefix = if why == "save" { "Design files were saved, but committing to main" } else { "Committing design files to main" };
self.say(th, "warn", "git", format!("{prefix} did not finish within {secs_str} (git or the repository lock is still busy); it will finish in the background.")).await;
}
Err(e) => self.say(th, "warn", "git", format!("Design files not committed to main: {e}")).await,
}
}
/// The documents' locks a thread holds go when its turn ends (a waiter is granted at once).
Expand Down
2 changes: 2 additions & 0 deletions native/host/src/agents/snapguard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,7 @@ impl Agents {
if design && self.in_review(th).await { return Err(sn::review_refusal(path.rsplit('/').next().unwrap_or(path))) }
let g = self.turn_guard(th);
if g.as_ref().is_some_and(|g| g.wrote) { return Ok(()) }
let prev_person = g.as_ref().is_some_and(|g| g.person);
let timed_out = || {
let secs = limit.as_secs_f64();
let secs_str = if secs >= 1.0 && secs.fract() == 0.0 { format!("{} s", secs as u64) } else { format!("{secs:.2} s") };
Expand Down Expand Up @@ -243,6 +244,7 @@ impl Agents {
match Self::await_detached(limit, async move { me.compute_guard(&th_s, &cwd, None, false).await }).await {
Ok(mut computed) => {
computed.wrote = true;
computed.person |= prev_person;
self.turn_guards.lock().unwrap().insert(th.to_string(), computed);
return Ok(());
}
Expand Down
67 changes: 67 additions & 0 deletions native/host/src/agents/tests/snapguard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -412,3 +412,70 @@ done
assert!(!after.wrote && after.review);
ag.shutdown();
}

#[tokio::test(flavor = "multi_thread")] async fn design_record_note_bounds_stalled_repo_lock_so_save_never_hangs() {
let bin = dir("sg-des-bin"); script(&bin, "claude", DOER);
let (hub, ag, _home, work) = start("sg-des-tmo", |w| {
std::fs::write(w.join("board.kicad_pcb"), board(4)).unwrap();
std::fs::write(w.join("board.kicad_pro"), "{}").unwrap();
git_out(w, &["init", "-q", "-b", "main"]);
git_out(w, &["config", "user.name", "t"]);
git_out(w, &["config", "user.email", "t@t"]);
git_out(w, &["add", "."]);
git_out(w, &["commit", "-qm", "init"]);
base_log(w, 1, "")
}, |_| Cli::standin(&bin)).await;

std::fs::write(work.join("board.kicad_pcb"), board(6)).unwrap();
let top = sn::top_of(&work.to_string_lossy()).await.unwrap();
let lock = sn::repo_lock(&top).await;
let from = len(&hub).await;
let t0 = Instant::now();
ag.design_record_note_within(T1, "save", "", Duration::from_millis(200)).await;
assert!(t0.elapsed() < Duration::from_secs(3), "design_record_note_within must bound stalled repo_lock, took {:?}", t0.elapsed());

let ev = log_from(&hub, from).await;
assert!(
ev.iter().any(|e| is(e, "ActivityLogged") && e["summary"].as_str().is_some_and(|s| s.contains("did not finish within"))),
"expected timeout ActivityLogged warning, got: {ev:?}"
);
assert!(
tokio::time::timeout(Duration::from_millis(80), sn::repo_lock(&top)).await.is_err(),
"repo_lock must still be held"
);

drop(lock);
tokio::time::timeout(Duration::from_secs(10), async {
loop {
let ev2 = log_from(&hub, from).await;
let committed_ev = ev2.iter().any(|e| is(e, "ActivityLogged") && e["summary"].as_str().is_some_and(|s| s.contains("Committed 1 design file to main")));
if committed_ev && git_out(&work, &["log", "-1", "--format=%s"]).contains("design:") { break }
tokio::time::sleep(Duration::from_millis(50)).await;
}
}).await.expect("detached design commit must finish and report completion once lock is released");
tokio::time::timeout(Duration::from_secs(2), sn::repo_lock(&top))
.await
.expect("repo_lock must become available once detached commit finishes");
ag.shutdown();
}

#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")] async fn repo_lock_canonicalizes_symlink_and_real_path() {
let d = crate::plat::tmp::short_dir("sg-canon-lock");
let real = d.path().join("real");
let link = d.path().join("link");
std::fs::create_dir_all(&real).unwrap();
std::os::unix::fs::symlink(&real, &link).unwrap();

let link_s = link.to_string_lossy().into_owned();
let real_s = real.to_string_lossy().into_owned();
let g = sn::repo_lock(&link_s).await;
assert!(
tokio::time::timeout(Duration::from_millis(80), sn::repo_lock(&real_s)).await.is_err(),
"symlink and canonical path must contend on the same repo_lock mutex"
);
drop(g);
tokio::time::timeout(Duration::from_secs(2), sn::repo_lock(&real_s))
.await
.expect("canonical path must acquire repo_lock once symlink holder drops");
}
3 changes: 2 additions & 1 deletion native/host/src/files/snapshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ Thumbs.db
/// once would race for `index.lock`.
pub async fn repo_lock(top: &str) -> tokio::sync::OwnedMutexGuard<()> {
static M: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, std::sync::Arc<tokio::sync::Mutex<()>>>>> = std::sync::OnceLock::new();
let m = { let mut g = M.get_or_init(Default::default).lock().unwrap(); g.entry(top.to_string()).or_default().clone() };
let key = crate::files::kicad::canonical::same_file(top);
let m = { let mut g = M.get_or_init(Default::default).lock().unwrap(); g.entry(key).or_default().clone() };
m.lock_owned().await
}

Expand Down
2 changes: 1 addition & 1 deletion native/host/src/kicad/canonical.rs
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,7 @@ pub async fn push_upstream(top: &str, branch: &str) -> String {
let up = upstream(top, branch).await;
if up.is_empty() { return up }
let (remote, rb) = up.split_once('/').map(|(a, b)| (a.to_string(), b.to_string())).unwrap_or_default();
let p = crate::files::git::run(top, &["push", "-q", &remote, &format!("{branch}:{rb}")]).await;
let p = crate::files::git::push(top, &["push", "-q", &remote, &format!("{branch}:{rb}")]).await;
if p.code == 0 { up } else { format!("not pushed: {}", p.out.trim().lines().last().unwrap_or("")) }
}
/// The main checkout of `root`: its top folder and branch, None when it is no git checkout on a branch (or a worktree).
Expand Down
31 changes: 29 additions & 2 deletions native/host/src/kicad/embed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1835,7 +1835,7 @@ async fn send_gui_raw(route: &GuiRoute, ty: &str, msg: Value, client: &str, time
match tokio::time::timeout_at(deadline + Duration::from_millis(1_000), r).await {
Ok(Ok(v)) => v,
Ok(Err(_)) => json!({"ok":false,"error":"no reply","why":"no reply","fallback":true}),
Err(_) => json!({"ok":false,"error":format!("KiCad did not answer in {} s", timeout_ms as f64 / 1000.0),"why":"timeout","fallback":true}),
Err(_) => json!({"ok":false,"error":format!("KiCad did not answer in {} s", timeout_ms as f64 / 1000.0),"why":"timeout"}),
}
}
async fn gui_call_in(route: &GuiRoute, ty: &str, msg: Value, client: &str, patient: Option<Duration>) -> Value {
Expand All @@ -1859,6 +1859,33 @@ pub async fn gui_call_timeout(route: &GuiRoute, ty: &str, msg: Value, client: &s
send_gui_raw(route, ty, msg, client, timeout_ms).await
}

#[cfg(test)]
pub(crate) fn mock_gui_route_for_test(
pro: &str,
handler: impl Fn(String, Value, oneshot::Sender<Value>) + Send + Sync + 'static,
) -> GuiRoute {
let (tx, mut rx) = mpsc::unbounded_channel();
let handler = std::sync::Arc::new(handler);
tokio::spawn(async move {
while let Some(msg) = rx.recv().await {
if let Msg::Raw { ty, msg, reply, .. } = msg {
handler(ty, msg, reply);
}
}
});
GuiRoute {
pro: pro.into(),
mode: "fork".into(),
sock: "/mock/gui.sock".into(),
desc: String::new(),
cli: String::new(),
argv: String::new(),
version: "10.99.0-bp.13".into(),
caps: vec!["coedit".into()],
tx,
}
}

/// One commit of item updates in the open editor as `client` (`coedit::client_name`): BeginCommit, UpdateItems, EndCommit, every one
/// with the document's header. KiCad routes a commit request without a header to the board editor (compatibility from before 11.0), so a
/// schematic commit whose EndCommit lacks it is never ended ("does not has a commit in progress") while its edit shows staged. A failed
Expand Down Expand Up @@ -3204,7 +3231,7 @@ impl Actor {
Some(dl) => {
let rem = dl.saturating_duration_since(tokio::time::Instant::now()).as_millis() as u64;
if rem == 0 {
let _ = reply.send(json!({"ok":false,"error":format!("KiCad did not answer in {} s", timeout as f64 / 1000.0),"why":"timeout","fallback":true}));
let _ = reply.send(json!({"ok":false,"error":format!("KiCad did not answer in {} s", timeout as f64 / 1000.0),"why":"timeout"}));
return;
}
timeout.min(rem).max(1)
Expand Down
Loading
Loading