← Commit history

0.2.103: update_pcb keeps board-only nets and pairs and returns Altium's Yes/No questions (#39); demo/show surfaces wait after a fresh open and fail on a failed step (#37, #38); unpicked agent requests withdrawn; new folders for sheets and boards

Colby Knox ·c97bab4a9a · ·parent 7db9a6b
16 files changed +240−46
CHANGELOG.md+14
@@ -1,5 +1,19 @@ # Changelog +## 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.+- **A Yes/No question Altium asks during `altium_update_pcb` comes back to you** (#39). Altium can raise a "Confirm" whose question is painted, so the bridge cannot read it. Answering it No stopped the update with `read_failed`. Now the question is photographed once it is drawn and returned as `altiumAsked[].shot`. When a No stopped the update, the reply is `errorCode: altium_asked`: read the question and call again with `confirm:"yes"`. The dialog log's photos of such boxes now show the question too (they were blank).+- **`altium_demo` and the `altium_show_*` surfaces no longer stall right after a document is loaded from disk** (#37, #38). After an open that loaded the file, the bridge waits for Altium to finish with it before selecting a part or switching views.+- **A failed step fails the beat** (#38). A step such as `PCB:SwitchTo2D` that does not complete makes the surface answer `success:false` with `errorCode: step_failed` and the step's error, and `altium_demo` lists it in `failedSteps` (with `failedProcesses`). Before, a 3D picture was returned as the 2D board.+- The board beats fit the board, not the whole drawing sheet (`PCB:Zoom Action=Board`), so a board with a stack-up table beside it fills the view.+- **A request Altium never picked up is withdrawn** (#37). When the agent did not take a command before its timeout, the command stayed waiting and either ran later, after the caller had moved on, or was overwritten by the next one. Now it is taken back and answered `errorCode: altium_busy` with `pickedUp:false` and `heartbeatAgeSec`. A command that was taken but is still running answers `agent_timeout` with `pickedUp:true`.+- `altium_show_symbol` and `altium_show_footprint` say "component not found" (`component_not_found`, with `available[]`) only when Altium said so, not on a timeout.+- `altium_build_schematic`, `altium_sch_create`, `altium_sch_sheet_symbol` and `altium_project_create` create the sheet's folder when it does not exist yet. A sheet in a new folder failed with "could not start the sheet from <template>", which read as a missing template.+- `altium_build_board` creates the board's folder when it does not exist yet, and answers `not_saved` when the board is not on disk afterwards. A board in a new folder was never written while the verb answered success.+- `altium_build_schematic` says why it failed: a netlist that differs from `nets` answers `errorCode: netlist_mismatch` with an error naming the count (it came back with an empty error).+- Tested on Altium Designer Develop 26.11.1: a board-only part with its own nets and a board-made pair kept through `update_pcb {execute, keepBoardOnly}` (read back from the board), the whole `altium_demo` tour, and the battery cases for every verb this release touched.+ ## 0.2.102  - **Script verbs no longer refuse with `agent_resident` after the agent lands in the wrong folder** (#36). The bridge chose the instance's agent folder once and then asked again when it wrote the path into the agent script. If the selected Altium was lost between the two (while Altium was starting, or when another request changed it), the script was written into the instance's folder but told to work in the shared legacy folder. Its loop then heartbeated where `altium_agent_status` and `altium_agent_stop` never looked, and every script verb (`altium_build_schematic`, `altium_create_symbol`, `altium_open_document`) waited and refused. Because the script was only written once per agent version, the wrong path survived Altium and bridge restarts.
bridge-rs/src/agent.rs+41−2
@@ -475,8 +475,32 @@ pub fn call_in(ws: &std::path::Path, command: &str, params: &[(&str, String)], p         }         std::thread::sleep(Duration::from_millis(2));     }-    json!({"success": false, "errorCode": "agent_timeout", "error": format!("agent did not answer within {}s", timeout.as_secs()),-           "agentAlive": is_alive(), "_hint": "a slow Altium process, or the engine halted on a modal — altium_check_dialogs / altium_agent_recover"})+    // Never picked up: the request is still in the inbox, so Altium was busy and the loop never got to it (#37: for+    // about two minutes after a library's first open on Develop). Withdraw it: left there it ran late, after the+    // caller had moved on, or the next request overwrote it and it was silently lost.+    let hb = hb_age(&ws).map(|d| (d.as_millis() as f64) / 1000.0);+    if withdraw_unread(&inbox, &id) {+        return json!({"success": false, "errorCode": "altium_busy", "pickedUp": false, "command": command,+            "error": format!("Altium was busy and the agent did not pick up '{command}' within {}s; the request was withdrawn, so it will not run later", timeout.as_secs()),+            "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."});+    }+    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(),+           "_hint": "The command may still finish in Altium. A slow Altium process, or the engine halted on a modal: altium_check_dialogs / altium_agent_recover"})+}++/// Take a request back out of the inbox when it is still there and still ours (`id=<id>` on its first line).+/// True when it was withdrawn. Pure apart from the inbox file.+pub fn withdraw_unread(inbox: &std::path::Path, id: &str) -> bool {+    let Ok(raw) = std::fs::read(inbox) else { return false };+    let text = String::from_utf8_lossy(&raw);+    if text.lines().next().map(|l| l.trim() == format!("id={id}")) != Some(true) { return false; }+    if std::fs::remove_file(inbox).is_err() { return false; }+    // its payload too, or the next request without one would be read with it+    if let Some(dir) = inbox.parent() { let _ = std::fs::remove_file(dir.join("request.payload")); }+    true }  /// A call that must NOT bootstrap the agent (status probes). Answers agent_not_running instead.@@ -503,6 +527,21 @@ pub fn is_agent_script_title(title: &str) -> bool { mod halt_tests {     use super::*; +    #[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()));+        let _ = std::fs::create_dir_all(&d);+        let inbox = d.join("request.txt");+        std::fs::write(&inbox, "id=abc\r\ncommand=lib_select\r\n").unwrap();+        std::fs::write(d.join("request.payload"), "x").unwrap();+        assert!(!withdraw_unread(&inbox, "other"));+        assert!(inbox.exists());+        assert!(withdraw_unread(&inbox, "abc"));+        assert!(!inbox.exists() && !d.join("request.payload").exists());+        assert!(!withdraw_unread(&inbox, "abc"));+        let _ = std::fs::remove_dir_all(&d);+    }+     #[test]     fn parked_means_started_here_and_never_exited() {         use std::time::UNIX_EPOCH;
bridge-rs/src/dialogs.rs+31−3
@@ -329,6 +329,28 @@ static REAPED_SHOTS: Mutex<Vec<Value>> = Mutex::new(Vec::new()); /// picture: answering No for the user must never be silent. static DECLINED: Mutex<Vec<Value>> = Mutex::new(Vec::new()); +/// While a verb runs that Altium may ask a painted Yes/No "Confirm" of (Update PCB, #39), the verb says how such a+/// box is answered: its caller's answer, or No as before. Either way the box is photographed once its question is+/// painted and handed back to the verb, so the caller can read what Altium asked. One holder at a time.+static CONFIRM_ANSWER: Mutex<Option<String>> = Mutex::new(None);+static CONFIRMS_SEEN: Mutex<Vec<Value>> = Mutex::new(Vec::new());++/// Hold painted Confirms for this verb until the guard is dropped; `answer` is "Yes" or "No" (None: No).+pub struct ConfirmHold;+impl ConfirmHold {+    pub fn new(answer: Option<&str>) -> Self {+        if let Ok(mut g) = CONFIRM_ANSWER.lock() { *g = Some(answer.unwrap_or("No").to_string()); }+        if let Ok(mut g) = CONFIRMS_SEEN.lock() { g.clear(); }+        ConfirmHold+    }+    /// The Confirms answered while held: [{title, pressed, shot}].+    pub fn seen(&self) -> Vec<Value> { CONFIRMS_SEEN.lock().map(|g| g.clone()).unwrap_or_default() }+}+impl Drop for ConfirmHold {+    fn drop(&mut self) { if let Ok(mut g) = CONFIRM_ANSWER.lock() { *g = None; } }+}+fn held_answer() -> Option<String> { CONFIRM_ANSWER.lock().ok().and_then(|g| g.clone()) }+ pub fn declined() -> Vec<Value> {     DECLINED.lock().map(|g| g.clone()).unwrap_or_default() }@@ -392,6 +414,9 @@ pub fn reap_once() -> usize {             Some(a) if cat != "unknown" && cat != "save_prompt" => a,             _ => continue,         };+        // a verb holding Confirms says how they are answered (#39)+        let held = if cat == "unreadable_confirm" { held_answer() } else { None };+        let act = held.clone().unwrap_or(act);         if cat != "single_ok_acknowledgement" && labels.len() > 1 && !labels.contains(&act.to_lowercase()) {             continue; // the catalog's action is not even on this dialog — do not improvise         }@@ -412,14 +437,17 @@ pub fn reap_once() -> usize {         let mut err_shot = Value::Null;         {             // the message is painted a moment after the box appears: a shot taken at once showed an empty-            // Error box (2026-10-22)-            std::thread::sleep(Duration::from_millis(600));+            // Error box (2026-10-22), and a Confirm's question was still blank at 600 ms (#39)+            std::thread::sleep(Duration::from_millis(if cat == "unreadable_confirm" { 1800 } else { 600 }));             let r = ab::call("desktop_screenshot_base64", json!({"hwnd": hwnd}), &[], 10);             if let Some(img) = r.get("image").or_else(|| r.get("base64")).and_then(|i| i.as_str()) {                 err_shot = json!(img);             }         }-        if cat == "unreadable_confirm" {+        if held.is_some() {+            if let Ok(mut g) = CONFIRMS_SEEN.lock() { g.push(json!({"title": title_str, "pressed": act, "shot": err_shot.clone()})); }+        }+        if cat == "unreadable_confirm" && act.eq_ignore_ascii_case("no") {             if let Ok(mut g) = DECLINED.lock() {                 g.push(json!({"atMs": now_ms(), "title": title_str, "pressed": act, "shot": err_shot.clone()}));                 let len = g.len();
bridge-rs/src/hier.rs+1−1
@@ -61,7 +61,7 @@ pub fn sheet_symbol(args: &Value) -> Value {             Ok(p) => p,             Err(e) => return json!({"success": false, "errorCode": "template_missing", "error": e}),         };-        if let Err(e) = std::fs::copy(&tpl, &child) { return json!({"success": false, "errorCode": "write_failed", "error": format!("could not create {child}: {e}")}); }+        if let Err(e) = support::copy_template(&tpl, &child) { return json!({"success": false, "errorCode": "write_failed", "error": e}); }         steps.push(json!({"childCreated": child}));     }     // the project lists the child (a sheet outside the project is not part of the design)
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.102";+pub const BRIDGE_VERSION: &str = "0.2.103";  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/project.rs+1−1
@@ -208,7 +208,7 @@ pub fn project_create(args: &Value) -> Value {     if let Err(e) = std::fs::create_dir_all(&dir).and_then(|_| std::fs::write(&prj, project_text(&name, &vars))) { return json!({"success": false, "errorCode": "write_failed", "error": e.to_string()}); }     // the sheet from Altium's template, titled; the board as Altium makes a new one, with its layer count     let tpl = match support::altium_public_file(r"Templates\ANSI B Landscape.SchDot") { Ok(p) => p, Err(e) => return json!({"success": false, "errorCode": "template_missing", "error": e}) };-    if let Err(e) = std::fs::copy(&tpl, &sch) { return json!({"success": false, "errorCode": "write_failed", "error": e.to_string()}); }+    if let Err(e) = support::copy_template(&tpl, &sch.to_string_lossy()) { return json!({"success": false, "errorCode": "write_failed", "error": e}); }     let mut steps = Vec::new();     if let Some(t) = support::s(args, "title") {         let r = crate::schsheet::page(&json!({"sheet": sch.to_string_lossy(), "title": t}));
bridge-rs/src/routing.rs+18−3
@@ -1202,6 +1202,11 @@ pub fn build_board(args: &Value) -> Value {             }         }     }+    // Altium saves into an existing folder only: a board in a new folder was never written while the verb answered+    // success (2026-11-19)+    if let Some(dir) = std::path::Path::new(pcb).parent().filter(|d| !d.as_os_str().is_empty()) {+        if let Err(e) = std::fs::create_dir_all(dir) { return err("write_failed", format!("could not create the folder {}: {e}", dir.display()), ""); }+    }     // the library must be the current document for the agent to read its footprints     let open = crate::support::agent_open(lib, 90);     if open.get("success").and_then(|v| v.as_bool()) != Some(true) { return open; }@@ -1220,6 +1225,9 @@ pub fn build_board(args: &Value) -> Value {     let placed_refs: Vec<String> = st["components"].as_array().cloned().unwrap_or_default().iter().filter_map(|c| c["ref"].as_str().map(str::to_string)).collect();     let missing: Vec<&str> = parts.iter().filter_map(|p| p["ref"].as_str()).filter(|r| !placed_refs.iter().any(|x| x == r)).collect();     let clean = wrong.is_empty() && missing.is_empty();+    if !std::path::Path::new(pcb).is_file() {+        return err("not_saved", format!("the board was built in Altium but {pcb} is not on disk"), "Save it with altium_save {filePath}, or check the folder can be written.");+    }     let reopened = reopen_listing_project(pcb);     json!({"success": clean, "errorCode": if clean { Value::Null } else { json!("readback_mismatch") }, "pcb": pcb, "projectReopened": reopened, "placed": d["placed"], "padsWired": d["padsWired"],            "outlineVertices": d["outlineVertices"], "missingParts": missing, "wrongPins": wrong, "revision": st["revision"], "unconnected": st["unconnected"],@@ -1587,7 +1595,7 @@ pub fn build_schematic(args: &Value) -> Value {         Ok(p) => p,         Err(e) => return err("template_missing", e, "Altium's sheet templates live under Public Documents\\Altium\\<install>\\Templates (AD26, ADDevelop, ...)."),     };-    if let Err(e) = std::fs::copy(&tpl_path, &sch) { return err("template_missing", format!("could not start the sheet from {tpl_path}: {e}"), ""); }+    if let Err(e) = crate::support::copy_template(&tpl_path, &sch) { return err("write_failed", e, "Check the folder of schPath can be written."); }     // the project: the sheet, the board, the libraries and the manufacturing OutJob, as Altium lists them     let dir = sch.rsplit_once(['\\', '/']).map(|(d, _)| d.to_string()).unwrap_or_default();     let stem = sch.rsplit_once(['\\', '/']).map(|(_, f)| f).unwrap_or(&sch).rsplit_once('.').map(|(s, _)| s.to_string()).unwrap_or_default();@@ -1642,10 +1650,17 @@ pub fn build_schematic(args: &Value) -> Value {     }     let compile_errors: Vec<Value> = c.get("data").and_then(|d| d.get("messages")).and_then(|m| m.as_array()).cloned().unwrap_or_default()         .into_iter().filter(|m| m["class"].as_str().map(|k| k.to_lowercase().contains("error")).unwrap_or(false)).collect();-    json!({"success": mismatches.is_empty(), "sch": sch, "project": prj, "placed": bd["placed"], "wires": bd["wires"], "labels": bd["labels"],+    let mut out = json!({"success": mismatches.is_empty(), "sch": sch, "project": prj, "placed": bd["placed"], "wires": bd["wires"], "labels": bd["labels"],            "pinsWithoutNet": bd["pinsWithoutNet"], "sheetMil": bd["sheetMil"], "nets": want.len(), "compiledNets": got.len(),            "mismatches": mismatches, "compileErrors": compile_errors,-           "_hint": "The sheet is drawn and saved inside its project, compiled, and its netlist compared pin by pin with nets (pins of parts on the sheet only). mismatches[] names any net that differs. Parts without a symbol (board-only pads) stay off the sheet."})+           "_hint": "The sheet is drawn and saved inside its project, compiled, and its netlist compared pin by pin with nets (pins of parts on the sheet only). mismatches[] names any net that differs. Parts without a symbol (board-only pads) stay off the sheet."});+    // a failure always says why: it came back with an empty error (2026-11-19)+    if !mismatches.is_empty() {+        out["errorCode"] = json!("netlist_mismatch");+        out["error"] = json!(format!("the compiled sheet's netlist differs from nets on {} net(s): see mismatches[]{}", mismatches.len(),+            if compile_errors.is_empty() { String::new() } else { format!("; Altium's compiler also reported {} error(s), see compileErrors[] (duplicate designators usually mean the project holds another sheet with the same parts)", compile_errors.len()) }));+    }+    out }  /// altium_select_net {net?, zoom?}: select one net as a whole (and nothing else); no net clears.
bridge-rs/src/sch.rs+56−12
@@ -291,6 +291,26 @@ pub fn part_diff(sheet: &[String], board: &[String]) -> (Vec<String>, Vec<String /// altium_update_pcb {projectPath, execute?, allowRemovals?}: the schematic's changes to the board (Altium's /// engineering change order). Without execute it only previews; it never removes board parts unless told. pub fn update_pcb(args: &Value) -> Value {+    // Altium can ask a painted Yes/No "Confirm" on the way (#39: the reaper answered No and the update stopped with+    // read_failed). The caller's confirm answers it; either way the question comes back photographed.+    let answer = s(args, "confirm").map(|a| if a.eq_ignore_ascii_case("yes") { "Yes" } else { "No" });+    let hold = crate::dialogs::ConfirmHold::new(answer);+    let mut r = update_pcb_run(args);+    let seen = hold.seen();+    if !seen.is_empty() {+        let declined = seen.iter().any(|c| c["pressed"].as_str().map(|p| p.eq_ignore_ascii_case("no")).unwrap_or(false));+        r["altiumAsked"] = json!(seen);+        if r.get("success").and_then(|b| b.as_bool()) != Some(true) && declined {+            r["readError"] = r.get("errorCode").cloned().unwrap_or(Value::Null);+            r["errorCode"] = json!("altium_asked");+            r["error"] = json!("Altium asked a Yes/No question during the update and it was answered No, which stopped it; the question is in altiumAsked[].shot");+            r["_hint"] = json!("Read the question in altiumAsked[].shot. If Yes is the right answer (Altium's 'automatically create component links' question, say), call again with confirm:\"yes\"; nothing was changed on the board.");+        }+    }+    r+}++fn update_pcb_run(args: &Value) -> Value {     if let Some(g) = support::need_licensed() { return g; }     let Some(prj) = s(args, "projectPath") else { return json!({"success": false, "errorCode": "bad_args", "error": "projectPath (.PrjPcb) is required"}) };     let text = std::fs::read(&prj).map(|b| String::from_utf8_lossy(&b).to_string()).unwrap_or_default();@@ -319,6 +339,16 @@ pub fn update_pcb(args: &Value) -> Value {     // the change order belongs to the project: a board open on its own has none, and Compare then opens nothing     if let Some(e) = support::must_open(&prj, 60) { return e; }     if let Some(e) = support::must_open(&board, 60) { return e; }+    // the nets on the board-only parts kept, read while the board is current (the change order is modal): the change+    // order would remove them with their connections (#39)+    let mut keep_nets: Vec<String> = Vec::new();+    for part in (if keep_board_only { remove.clone() } else { vec![] }).iter().take(300) {+        let r = agent::call("component_pins", &[("designator", part.clone())], None, Duration::from_secs(30));+        for p in r.get("data").and_then(|d| d.get("pins")).and_then(|p| p.as_array()).cloned().unwrap_or_default() {+            let n = st(&p["net"]);+            if !n.is_empty() && !keep_nets.contains(&n) { keep_nets.push(n); }+        }+    }     agent::call("run_process", &[("process", "WorkspaceManager:Compare".into()), ("params", "ObjectKind=Project|Action=UpdateMe".into())], None, Duration::from_secs(6));     let find = |needle: &str| -> Option<Value> {         instance::invalidate_snapshot();@@ -377,7 +407,7 @@ pub fn update_pcb(args: &Value) -> Value {     // were about to be removed by the next change order, 2026-10-22)     let keep_parts: Vec<String> = if keep_board_only { remove.clone() } else { vec![] };     let keep_classes = args.get("removeBoardOnlyClasses").and_then(|b| b.as_bool()) != Some(true);-    let (rows, unticked) = eco_walk(hwnd, &keep_parts, keep_classes);+    let (rows, unticked) = eco_walk(hwnd, &keep_parts, &keep_nets, keep_classes);     steps.push(json!({"walked": rows.len(), "unticked": unticked.len()}));     if !execute {         let closed = match button_rect(hwnd, "Close") {@@ -463,13 +493,22 @@ fn eco_page(hwnd: i64) -> Vec<(String, Value)> {  /// Should this enabled row be unticked? Board-only parts (keep_parts) and, unless told otherwise, the board's own /// net classes, differential pairs, rules and rooms, which the change order removes because no sheet has them.-pub fn eco_should_untick(group: &str, text: &str, keep_parts: &[String], keep_classes: bool) -> bool {+/// `keep_nets` are the nets on those board-only parts: the change order removes a net no sheet has, and with it the+/// connections between board-only pins (#39).+pub fn eco_should_untick(group: &str, text: &str, keep_parts: &[String], keep_nets: &[String], keep_classes: bool) -> bool {     let g = group.to_ascii_lowercase();     let body = text.trim_start_matches("True ").trim_start_matches("False ");-    if keep_classes && ["remove net classes", "remove differential pairs", "remove rules", "remove rooms", "remove component classes", "remove differential pair classes"].iter().any(|k| g.starts_with(k)) {+    // by the singular stem: Altium names the group "Remove Differential Pair(1)", which "remove differential pairs"+    // never matched, so board-made pairs were removed (#39)+    if keep_classes && ["remove net class", "remove differential pair", "remove rule", "remove room", "remove component class"].iter().any(|k| g.starts_with(k)) {         return true;     }     let des = body.strip_prefix("Remove ").and_then(|r| r.split_whitespace().next()).unwrap_or("");+    if g.starts_with("remove nets") || g.starts_with("remove net(") {+        // "Remove BN1 From B.PcbDoc": the net name is everything before the last " From "+        let net = body.strip_prefix("Remove ").and_then(|r| r.rsplit_once(" From ").map(|(n, _)| n)).unwrap_or("");+        return keep_nets.iter().any(|k| k.eq_ignore_ascii_case(net));+    }     if g.starts_with("remove components") { return keep_parts.iter().any(|k| k.eq_ignore_ascii_case(des)); }     if g.starts_with("remove pins from nets") {         let part = des.rsplit_once('-').map(|(p, _)| p).unwrap_or(des);@@ -480,7 +519,7 @@ pub fn eco_should_untick(group: &str, text: &str, keep_parts: &[String], keep_cl  /// Walk EVERY row of the change order (the grid is virtualized and UIA cannot scroll it: select a row and page /// down), unticking what eco_should_untick names. Answers the groups with their rows, and what was unticked.-fn eco_walk(hwnd: i64, keep_parts: &[String], keep_classes: bool) -> (Vec<Value>, Vec<String>) {+fn eco_walk(hwnd: i64, keep_parts: &[String], keep_nets: &[String], keep_classes: bool) -> (Vec<Value>, Vec<String>) {     let mut seen: Vec<String> = Vec::new();     let mut unticked = Vec::new();     let mut groups: Vec<Value> = Vec::new();@@ -505,7 +544,7 @@ fn eco_walk(hwnd: i64, keep_parts: &[String], keep_classes: bool) -> (Vec<Value>             if !data { groups.push(json!({"group": t, "rows": []})); continue; }             let group = groups.last().and_then(|g| g["group"].as_str()).unwrap_or("").to_string();             let mut enabled = t.starts_with("True ");-            if enabled && eco_should_untick(&group, t, keep_parts, keep_classes) {+            if enabled && eco_should_untick(&group, t, keep_parts, keep_nets, keep_classes) {                 let (x, y) = (r["x"].as_f64().unwrap_or(0.0) + 3.5 * r["h"].as_f64().unwrap_or(0.0), r["centerY"].as_f64().unwrap_or(0.0));                 let c = ab::call("desktop_click", json!({"hwnd": hwnd, "x": x.round() as i64, "y": y.round() as i64, "reason": "leave a board-only item out of the change order"}), &[], 20);                 if c.get("success").and_then(|b| b.as_bool()) == Some(true) { enabled = false; unticked.push(t.trim_start_matches("True ").to_string()); selected = true; }@@ -680,13 +719,18 @@ mod tests {     #[test]     fn the_change_order_leaves_board_only_items_alone() {         let keep = vec!["TP1".to_string()];-        assert!(eco_should_untick("Remove Components(7)", "True Remove TP1 From B.PcbDoc", &keep, true));-        assert!(!eco_should_untick("Remove Components(7)", "True Remove TP10 From B.PcbDoc", &keep, true));-        assert!(eco_should_untick("Remove Pins From Nets(7)", "True Remove TP1-1 from SW In B.PcbDoc", &keep, true));-        assert!(!eco_should_untick("Remove Pins From Nets(7)", "True Remove R1-1 from SW In B.PcbDoc", &keep, true));-        assert!(eco_should_untick("Remove Net Classes(2)", "True Remove Power From B.PcbDoc", &[], true));-        assert!(!eco_should_untick("Remove Net Classes(2)", "True Remove Power From B.PcbDoc", &[], false));-        assert!(!eco_should_untick("Add Components(1)", "True Add U3 To B.PcbDoc", &keep, true));+        assert!(eco_should_untick("Remove Components(7)", "True Remove TP1 From B.PcbDoc", &keep, &[], true));+        assert!(!eco_should_untick("Remove Components(7)", "True Remove TP10 From B.PcbDoc", &keep, &[], true));+        assert!(eco_should_untick("Remove Pins From Nets(7)", "True Remove TP1-1 from SW In B.PcbDoc", &keep, &[], true));+        assert!(!eco_should_untick("Remove Pins From Nets(7)", "True Remove R1-1 from SW In B.PcbDoc", &keep, &[], true));+        assert!(eco_should_untick("Remove Net Classes(2)", "True Remove Power From B.PcbDoc", &[], &[], true));+        assert!(!eco_should_untick("Remove Net Classes(2)", "True Remove Power From B.PcbDoc", &[], &[], false));+        assert!(!eco_should_untick("Add Components(1)", "True Add U3 To B.PcbDoc", &keep, &[], true));+        // #39, as Altium Designer Develop 26.11.1 names them: a board-made pair, and the nets of a board-only part+        assert!(eco_should_untick("Remove Differential Pair(1)", "True Remove DP From j39b.PcbDoc", &[], &[], true));+        let nets = vec!["BN1".to_string(), "DP_P".to_string()];+        assert!(eco_should_untick("Remove Nets(3)", "True Remove BN1 From j39b.PcbDoc", &keep, &nets, true));+        assert!(!eco_should_untick("Remove Nets(3)", "True Remove OLD From j39b.PcbDoc", &keep, &nets, true));     }      use super::*;
bridge-rs/src/schsheet.rs+1−1
@@ -564,7 +564,7 @@ pub fn create(args: &Value) -> Value {     if dry(args) { return json!({"success": true, "dryRun": true, "sheet": path, "page": page_no, "root": root, "sheetName": name}); }     if let Some(g) = support::need_licensed() { return g; }     let tpl = match support::altium_public_file(r"Templates\ANSI B Landscape.SchDot") { Ok(p) => p, Err(e) => return json!({"success": false, "errorCode": "template_missing", "error": e}) };-    if let Err(e) = std::fs::copy(&tpl, &path) { return json!({"success": false, "errorCode": "write_failed", "error": format!("could not create {path}: {e}")}); }+    if let Err(e) = support::copy_template(&tpl, &path) { return json!({"success": false, "errorCode": "write_failed", "error": e}); }     // page, title block and page number on the new sheet     let mut a = args.clone();     a["sheet"] = json!(path);
bridge-rs/src/support.rs+10
@@ -274,6 +274,16 @@ mod tests {     } } +/// Start a new document from one of Altium's templates: the destination folder is made first. An error names the+/// file that could not be written: a sheet in a folder that did not exist yet failed as "could not start the sheet+/// from <template>", which read as a missing template (#39 testing, 2026-11-19).+pub fn copy_template(tpl: &str, dest: &str) -> Result<(), String> {+    if let Some(dir) = std::path::Path::new(dest).parent().filter(|d| !d.as_os_str().is_empty()) {+        std::fs::create_dir_all(dir).map_err(|e| format!("could not create the folder {}: {e}", dir.display()))?;+    }+    std::fs::copy(tpl, dest).map(|_| ()).map_err(|e| format!("could not write {dest} from the template {tpl}: {e}"))+}+ /// A file under Altium's Public Documents tree (`<root>\<install key>\<rel>`, e.g. Templates\ANSI C /// Landscape.SchDot or OutputJobs\Fabrication.OutJob). Each install keeps its own folder (AD26, /// ADDevelop, ...): the running instance's first, then any install that has the file. The battery
bridge-rs/src/surfaces.rs+60−16
@@ -31,6 +31,35 @@ fn mark_demo(mut out: Value, used_demo: bool) -> Value {     out } +/// After an open that loaded the document from disk, Altium can stay busy with it for a while (#37, #38: up to two+/// minutes on Altium Designer Develop), and a command sent meanwhile timed out. Wait for the agent to answer a ping+/// before the next step. Quick opens (already open) skip it.+fn settle_after_open(open: &Value, timeout: Duration, steps: &mut Vec<Value>) {+    let ms = open.get("roundtripMs").and_then(|v| v.as_u64()).unwrap_or(0);+    if ms < 1500 { return; }+    let t = std::time::Instant::now();+    let p = agent::call("ping", &[], None, timeout);+    steps.push(json!({"settle": "the document was loaded from disk: waited for Altium to finish with it", "ok": p.get("success"), "ms": t.elapsed().as_millis() as u64}));+}++/// Run follow-up processes; returns the names of the ones that failed (#38: a failed SwitchTo2D used to leave the+/// beat at success:true over a 3D picture).+fn run_steps(commands: &[(&str, &str)], timeout: Duration, steps: &mut Vec<Value>) -> Vec<String> {+    let mut failed = Vec::new();+    for (cmd, params) in commands {+        let rr = agent::call("run_process", &[("process", cmd.to_string()), ("params", params.to_string())], None, timeout);+        let ok = rr.get("success").and_then(|b| b.as_bool()) == Some(true);+        let mut st = json!({"process": cmd, "params": params, "ok": ok, "ms": rr.get("roundtripMs")});+        if !ok {+            st["errorCode"] = rr.get("errorCode").cloned().unwrap_or(Value::Null);+            st["error"] = rr.get("error").cloned().or_else(|| rr.get("data").and_then(|d| d.get("error")).cloned()).unwrap_or(Value::Null);+            failed.push(cmd.to_string());+        }+        steps.push(st);+    }+    failed+}+ /// Open a document through the agent, run follow-up processes, return the frame. pub fn open_then(path: &str, commands: &[(&str, &str)], timeout: Duration, label: &str) -> Value {     if let Some(g) = support::need_licensed() {@@ -46,16 +75,21 @@ pub fn open_then(path: &str, commands: &[(&str, &str)], timeout: Duration, label         out["steps"] = json!(steps);         return out;     }-    for (cmd, params) in commands {-        let rr = agent::call("run_process", &[("process", cmd.to_string()), ("params", params.to_string())], None, timeout);-        steps.push(json!({"process": cmd, "params": params, "ok": rr.get("success"), "ms": rr.get("roundtripMs")}));-    }+    settle_after_open(&r, timeout, &mut steps);+    let failed = run_steps(commands, timeout, &mut steps);     std::thread::sleep(Duration::from_millis(600));     let dl = dialogs::scan_scoped(true);     let frame = shot::shot_of_main();     // a cached snapshot answered the PREVIOUS document's title (a SchDoc for a board just shown, 2026-10-22)     instance::invalidate_snapshot();     let mw = instance::main_window().unwrap_or(json!({}));+    if !failed.is_empty() {+        return json!({"success": false, "errorCode": "step_failed", "surface": label, "path": path, "steps": steps, "failedSteps": failed,+            "error": format!("{} did not complete, so the picture is not what {label} should show", failed.join(", ")),+            "title": mw.get("title"), "document": mw.get("document"), "dialogsDetected": dl.len(), "dialogs": dl, "shot": frame,+            "windowEtiquette": "background", "elapsedSec": support::elapsed_round(t0),+            "_hint": "Do not narrate the picture as the intended view. steps[] gives each failed step's error; altium_check_dialogs, then call again."});+    }     let ok = dl.is_empty();     json!({"success": ok, "surface": label, "path": path, "steps": steps,            "title": mw.get("title"), "document": mw.get("document"),@@ -89,20 +123,24 @@ pub fn lib_surface(args: &Value, kind: &str, default_path: &str, label: &str, af         out["steps"] = json!(steps);         return out;     }+    settle_after_open(&r, timeout, &mut steps);     let sel = agent::call("lib_select", &[("kind", kind.to_string()), ("name", name.clone())], None, timeout);     steps.push(json!({"lib_select": if name.is_empty() { "(first)" } else { &name }, "result": sel.get("data"), "ms": sel.get("roundtripMs")}));     if sel.get("success").and_then(|b| b.as_bool()) != Some(true) {-        let lst = agent::call("lib_list", &[("kind", kind.to_string()), ("limit", "50".into())], None, Duration::from_secs(30));-        let mut out = sel;+        let mut out = sel.clone();         out["steps"] = json!(steps);-        out["available"] = lst.get("data").and_then(|d| d.get("names")).cloned().unwrap_or(Value::Null);-        out["_hint"] = json!("Component not found in that library — pick one of available[] (altium_list_library shows all).");+        out["failedSteps"] = json!(["lib_select"]);+        // only a reply from the agent saying so means the part is not there; a timeout or a busy Altium is not that (#37)+        let not_found = sel.get("data").and_then(|d| d.get("error")).and_then(|e| e.as_str()).map(|e| e.starts_with("component not found")).unwrap_or(false);+        if not_found {+            let lst = agent::call("lib_list", &[("kind", kind.to_string()), ("limit", "50".into())], None, Duration::from_secs(30));+            out["errorCode"] = json!("component_not_found");+            out["available"] = lst.get("data").and_then(|d| d.get("names")).cloned().unwrap_or(Value::Null);+            out["_hint"] = json!("Component not found in that library: pick one of available[] (altium_list_library shows all).");+        }         return out;     }-    for (cmd, params) in after {-        let rr = agent::call("run_process", &[("process", cmd.to_string()), ("params", params.to_string())], None, Duration::from_secs(60));-        steps.push(json!({"process": cmd, "params": params, "ok": rr.get("success"), "ms": rr.get("roundtripMs")}));-    }+    let failed = run_steps(after, Duration::from_secs(60), &mut steps);     std::thread::sleep(Duration::from_millis(600));     let mut dl = dialogs::scan_scoped(true);     shot::attach_dialog_shots(&mut dl);@@ -110,13 +148,18 @@ pub fn lib_surface(args: &Value, kind: &str, default_path: &str, label: &str, af     let mw = instance::main_window().unwrap_or(json!({}));     let no_proof = frame.get("proofUnavailable").and_then(|b| b.as_bool()) == Some(true);     let selected = sel.get("data").and_then(|d| d.get("selected")).cloned().unwrap_or(Value::Null);-    let mut out = json!({"success": dl.is_empty() && !no_proof, "surface": label, "path": path, "demoFallback": demo,+    let mut out = json!({"success": dl.is_empty() && !no_proof && failed.is_empty(), "surface": label, "path": path, "demoFallback": demo,         "selected": selected,         "steps": steps, "title": mw.get("title"), "dialogsDetected": dl.len(), "dialogs": dl, "shot": frame,         "windowEtiquette": "background", "elapsedSec": support::elapsed_round(t0),         "_hint": format!("{label}: {:?} in {:?}. shot.image is the frame.",             out_str(&out_sel(&sel)), mw.get("document").and_then(|d| d.as_str()).unwrap_or(""))});-    if no_proof {+    if !failed.is_empty() {+        out["errorCode"] = json!("step_failed");+        out["failedSteps"] = json!(failed);+        out["error"] = json!(format!("{} did not complete, so the picture is not what {label} should show", failed.join(", ")));+        out["_hint"] = json!("Do not narrate the picture as the intended view. steps[] gives each failed step's error; altium_check_dialogs, then call again.");+    } else if no_proof {         out["errorCode"] = json!("proof_unavailable");         out["error"] = out["shot"].get("reason").cloned().unwrap_or(Value::Null);         out["_hint"] = json!("The surface was opened and selected correctly — only the CAPTURE failed, because the Altium window is minimized. The bridge restores it into the background automatically; if it is still minimized, something re-minimized it mid-call.");@@ -152,14 +195,14 @@ pub fn show_2d_board(args: &Value) -> Value {     if let Some(e) = stray_path(args, &["filePath"]) { return e; }     let demo = s(args, "filePath").is_none();     let p = s(args, "filePath").unwrap_or_else(support::demo_pcb);-    mark_demo(open_then(&p, &[("PCB:SwitchTo2D", ""), ("PCB:Zoom", "Action=All")], timeout_of(args, 120), "2d_board"), demo)+    mark_demo(open_then(&p, &[("PCB:SwitchTo2D", ""), ("PCB:Zoom", "Action=Board")], timeout_of(args, 120), "2d_board"), demo) }  pub fn show_3d_board(args: &Value) -> Value {     if let Some(e) = stray_path(args, &["filePath"]) { return e; }     let demo = s(args, "filePath").is_none();     let p = s(args, "filePath").unwrap_or_else(support::demo_pcb);-    mark_demo(open_then(&p, &[("PCB:SwitchTo3D", ""), ("PCB:Zoom", "Action=All")], timeout_of(args, 120), "3d_board"), demo)+    mark_demo(open_then(&p, &[("PCB:SwitchTo3D", ""), ("PCB:Zoom", "Action=Board")], timeout_of(args, 120), "3d_board"), demo) }  pub fn show_symbol(args: &Value) -> Value {@@ -389,6 +432,7 @@ pub fn demo(args: &Value) -> Value {     let mut out = json!({"success": ok, "done": false, "stage": stage, "label": label, "narrate": narrate,         "screenshots": shots, "steps": r.get("steps"), "dialogs": r.get("dialogs"),         "failedSteps": if ok { json!([]) } else { json!([label]) },+        "failedProcesses": r.get("failedSteps").cloned().unwrap_or(json!([])),         "nextCall": {"verb": "altium_demo", "args": {"stage": stage + 1}},         "_hint": format!("Beat {}/{} ({label}). Narrate, show the screenshot, then call altium_demo {{stage:{}}}.",                          stage + 1, DEMO_BEATS.len(), stage + 1)});
bridge-rs/src/verbs.rs+2−2
@@ -1312,8 +1312,8 @@ fn describe() -> Value {             &["sch_edit", "export_pdf"], &[],             json!({"sheet": "C:/proj/Main.SchDoc", "set": {"Title": "12 V to 5 V buck", "Revision": "B"}})),         verb_doc("update_pcb", "Design > Update PCB Document from the schematic (the engineering change order): parts added, removed or renamed, nets and footprints updated on the board. Previews by default; execute:true runs it (Execute Changes, Close), refusing to delete board parts unless allowRemovals:true.",-            json!({"projectPath": "path to the .PrjPcb (required)", "execute": "bool, default false - false only previews", "allowRemovals": "bool, default false - let the change order delete board parts that are on no sheet", "timeout": "seconds, default 300"}),-            json!({"executed": "bool", "preview": "{addParts, removeParts, sheetParts, boardParts}", "changeOrder": "[string] - the dialog's first page (groups carry counts)", "afterExecute": "[string]", "steps": "[..]", "dialogs": "[..] - anything Altium asked", "board": "path"}), 600,+            json!({"projectPath": "path to the .PrjPcb (required)", "execute": "bool, default false - false only previews", "allowRemovals": "bool, default false - let the change order delete board parts that are on no sheet", "keepBoardOnly": "bool - run it and leave board-only parts (on no sheet) on the board, with their nets", "detail": "bool - open the change order and list every row (and what would be unticked) without running it", "removeBoardOnlyClasses": "bool, default false - let it remove the board's own net classes, differential pairs, rules and rooms (kept by default)", "confirm": "yes | no (default no) - the answer to a painted Yes/No 'Confirm' Altium raises during the update; read its question in altiumAsked first", "timeout": "seconds, default 300"}),+            json!({"executed": "bool", "preview": "{addParts, removeParts, sheetParts, boardParts}", "altiumAsked": "[{title, pressed, shot}] - Yes/No questions Altium asked, photographed once painted; errorCode altium_asked when a No stopped the update", "changeOrder": "[string] - the dialog's first page (groups carry counts)", "afterExecute": "[string]", "steps": "[..]", "dialogs": "[..] - anything Altium asked", "board": "path"}), 600,             "Preview first (the default): removeParts are board parts on no sheet (test pads, fiducials, mounting holes) that the change order would DELETE; it refuses them unless allowRemovals:true. New parts land beside the board outline: place them (altium_move_parts) and check with altium_routing_drc.",             &["annotate", "sch_place_part", "move_parts", "routing_drc"],             &["Save the sheets first (the sch_* verbs save by default).", "The project must contain a .PcbDoc."],
package.json+1−1
@@ -1,6 +1,6 @@ {   "slug": "altium-bridge",-  "version": "0.2.102",+  "version": "0.2.103",   "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.102",+  "version": "0.2.103",   "hero": {     "type": "image",     "path": "screenshots/hero.png"
src/BRIDGE_VERSION+1−1
@@ -1 +1 @@-0.2.102+0.2.103
src/bridge.json+1−1
@@ -2,7 +2,7 @@   "manifest_version": 1,   "name": "altium",   "displayName": "Altium Designer",-  "version": "0.2.102",+  "version": "0.2.103",   "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",