← Commit history

altium-bridge 0.2.91: a halted agent no longer takes the bridge down (#30); engineParked in readiness, status, agent_status and check_dialogs; panics answer as errors with a crash log; 0.2.90 release record

Colby Knox ·097bf1eb55 · ·parent db48e3c
12 files changed +236−19
CHANGELOG.md+11
@@ -1,5 +1,16 @@ # Changelog +## 0.2.91++- **A halted agent no longer takes the bridge down** (#30). When the agent stopped in Altium's script debugger right after it started, every agent verb, `agent_start` and `agent_recover` included, healed it by recovering and starting again, and each start met the same halt and began the next recover. Nothing ended the loop: the bridge restarted the agent about every 30 s, raised Altium's Error box each time, and the request thread's stack eventually ran out, which ends the whole process with no log (197 restarts on one machine). Now a start or recover never heals from inside itself:+  - `agent_start` answers `agent_halted_after_start` with Altium's own error box (`errorShot`) and stops the script, so Altium is not left on a breakpoint.+  - `agent_recover` ends with `agent_halts_on_start` after its second try, and stops the script again.+  - An agent verb gives the same honest answer. The bridge stays up throughout.+- **A script parked in Altium's debugger is now reported.** `readiness`, `status`, `agent_status` and `check_dialogs` answer `engineParked: true` with what to do, when the agent's script is stopped on a breakpoint with no dialog (the state where Altium refuses to close a document or exit). `agent_recover` frees it, verified by starting a fresh agent.+- **An internal error answers as an error.** A panic in a verb used to drop the connection, which reads as a dead bridge; it now answers `bridge_panic` and is written to `altium-bridge-crash.log` beside the exe, a log that survives restarts. Request threads get a 16 MB stack.+- `agent_recover` stops each open agent script once (the same tab was found up to four times), and gets a 240 s budget: it verifies by starting the agent, twice if needed.+- Tested on Altium Designer Develop 26.9 with the agent made to halt on its first command (a test hook the agent ignores unless the bridge's tests drop its flag file): 0.2.90 looped for six minutes; 0.2.91 answered in 20 to 27 s with the same bridge process, and recovered a real breakpoint halt in 12 s.+ ## 0.2.90  - **Eleven verbs new in the standard** (EDA Bridge Standard #29, 0.30.14):
bridge-rs/src/agent.rs+86
@@ -20,6 +20,56 @@ use std::time::{Duration, Instant, SystemTime}; pub const ALIVE_SEC: u64 = 60; pub const RESPONSIVE_SEC: u64 = 3; +// adom/altium-bridge#30: `call` heals a dead or halted agent by running `recover` and `start`, and both of those call+// the agent again (`start` closes old agent projects, `recover` verifies by starting). When the agent halted every time+// it ran, each heal began the next one, with no end: the request thread's stack ran out and the whole process died with+// no log, about every 90 s (197 respawns on one machine). While a start or recover is in progress on this thread, agent+// calls made inside it never heal; they answer what they found.+thread_local! {+    static HEALING: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };+}++/// Held for the length of a `lifecycle::start` or `recover`: agent calls under it do not heal.+pub struct HealGuard;+impl HealGuard {+    pub fn enter() -> HealGuard {+        HEALING.with(|h| h.set(h.get() + 1));+        HealGuard+    }+}+impl Drop for HealGuard {+    fn drop(&mut self) {+        HEALING.with(|h| h.set(h.get().saturating_sub(1)));+    }+}++/// True inside a start or recover on this thread.+pub fn healing() -> bool {+    HEALING.with(|h| h.get() > 0)+}++/// Altium is running, the agent's own script is the document in front, and its loop stopped without exiting: a clean+/// exit (agent_stop, auto-stop, Altium closing) deletes hb.txt, a script parked in Altium's debugger (a breakpoint or a+/// runtime error) leaves it behind and it goes stale. Nothing in this state answers, and Altium refuses to close a+/// document or exit until the script is stopped. Every workspace is looked at, not only the selected one: a respawned+/// bridge has no instance selected yet, and the parked loop's hb.txt sits in its instance folder (found testing #30).+/// A loop busy in one long command of THIS bridge also stops heartbeating, so a command in flight is not a park.+/// `recover` deletes hb.txt, so this reads false after a recover whatever happened.+pub fn engine_parked() -> bool {+    const PARKED_AFTER: Duration = Duration::from_secs(15);+    if IN_FLIGHT.lock().map(|g| g.is_some()).unwrap_or(false) {+        return false;+    }+    let root = agent_root();+    let mut dirs = vec![root.clone()];+    if let Ok(rd) = std::fs::read_dir(&root) {+        dirs.extend(rd.flatten().map(|e| e.path()).filter(|p| p.is_dir()));+    }+    let ages: Vec<Duration> = dirs.iter().filter_map(|d| hb_age(d)).collect();+    !ages.is_empty() && ages.iter().all(|a| *a > PARKED_AFTER)+        && crate::health::is_running() && is_agent_script_title(&main_title())+}+ pub fn cache_dir() -> PathBuf {     let local = std::env::var("LOCALAPPDATA").unwrap_or_else(|_| r"C:\Users\Public".into());     PathBuf::from(local).join("Adom Bridge").join("bridges-cache").join("altium")@@ -121,6 +171,10 @@ const PCB_EDIT_COMMANDS: &[&str] = &["add_body", "add_rule", "apply_pours", "app     "remove_pours", "set_outline", "set_rule", "swap_footprint", "test_board", "xcopy_footprint"];  pub fn call(command: &str, params: &[(&str, String)], payload: Option<&str>, timeout: Duration) -> Value {+    if !is_alive() && healing() {+        return json!({"success": false, "errorCode": "agent_not_running", "command": command,+            "error": format!("the agent loop is not running, and '{command}' was asked for during an agent start or recover, which does not start another one")});+    }     if !is_alive() {         // A dead agent with Altium still showing the agent's script is a script PARKED ON A         // BREAKPOINT: Altium's debugger breaks on any raised exception, even one the agent's own@@ -195,6 +249,14 @@ pub fn call_in(ws: &std::path::Path, command: &str, params: &[(&str, String)], p             "_hint": "The agent runs ONE command at a time inside Altium. Wait and retry, or if busyForSec is far beyond what that command should take: altium_check_dialogs (a box may be blocking it), then altium_agent_recover."});     }     if let Ok(mut g) = IN_FLIGHT.lock() { *g = Some((command.to_string(), Instant::now())); }+    // cleared on every way out, so "a command is in flight" means one is (engine_parked reads it; it used to stay set)+    struct ClearInFlight;+    impl Drop for ClearInFlight {+        fn drop(&mut self) {+            if let Ok(mut g) = IN_FLIGHT.lock() { *g = None; }+        }+    }+    let _in_flight = ClearInFlight;     if let Some(p) = payload {         let tmp = ws.join("request.payload.tmp");         if std::fs::write(&tmp, p).is_ok() {@@ -263,10 +325,19 @@ pub fn call_in(ws: &std::path::Path, command: &str, params: &[(&str, String)], p                     "_hint": "READ errorShot (PNG of Altium's box, e.g. 'Undeclared identifier: X at Line:N'). The bridge answered OK so the agent loop is still resident; fix the script text and send it again."});             }             if let Some(ev) = crate::dialogs::script_error_since(posted_unix_ms) {+                if healing() {+                    // inside a start or recover: that caller frees the engine; a recover from here would start the+                    // agent, meet the same error and recover again (#30)+                    return json!({"success": false, "errorCode": "agent_script_error", "command": command,+                        "error": format!("the agent script raised a runtime error while running '{command}' (Altium showed an 'Error' box; its text is in errorShot)"),+                        "errorShot": ev.get("shot").cloned().unwrap_or(Value::Null), "agentAlive": is_alive()});+                }                 let recovered = crate::lifecycle::recover(&format!("auto: script Error box during agent command '{command}'"));                 // a board edit halted between PCBServer.PreProcess and PostProcess leaves Altium "in a command":                 // every later save is refused until it is closed                 let rebalanced = if PCB_EDIT_COMMANDS.contains(&command) {+                    // under a guard: a postprocess that raised too would otherwise recover and postprocess again (#30)+                    let _g = HealGuard::enter();                     Some(call("pcb_postprocess", &[], None, Duration::from_secs(30)).get("data").and_then(|d| d.get("ok")).cloned().unwrap_or(Value::Null))                 } else { None };                 return json!({"success": false, "errorCode": "agent_script_error", "command": command,@@ -309,6 +380,21 @@ pub fn is_agent_script_title(title: &str) -> bool { mod halt_tests {     use super::*; +    #[test]+    fn heal_guard_nests_and_clears() {+        assert!(!healing());+        {+            let _a = HealGuard::enter();+            assert!(healing());+            {+                let _b = HealGuard::enter();+                assert!(healing());+            }+            assert!(healing(), "the outer start or recover is still running");+        }+        assert!(!healing());+    }+     #[test]     fn one_spelling_per_windows_path() {         assert_eq!(win_path("C:/x/y\\a.PcbLib"), "C:\\x\\y\\a.PcbLib");
bridge-rs/src/lifecycle.rs+49−1
@@ -452,7 +452,22 @@ fn start_modal_watcher() -> (std::sync::Arc<std::sync::atomic::AtomicBool>, std:  // ---- start / stop / recover -------------------------------------------------- -pub fn start(mut wait: Duration) -> Value {+pub fn start(wait: Duration) -> Value {+    let top = !agent::healing();+    let _g = agent::HealGuard::enter();+    let out = start_impl(wait);+    // #30: the agent came up and halted at once. A start that is not itself part of a recover frees the engine here,+    // once, so Altium is not left parked on the agent's script (it then refuses to close documents or exit).+    if top && out.get("errorCode").and_then(|c| c.as_str()) == Some("agent_halted_after_start") {+        let mut out = out;+        let freed = recover_without_restart("agent_start: the agent halted right after it started");+        out["engineStopped"] = freed.get("steps").cloned().unwrap_or(Value::Null);+        return out;+    }+    out+}++fn start_impl(mut wait: Duration) -> Value {     // NEVER bootstrap into the legacy workspace. Every hard freeze in adom/altium-bridge#6     // traces back to an agent that started with no instance resolved (auto-launch cold starts,     // and once a transient resolve miss right after an Altium restart): the loop lands in the@@ -543,6 +558,17 @@ pub fn start(mut wait: Duration) -> Value {                 // Projects panel; ten were stacked there by 2026-10-15)                 let c = agent::call("close_old_agents", &[], None, Duration::from_secs(30));                 out["oldAgentProjectsClosed"] = c.get("data").and_then(|d| d.get("closed")).cloned().unwrap_or(Value::Null);+                // the first command after the heartbeat is the proof the loop serves: an agent that heartbeat once and+                // then raised a script error, or went quiet, is not running whatever its heartbeat file says (#30)+                let code = c.get("errorCode").and_then(|e| e.as_str()).unwrap_or("");+                if c.get("success").and_then(|b| b.as_bool()) == Some(false)+                    && matches!(code, "agent_script_error" | "agent_timeout" | "agent_not_running") {+                    return json!({"success": false, "errorCode": "agent_halted_after_start", "firstCommand": "close_old_agents",+                        "firstCommandError": code, "error": c.get("error").cloned().unwrap_or(Value::Null),+                        "errorShot": c.get("errorShot").cloned().unwrap_or(Value::Null), "startedInSec": t0.elapsed().as_secs_f64(),+                        "dialogs": crate::dialogs::scan(), "install": inst,+                        "_hint": "The agent script started in Altium and stopped on its first command. READ errorShot when it is present: it is Altium's own error box, naming the line. The bridge has sent the stop, so Altium is not left on a breakpoint (if Altium still refuses to close a document, press Stop on its Debug toolbar). Please report it on adom/altium-bridge with this reply, the Altium version and errorShot: it is a bug in the agent on this Altium build."});+                }                 if retried {                     out["resentBootstrap"] = json!(true);                     out["_hint"] = json!("The first RunScript hand-off was swallowed (Altium was busy); the bridge sent it again and the agent came up. Nothing for the caller to do.");@@ -699,6 +725,7 @@ pub fn recover_without_restart(reason: &str) -> Value { }  fn recover_impl(reason: &str, verify_by_restart: bool) -> Value {+    let _g = agent::HealGuard::enter();     let mut steps: Vec<Value> = vec![json!({"reason": reason})];     // A modal orphan answers NOTHING: every -R below would bounce off "another instance is busy"     // and each bounce spawns a helper X2. Say so instead of thrashing for 10 s.@@ -745,6 +772,10 @@ fn recover_impl(reason: &str, verify_by_restart: bool) -> Value {     let open_tabs: Vec<String> = main.map(|hw| ab::call("desktop_find_controls", json!({"hwnd": hw, "contains": "AdomAgent_"}), &[], 20))         .and_then(|r| r.get("matches").and_then(|m| m.as_array()).cloned()).unwrap_or_default().iter()         .filter_map(|m| m.get("name").and_then(|n| n.as_str())).filter(|n| n.to_lowercase().ends_with(".pas")).map(str::to_string).collect();+    // one tab is found several times (its tab, the editor's caption, the Projects panel): stop each script once+    let mut open_tabs = open_tabs;+    open_tabs.sort();+    open_tabs.dedup();     if let (Some(exe), Some(hw)) = (x2_exe(), main.filter(|_| !open_tabs.is_empty())) {         // brought forward through Altium's own OpenObject when the script's file exists (no UI touched); a tab whose         // file a redeploy deleted (an older agent generation) can only be reached by its tab@@ -839,10 +870,27 @@ fn recover_impl(reason: &str, verify_by_restart: bool) -> Value {             let again = start(Duration::from_secs(45));             ok = again.get("success").and_then(|b| b.as_bool()) == Some(true) && agent::is_alive();             steps.push(json!({"secondTry": ok}));+            if !ok {+                // the verifying start ran the agent, and it halted again: stop it once more without starting, so this+                // recover never leaves Altium on the breakpoint it was asked to clear (#30)+                for k in ["errorCode", "errorShot", "firstCommand"] {+                    if let Some(v) = again.get(k).filter(|v| !v.is_null()) { steps.push(json!({k: v})); }+                }+                let stopped = recover_impl("the verifying start halted again", false);+                steps.push(json!({"stoppedAgain": stopped.get("steps").cloned().unwrap_or(Value::Null)}));+            }         }         verified = json!(ok);     }     let freed = verified.as_bool().unwrap_or(true);+    // #30: the engine was freed, but the agent halts every time it starts. Not the same answer as a parked engine:+    // Altium is usable by hand and closes normally, and nothing the caller clicks will change it.+    let halts_on_start = !freed+        && steps.iter().any(|s| s.get("errorCode").and_then(|c| c.as_str()) == Some("agent_halted_after_start"));+    if halts_on_start {+        return json!({"success": false, "engineFree": verified, "steps": steps, "errorCode": "agent_halts_on_start",+            "_hint": "The bridge stopped the script again after each try, so Altium should close normally (if it refuses, press Stop on its Debug toolbar), but the agent halts on its first command every time it starts, so agent verbs cannot run on this Altium. steps holds Altium's own error box (errorShot) when it showed one. Please report it on adom/altium-bridge with this reply and the Altium version: it is a bug in the agent on this Altium build. Verbs that do not need the agent (status, readiness, check_dialogs, windows, screenshots) still work."});+    }     json!({"success": freed, "engineFree": verified, "steps": steps,            "errorCode": if freed { Value::Null } else { json!("engine_still_parked") },            "_hint": if !verify_by_restart { "Sent the stop to every agent script; NOT verified (no agent loop was started, because the caller is about to close Altium)." }
bridge-rs/src/main.rs+42−3
@@ -79,7 +79,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.90";+pub const BRIDGE_VERSION: &str = "0.2.91";  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());@@ -88,6 +88,31 @@ fn json_response(status: u16, body: &serde_json::Value) -> Response<std::io::Cur         .with_header(Header::from_bytes("Content-Type", "application/json").unwrap()) } +/// Append-only, beside the exe: the bridge's stdout log is rewritten on every respawn, so a crash erased its own cause+/// (#30: 197 respawns and one banner line).+fn crash_log_path() -> std::path::PathBuf {+    std::env::current_exe().ok().and_then(|p| p.parent().map(|d| d.to_path_buf()))+        .unwrap_or_else(std::env::temp_dir).join("altium-bridge-crash.log")+}++fn install_crash_log() {+    std::panic::set_hook(Box::new(|info| {+        let thread = std::thread::current().name().unwrap_or("?").to_string();+        let line = format!("[{}] bridge {BRIDGE_VERSION} panic in thread {thread}: {info}\n",+            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0));+        eprint!("{line}");+        let path = crash_log_path();+        // keep it small: start over past 256 KB+        if std::fs::metadata(&path).map(|m| m.len() > 256 * 1024).unwrap_or(false) {+            let _ = std::fs::remove_file(&path);+        }+        if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&path) {+            use std::io::Write;+            let _ = f.write_all(line.as_bytes());+        }+    }));+}+ fn main() {     let args: Vec<String> = std::env::args().collect();     let port: u16 = args@@ -112,8 +137,11 @@ fn main() {     // bridge kept grinding the abandoned request, and the queue only grew (the 30-verb cascades the     // verb battery found, 2026-09-20). Agent-bound work still serialises where it must: the agent's     // one-file inbox, which now answers a NAMED agent_busy instead of a dropped connection.+    install_crash_log();     for mut req in server.incoming_requests() {-        let spawned = std::thread::Builder::new().name("altium-request".into()).spawn(move || {+        // 16 MB, not the 2 MB default: a request runs Altium's whole lifecycle (start, recover, their checks) on its own+        // thread, and a stack overflow ends the PROCESS with no log at all (adom/altium-bridge#30)+        let spawned = std::thread::Builder::new().name("altium-request".into()).stack_size(16 << 20).spawn(move || {         let t0 = Instant::now();         let path = req.url().to_string();         let method = req.method().clone();@@ -134,7 +162,18 @@ fn main() {                     Ok(v) => {                         let command = v.get("command").and_then(|c| c.as_str()).unwrap_or("").to_string();                         let vargs = v.get("args").cloned().unwrap_or_else(|| serde_json::json!({}));-                        let mut out = verbs::handle(&command, &vargs, &forwarded);+                        // a panic answers as an error, never as a dropped connection the caller reads as a dead bridge (#30)+                        let mut out = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| verbs::handle(&command, &vargs, &forwarded))) {+                            Ok(v) => v,+                            Err(p) => {+                                let msg = p.downcast_ref::<String>().cloned()+                                    .or_else(|| p.downcast_ref::<&str>().map(|s| s.to_string())).unwrap_or_else(|| "(no message)".into());+                                serde_json::json!({"success": false, "errorCode": "bridge_panic", "command": command,+                                    "error": format!("the bridge hit an internal error running '{command}': {msg}"),+                                    "crashLog": crash_log_path().to_string_lossy(),+                                    "_hint": "A bug in altium-bridge, not in Altium. The bridge is still running. Please report it with this reply and the crash log's last lines."})+                            }+                        };                         if let Some(o) = out.as_object_mut() {                             // Bridge SDK: invite the bug report IN THE OUTPUT, on every failure. The AI driving                             // this bridge is standing on the one machine where the failure happened and holds
bridge-rs/src/misc.rs+10−1
@@ -40,6 +40,8 @@ pub fn prewarm(_args: &Value) -> Value {         "_hint": "Run it again any time: a step already done is skipped. ready: installed, the agent's script written, and, with Altium running, the agent resident."}) } +const PARKED_HINT: &str = "The agent's script is PARKED in Altium's script debugger (stopped on a breakpoint or after a runtime error): no agent verb can run, and Altium refuses to close a document or exit until it is stopped. altium_agent_recover stops it; if engineParked stays true, ask the user to press Stop on Altium's Debug toolbar (Debug > Stop).";+ pub fn readiness(_args: &Value) -> Value {     let inst = support::first_install();     let lic = instance::licence_state();@@ -61,6 +63,8 @@ pub fn readiness(_args: &Value) -> Value {     } else if licensed == Some(false) {         format!("Altium is running but the title says {:?} — scripting is refused without a licence. altium_license '{{}}' drives the trial/On-Demand flow.",             lic.get("state").and_then(|st| st.as_str()).unwrap_or("?"))+    } else if !alive && agent::engine_parked() {+        PARKED_HINT.to_string()     } else if !alive {         "Licensed and running; the agent loop is not resident — altium_agent_start (≈8s), then drive.".to_string()     } else {@@ -69,6 +73,7 @@ pub fn readiness(_args: &Value) -> Value {     let mut out = json!({"success": true, "hostApp": support::HOST_APP, "installed": inst.is_some(), "install": inst,         "running": running, "licensed": licensed, "licenceState": lic.get("state"),         "adVersion": lic.get("adVersion"), "agentAlive": alive, "agentResidentAnywhere": resident_anywhere,+        "engineParked": running && !alive && agent::engine_parked(),         "ready": ready, "engine": "rust", "_hint": hint});     // Surface a loop that is resident somewhere the current selection does not point at — the exact     // blind spot behind #6. It is a live freeze-on-close hazard until torn down (altium_close does@@ -118,7 +123,11 @@ pub fn agent_status(_args: &Value) -> Value {             json!({"workspace": ws.to_string_lossy(), "heartbeatAgeSec": age})).collect::<Vec<_>>(),         "heartbeat": agent::heartbeat(), "workspace": agent::workspace_dir().to_string_lossy(),         "engine": "rust"});-    if alive && !agent::is_responsive() {+    let parked = !alive && agent::engine_parked();+    out["engineParked"] = json!(parked);+    if parked {+        out["_hint"] = json!(PARKED_HINT);+    } else if alive && !agent::is_responsive() {         out["_hint"] = json!("Loop is alive but busy inside a long Altium process (no heartbeat while a RunProcess runs). Wait; do not start a second agent.");     } else if resident_anywhere && !alive {         // the #6 blind spot: a loop is resident in a workspace the selection does not point at
bridge-rs/src/verbs.rs+15−9
@@ -205,10 +205,11 @@ fn describe() -> Value {         verb_doc("describe", "This list - the bridge's verbs and schemas for ab's Verbs tab.", json!({}), json!({"verbs": "[{name, summary, input, output, ...}]"}), 5, "Static; safe to call any time.", &["status"], &[], json!({})),         // ---- health / lifecycle ----         verb_doc("readiness", "The one-call gate: is Altium installed, running, licensed, and is the resident agent alive? Answers with Altium closed and never touches the script engine.", json!({}),-            json!({"installed": "bool", "install": "{base_dir, exe, system_dir, major} | null", "running": "bool", "licensed": "bool | null", "licenceState": "string", "adVersion": "string | null", "agentAlive": "bool - the selected instance", "agentResidentAnywhere": "bool - any workspace", "ready": "bool - all four true", "agentLiveWorkspaces": "[{workspace, heartbeatAgeSec}] - only when a loop lives outside the selection"}), 15,+            json!({"installed": "bool", "install": "{base_dir, exe, system_dir, major} | null", "running": "bool", "licensed": "bool | null", "licenceState": "string", "adVersion": "string | null", "agentAlive": "bool - the selected instance", "agentResidentAnywhere": "bool - any workspace", "engineParked": "bool - the agent's script is stopped in Altium's debugger", "ready": "bool - all four true", "agentLiveWorkspaces": "[{workspace, heartbeatAgeSec}] - only when a loop lives outside the selection"}), 15,             "Follow _hint: not installed -> altium_install; not running -> altium_launch; licensed:false -> altium_ensure_licensed; agent down -> just call the verb you need (it bootstraps the agent) or altium_agent_start. ready:true -> altium_state.",             &["status", "launch", "ensure_licensed", "agent_start"],-            &["agentAlive is the SELECTED instance's view. agentResidentAnywhere:true beside agentAlive:false means a loop lives in another workspace: close through altium_close, never the window X."], json!({})),+            &["agentAlive is the SELECTED instance's view. agentResidentAnywhere:true beside agentAlive:false means a loop lives in another workspace: close through altium_close, never the window X.",+              "engineParked:true = the agent's script is stopped on a breakpoint in Altium's debugger, with no dialog: nothing agent-backed runs and Altium refuses to close. altium_agent_recover stops it (#30)."], json!({})),         verb_doc("diagnostics", "Bridge-side facts for a bug report: environment variables, every Altium install found, Altium's windows, the agent status block and the cache directory.", json!({}),             json!({"env": "{LOCALAPPDATA, APPDATA, USERPROFILE, ProgramFiles, ADOM_BIND_HOST, ADOM_DIRECT_API_URL}", "installs": "[{base_dir, exe, system_dir, major}] newest major first", "windows": "[{hwnd, title, kind, className, pid, rect}]", "agent": "the altium_agent_status reply", "cacheDir": "path"}), 15,             "installs:[] means Altium is not installed (altium_install). Otherwise altium_readiness for the verdict and altium_instances when several Altiums run.",@@ -226,7 +227,7 @@ fn describe() -> Value {               "shots[] are full-size base64 PNGs of every main and dialog window; pass screenshots:false when you only need the data."], json!({"screenshots": false})),         verb_doc("check_dialogs", "List every Altium dialog currently open, classified, each with a screenshot (the only way to READ one: Altium paints its dialog text).",             json!({"screenshots": "bool, default true"}),-            json!({"dialogsDetected": "int", "dialogs": "[{hwnd, pid, title, className, body, buttons, category, safeAction, meaning, ownedByMainInstance, rect, shot: base64 png}]"}), 30,+            json!({"dialogsDetected": "int", "dialogs": "[{hwnd, pid, title, className, body, buttons, category, safeAction, meaning, ownedByMainInstance, rect, shot: base64 png}]", "engineParked": "bool - no dialog, but the agent's script is stopped in Altium's debugger: altium_agent_recover"}), 30,             "READ dialogs[].shot, decide, then altium_dismiss_dialogs {button, titles:[..]}. A script 'Error' box: altium_agent_recover. A save prompt on close: see altium_close discardChanges.",             &["dismiss_dialogs", "dialog_log", "agent_recover", "window_info"],             &["category and safeAction are suggestions. A save_prompt is never auto-answered: it names documents that may belong to the user or another AI thread.",@@ -267,23 +268,25 @@ fn describe() -> Value {             &["agent_status", "agent_stop", "agent_recover", "eval"],             &["The bootstrap ACTIVATES Altium for a moment (it opens the .PrjScr in the script editor); the bridge hands the user's foreground window back.",               "no_heartbeat = the engine halted behind a script Error modal: altium_check_dialogs, then altium_agent_recover.",+              "agent_halted_after_start = the agent came up and stopped on its first command (errorShot is Altium's box). The bridge already stopped the script, so Altium is not left parked; it is a bug in the agent on this Altium build: report it with errorShot (#30).",               "The loop exits by itself 15 s after the last request (while it runs Altium ignores the user's clicks, #27); the next verb restarts it in 2.5-4 s. Call altium_agent_stop when you hand Altium back to the user."], json!({})),         verb_doc("agent_stop", "Stop the selected instance's resident agent loop (drops a stop file and waits up to 12 s for the heartbeat to go stale).", json!({}),             json!({"wasRunning": "bool", "stoppedInSec": "float"}), 20,             "Call it when you hand Altium back to the user: while the loop is resident Altium ignores their clicks (it also stops by itself 15 s after the last verb). Needed before altium_run_script (the -R lanes refuse while a loop is resident). altium_close stops every workspace's loop itself. The next agent-backed verb restarts the agent. Clears the 'Adom is driving' taskbar badge.",             &["agent_start", "agent_status", "run_script", "close"], &["'the loop did not exit' -> altium_agent_recover.", "With several Altiums running pass instance: to stop the right loop."], json!({})),         verb_doc("agent_status", "Is the agent loop alive and responsive, in which workspace, and is any loop resident anywhere? Read-only; never starts the agent.", json!({}),-            json!({"alive": "bool - selected instance", "responsive": "bool", "residentAnywhere": "bool", "liveWorkspaces": "[{workspace, heartbeatAgeSec}]", "heartbeat": "{ageSec, tick, ...} | null", "workspace": "path"}), 10,+            json!({"alive": "bool - selected instance", "responsive": "bool", "residentAnywhere": "bool", "liveWorkspaces": "[{workspace, heartbeatAgeSec}]", "heartbeat": "{ageSec, tick, ...} | null", "workspace": "path", "engineParked": "bool"}), 10,             "alive with responsive:false = the loop is busy inside a long Altium process: wait, do not start a second agent. Not alive: call the verb you need, it bootstraps.",             &["agent_start", "agent_recover", "readiness"], &["residentAnywhere:true with alive:false is a freeze-on-close hazard: altium_close tears every loop down before the app exits."], json!({})),         verb_doc("agent_recover", "Un-halt the script engine: clear the PCB transaction, press OK on open Altium dialogs, send EditScript:Stop, reap the busy notice and delete stale request files.",             json!({"reason": "string - optional, recorded in steps"}),-            json!({"steps": "[{reason} | {dialog, pressed} | {editScriptStop, exited, sec} | busy-notice reap]"}), 60,+            json!({"steps": "[{reason} | {dialog, pressed} | {editScriptStop, exited, sec} | busy-notice reap]", "engineFree": "bool - verified by starting a fresh agent"}), 240,             "Use after agent_timeout / no_heartbeat / instance_busy, or when Altium sits on AdomAgent_*.pas in its debugger. Then call your verb again: it restarts the agent. Never ask the user to click.",             &["check_dialogs", "agent_start", "dialog_log", "selftest_script_error"],             &["A modal orphan (main window disabled, no dialog on screen) answers nothing: recover refuses with altium_modal_orphan instead of firing -R hand-offs that all bounce off 'another instance is busy'. Escape it with altium_close {discardChanges:true}.",-              "It presses OK on EVERY Altium dialog it finds, not only the script Error box: altium_check_dialogs first if a save prompt may be up.",-              "An agent_script_error reply was ALREADY recovered by the bridge (autoRecovered): do not recover again, and do not resend the same command - it will halt again."],+              "It presses OK only on the script Error box (a lone OK titled Error or X2). Any other dialog, a save prompt included, stops it with blocked_by_dialog: read it with altium_check_dialogs.",+              "An agent_script_error reply was ALREADY recovered by the bridge (autoRecovered): do not recover again, and do not resend the same command - it will halt again.",+              "agent_halts_on_start = the engine was freed, but the agent stops on its first command every time it starts, so agent verbs cannot run on this Altium: report it with steps[].errorShot. recover never loops on it (#30)."],             json!({"reason": "agent_timeout on read_board"})),         verb_doc("run_script", "One shot: run a procedure of YOUR OWN .PrjScr through Altium's -R command line. Only for when the agent is NOT resident.",             json!({"prjscr": "absolute path to a .PrjScr on this machine (required)", "proc": "string, default 'Main'", "timeout": "seconds, default 60"}),@@ -1855,8 +1858,11 @@ pub fn dispatch(command: &str, args: &Value, _forwarded: &[(String, String)]) ->             if args.get("screenshots").and_then(|b| b.as_bool()).unwrap_or(true) {                 crate::shot::attach_dialog_shots(&mut d);             }-            json!({"success": true, "dialogsDetected": d.len(), "dialogs": d,-                   "_hint": if d.is_empty() { "No Altium dialogs open." } else {+            // #30: a script parked in the debugger has no dialog, yet blocks everything; say so here, where callers look+            let parked = crate::agent::engine_parked();+            json!({"success": true, "dialogsDetected": d.len(), "dialogs": d, "engineParked": parked,+                   "_hint": if parked { "No dialog is open, but the agent's script is PARKED in Altium's script debugger: no agent verb can run and Altium refuses to close until it is stopped. altium_agent_recover stops it; if engineParked stays true, ask the user to press Stop on Altium's Debug toolbar." }+                       else if d.is_empty() { "No Altium dialogs open." } else {                        "ANALYZE before acting: category/safeAction are suggestions; a save prompt is never auto-answered." }})         }         "dismiss_dialogs" => {
package.json+1−1
@@ -1,6 +1,6 @@ {   "slug": "altium-bridge",-  "version": "0.2.90",+  "version": "0.2.91",   "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.90",+  "version": "0.2.91",   "hero": {     "type": "image",     "path": "screenshots/hero.png"
scripts/releases/0.2.90.jsonadded+15
@@ -0,0 +1,15 @@+{+  "name": "altium",+  "version": "0.2.90",+  "url": "https://wiki.adom.inc/download/adom/altium-bridge/0.2.90/adom-bridge-altium-v0.2.90.zip",+  "sha256": "ae37ab8fa2b16e17e4eb09ad277f31658d97b95936a8fc1113a7f831dd0da836",+  "size": 4006955,+  "verbPrefixes": [+    "altium_"+  ],+  "healthEndpoint": "/health",+  "updateManifestUrl": "https://wiki.adom.inc/api/v1/pages/altium-bridge/files/adom-bridge-altium-manifest.json",+  "insidersManifestUrl": "https://wiki.adom.inc/api/v1/pages/insiders/files/altium-bridge/version.json",+  "released_at": "2026-11-03T20:34:52.397622Z",+  "tier": "insiders"+}
src/BRIDGE_VERSION+1−1
@@ -1 +1 @@-0.2.90+0.2.91
src/agent/AdomAgent.pas.tmpl+3
@@ -9618,6 +9618,9 @@ End;  Function CmdCloseOldAgents(Lines : TStringList) : String; Begin+    { test hook for adom/altium-bridge#30, inert unless the bridge's tests drop this file: an agent that halts on its+      first command after starting }+    If FileExists(WORKSPACE + 'test_halt_after_start') Then AdomDeliberateUndeclaredIdentifierForSelfTest(30);     Result := '{' + JRaw('ok','true') + ',' + JRaw('closed', IntToStr(CloseOldAgents)) + '}'; End; 
src/bridge.json+2−2
@@ -2,7 +2,7 @@   "manifest_version": 1,   "name": "altium",   "displayName": "Altium Designer",-  "version": "0.2.90",+  "version": "0.2.91",   "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",@@ -329,7 +329,7 @@       "placement_check": 180,       "auto_classes": 180,       "length_tune": 120,-      "agent_start": 120,+      "agent_start": 120, "agent_recover": 240,       "run_outjob": 600,       "silk_state": 180,       "apply_silkscreen": 600,