← Commit history

v2.1.8: Two fixes from adom/adom-parts-search#14 (John, on a Linux Hydrogen box):

Colby Knox ·d633c2f9d7 · ·parent d5abf71
11 files changed +82−69
Cargo.lock+1−1
@@ -10,7 +10,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"  [[package]] name = "adom-parts-search"-version = "2.1.7"+version = "2.1.8" dependencies = [  "base64",  "clap",
Cargo.toml+1−1
@@ -1,6 +1,6 @@ [package] name = "adom-parts-search"-version = "2.1.7"+version = "2.1.8" 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.7+2.1.8
install.sh

  
package.json+1−40
@@ -34,44 +34,5 @@     "SKILL.md",     "BUILD-SKILL.md",     "CHANGELOG.md"-  ],-  "changelog": "Two fixes from adom/adom-parts-search#14 (John, on a Linux Hydrogen box):",-  "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+}
src/app/mod.rs+2−2
@@ -232,7 +232,7 @@ fn build_status(state: &AppState) -> Value {         "_hint": "adom-parts-search show \"LM555\" runs a search and renders it here"}));     let boxes = taskbar::list_targets();     let pinned = s.taskbar_box.trim().to_string();-    let target_box = if pinned.is_empty() { boxes.first().cloned() } else { Some(pinned) };+    let target_box = taskbar::resolve_target(&pinned);     let target_info = json!({"box": target_box, "connected": !boxes.is_empty()});     let fails = leds.iter().filter(|l| l.get("state").and_then(|s| s.as_str()) == Some("fail")).count();     let warns = leds.iter().filter(|l| l.get("state").and_then(|s| s.as_str()) == Some("warn")).count();@@ -419,7 +419,7 @@ fn demo_caption(state: &AppState, step: Option<u32>, text: &str) {     let _ = step;     std::thread::spawn(move || {         use std::process::{Command, Stdio};-        let target = if pinned.trim().is_empty() { crate::taskbar::list_targets().into_iter().next() } else { Some(pinned.trim().to_string()) };+        let target = crate::taskbar::resolve_target(&pinned);         let Some(target) = target else { return };         let args = if text.is_empty() { json!({"action": "hide", "id": "parts-search-demo"}) }             else { json!({"id": "parts-search-demo", "text": text, "duration": 60000}) };
src/app/ui.html+4−4
@@ -617,10 +617,10 @@ select.sel:disabled{opacity:.5;cursor:not-allowed}         <div class="wrapper">           <h4 class="name" title="taskbarBox"><span class="prefix">Taskbar: </span><span class="title">Desktop box</span></h4>           <div class="setting-row">-            <select class="sel" id="selBox" aria-label="Desktop box carrying the taskbar button"><option value="">First connected box</option></select>+            <select class="sel" id="selBox" aria-label="Desktop box carrying the taskbar button"><option value="">This machine</option></select>             <span class="set-check-label">which Adom Desktop to paint on</span>           </div>-          <span class="default-hint">Default: First connected box</span>+          <span class="default-hint">Default: This machine</span>         </div>       </div>     </section>@@ -982,7 +982,7 @@ function paintSettings(){ } async function openSettings(){   try{const r=await fetch('api/settings');const d=await r.json();if(d.settings)Object.assign(settings,d.settings);remember();-    const sb=$('#selBox');const cur=settings.taskbarBox;sb.innerHTML='<option value="">First connected box</option>'+(d.boxes||[]).map(b=>'<option value="'+escape(b)+'">'+escape(b)+'</option>').join('');sb.value=cur;+    const sb=$('#selBox');const cur=settings.taskbarBox;sb.innerHTML='<option value="">This machine</option>'+(d.boxes||[]).map(b=>'<option value="'+escape(b)+'">'+escape(b)+'</option>').join('');sb.value=cur;     $('#settingsStatus').textContent=(d.boxes||[]).length?((d.boxes||[]).length+' desktop box'+((d.boxes||[]).length>1?'es':'')+' connected'):'no desktop box connected';   }catch{}   paintSettings();paintVendorStatus();@@ -1003,7 +1003,7 @@ function bindToggle(id,key,label){$(id).addEventListener('click',()=>{const prev bindToggle('#tglInStock','inStockOnly','In stock only by default');bindToggle('#tglMouser','vendorMouser','Mouser');bindToggle('#tglDigikey','vendorDigikey','DigiKey');bindToggle('#tglJlcpcb','vendorJlcpcb','JLCPCB'); bindToggle('#tglImages','showImages','Product photos');bindToggle('#tglTaskbar','taskbarProgress','Taskbar progress bar');bindToggle('#tglSay','showSayStrip','Say it strip'); $('#policySet').addEventListener('change',e=>{const v=e.target.value;if(!v||v===settings.policy)return;const prev={policy:settings.policy};saveSettings({policy:v},prev).then(ok=>{if(ok){toast('Policy: '+(v==='cheapest'?'cheapest in stock':'Mouser preferred')+'. Run the search again to re-rank.','success');if(lastResults)renderRecommendation(lastResults.recommendation,lastResults.empty_state,lastResults.policy);}});});-$('#selBox').addEventListener('change',e=>{const prev={taskbarBox:settings.taskbarBox};saveSettings({taskbarBox:e.target.value},prev).then(ok=>{if(ok)toast('Taskbar bar paints on '+(settings.taskbarBox||'the first connected box'),'success');});});+$('#selBox').addEventListener('change',e=>{const prev={taskbarBox:settings.taskbarBox};saveSettings({taskbarBox:e.target.value},prev).then(ok=>{if(ok)toast('Taskbar bar paints on '+(settings.taskbarBox||'this machine'),'success');});}); (function(){const btn=$('#btnRestore'),lbl=$('#restoreLabel'),ic=$('#restoreIcon');let armed=false,t=null;   const RESTORE='M13 3a9 9 0 0 0-9 9H1l3.89 3.89.07.14L9 12H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42A8.954 8.954 0 0 0 13 21a9 9 0 0 0 0-18m-1 5v5l4.28 2.54.72-1.21-3.5-2.08V8z';   const ALERT='M11 15h2v2h-2v-2m0-8h2v6h-2V7m1-5C6.47 2 2 6.5 2 12a10 10 0 0 0 10 10 10 10 0 0 0 10-10A10 10 0 0 0 12 2m0 18a8 8 0 0 1-8-8 8 8 0 0 1 8-8 8 8 0 0 1 8 8 8 8 0 0 1-8 8z';
src/settings.rs+1−1
@@ -25,7 +25,7 @@ pub struct Settings {     pub show_images: bool,     /// Paint a progress bar on the Hydrogen taskbar button while a search runs.     pub taskbar_progress: bool,-    /// Which Adom Desktop box carries the taskbar button ("" = first connected).+    /// Which Adom Bridge machine carries the taskbar button and captions ("" = this machine; see taskbar::resolve_target).     pub taskbar_box: String,     /// Show the "Say it to your AI" strip at the top of the page. The X on     /// the strip turns this off; Settings turns it back on.
src/taskbar.rs+41−5
@@ -40,14 +40,50 @@ pub fn record_ms(ms: u64) {     let _ = std::fs::write(timing_path(), serde_json::to_string_pretty(&v).unwrap_or_default()); } -/// Which box? Settings can pin one; otherwise the first connected target.+/// Which box? The one the dashboard runs on, unless the user picked another (adom/adom-parts-search#14: on a Linux+/// box it painted John's laptop, the first target listed). Order: the box pinned in Settings, this machine+/// (`adom-bridge targets` thisMachine), the primary machine, a target named like this host. Never "whichever is+/// listed first": a progress bar or a caption on someone else's screen is worse than none. /// Resolved per run (cheap, ~10ms) so a box that reconnects is found.-fn resolve_target(pinned: &str) -> Option<String> {+pub fn resolve_target(pinned: &str) -> Option<String> {     if !pinned.trim().is_empty() { return Some(pinned.trim().to_string()); }-    let out = Command::new("adom-bridge").arg("targets")-        .stdin(Stdio::null()).output().ok()?;+    let out = Command::new("adom-bridge").arg("targets").stdin(Stdio::null()).output().ok()?;     let v: Value = serde_json::from_slice(&out.stdout).ok()?;-    v.get("targets")?.as_array()?.first()?.get("name")?.as_str().map(|s| s.to_string())+    let host = std::fs::read_to_string("/etc/hostname").ok().map(|h| h.trim().to_string()).filter(|h| !h.is_empty())+        .or_else(|| std::env::var("HOSTNAME").ok());+    choose_target(&v, host.as_deref())+}++fn choose_target(v: &Value, host: Option<&str>) -> Option<String> {+    let names: Vec<String> = v.get("targets").and_then(|t| t.as_array()).map(|a| a.iter()+        .filter_map(|t| t.get("name").and_then(|n| n.as_str()).map(String::from)).collect()).unwrap_or_default();+    let listed = |n: &str| names.iter().find(|x| x.eq_ignore_ascii_case(n)).cloned();+    let field = |k: &str| v.get(k).and_then(|x| x.as_str()).map(str::trim).filter(|s| !s.is_empty());+    field("thisMachine").and_then(listed)+        .or_else(|| field("primaryMachine").and_then(listed))+        .or_else(|| host.and_then(listed))+}++#[cfg(test)]+mod target_tests {+    use super::choose_target;+    use serde_json::json;+    fn targets(this: Option<&str>, primary: Option<&str>) -> serde_json::Value {+        json!({"thisMachine": this, "primaryMachine": primary,+               "targets": [{"name": "AdomLapper"}, {"name": "m5-ubuntu"}, {"name": "winvm"}]})+    }+    /// adom/adom-parts-search#14: John's laptop was listed first and won on m5-ubuntu.+    #[test]+    fn this_machine_beats_the_first_listed() {+        assert_eq!(choose_target(&targets(Some("m5-ubuntu"), None), None).as_deref(), Some("m5-ubuntu"));+    }+    #[test]+    fn then_primary_then_hostname_then_nothing() {+        assert_eq!(choose_target(&targets(None, Some("winvm")), Some("m5-ubuntu")).as_deref(), Some("winvm"));+        assert_eq!(choose_target(&targets(None, None), Some("M5-Ubuntu")).as_deref(), Some("m5-ubuntu"));+        assert_eq!(choose_target(&targets(None, None), Some("elsewhere")), None, "never the first listed");+        assert_eq!(choose_target(&targets(Some("gone"), None), None), None, "thisMachine must be a listed target");+    } }  pub fn list_targets() -> Vec<String> {
src/vendors.rs+30−14
@@ -175,24 +175,26 @@ pub struct Recommendation { /// be filtered down to zero hits. fn filter_relevant(hits: &[VendorHit], query: &str) -> Vec<VendorHit> {     let q_lower = query.to_lowercase();-    // Primary token: longest alphanumeric run in the query.-    let primary: String = q_lower-        .split(|c: char| !c.is_ascii_alphanumeric())-        .filter(|s| s.len() >= 3)-        .max_by_key(|s| s.len())-        .unwrap_or("")-        .to_string();-    if primary.is_empty() {+    let words: Vec<&str> = q_lower.split(|c: char| !c.is_ascii_alphanumeric()).filter(|s| s.len() >= 3).collect();+    if words.is_empty() {         return hits.to_vec();     }-    hits.iter().filter(|h| {+    // A word counts when it is in the MPN, the description, or the MPN with its punctuation dropped (LCSC lists+    // PMEG6010CEJ,115 and EEEFK1H101P, so PMEG6010CEJ115 or EEE-FK1H101P must not throw the right part away,+    // adom/adom-jlcpcb#3).+    let found = |h: &VendorHit, w: &str| {         let mpn = h.mpn.to_lowercase();-        let desc = h.description.to_lowercase();-        // Also with the part number's punctuation dropped: LCSC lists PMEG6010CEJ,115 and EEEFK1H101P, so a search-        // for PMEG6010CEJ115 or EEE-FK1H101P must not throw the right part away here (adom/adom-jlcpcb#3).         let mpn_alnum: String = mpn.chars().filter(|c| c.is_ascii_alphanumeric()).collect();-        mpn.contains(&primary) || desc.contains(&primary) || mpn_alnum.contains(&primary)-    }).cloned().collect()+        mpn.contains(w) || h.description.to_lowercase().contains(w) || mpn_alnum.contains(w)+    };+    if words.len() == 1 {+        return hits.iter().filter(|h| found(h, words[0])).cloned().collect();+    }+    // Several words: a hit stays when it has at least half of them. Keying on the longest word alone dropped every+    // DigiKey hit for "10k 0402 resistor", since DigiKey writes "RES 10K OHM 1% 1/16W 0402" (adom/adom-parts-search#14);+    // half keeps those (10k + 0402) and still drops a 0402 capacitor (0402 only).+    let need = (words.len() + 1) / 2;+    hits.iter().filter(|h| words.iter().filter(|w| found(h, w)).count() >= need).cloned().collect() }  #[cfg(test)]@@ -212,6 +214,20 @@ mod relevance_tests {         // an unrelated "popular part" answer is still filtered out         assert_eq!(filter_relevant(&[hit("CL05B104KO5NNNC")], "PMEG6010CEJ115").len(), 0);     }++    fn hit_desc(mpn: &str, desc: &str) -> VendorHit { let mut h = hit(mpn); h.description = desc.into(); h }++    /// adom/adom-parts-search#14: DigiKey abbreviates "resistor" to RES, and every DigiKey hit was dropped.+    #[test]+    fn a_keyword_query_keeps_hits_that_match_most_words() {+        let dk = hit_desc("CRCW040210K0FKED", "RES 10K OHM 1% 1/16W 0402");+        let mouser = hit_desc("RC0402FR-0710KL", "Thick Film Resistors - SMD 10 kOhms 0402");+        let cap = hit_desc("CL05B104KO5NNNC", "CAP CER 0.1UF 16V X7R 0402");+        let kept = filter_relevant(&[dk, mouser, cap], "10k 0402 resistor");+        assert_eq!(kept.iter().map(|h| h.mpn.as_str()).collect::<Vec<_>>(), ["CRCW040210K0FKED", "RC0402FR-0710KL"]);+        // two words: one is enough+        assert_eq!(filter_relevant(&[hit_desc("X", "RES 10K OHM 0402")], "10k resistor").len(), 1);+    } }  /// Translate a raw backend error into a short title + longer explanation
uninstall.sh