by adom
Let an AI (Claude, ChatGPT, Codex or any agent) run Altium Designer for you: create symbols and footprints, place parts (also from Altium 365), wire and annotate schematics, Update PCB, set the stack-up and rules, route, pour copper, add mounting holes and stitching vias, run ERC and DRC, and make Gerbers, BOMs and STEP. Free in Hydrogen; bring your own AI and Altium licence.
← Commit history
0.2.104: leave Altium alone while a long command runs; keep the agent after long commands; faster routing_state on large boards (#39)
11 files changed
+267−32
CHANGELOG.md+9@@ -1,5 +1,14 @@ # Changelog +## 0.2.104++- **The bridge no longer closes Altium while a long command runs** (#39). Altium runs the agent in its main thread, so its window stops responding for as long as a command runs: a long `altium_eval`, or `altium_routing_state` on a large board. The bridge's close watchdog took that for a stuck shutdown, stopped the agent and, after 45 s, ended Altium. Now it knows the bridge's own command is running and leaves Altium alone (`busyHang` in `altium_dialog_log`).+- A window that hangs with no command of the bridge running (Altium loading a large board, say) is no longer counted as a close either: it is reported, never ended. And a close the bridge asked of one Altium no longer applies to a new Altium started after it.+- **The agent stays running after a long command.** It stopped after 15 s with no new request, counted from when the last command started, so any command over 15 s ended the agent as it answered and the next call had to start it again (about 3 s each time). It now counts from when the command finished.+- **`altium_routing_state` is faster on large boards.** The time spent outside Altium on a warm call went from 10.7 s to 0.3 s on a 10,000-track board, and the connectivity check from 0.5 s to 0.04 s. The agent reads each object's type once instead of up to seven times.+- `altium_eval` waits up to 600 s for its reply (`timeout`, default 60). The ab budget was 60 s, so a longer script's reply was cut off while the script kept running.+- Tested on Altium Designer 26.11.1: a 70 s `altium_eval` in both lanes and a 48 s `altium_routing_state` on a 50,000-object board, both with Altium left running. the new connectivity check gave the same counts as the old one on two large example boards, and the battery cases for the touched verbs passed.+ ## 0.2.103 - **`altium_update_pcb` keeps everything a board-only part needs with `keepBoardOnly`** (#39). The change order removed the nets of parts that are on no sheet, which cut the connections between their pins, and the board's own differential pairs. Altium names that group "Remove Differential Pair(1)", which the bridge did not recognise. Both now stay unticked; `removeBoardOnlyClasses:true` still lets pairs, classes, rules and rooms go. `keepBoardOnly`, `detail` and `removeBoardOnlyClasses` are now documented.
bridge-rs/src/agent.rs+57@@ -312,6 +312,31 @@ pub fn call(command: &str, params: &[(&str, String)], payload: Option<&str>, tim /// The agent command currently posted (the agent serves one at a time): named in agent_busy. static IN_FLIGHT: std::sync::Mutex<Option<(String, Instant)>> = std::sync::Mutex::new(None); +/// The last command posted, kept after a call timed out with the command taken, so the close watchdog can tell+/// Altium working on it from Altium wedged (#39: a long eval was killed as a wedged close).+struct Taken { ws: PathBuf, id: String, command: String, posted: SystemTime }+static TAKEN: std::sync::Mutex<Option<Taken>> = std::sync::Mutex::new(None);++/// A command of this bridge the agent is still running, with how long it has run (s). Altium's main window stops+/// answering while it runs, because the loop runs in Altium's main thread.+pub fn command_running() -> Option<(String, u64)> {+ if let Some((c, at)) = IN_FLIGHT.lock().ok().and_then(|g| g.clone()) { return Some((c, at.elapsed().as_secs())); }+ let g = TAKEN.lock().ok()?;+ let t = g.as_ref()?;+ still_running(&t.ws, &t.id, t.posted)+ .then(|| (t.command.clone(), SystemTime::now().duration_since(t.posted).map(|d| d.as_secs()).unwrap_or(0)))+}++/// A posted command is still running when it has no answer and the loop has not heartbeat since it was posted: the+/// loop heartbeats only between commands. No heartbeat file means the loop has exited. Pure apart from the files.+pub fn still_running(ws: &std::path::Path, id: &str, posted: SystemTime) -> bool {+ if ws.join(format!("response_{id}.json")).exists() { return false; }+ match std::fs::metadata(ws.join("hb.txt")).and_then(|m| m.modified()) {+ Ok(t) => t <= posted,+ Err(_) => false,+ }+}+ /// A Windows path in one spelling: Altium opens a SECOND document for the same file under another spelling /// (C:/x/a.PcbLib beside C:\x\a.PcbLib), and an edit made on one was never seen by a read of the other (three /// copies of Battery.PcbLib, 2026-10-30). Every drive-letter path goes to the agent with backslashes.@@ -393,6 +418,17 @@ pub fn call_in(ws: &std::path::Path, command: &str, params: &[(&str, String)], p return json!({"success": false, "error": format!("cannot post request: {e}")}); } let t_post = t0.elapsed().as_millis() as u64;+ // forgotten on every way out except a timeout with the command taken: that one is still running in Altium+ struct ForgetTaken(bool);+ impl Drop for ForgetTaken {+ fn drop(&mut self) {+ if !self.0 { if let Ok(mut g) = TAKEN.lock() { *g = None; } }+ }+ }+ if let Ok(mut g) = TAKEN.lock() {+ *g = Some(Taken { ws: ws.clone(), id: id.clone(), command: command.to_string(), posted: SystemTime::now() });+ }+ let mut taken = ForgetTaken(false); let posted_unix_ms = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map(|x| x.as_millis() as u64).unwrap_or(0); let mut next_halt_check = Duration::from_millis(400); let resp = ws.join(format!("response_{id}.json"));@@ -485,6 +521,7 @@ pub fn call_in(ws: &std::path::Path, command: &str, params: &[(&str, String)], p "heartbeatAgeSec": hb, "agentAlive": is_alive(), "_hint": "Nothing was changed. Altium was still busy with something of its own (a document it was loading, or its own work in the background): altium_check_dialogs for anything waiting, then send the same call again."}); }+ taken.0 = true; json!({"success": false, "errorCode": "agent_timeout", "pickedUp": true, "command": command, "error": format!("the agent took '{command}' but did not answer within {}s", timeout.as_secs()), "heartbeatAgeSec": hb, "agentAlive": is_alive(),@@ -527,6 +564,26 @@ pub fn is_agent_script_title(title: &str) -> bool { mod halt_tests { use super::*; + #[test]+ fn a_taken_command_runs_until_its_answer_or_the_next_heartbeat() {+ let ws = std::env::temp_dir().join(format!("adom-taken-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&ws);+ std::fs::create_dir_all(&ws).unwrap();+ std::fs::write(ws.join("hb.txt"), "1").unwrap();+ std::thread::sleep(Duration::from_millis(30));+ let posted = SystemTime::now();+ assert!(still_running(&ws, "r1", posted), "heartbeat older than the post, no answer");+ std::fs::write(ws.join("response_r1.json"), "{}").unwrap();+ assert!(!still_running(&ws, "r1", posted), "answered");+ std::fs::remove_file(ws.join("response_r1.json")).unwrap();+ std::thread::sleep(Duration::from_millis(30));+ std::fs::write(ws.join("hb.txt"), "2").unwrap();+ assert!(!still_running(&ws, "r1", posted), "the loop heartbeat again, so the command ended");+ std::fs::remove_file(ws.join("hb.txt")).unwrap();+ assert!(!still_running(&ws, "r1", posted), "no heartbeat file: the loop exited");+ let _ = std::fs::remove_dir_all(&ws);+ }+ #[test] fn an_unread_request_is_withdrawn_only_when_it_is_ours() { let d = std::env::temp_dir().join(format!("adom-withdraw-{}", std::process::id()));
bridge-rs/src/lifecycle.rs+71−13@@ -1121,19 +1121,27 @@ const KILL_AFTER_SEC: u64 = 45; /// be a legitimate long computation (a big DRC trips IsHungAppWindow too) and is never killed, /// only reported. static LAST_CLOSE_AT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);+/// The Altiums running when the bridge asked for the close: a close is about them, not a new Altium started after+/// it (#39: a fresh Altium opening a big board within 5 minutes of the old one closing was treated as wedged).+static CLOSED_PIDS: std::sync::Mutex<Vec<u32>> = std::sync::Mutex::new(Vec::new());++fn now_secs() -> u64 {+ std::time::SystemTime::now().duration_since(std::time::SystemTime::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)+} pub fn note_close_initiated() {- let now = std::time::SystemTime::now().duration_since(std::time::SystemTime::UNIX_EPOCH)- .map(|d| d.as_secs()).unwrap_or(0);- LAST_CLOSE_AT.store(now, std::sync::atomic::Ordering::Relaxed);+ if let Ok(mut g) = CLOSED_PIDS.lock() { *g = crate::win32::pids_of("X2.EXE").unwrap_or_default(); }+ LAST_CLOSE_AT.store(now_secs(), std::sync::atomic::Ordering::Relaxed);+}++/// A close the bridge asked for in the last 5 minutes, of one of these Altiums. Pure.+pub fn close_applies(closed_at: u64, now: u64, closed: &[u32], pids: &[u32]) -> bool {+ closed_at != 0 && now.saturating_sub(closed_at) < 300 && pids.iter().any(|p| closed.contains(p)) } -fn close_was_recent() -> bool {- let at = LAST_CLOSE_AT.load(std::sync::atomic::Ordering::Relaxed);- if at == 0 { return false; }- let now = std::time::SystemTime::now().duration_since(std::time::SystemTime::UNIX_EPOCH)- .map(|d| d.as_secs()).unwrap_or(0);- now.saturating_sub(at) < 300+fn close_was_recent_for(pids: &[u32]) -> bool {+ let closed = CLOSED_PIDS.lock().map(|g| g.clone()).unwrap_or_default();+ close_applies(LAST_CLOSE_AT.load(std::sync::atomic::Ordering::Relaxed), now_secs(), &closed, pids) } #[derive(Default)]@@ -1148,6 +1156,14 @@ struct WatchState { close_involved_agent: bool, /// pids already escalated, never re-killed escalated: std::collections::BTreeSet<u32>,+ /// this hang was logged as the bridge's own command at work+ busy_noted: bool,+}++/// A main window that stops answering while this bridge's own command runs is that command at work, not a wedged+/// close: unless a window is gone or a close was asked for, the watchdog leaves it alone (#39). Pure.+pub fn hang_is_our_command(any_window_gone: bool, close_recent: bool, running: bool) -> bool {+ running && !any_window_gone && !close_recent } fn live_agent_workspaces() -> Vec<(String, PathBuf)> {@@ -1190,20 +1206,41 @@ fn close_watch_once(st: &mut WatchState) { } st.windows_gone_since = None; st.close_involved_agent = false;+ st.busy_noted = false; return; } + // Altium's main thread runs the agent loop, so a long command (an eval, a big board read) hangs the window for as+ // long as it runs. On 0.2.103 and before that hang dropped the stop file, counted as a bridge-involved close and+ // killed Altium after 45 s (#39).+ let any_gone = x2_pids.iter().any(|p| !crate::win32::pid_has_main_window(*p, &windows));+ if let Some((cmd, secs)) = agent::command_running() {+ if hang_is_our_command(any_gone, close_was_recent_for(&x2_pids), true) {+ if !st.busy_noted {+ st.busy_noted = true;+ crate::dialogs::note_event(json!({"busyHang": cmd, "runningSec": secs,+ "note": format!("Altium's window is not responding while the bridge's '{cmd}' runs ({secs} s so far): that is the command at work, left alone")}));+ }+ st.windows_gone_since = None;+ return;+ }+ }+ // Some X2 is in the freeze signature: its main window is GONE or HUNG (the live freezes of // 2026-09-02 showed BOTH shapes; the fatal one keeps the frame visible and non-responding). // Stage 1: free every previously-seen resident loop NOW - harmless if the close is healthy, // decisive if the shutdown is about to wedge on the script engine.+ // Only a window that is gone, or a close the bridge asked of this Altium, makes it a close: a window that is merely+ // hung can be Altium loading a big board, and counting it let the zombie-breaker kill a working Altium (#39).+ let closing = any_gone || close_was_recent_for(&x2_pids); for (key, ws) in &live { if st.seen_ws.contains(key) { let _ = std::fs::write(ws.join("stop"), "1"); st.seen_ws.remove(key);- st.close_involved_agent = true;- crate::dialogs::note_event(json!({"closeWatchdog": key,- "note": "Altium main window gone or hung while a resident loop heartbeats - stop file dropped so the loop exits instead of wedging the shutdown (adom/altium-bridge#6)"}));+ if closing { st.close_involved_agent = true; }+ crate::dialogs::note_event(json!({"closeWatchdog": key, "closing": closing,+ "note": if closing { "Altium main window gone, or hung after the bridge asked it to close, while a resident loop heartbeats - stop file dropped so the loop exits instead of wedging the shutdown (adom/altium-bridge#6)" }+ else { "Altium main window hung while a resident loop heartbeats and no command of the bridge runs - stop file dropped so the loop exits; not a close, so Altium is never killed for it" }})); } } @@ -1224,8 +1261,8 @@ fn close_watch_once(st: &mut WatchState) { if since.elapsed() < Duration::from_secs(KILL_AFTER_SEC) { return; }- let bridge_involved = st.close_involved_agent || close_was_recent(); for pid in wedged {+ let bridge_involved = st.close_involved_agent || close_was_recent_for(&[pid]); st.escalated.insert(pid); if bridge_involved { ab::call("notify_user", json!({@@ -1251,6 +1288,27 @@ fn close_watch_once(st: &mut WatchState) { } } +#[cfg(test)]+mod watchdog_tests {+ use super::*;++ #[test]+ fn a_hang_during_our_command_is_left_alone_but_a_close_is_not() {+ assert!(hang_is_our_command(false, false, true), "a long eval: the window hangs, nothing closed");+ assert!(!hang_is_our_command(true, false, true), "the main window is gone: a close");+ assert!(!hang_is_our_command(false, true, true), "the bridge asked Altium to close");+ assert!(!hang_is_our_command(false, false, false), "no command of ours runs");+ }++ #[test]+ fn a_close_is_about_the_altium_it_closed() {+ assert!(close_applies(1000, 1100, &[7], &[7]), "the closed Altium, a minute later");+ assert!(!close_applies(1000, 1100, &[7], &[9]), "a new Altium started after the close");+ assert!(!close_applies(1000, 1400, &[7], &[7]), "more than 5 minutes ago");+ assert!(!close_applies(0, 100, &[], &[7]), "no close asked");+ }+}+ pub fn start_close_watchdog() -> bool { if CLOSE_WATCHDOG.swap(true, std::sync::atomic::Ordering::SeqCst) { return false;
bridge-rs/src/main.rs+1−1@@ -81,7 +81,7 @@ use tiny_http::{Header, Method, Response, Server}; /// Attached to every failed reply (see the /command handler). const REPORT_ISSUES: &str = "If this looks like an altium-bridge BUG (not a refusal you expected), report it: check for a duplicate with `adom-wiki issue list adom/altium-bridge`, then `adom-wiki issue create adom/altium-bridge --title \"<verb>: <one-line symptom>\" --category bug-report --body \"<what you ran, what you expected, what happened, the VERBATIM response JSON (and errorShot if present), bridgeVersion, the Altium version from altium_status, the OS>\"`. A relay, routing, toast or lifecycle problem belongs on adom/adom-bridge instead. Reports from real machines are how this bridge gets correct: three different Altium builds behaved three different ways in one weekend."; -pub const BRIDGE_VERSION: &str = "0.2.103";+pub const BRIDGE_VERSION: &str = "0.2.104"; fn json_response(status: u16, body: &serde_json::Value) -> Response<std::io::Cursor<Vec<u8>>> { let data = serde_json::to_vec(body).unwrap_or_else(|_| b"{}".to_vec());
bridge-rs/src/routing.rs+110−5@@ -155,7 +155,52 @@ fn on(cu: &Cu, layer: &str) -> bool { fn touch(x: &Cu, y: &Cu) -> bool { let shared = ["F.Cu", "B.Cu"].iter().any(|l| on(x, l) && on(y, l)) || matches!(x, Cu::Pad { layers, .. } if layers.iter().any(|l| l == "*.Cu")) && matches!(y, Cu::Pad { layers, .. } if layers.iter().any(|l| l == "*.Cu")) || (1..31).any(|k| { let l = format!("In{k}.Cu"); on(x, &l) && on(y, &l) });- if !shared { return false; }+ shared && touch_geom(x, y)+}++/// The copper layers an item is on, one bit each (F.Cu, B.Cu, In1..In30): `touch`'s shared-layer test, read once.+fn layer_mask(cu: &Cu) -> u32 {+ let mut m = 0u32;+ if on(cu, "F.Cu") { m |= 1; }+ if on(cu, "B.Cu") { m |= 2; }+ for k in 1..31 { if on(cu, &format!("In{k}.Cu")) { m |= 1 << (k + 1); } }+ m+}++fn is_multi(cu: &Cu) -> bool { matches!(cu, Cu::Pad { layers, .. } if layers.iter().any(|l| l == "*.Cu")) }++/// Where an item's copper can reach: every kind of touch needs the two boxes to meet.+fn bbox(cu: &Cu) -> (f64, f64, f64, f64) {+ match cu {+ Cu::Pad { c, half, .. } => (c.0 - half, c.1 - half, c.0 + half, c.1 + half),+ Cu::Via { c, r } => (c.0 - r, c.1 - r, c.0 + r, c.1 + r),+ Cu::Seg { a, b, half, .. } => (a.0.min(b.0) - half, a.1.min(b.1) - half, a.0.max(b.0) + half, a.1.max(b.1) + half),+ Cu::Pour { poly, .. } => poly.iter().fold((f64::MAX, f64::MAX, f64::MIN, f64::MIN), |m, p| (m.0.min(p.0), m.1.min(p.1), m.2.max(p.0), m.3.max(p.1))),+ }+}++/// The pairs of items that touch, as `touch` judges them, without trying every pair: a sweep over the boxes along x+/// (a 4559-pad board compared about a million pairs per ground net, #39).+fn touching_pairs(items: &[Cu]) -> Vec<(usize, usize)> {+ let eps = 2e-4;+ let boxes: Vec<(f64, f64, f64, f64)> = items.iter().map(bbox).collect();+ let masks: Vec<u32> = items.iter().map(layer_mask).collect();+ let multi: Vec<bool> = items.iter().map(is_multi).collect();+ let mut order: Vec<usize> = (0..items.len()).collect();+ order.sort_by(|a, b| boxes[*a].0.partial_cmp(&boxes[*b].0).unwrap_or(std::cmp::Ordering::Equal));+ let mut out = Vec::new();+ for (k, &i) in order.iter().enumerate() {+ for &j in &order[k + 1..] {+ if boxes[j].0 > boxes[i].2 + eps { break; }+ if boxes[j].1 > boxes[i].3 + eps || boxes[i].1 > boxes[j].3 + eps { continue; }+ if (masks[i] & masks[j]) == 0 && !(multi[i] && multi[j]) { continue; }+ if touch_geom(&items[i], &items[j]) { out.push((i.min(j), i.max(j))); }+ }+ }+ out+}++fn touch_geom(x: &Cu, y: &Cu) -> bool { let eps = 1e-4; match (x, y) { (Cu::Pad { c: a, half: ha, .. }, Cu::Pad { c: b, half: hb, .. }) => ((a.0 - b.0).powi(2) + (a.1 - b.1).powi(2)).sqrt() <= ha + hb + eps,@@ -208,14 +253,14 @@ pub fn unrouted(st: &Value) -> (usize, Vec<Value>, Vec<Value>) { let n = items.len(); let mut parent: Vec<usize> = (0..n).collect(); fn find(p: &mut Vec<usize>, x: usize) -> usize { let mut r = x; while p[r] != r { r = p[r]; } let mut y = x; while p[y] != r { let nx = p[y]; p[y] = r; y = nx; } r }- for i in 0..n { for j in (i + 1)..n { if touch(&items[i], &items[j]) { let (a, b) = (find(&mut parent, i), find(&mut parent, j)); if a != b { parent[a] = b; } } } }+ for (i, j) in touching_pairs(&items) { let (a, b) = (find(&mut parent, i), find(&mut parent, j)); if a != b { parent[a] = b; } } // a group that holds no pad (a stray track or via) still counts: copper that reaches nothing is a // connection not made. A group that is only pour is isolated copper (an island, or a pour that reaches no // pad): listed, not counted, as KiCad's DRC and the standard treat it- let roots: std::collections::BTreeSet<usize> = (0..n).map(|i| find(&mut parent, i)).collect();+ let mut by_root: std::collections::BTreeMap<usize, Vec<usize>> = std::collections::BTreeMap::new();+ for i in 0..n { let r = find(&mut parent, i); by_root.entry(r).or_default().push(i); } let mut groups = 0;- for r in &roots {- let members: Vec<usize> = (0..n).filter(|i| find(&mut parent, *i) == *r).collect();+ for members in by_root.into_values() { if members.iter().all(|i| matches!(items[*i], Cu::Pour { .. })) { for i in members { if let Cu::Pour { poly, layer } = &items[i] { let (cx, cy) = poly.iter().fold((0.0, 0.0), |a, p| (a.0 + p.0, a.1 + p.1));@@ -1765,3 +1810,63 @@ mod project_listing_tests { assert_eq!(poly_ring(&[json!([0, 0]), json!([k, 0.0]), json!([k, k])]).len(), 3); } }++#[cfg(test)]+mod big_board_bench {+ use super::*;++ /// Jelle's board (#39): 1219 parts, 4559 pads, 758 nets, nothing routed.+ pub fn jelle_sized() -> Value {+ let mut pads = Vec::new();+ let mut seed: u64 = 7;+ let mut rnd = || { seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); (seed >> 33) as f64 / (1u64 << 31) as f64 };+ for k in 0..4559 {+ let net = if k % 4 == 0 { "GND".to_string() } else if k % 9 == 0 { "+3V3".to_string() } else { format!("N{}", k % 756) };+ pads.push(json!({"ref": format!("U{}", k / 4), "name": "1", "x": rnd() * 200.0, "y": rnd() * 150.0, "sizeX": 0.6, "sizeY": 0.9,+ "layer": if k % 7 == 0 { "*.Cu" } else { "F.Cu" }, "net": net}));+ }+ json!({"pads": pads, "tracks": [], "vias": [], "polygons": []})+ }++ #[test]+ fn the_sweep_finds_exactly_the_pairs_every_pair_finds() {+ let mut seed: u64 = 11;+ let mut rnd = || { seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); (seed >> 33) as f64 / (1u64 << 31) as f64 };+ let layers = ["F.Cu", "B.Cu", "In1.Cu", "In2.Cu", "*.Cu"];+ let mut items = Vec::new();+ for k in 0..400 {+ let (x, y) = (rnd() * 20.0, rnd() * 20.0);+ items.push(match k % 4 {+ 0 => Cu::Pad { c: (x, y), half: 0.2 + rnd() * 0.6, layers: vec![layers[(rnd() * 5.0) as usize % 5].to_string()] },+ 1 => Cu::Seg { a: (x, y), b: (x + rnd() * 4.0 - 2.0, y + rnd() * 4.0 - 2.0), half: 0.1 + rnd() * 0.2, layer: layers[(rnd() * 4.0) as usize % 4].to_string() },+ 2 => Cu::Via { c: (x, y), r: 0.3 },+ _ => Cu::Pour { poly: vec![(x, y), (x + 3.0, y), (x + 3.0, y + 2.0), (x, y + 2.0)], layer: layers[(rnd() * 4.0) as usize % 4].to_string() },+ });+ }+ let mut brute = Vec::new();+ for i in 0..items.len() { for j in (i + 1)..items.len() { if touch(&items[i], &items[j]) { brute.push((i, j)); } } }+ let mut sweep = touching_pairs(&items);+ sweep.sort();+ assert!(brute.len() > 100, "the sample must have touches: {}", brute.len());+ assert_eq!(sweep, brute);+ }++ #[test]+ #[ignore]+ fn time_unrouted_on_a_saved_routing_state() {+ let Ok(path) = std::env::var("RS_JSON") else { return };+ let st: Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();+ let t = std::time::Instant::now();+ let (n, split, iso) = unrouted(&st);+ eprintln!("saved board: unrouted {n}, {} split, {} isolated in {} ms", split.len(), iso.len(), t.elapsed().as_millis());+ }++ #[test]+ #[ignore]+ fn time_unrouted_on_a_board_of_jelles_size() {+ let st = jelle_sized();+ let t = std::time::Instant::now();+ let (n, split, _) = unrouted(&st);+ eprintln!("unrouted {n} over {} split nets in {} ms", split.len(), t.elapsed().as_millis());+ }+}
bridge-rs/src/verbs.rs+1−1@@ -83,7 +83,7 @@ fn describe() -> Value { json!({"count": "int", "instances": "[{pid, key, edition, licensed, agentAlive, ...}]"}), 15, "With several running, other verbs REFUSE without instance:<pid|key|word> - guessing means acting inside another AI thread's Altium.", &["status"], &["Develop writes NO licence tail when it HOLDS the seat - blank licenceState there means licensed."], json!({})),- verb_doc("eval", "Run a DelphiScript snippet inside Altium (optional Var block, then Begin ... End;) on the CURRENT document, or on filePath opened first.", json!({"text": "string - [Var X : Integer;] Begin ... End;", "filePath": "optional: the document to make current first (a .PcbDoc for PCBServer.GetCurrentPCBBoard)", "timeout": "int seconds"}),+ verb_doc("eval", "Run a DelphiScript snippet inside Altium (optional Var block, then Begin ... End;) on the CURRENT document, or on filePath opened first.", json!({"text": "string - [Var X : Integer;] Begin ... End;", "filePath": "optional: the document to make current first (a .PcbDoc for PCBServer.GetCurrentPCBBoard)", "timeout": "int seconds the reply waits (default 60, up to 600). Altium's window does not respond while the script runs; the bridge knows it is the script and leaves Altium alone."}), json!({"success": "bool (false + errorShot when Altium raised an error box)", "errorCode": "script_error", "errorShot": "PNG of Altium's error box"}), 30, "Single quotes only (no double quotes). A Var block before Begin is allowed. Capture output by writing a file, not by returning a value. Pass filePath: after an export the OutJob is current and GetCurrentPCBBoard is Nil.", &["run_command"], &["An undeclared identifier HALTS the engine with a modal that Try/Except cannot catch.", "ShowMessage blocks the loop behind a modal - never use it."], json!({"text": "Begin PCBServer.GetCurrentPCBBoard.ViewManager_FullUpdate; End;"})),
package.json+1−1@@ -1,6 +1,6 @@ { "slug": "altium-bridge",- "version": "0.2.103",+ "version": "0.2.104", "type": "app", "description": "Let an AI (Claude, ChatGPT, Codex or any agent) run Altium Designer for you: create symbols and footprints, place parts (also from Altium 365), wire and annotate schematics, Update PCB, set the stack-up and rules, route, pour copper, add mounting holes and stitching vias, run ERC and DRC, and make Gerbers, BOMs and STEP. Free in Hydrogen; bring your own AI and Altium licence.", "tags": [
page.json+1−1@@ -4,7 +4,7 @@ "type": "app", "title": "Altium Bridge: AI for Altium Designer", "brief": "Let an AI (Claude, ChatGPT, Codex or any agent) run Altium Designer for you: create symbols and footprints, place parts (also from Altium 365), wire and annotate schematics, Update PCB, set the stack-up and rules, route, pour copper, add mounting holes and stitching vias, run ERC and DRC, and make Gerbers, BOMs and STEP. Free in Hydrogen; bring your own AI and Altium licence.",- "version": "0.2.103",+ "version": "0.2.104", "hero": { "type": "image", "path": "screenshots/hero.png"
src/BRIDGE_VERSION+1−1@@ -1 +1 @@-0.2.103+0.2.104
src/agent/AdomAgent.pas.tmpl+13−8@@ -6225,7 +6225,7 @@ Var Seg : TPolySegment; LT, LA, LV, LP, LC, LG, LO : TStringList; Own, Pts : String;- K, Unrouted : Integer;+ K, Unrouted, Oid : Integer; PR : TCoordRect; PX, PY, PW, PH, PRot, PS : Integer; Begin@@ -6241,14 +6241,16 @@ Begin Prim := BIt.FirstPCBObject; While Prim <> Nil Do Begin- If Prim.ObjectId = eTrackObject Then+ { one ObjectId read per object: each is a call into Altium, and the chain read it up to seven times (#39) }+ Oid := Prim.ObjectId;+ If Oid = eTrackObject Then Begin Trk := Prim; If Not Trk.InComponent Then LT.Add('[' + IntToStr(Trk.x1) + ',' + IntToStr(Trk.y1) + ',' + IntToStr(Trk.x2) + ',' + IntToStr(Trk.y2) + ',' + IntToStr(Trk.Width) + ',' + IntToStr(Trk.Layer) + ',' + NetOf(Trk) + ']'); End- Else If Prim.ObjectId = eArcObject Then+ Else If Oid = eArcObject Then Begin Arc := Prim; If Not Arc.InComponent Then@@ -6256,13 +6258,13 @@ Begin IntToStr(Round(Arc.StartAngle * 1000)) + ',' + IntToStr(Round(Arc.EndAngle * 1000)) + ',' + IntToStr(Arc.LineWidth) + ',' + IntToStr(Arc.Layer) + ',' + NetOf(Arc) + ']'); End- Else If Prim.ObjectId = eViaObject Then+ Else If Oid = eViaObject Then Begin Via := Prim; LV.Add('[' + IntToStr(Via.x) + ',' + IntToStr(Via.y) + ',' + IntToStr(Via.Size) + ',' + IntToStr(Via.HoleSize) + ',' + IntToStr(Via.LowLayer) + ',' + IntToStr(Via.HighLayer) + ',' + NetOf(Via) + ']'); End- Else If Prim.ObjectId = ePadObject Then+ Else If Oid = ePadObject Then Begin Pad := Prim; Own := '';@@ -6280,7 +6282,7 @@ Begin IntToStr(PW) + ',' + IntToStr(PH) + ',' + IntToStr(PRot) + ',' + IntToStr(Pad.Layer) + ',' + IntToStr(Pad.HoleSize) + ',' + NetOf(Pad) + ',' + IntToStr(PS) + ']'); End- Else If Prim.ObjectId = eComponentObject Then+ Else If Oid = eComponentObject Then Begin Comp := Prim; Own := '';@@ -6289,12 +6291,12 @@ Begin IntToStr(Round(Comp.Rotation * 1000)) + ',' + IntToStr(Comp.Layer) + ',"' + JsonEsc(Comp.Pattern) + '",' + IntToStr(GroupCount(Comp, eComponentBodyObject)) + ',"' + JsonEsc(Own) + '"]'); End- Else If Prim.ObjectId = ePolyObject Then+ Else If Oid = ePolyObject Then Begin Poly := Prim; LG.Add('[' + NetOf(Poly) + ',' + IntToStr(Poly.Layer) + ',[' + PolySegPts(Poly) + ']]'); End- Else If Prim.ObjectId = eConnectionObject Then+ Else If Oid = eConnectionObject Then Unrouted := Unrouted + 1; Prim := BIt.NextPCBObject; End;@@ -10886,6 +10888,9 @@ Begin Body := '{' + JRaw('ok', 'false') + ',' + JStr('error', 'exception in agent while handling ' + Cmd) + '}'; End; TDone := GetTickCount;+ { idle counts from the end of a command: from its start, any command over AUTO_STOP_MS ended the loop as soon as+ it answered, and the next call paid a restart (adom/altium-bridge#39) }+ If (Cmd <> 'state') And (Cmd <> 'ping') Then gLastReqTick := TDone; { wrap: id + timing + the handler body as "data"; agentPhases = read/dispatch ms + the loop tick that saw the request } WriteDirect(WORKSPACE + 'response_' + Id + '.json', '{' + JStr('id', Id) + ',' + JStr('command', Cmd) + ',' + JRaw('durationMs', IntToStr(TDone - T0)) + ',' +
src/bridge.json+2−1@@ -2,7 +2,7 @@ "manifest_version": 1, "name": "altium", "displayName": "Altium Designer",- "version": "0.2.103",+ "version": "0.2.104", "description": "Drive Altium Designer from Adom: a resident DelphiScript agent (eval + the 1,100-command process launcher), the X2 -R command line, UIA over the VCL shell, dialogs by PID, screenshots of every Altium window, and Altium 365.", "homepage": "https://wiki.adom.inc/adom/altium-bridge", "docs": "https://wiki.adom.inc/adom/altium-bridge",@@ -311,6 +311,7 @@ "default": 60, "verbs": { "launch": 240,+ "eval": 600, "panelize": 240, "impedance": 120, "current_capacity": 120, "plan_route": 300, "place_decoupling": 300, "plan_fanout": 300, "estimate_cost": 120, "simulate": 900, "export_spice": 900, "update_footprints_from_library": 600, "lint_library": 600, "export_pos": 120, "verb_times": 15, "prewarm": 120, "render_board": 300, "log_tail": 60, "sch_batch": 900, "import_step": 180, "edit_pours": 600, "export_3d": 360, "tool_update": 150, "import_design": 900, "sch_no_connect": 150, "sch_label": 150, "sch_wire": 150, "edit_tracks": 300, "select_items": 60, "preferences": 60, "extensions": 60, "cancel_run": 15, "physical_properties": 15, "model_check": 180, "place_parts": 600,