← Commit history

v2.1.10: Every request to the wiki says where Parts Search runs (the CLI thread, PR #7), so the wiki can tell Hydrogen traffic from cloud containers and bare machines and keep scheduled runs out of its people stats.

Colby Knox ·75e82bac1a · ·parent deb4abb
13 files changed +155−91
Cargo.lock+1−1
@@ -10,7 +10,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"  [[package]] name = "adom-parts-search"-version = "2.1.9"+version = "2.1.10" dependencies = [  "base64",  "clap",
Cargo.toml+1−1
@@ -1,6 +1,6 @@ [package] name = "adom-parts-search"-version = "2.1.9"+version = "2.1.10" edition = "2021" description = "Parts Search Electronics component search — CLI, backend HTTP service, and Hydrogen webview app" license = "MIT"
VERSION+1−1
@@ -1 +1 @@-2.1.9+2.1.10
install.sh

  
package.json+1−40
@@ -34,44 +34,5 @@     "SKILL.md",     "BUILD-SKILL.md",     "CHANGELOG.md"-  ],-  "changelog": "Every request to the wiki says where Parts Search runs (the CLI thread, PR #7), so the wiki can tell Hydrogen traffic from cloud containers and bare machines and keep scheduled runs out of its people stats.",-  "discovery_triggers": [-    "parts search",-    "find part",-    "source component",-    "source part",-    "compare distributors",-    "compare vendors",-    "Mouser or DigiKey",-    "BOM sourcing",-    "price this part",-    "where can I get",-    "check stock",-    "parts availability",-    "fastest delivery",-    "cheapest part",-    "component search",-    "part lookup",-    "price breaks"-  ],-  "discovery_pitch": "Search Mouser, DigiKey and JLCPCB in parallel with product photos; Mouser-preferred best-source pick. Say 'with parts search' to your AI.",-  "sample_prompts": [-    {-      "label": "source an STM32F103RBT6",-      "prompt": "source an STM32F103RBT6"-    },-    {-      "label": "where can I get an ESP32-S3-WROOM cheape",-      "prompt": "where can I get an ESP32-S3-WROOM cheapest and fastest"-    },-    {-      "label": "compare Mouser, DigiKey and JLCPCB for a",-      "prompt": "compare Mouser, DigiKey and JLCPCB for an LM555"-    },-    {-      "label": "price this BOM across distributors",-      "prompt": "price this BOM across distributors"-    }   ]-}\ No newline at end of file+}
page.json+8−45
@@ -33,25 +33,13 @@   },   "hero": {     "type": "image",-    "path": "screenshots/hero.png"+    "path": "docs/hero.png"   },   "sample_prompts": [-    {-      "label": "source an STM32F103RBT6",-      "prompt": "source an STM32F103RBT6"-    },-    {-      "label": "where can I get an ESP32-S3-WROOM cheape",-      "prompt": "where can I get an ESP32-S3-WROOM cheapest and fastest"-    },-    {-      "label": "compare Mouser, DigiKey and JLCPCB for a",-      "prompt": "compare Mouser, DigiKey and JLCPCB for an LM555"-    },-    {-      "label": "price this BOM across distributors",-      "prompt": "price this BOM across distributors"-    }+    "source an STM32F103RBT6",+    "where can I get an ESP32-S3-WROOM cheapest and fastest",+    "compare Mouser, DigiKey and JLCPCB for an LM555",+    "price this BOM across distributors"   ],   "discovery_triggers": [     "parts search",@@ -66,37 +54,12 @@     "where can I get",     "check stock",     "parts availability",-    "fastest delivery",-    "cheapest part",-    "component search",-    "part lookup",-    "price breaks"+    "fastest delivery"   ],-  "discovery_pitch": "Search Mouser, DigiKey and JLCPCB in parallel with product photos; Mouser-preferred best-source pick. Say 'with parts search' to your AI.",+  "discovery_pitch": "Search Mouser + DigiKey + JLCPCB in parallel from one interface, with product photos and a Mouser-preferred best-source pick.",   "metadata": {     "platform": "linux"   },   "category": "tools",-  "org": "adom",-  "description": "One search box across Mouser, DigiKey and JLCPCB. Parallel queries, side-by-side product photos, and a Mouser-preferred recommendation that reasons around stock and lead time. Dock Bar ready: serve, health, settings, Say it.",-  "dependencies": {},-  "needs_sudo": false,-  "scripts": {-    "install": "./install.sh",-    "uninstall": "./uninstall.sh"-  },-  "files": [-    "bin/**",-    "skills/**",-    "docs/icon.svg",-    "dockbar.json",-    "install.sh",-    "uninstall.sh",-    "package.json",-    "README.md",-    "SKILL.md",-    "BUILD-SKILL.md",-    "CHANGELOG.md"-  ],-  "changelog": "Every request to the wiki says where Parts Search runs (the CLI thread, PR #7), so the wiki can tell Hydrogen traffic from cloud containers and bare machines and keep scheduled runs out of its people stats."+  "org": "adom" }\ No newline at end of file
publish.sh+1−1
@@ -181,7 +181,7 @@ ok "registry tarball clean + release binary returns --version $VERSION" step "7. push page repo (dockbar.json, docs, screenshots, source)" PAGE_FILES=(dockbar.json docs/icon.svg README.md SKILL.md BUILD-SKILL.md CHANGELOG.md VERSION Cargo.toml Cargo.lock   package.json page.json build.sh publish.sh install.sh uninstall.sh LICENSE-  src/main.rs src/cli.rs src/install.rs src/serve.rs src/settings.rs src/taskbar.rs src/vendors.rs src/wiki.rs+  src/main.rs src/cli.rs src/install.rs src/serve.rs src/settings.rs src/taskbar.rs src/vendors.rs src/wiki.rs src/host.rs   src/app/mod.rs src/app/tab.rs src/app/ui.html src/app/vendor/newbie-panel.js skills/adom-parts-search-dock/SKILL.md) for f in src/app/audio/demo-*.mp3 src/app/audio/narration.json; do [ -f "$f" ] && PAGE_FILES+=("$f"); done for f in src/app/fonts/*.woff2 screenshots/*.png docs/hero.png; do [ -f "$f" ] && PAGE_FILES+=("$f"); done
src/app/mod.rs+1−1
@@ -181,7 +181,7 @@ fn vendor_led(label: &str, key: &str, enabled: bool, last: Option<&Value>) -> Va fn probe_wiki() -> Value {     let agent = ureq::AgentBuilder::new().timeout(Duration::from_millis(2500)).build();     let t0 = Instant::now();-    match agent.get(&format!("{}/health", crate::wiki::DEFAULT_WIKI)).set("X-Adom-Caller", "parts-search-status").call() {+    match crate::host::tag(agent.get(&format!("{}/health", crate::wiki::DEFAULT_WIKI)).set("X-Adom-Caller", "parts-search-status")).call() {         Ok(_) => { let ms = t0.elapsed().as_millis() as u64;             json!({"label": "Wiki", "state": "ok", "short": format!("{} ms", ms), "detail": format!("wiki.adom.inc reachable, {} ms", ms),                    "_hint": "Every search also asks the Adom wiki: a component page with ready-made CAD, Verified, Adom stock"}) }
src/host.rsadded+136
@@ -0,0 +1,136 @@+//! X-Adom-Host: which Adom host launched this CLI, so the wiki can tell local+//! Hydrogen traffic from cloud containers and bare machines. The first rule+//! that matches wins:+//! 1. ADOM_HOST, when set and not empty (any launcher can claim its CLIs);+//! 2. the first line of ~/.adom/host (Hydrogen rewrites it on every launch);+//! 3. `cloud` when /var/run/adom/api-key exists (an Adom cloud container);+//! 4. the OS name: windows, macos or linux.+//!+//! Read once per process, never cached across runs. Only a short, cleaned+//! name and version goes out: never a path, a username or a machine name.++use std::path::Path;+use std::sync::OnceLock;++pub const HEADER: &str = "X-Adom-Host";+const MAX_LEN: usize = 80;++pub fn value() -> &'static str {+    static V: OnceLock<String> = OnceLock::new();+    V.get_or_init(|| {+        let home = std::env::var_os("HOME")+            .or_else(|| std::env::var_os("USERPROFILE"))+            .filter(|h| !h.is_empty())+            .map(std::path::PathBuf::from);+        detect(+            std::env::var("ADOM_HOST").ok().as_deref(),+            home.as_deref().map(|h| h.join(".adom").join("host")).as_deref(),+            Path::new("/var/run/adom/api-key"),+            os_name(),+        )+    })+}++fn os_name() -> &'static str {+    match std::env::consts::OS {+        "macos" => "macos",+        "windows" => "windows",+        _ => "linux",+    }+}++fn detect(env: Option<&str>, host_file: Option<&Path>, cloud_key: &Path, os: &str) -> String {+    if let Some(v) = env.map(clean).filter(|v| !v.is_empty()) {+        return v;+    }+    if let Some(v) = host_file+        .and_then(|p| std::fs::read_to_string(p).ok())+        .and_then(|s| s.lines().next().map(clean))+        .filter(|v| !v.is_empty())+    {+        return v;+    }+    if cloud_key.exists() {+        return "cloud".into();+    }+    os.into()+}++/// Keep `[A-Za-z0-9._+/ -]`, trimmed, at most 80 characters.+fn clean(s: &str) -> String {+    let kept: String = s+        .trim()+        .chars()+        .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '+' | '/' | ' ' | '-'))+        .take(MAX_LEN)+        .collect();+    kept.trim().to_string()+}++/// X-Adom-Run: `background` when ADOM_RUN=background (a scheduled or hook+/// run, such as adom/hook's cron), so the wiki counts it as background traffic+/// rather than a person. A normal run sends nothing.+pub const RUN_HEADER: &str = "X-Adom-Run";++pub fn run_background() -> bool {+    is_background(std::env::var("ADOM_RUN").ok().as_deref())+}++/// Both headers on one ureq request.+pub fn tag(req: ureq::Request) -> ureq::Request {+    let req = req.set(HEADER, value());+    if run_background() { req.set(RUN_HEADER, "background") } else { req }+}++fn is_background(v: Option<&str>) -> bool {+    v.map(|s| s.trim().eq_ignore_ascii_case("background")).unwrap_or(false)+}++#[cfg(test)]+mod tests {+    use super::*;++    fn dir(tag: &str) -> std::path::PathBuf {+        let d = std::env::temp_dir().join(format!("partssearch-host-{}-{tag}", std::process::id()));+        let _ = std::fs::remove_dir_all(&d);+        std::fs::create_dir_all(&d).unwrap();+        d+    }++    #[test]+    fn the_first_matching_rule_wins() {+        let d = dir("rules");+        let file = d.join("host");+        let key = d.join("api-key");+        // nothing present: the OS+        assert_eq!(detect(None, Some(&file), &key, "macos"), "macos");+        // a cloud container+        std::fs::write(&key, "k").unwrap();+        assert_eq!(detect(None, Some(&file), &key, "linux"), "cloud");+        // Hydrogen's file beats the cloud key; only the first line, trimmed+        std::fs::write(&file, "  hydrogen-desktop/1.0.780  \nsecond line\n").unwrap();+        assert_eq!(detect(None, Some(&file), &key, "linux"), "hydrogen-desktop/1.0.780");+        // ADOM_HOST beats everything; an empty one is ignored+        assert_eq!(detect(Some("adom-bridge/2.1.208"), Some(&file), &key, "linux"), "adom-bridge/2.1.208");+        assert_eq!(detect(Some("  "), Some(&file), &key, "linux"), "hydrogen-desktop/1.0.780");+        // an empty file falls through+        std::fs::write(&file, "\n").unwrap();+        assert_eq!(detect(None, Some(&file), &key, "linux"), "cloud");+    }++    #[test]+    fn values_are_cleaned_and_capped() {+        assert_eq!(clean("Claude Desktop/1.2 (C:\\Users\\me)"), "Claude Desktop/1.2 CUsersme");+        assert_eq!(clean("a\r\nb\u{e9}c"), "abc");+        assert_eq!(clean(&"x".repeat(200)).len(), 80);+    }++    #[test]+    fn only_adom_run_background_marks_the_run() {+        assert!(is_background(Some("background")));+        assert!(is_background(Some(" Background ")));+        assert!(!is_background(Some("")));+        assert!(!is_background(Some("foreground")));+        assert!(!is_background(None));+    }+}
src/install.rs+1−1
@@ -27,7 +27,7 @@ const WIKI_BUILD_SKILL_URL: &str = "https://wiki.adom.inc/api/v1/pages/adom/adom  fn fetch_or_fallback(url: &str, fallback: &'static str, label: &str) -> String {     let agent = ureq::AgentBuilder::new().timeout(Duration::from_secs(5)).build();-    match agent.get(url).call() {+    match crate::host::tag(agent.get(url)).call() {         Ok(r) => match r.into_string() {             Ok(body) if body.len() >= 200 => body,             _ => {
src/main.rs+1
@@ -11,6 +11,7 @@  mod app; mod cli;+mod host; mod install; mod serve; mod settings;
src/wiki.rs+3
@@ -189,6 +189,7 @@ pub fn post_route(r: &Route, body: Value) -> Result<Value, String> {     netlog("POST", &r.url);     let mut req = agent.post(&r.url).set("Content-Type", "application/json")         .set("User-Agent", concat!("adom-parts-search/", env!("CARGO_PKG_VERSION"))).set("X-Adom-Client", concat!("adom-parts-search/", env!("CARGO_PKG_VERSION")));+    req = crate::host::tag(req);     for (k, v) in &r.headers { req = req.set(k, v); }     match req.send_json(body) {         Ok(x) => x.into_json().map_err(|e| format!("JSON: {}", e)),@@ -216,6 +217,7 @@ fn get(base: &str, path: &str, tok: &Option<String>, secs: u64) -> Result<Value,     let mut req = agent.get(&format!("{}{}", base.trim_end_matches('/'), path))         .set("User-Agent", concat!("adom-parts-search/", env!("CARGO_PKG_VERSION")))         .set("X-Adom-Caller", "parts-search");+    req = crate::host::tag(req);     if let Some(t) = tok { req = req.set("Authorization", &format!("Bearer {}", t)); }     match req.call() {         Ok(r) => r.into_json().map_err(|e| format!("JSON: {}", e)),@@ -230,6 +232,7 @@ fn post(base: &str, path: &str, body: Value, tok: &Option<String>, secs: u64) ->     let mut req = agent.post(&format!("{}{}", base.trim_end_matches('/'), path))         .set("User-Agent", concat!("adom-parts-search/", env!("CARGO_PKG_VERSION")))         .set("X-Adom-Caller", "parts-search").set("Content-Type", "application/json");+    req = crate::host::tag(req);     if let Some(t) = tok { req = req.set("Authorization", &format!("Bearer {}", t)); }     match req.send_json(body) {         Ok(r) => r.into_json().map_err(|e| format!("JSON: {}", e)),
uninstall.sh