← Commit history

0.2.97: agent starts under a non-ASCII Windows user name (#30): ASCII-only workspace literal, BOM on non-ASCII request/spec files, \u escapes in replies; no recover after a clean idle stop

Colby Knox ·d989b65bbe · ·parent 3f77548
11 files changed +130−17
CHANGELOG.md+7
@@ -1,5 +1,12 @@ # Changelog +## 0.2.97++- **The agent starts when the Windows user name has accented or non-Latin letters** (#30). The agent's script carries its workspace folder, and the bridge wrote it as UTF-8 without a byte-order mark. Altium's script engine reads such a file as ANSI, so `C:\Users\Iván…` became `C:\Users\Iván…`, a folder that does not exist. The first heartbeat write failed, the script stopped in Altium's debugger, and `altium_agent_start` ended with `no_heartbeat`. The path is now written with Pascal character codes (`'Iv'#225'n'`), so the script file is plain ASCII and reads the same in any code page.+- **Accented paths and names in requests and replies.** Request files and spec files that contain non-ASCII text now carry a UTF-8 byte-order mark, which Altium reads as Unicode, so a document under such a folder opens. A spec file you pass in that is UTF-8 without one is copied with the mark. The agent writes every non-ASCII character in its replies as `\uXXXX`, where it used to write ANSI bytes the bridge could not read as UTF-8 and waited out the timeout.+- **No 23 s recovery after the agent idles.** The agent stops itself 15 s after the last verb. When Altium's title still named the agent's script (common right after Altium starts), the next verb read that as a script stuck in the debugger and ran a full recovery before starting the agent again. A clean stop is now recognised from the agent's own record, and the verb simply starts the agent (about 3 s). A start that halts before the agent writes anything is still caught.+- Tested on Altium Designer 26.11.1: a bridge whose workspace sat under a folder named with á, € and Ж started its agent in 3 s, and opened and reported `Placa_ñ.PcbDoc` with the name intact. After an idle stop with the agent script in the title, the next open took 4 s with no recovery. 22 lifecycle, board, footprint and symbol verbs passed.+ ## 0.2.96  - **A failed process query no longer reads as "Altium is not running".** Adom Bridge 2.1.189 limits its `process_list` query to 20 s and answers `process_query_failed` when it does not finish, where it used to return an empty list. A query slower than the bridge's own 15 s wait came back as `ab_unreachable`. In both cases the bridge saw no Altium, so verbs refused with `altium_not_running` while Altium was open. When `process_list` returns no list, the bridge now reads Altium's processes and executable paths from Windows itself, and the instance keys (`AD26`, `ADDevelop`) come out the same.
bridge-rs/src/agent.rs+48−3
@@ -116,6 +116,24 @@ pub fn parked_workspaces() -> Vec<PathBuf> {     }).collect() } +/// Whether this workspace's last loop exited cleanly: the agent writes `stoppedTick` into agent.json on the way out,+/// and recover writes it for the loops it stopped. Altium's title keeps naming the agent's script after a clean idle+/// stop, so the title alone sent every verb after a 15 s pause through a 23 s recover (#30). Pure over the file text.+pub fn stopped_cleanly_text(agent_json: &str) -> bool {+    agent_json.contains("\"stoppedTick\"")+}++fn stopped_cleanly(ws: &std::path::Path) -> bool {+    std::fs::read_to_string(ws.join("agent.json")).map(|t| stopped_cleanly_text(&t)).unwrap_or(false)+}++/// Before each StartAgent: a start that halts before the agent writes anything (a workspace path it cannot write, #30)+/// must not still read as the previous loop's clean stop.+pub fn mark_start_sent() {+    let ms = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0);+    let _ = std::fs::write(workspace_dir().join("agent.json"), json!({"startSentMs": ms}).to_string());+}+ /// After recover has sent the stop: record each parked loop as stopped, the way the agent would on a clean exit. pub fn mark_parked_stopped(why: &str) -> Vec<String> {     let mut out = Vec::new();@@ -246,7 +264,7 @@ pub fn call(command: &str, params: &[(&str, String)], payload: Option<&str>, tim         // script into a parked engine and block until ab's HTTP timeout, and so would every verb after         // it (the 30-verb cascade the battery found, 2026-09-20). Free the engine first.         let mut freed = Value::Null;-        if crate::health::is_running() && (is_agent_script_title(&main_title()) || engine_parked()) {+        if crate::health::is_running() && (engine_parked() || (is_agent_script_title(&main_title()) && !stopped_cleanly(&workspace_dir()))) {             crate::trace::step(&format!("call {command}: agent dead and the engine parked, recovering first"));             freed = crate::lifecycle::recover(&format!("auto: agent dead and the engine parked on the agent script before '{command}'"));             crate::dialogs::note_event(json!({"title": "(silent script halt)", "category": "engine_parked_cleared", "pressed": "EditScript:Stop", "ok": true,@@ -285,6 +303,33 @@ static IN_FLIGHT: std::sync::Mutex<Option<(String, Instant)>> = std::sync::Mutex /// 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.+/// Bytes for a text file the agent reads with `TStringList.LoadFromFile`. Altium's script engine reads a file with no+/// byte-order mark as ANSI, so UTF-8 `á` became `á` and a path under a profile like `C:\Users\Iván` did not exist+/// (#30). With a UTF-8 BOM it reads the text as Unicode (measured on AD 26.11.1). Plain ASCII is written as before.+pub fn agent_text(s: &str) -> Vec<u8> {+    if s.is_ascii() || s.starts_with('\u{feff}') {+        return s.as_bytes().to_vec();+    }+    let mut v = vec![0xEF, 0xBB, 0xBF];+    v.extend_from_slice(s.as_bytes());+    v+}++/// A caller's spec file for the agent: when it is UTF-8 with non-ASCII text and no BOM, a copy with the BOM is staged+/// in the agent workspace and its path returned, so `10 kΩ` reaches Altium as written. Any other file is used as is.+pub fn agent_readable(path: &str) -> String {+    let bytes = match std::fs::read(path) { Ok(b) => b, Err(_) => return path.to_string() };+    let text = match std::str::from_utf8(&bytes) { Ok(t) => t, Err(_) => return path.to_string() };+    if text.is_ascii() || text.starts_with('\u{feff}') {+        return path.to_string();+    }+    let staged = workspace_dir().join(format!("spec_{}.txt", &crate::lifecycle::sha256_hex(&bytes)[..12]));+    match std::fs::write(&staged, agent_text(text)) {+        Ok(()) => staged.to_string_lossy().to_string(),+        Err(_) => path.to_string(),+    }+}+ pub fn win_path(v: &str) -> String {     let b = v.as_bytes();     if b.len() >= 3 && b[0].is_ascii_alphabetic() && b[1] == b':' && (b[2] == b'/' || b[2] == b'\\') { v.replace('/', "\\") } else { v.to_string() }@@ -324,12 +369,12 @@ pub fn call_in(ws: &std::path::Path, command: &str, params: &[(&str, String)], p     let _in_flight = ClearInFlight;     if let Some(p) = payload {         let tmp = ws.join("request.payload.tmp");-        if std::fs::write(&tmp, p).is_ok() {+        if std::fs::write(&tmp, agent_text(p)).is_ok() {             let _ = std::fs::rename(&tmp, ws.join("request.payload"));         }     }     let tmp = ws.join("request.txt.tmp");-    if let Err(e) = std::fs::write(&tmp, format!("{}\r\n", lines.join("\r\n"))) {+    if let Err(e) = std::fs::write(&tmp, agent_text(&format!("{}\r\n", lines.join("\r\n")))) {         return json!({"success": false, "error": format!("cannot write request: {e}")});     }     if let Err(e) = std::fs::rename(&tmp, &inbox) {
bridge-rs/src/footprint.rs+1−1
@@ -49,7 +49,7 @@ pub fn from_land_pattern(args: &Value) -> Value {     let _ = std::fs::create_dir_all(&dir);     let safe: String = name.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect();     let path = dir.join(format!("{safe}.spec"));-    if let Err(e) = std::fs::write(&path, &text) { return json!({"success": false, "errorCode": "write_failed", "error": format!("{}: {e}", path.display())}); }+    if let Err(e) = std::fs::write(&path, crate::agent::agent_text(&text)) { return json!({"success": false, "errorCode": "write_failed", "error": format!("{}: {e}", path.display())}); }     let mut r = crate::library::build_footprint(&json!({"libraryPath": lib, "spec": path.to_string_lossy(), "timeout": 240}));     // a 3D body when the height is known: an extruded box the size of the body     let body = args.get("body").cloned().unwrap_or(json!({}));
bridge-rs/src/library.rs+4−4
@@ -123,7 +123,7 @@ pub fn build_footprint(args: &Value) -> Value {         return json!({"success": false, "error": "libraryPath (.PcbLib) and spec (Windows path to a kicad2altium spec) are required"});     }     with_shot(agent::call("build_footprint",-        &[("libraryPath", s_or(args, "libraryPath", "")), ("spec", s_or(args, "spec", ""))],+        &[("libraryPath", s_or(args, "libraryPath", "")), ("spec", agent::agent_readable(&s_or(args, "spec", "")))],         None, timeout_of(args, 240))) } @@ -135,7 +135,7 @@ pub fn build_symbol_modes(args: &Value) -> Value {         return json!({"success": false, "error": "libraryPath (.SchLib) and spec (Windows path to a symbol_modes spec) are required"});     }     with_shot(agent::call("build_symbol_modes",-        &[("libraryPath", s_or(args, "libraryPath", "")), ("spec", s_or(args, "spec", ""))],+        &[("libraryPath", s_or(args, "libraryPath", "")), ("spec", agent::agent_readable(&s_or(args, "spec", "")))],         None, timeout_of(args, 240))) } @@ -629,7 +629,7 @@ pub fn import_part(args: &Value) -> Value {             "_hint": "See the altium-part-import skill for the spec format; altium_create_footprint / altium_create_symbol build a single item."});     }     if let Some(spec) = s(args, "footprintSpec").filter(|v| !v.is_empty()) {-        let r = agent::call("build_footprint", &[("libraryPath", pcb_lib.clone()), ("spec", spec)], None, Duration::from_secs(240));+        let r = agent::call("build_footprint", &[("libraryPath", pcb_lib.clone()), ("spec", agent::agent_readable(&spec))], None, Duration::from_secs(240));         if r.get("success").and_then(|b| b.as_bool()) != Some(true) {             let mut out = r;             out["success"] = json!(false);@@ -656,7 +656,7 @@ pub fn import_part(args: &Value) -> Value {     let mut sym_name = s(args, "symbolName");     if let Some(spec) = s(args, "symbolSpec").filter(|v| !v.is_empty()) {         support::agent_open(&sch_lib, 60);-        let r = agent::call("build_symbol_modes", &[("libraryPath", sch_lib.clone()), ("spec", spec)], None, Duration::from_secs(240));+        let r = agent::call("build_symbol_modes", &[("libraryPath", sch_lib.clone()), ("spec", agent::agent_readable(&spec))], None, Duration::from_secs(240));         if r.get("success").and_then(|b| b.as_bool()) != Some(true) {             let mut out = r;             out["success"] = json!(false);
bridge-rs/src/lifecycle.rs+61−1
@@ -44,8 +44,29 @@ fn ws_str() -> String {     if s.ends_with('\\') { s } else { format!("{s}\\") } } +/// The inside of a Pascal string literal, in ASCII only: `'` doubled, and every other character outside printable ASCII+/// written as a `'#<code>'` character constant (UTF-16 units, so any character fits). The agent's own file is read as+/// ANSI, so a UTF-8 `Iván` in the workspace path became `Iván`, a folder that does not exist, and the first heartbeat+/// write halted the script (#30). Pure.+pub fn pascal_literal_inner(s: &str) -> String {+    let mut out = String::new();+    for c in s.chars() {+        if c == '\'' {+            out.push_str("''");+        } else if (' '..='~').contains(&c) {+            out.push(c);+        } else {+            let mut buf = [0u16; 2];+            for u in c.encode_utf16(&mut buf) {+                out.push_str(&format!("'#{u}'"));+            }+        }+    }+    out+}+ fn rendered(raw: &str) -> String {-    raw.replace("__WORKSPACE__", &ws_str().replace('\'', "''"))+    raw.replace("__WORKSPACE__", &pascal_literal_inner(&ws_str()))         .replace("__GEN__", &agent_base(raw)) } @@ -532,6 +553,7 @@ fn start_impl(mut wait: Duration) -> Value {     let user_fg = foreground_hwnd();     let t0 = Instant::now();     let strays = kill_stray_helpers();+    agent::mark_start_sent();     crate::trace::step("start: sending StartAgent");     let mut lane = run_script_lane("StartAgent", Duration::from_secs(30));     crate::trace::step(&format!("start: StartAgent lane -> success={:?} errorCode={:?}", lane.get("success"), lane.get("errorCode")));@@ -866,6 +888,10 @@ fn recover_impl(reason: &str, verify_by_restart: bool) -> Value {         let _ = std::fs::remove_file(ws.join(n));     }     let marked = agent::mark_parked_stopped("bridge recover");+    // a loop that halted before writing agent.json (#30) is stopped now too: say so, or the title reads it as parked again+    if !std::fs::read_to_string(ws.join("agent.json")).map(|t| agent::stopped_cleanly_text(&t)).unwrap_or(false) {+        let _ = std::fs::write(ws.join("agent.json"), json!({"stoppedTick": 0, "stoppedBy": "bridge recover"}).to_string());+    }     if !marked.is_empty() {         steps.push(json!({"parkedLoopsStopped": marked.len()}));     }@@ -1195,6 +1221,40 @@ pub fn sha256_hex(data: &[u8]) -> String { mod tests {     use super::sha256_hex; +    #[test]+    fn workspace_literal_is_ascii_for_any_user_name() {+        use super::pascal_literal_inner as lit;+        // ASCII paths are written exactly as before+        assert_eq!(lit(r"C:\Users\olive\AppData\"), r"C:\Users\olive\AppData\");+        assert_eq!(lit("O'Brien"), "O''Brien");+        // the profile from #30: á and é become character constants Altium reads the same in any code page+        let l = lit(r"C:\Users\IvánMéndez\");+        assert!(l.is_ascii());+        assert_eq!(l, r"C:\Users\Iv'#225'nM'#233'ndez\");+        // outside the BMP: both UTF-16 halves+        assert_eq!(lit("\u{1F600}"), "'#55357''#56832'");+    }++    #[test]+    fn only_a_recorded_clean_stop_clears_the_title_signal() {+        use crate::agent::stopped_cleanly_text as clean;+        assert!(clean(r#"{"version":"0.1.0","stoppedTick":118191359,"requests":5}"#));+        assert!(clean(r#"{"stoppedTick":0,"stoppedBy":"bridge recover"}"#));+        assert!(!clean(r#"{"version":"0.1.0","startedTick":118000200,"workspace":"C:\\x\\"}"#));+        assert!(!clean(r#"{"startSentMs":1794500000000}"#));+    }++    #[test]+    fn agent_text_marks_unicode_and_leaves_ascii_alone() {+        use crate::agent::agent_text;+        assert_eq!(agent_text("id=1\r\n"), b"id=1\r\n".to_vec());+        let t = agent_text("path=C:\\Users\\Iván\r\n");+        assert_eq!(&t[..3], &[0xEF, 0xBB, 0xBF]);+        assert_eq!(std::str::from_utf8(&t[3..]).unwrap(), "path=C:\\Users\\Iván\r\n");+        // already marked: not marked twice+        assert_eq!(agent_text("\u{feff}é").len(), "\u{feff}é".len());+    }+     #[test]     fn sha256_matches_reference_vectors() {         assert_eq!(sha256_hex(b""), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
bridge-rs/src/main.rs+1−1
@@ -80,7 +80,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.96";+pub const BRIDGE_VERSION: &str = "0.2.97";  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());
package.json+1−1
@@ -1,6 +1,6 @@ {   "slug": "altium-bridge",-  "version": "0.2.96",+  "version": "0.2.97",   "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+2−3
@@ -4,14 +4,13 @@   "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.96",+  "version": "0.2.97",   "hero": {     "type": "image",     "path": "screenshots/hero.png"   },   "author": {-    "name": "John Lauer",-    "email": "[email protected]"+    "name": "John Lauer"   },   "tags": [     "altium",
src/BRIDGE_VERSION+1−1
@@ -1 +1 @@-0.2.96+0.2.97
src/agent/AdomAgent.pas.tmpl+3−1
@@ -242,7 +242,9 @@ Begin         Else If C = #13 Then E := '\r'         Else If C = #10 Then E := '\n'         Else If C = #9 Then E := '\t'-        Else If Ord(C) < 32 Then E := ' ';+        Else If Ord(C) < 32 Then E := ' '+        { non-ASCII as \uXXXX: SaveToFile writes ANSI, which is not the UTF-8 the bridge reads (#30) }+        Else If Ord(C) > 126 Then E := '\u' + IntToHex(Ord(C), 4);         If E <> '' Then         Begin             If I > Start Then Result := Result + Copy(S, Start, I - Start);
src/bridge.json+1−1
@@ -2,7 +2,7 @@   "manifest_version": 1,   "name": "altium",   "displayName": "Altium Designer",-  "version": "0.2.96",+  "version": "0.2.97",   "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",