← Commit history
v2.1.0: Searches go through the Adom wiki only: wiki.adom.inc -> Component Ocean -> Mouser / DigiKey / JLCPCB (Ray, 2026-11-04, after John asked for native wiki search).
12 files changed
+345−334
Cargo.lock+1−1@@ -10,7 +10,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "adom-parts-search"-version = "2.0.18"+version = "2.1.0" dependencies = [ "base64", "clap",
Cargo.toml+1−1@@ -1,6 +1,6 @@ [package] name = "adom-parts-search"-version = "2.0.18"+version = "2.1.0" edition = "2021" description = "Parts Search Electronics component search — CLI, backend HTTP service, and Hydrogen webview app" license = "MIT"
VERSION+1−1@@ -1 +1 @@-2.0.18+2.1.0
install.shpackage.json+1−40@@ -38,44 +38,5 @@ "SKILL.md", "BUILD-SKILL.md", "CHANGELOG.md"- ],- "changelog": "Searches go through the Adom wiki only: wiki.adom.inc -> Component Ocean -> Mouser / DigiKey / JLCPCB (Ray, 2026-11-04, after John asked for native wiki search).",- "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"- } ]-}+}
page.json+8−49@@ -5,7 +5,6 @@ "title": "Parts Search", "brief": "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.", "version": "2.1.0",- "changelog": "Searches go through the Adom wiki only: wiki.adom.inc -> Component Ocean -> Mouser / DigiKey / JLCPCB (Ray, 2026-11-04, after John asked for native wiki search).", "install": { "binary_name": "adom-parts-search", "install_dir": "",@@ -34,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",@@ -67,40 +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": {- "adom/adom-mouser": "*",- "adom/adom-digikey": "*",- "adom/adom-jlcpcb": "*"- },- "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"- ]+ "org": "adom" }
src/app/mod.rs+68−37@@ -149,41 +149,62 @@ fn backends(state: &AppState) -> (String, String, String) { ) } -/// One vendor backend facet: probe /health with a 2.5s budget.-fn probe_backend(label: &str, url: &str, enabled: bool) -> Value {+/// One vendor's light, from how it answered in the last search (through the wiki and Component Ocean). No probe.+fn vendor_led(label: &str, key: &str, enabled: bool, last: Option<&Value>) -> Value { if !enabled { return json!({"label": label, "state": "warn", "short": "off", "detail": "switched off in Settings",- "_hint": "Turn it on in Settings (the cog) or `adom-parts-search settings set vendor{label} on`"});+ "_hint": format!("Turn it on in Settings (the cog) or `adom-parts-search settings set vendor{} on`", label)}); }+ let Some(b) = last.and_then(|r| r.get(key)) else {+ return json!({"label": label, "state": "ok", "short": "ready", "detail": format!("{} answers come through the Adom wiki and Component Ocean; no search yet", label),+ "_hint": "Run a search; this light then shows how the vendor answered"});+ };+ if b.get("ok").and_then(|x| x.as_bool()).unwrap_or(false) {+ let age = b.get("age_s").and_then(|x| x.as_u64());+ let short = match (b.get("from_cache").and_then(|x| x.as_bool()), age) {+ (Some(true), Some(a)) if a >= 3600 => format!("cached {}h", a / 3600),+ (Some(true), Some(a)) => format!("cached {}m", a / 60),+ (Some(false), _) => "live".to_string(),+ _ => "ok".to_string(),+ };+ json!({"label": label, "state": "ok", "short": short,+ "detail": format!("{} answered the last search through Component Ocean ({})", label, short),+ "_hint": "Component Ocean serves each vendor from its cache and fetches live only when stale"})+ } else {+ json!({"label": label, "state": "fail", "short": "no answer",+ "detail": b.get("error").and_then(|x| x.as_str()).unwrap_or("no answer in the last search").to_string(),+ "_hint": b.get("error_hint").and_then(|x| x.as_str()).unwrap_or("Retry in a minute").to_string()})+ }+}++/// The Wiki facet: wiki.adom.inc's /health with a 2.5s budget.+fn probe_wiki() -> Value { let agent = ureq::AgentBuilder::new().timeout(Duration::from_millis(2500)).build(); let t0 = Instant::now();- // Labelled, so the backends' usage stats can tell a status light from a person.- match agent.get(&format!("{}/health", url.trim_end_matches('/')))- .set("X-Adom-Caller", "parts-search-status").call() {- Ok(r) => {- let ms = t0.elapsed().as_millis() as u64;- let v: Value = r.into_json().unwrap_or(json!({}));- let ok = v.get("ok").and_then(|b| b.as_bool()).unwrap_or(true);- let mut detail = format!("reachable, {} ms", ms);- let mut st = if ok { "ok" } else { "warn" };- let mut quota_hit = false;- if let Some(q) = v.get("quota") {- let searches = q.get("searches").and_then(|n| n.as_u64()).unwrap_or(0);- quota_hit = q.get("first_quota_hit_ts").map(|t| !t.is_null()).unwrap_or(false);- detail = format!("{}; {} searches today", detail, searches);- if quota_hit { st = "warn"; detail.push_str("; daily quota hit, resets midnight CT"); }- }- let short = if st == "ok" { format!("{} ms", ms) } else if quota_hit { "quota hit".to_string() } else { "degraded".to_string() };- json!({"label": label, "state": st, "short": short, "detail": detail, "_hint": "Vendor backend answered its /health; no action needed"})- }- Err(e) => json!({"label": label, "state": "fail", "detail": format!("no answer: {}", crate::strip_ansi(&e.to_string()).chars().take(80).collect::<String>()),- "_hint": format!("The {} backend at {} is down or the slug rotated. Override with --{}-api or the {}_API env var, or ping an Adom admin.", label, url, label.to_lowercase(), label.to_uppercase())}),+ match 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"}) }+ Err(e) => json!({"label": "Wiki", "state": "fail", "short": "down",+ "detail": format!("wiki.adom.inc did not answer: {}", crate::strip_ansi(&e.to_string()).chars().take(80).collect::<String>()),+ "_hint": "Searches still reach the vendors; wiki pages and requests come back when it answers. Check https://wiki.adom.inc/health"}),+ }+}++/// The Requests facet: a part with no page can be requested only when signed in to the wiki (the wiki's own+/// request box asks a signed-out visitor for an email instead).+fn requests_led() -> Value {+ if crate::wiki::signed_in() {+ json!({"label": "Requests", "state": "ok", "short": "signed in", "detail": "signed in to the wiki: a part with no page can be requested",+ "_hint": "adom-parts-search request <MPN> asks Adom's factory to build it"})+ } else {+ json!({"label": "Requests", "state": "warn", "short": "signed out", "detail": "not signed in to the wiki: search works, requests need a sign-in",+ "_hint": "Run `adom-wiki auth login` (or set ADOM_WIKI_TOKEN), then search again"}) } } fn build_status(state: &AppState) -> Value { let s = state.settings.lock().unwrap().clone();- let (m, d, j) = backends(state); let cached = state.probe_cache.lock().unwrap().clone(); let reuse = cached.filter(|(at, v)| { let healthy = v.iter().all(|l| l.get("state").and_then(|x| x.as_str()) == Some("ok"));@@ -192,15 +213,14 @@ fn build_status(state: &AppState) -> Value { let mut leds: Vec<Value> = match reuse { Some((_, v)) => v, None => {- let (tx, rx) = std::sync::mpsc::channel();- for (label, url, on) in [("Mouser", m.clone(), s.vendor_mouser), ("DigiKey", d.clone(), s.vendor_digikey), ("JLCPCB", j.clone(), s.vendor_jlcpcb)] {- let tx = tx.clone();- std::thread::spawn(move || { let _ = tx.send((label, probe_backend(label, &url, on))); });- }- drop(tx);- let mut got: Vec<(&str, Value)> = rx.iter().collect();- got.sort_by_key(|(l, _)| match *l { "Mouser" => 0, "DigiKey" => 1, _ => 2 });- let v: Vec<Value> = got.into_iter().map(|(_, v)| v).collect();+ // no vendor service is probed (Ray, 2026-11-04: the app talks to wiki.adom.inc only): each vendor's light+ // says how it answered in the last search, through the wiki and Component Ocean+ let last = state.last_results.lock().unwrap().clone();+ let mut v: Vec<Value> = [("Mouser", "mouser", s.vendor_mouser), ("DigiKey", "digikey", s.vendor_digikey), ("JLCPCB", "jlcpcb", s.vendor_jlcpcb)]+ .into_iter().map(|(label, key, on)| vendor_led(label, key, on, last.as_ref())).collect();+ // the Adom wiki facet first: searched beside the vendors, and the only way to request a part+ v.insert(0, requests_led());+ v.insert(0, probe_wiki()); *state.probe_cache.lock().unwrap() = Some((Instant::now(), v.clone())); v }@@ -216,11 +236,13 @@ fn build_status(state: &AppState) -> Value { 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();- // Rollup we own: every backend down = fail; any backend down or a quota hit = warn.- let rollup = if fails >= 3 { "fail" } else if fails > 0 || warns > 0 { "warn" } else { "ok" };+ // Rollup we own: the wiki down = fail (every result comes through it); a vendor failing in the last search or+ // being signed out of the wiki = warn.+ let wiki_down = leds.iter().any(|l| l.get("label").and_then(|x| x.as_str()) == Some("Wiki") && l.get("state").and_then(|x| x.as_str()) == Some("fail"));+ let rollup = if wiki_down { "fail" } else if fails > 0 || warns > 0 { "warn" } else { "ok" }; json!({ "app": "adom-parts-search", "version": VERSION, "state": rollup, "label": "Parts Search",- "detail": match rollup { "ok" => "all three vendor backends reachable".to_string(), "fail" => "no vendor backend is reachable".to_string(), _ => format!("{} vendor backend(s) degraded", fails + warns) },+ "detail": match rollup { "ok" => "the Adom wiki is reachable; vendor results come through it".to_string(), "fail" => "the Adom wiki and the vendors behind it are not answering".to_string(), _ => format!("{} light(s) need attention: signed out, or a vendor failed in the last search", fails + warns) }, "leds": leds, "uptime_s": state.started.elapsed().as_secs(), "port": state.port,@@ -727,6 +749,15 @@ fn handle(mut req: Request, state: Arc<AppState>, no_tab: bool, tab_name: &str) "timing": {"search_avg_ms": taskbar::average_ms()}, "backends": { "mouser": backends(&state).0, "digikey": backends(&state).1, "jlcpcb": backends(&state).2 } }))+ } else if method == Method::Post && ends("/api/request") {+ // the page's Request button: the wiki's own request flow for a part with no page+ let body = read_body(&mut req).unwrap_or(json!({}));+ let mpn = body.get("mpn").and_then(|v| v.as_str()).unwrap_or("").trim().to_string();+ if mpn.is_empty() { (400, json!({"error": "mpn is required", "_hint": "POST /api/request {\"mpn\": \"LM2903L-Q1\"}"})) }+ else { match crate::wiki::request(&mpn, body.get("urgency").and_then(|v| v.as_str()).unwrap_or("now"), None) {+ Ok(v) => (200, v),+ Err(e) => (if e.starts_with("not signed in") { 401 } else { 502 }, json!({"error": e})),+ } } } else if method == Method::Post && (ends("/search") || ends("/api/search")) { match read_body(&mut req) { Ok(body) => {
src/app/ui.html+61−4@@ -182,6 +182,23 @@ main>:first-child{margin-top:0} .recommendation .prov{color:var(--text-2);font-size:12px;margin-top:4px} .recommendation.empty{background:linear-gradient(90deg,rgba(210,153,34,.10),rgba(210,153,34,.02));border-color:rgba(210,153,34,.35)} .recommendation.empty .label,.recommendation.empty .ricon{color:var(--yellow)}+.wikibox{border:1px solid var(--border);background:var(--surface);border-radius:14px;padding:14px 18px;margin-bottom:16px;animation:fadein .3s ease}+.wikibox.ready{border-color:rgba(0,184,177,.55);background:linear-gradient(90deg,rgba(0,184,177,.12),rgba(0,184,177,.02) 70%)}+.wikibox .wlabel{font:600 12px var(--brand-heading);letter-spacing:.02em;color:var(--accent)}+.wikibox .wmain{font:600 17px/1.3 var(--brand-heading);color:var(--text);margin-top:2px;overflow-wrap:anywhere}+.wikibox .wmain a{color:var(--text)}+.wikibox .chips{display:flex;flex-wrap:wrap;gap:6px;margin-top:8px}+.wikibox .chip{font:500 12px var(--brand-body);padding:2px 9px;border-radius:999px;border:1px solid var(--border);color:var(--text-2)}+.wikibox .chip.on{border-color:rgba(0,184,177,.55);color:var(--accent)}+.wikibox .chip.ver{border-color:rgba(63,185,80,.6);color:var(--green)}+.wikibox .chip.stale{border-color:rgba(210,153,34,.6);color:var(--yellow)}+.wikibox .chip.tag{border-color:rgba(140,107,247,.6);color:#b9a3ff}+.wikibox .wsub{color:var(--text-body);font-size:13px;margin-top:8px}+.wikibox .wlist{margin:8px 0 0;padding:0;list-style:none;display:grid;gap:4px}+.wikibox .wlist li{font-size:13px;color:var(--text-body);overflow-wrap:anywhere}+.wikibox .wlist a{color:var(--text)}+.wikibox .wact{margin-top:10px;display:flex;flex-wrap:wrap;gap:8px;align-items:center}+.wikibox .wnote{color:var(--text-2);font-size:12px;margin-top:6px} .recommendation .es-hint{color:var(--text-body);font-size:12.5px;margin-top:6px;padding-top:6px;border-top:1px dashed var(--border)} /* The three columns */@@ -429,6 +446,7 @@ select.sel:disabled{opacity:.5;cursor:not-allowed} <div class="examples" id="examples" aria-label="Example searches"><span class="ex-label">Try</span></div> <div id="status" class="statusline"></div> <div id="pbar" class="pbar"><div></div></div>+ <div id="wiki" aria-live="polite"></div> <div id="recommendation"></div> <div id="grid" class="grid">@@ -488,7 +506,7 @@ select.sel:disabled{opacity:.5;cursor:not-allowed} <section class="settings-card" id="card-search"> <h3 class="card-title">Search defaults <span class="card-status" id="stSearch"></span></h3>- <p class="card-desc">Every search goes to the vendors you have enabled below as one parallel request, and each vendor answers with up to this many hits. The limit is per vendor, so 5 means up to 15 cards. The search bar shows the same two controls; what you pick there applies to that one search, while what you pick here is where the bar starts next time, and what the CLI (<code>adom-parts-search search</code>) uses when no flag is given.</p>+ <p class="card-desc">Every search asks the Adom wiki for the vendors you have enabled below in one request, and each vendor answers with up to this many hits. The limit is per vendor, so 5 means up to 15 cards. The search bar shows the same two controls; what you pick there applies to that one search, while what you pick here is where the bar starts next time, and what the CLI (<code>adom-parts-search search</code>) uses when no flag is given.</p> <div class="wrapper"> <h4 class="name" title="defaultLimit"><span class="prefix">Search: </span><span class="title">Results per vendor</span></h4> <div class="setting-row">@@ -527,7 +545,7 @@ select.sel:disabled{opacity:.5;cursor:not-allowed} <section class="settings-card" id="card-vendors"> <h3 class="card-title">Vendors <span class="card-status" id="stVendors"></span></h3>- <p class="card-desc">Each vendor is reached through its own Adom backend service, which holds that vendor's API key so nothing secret lives on this machine: Mouser and DigiKey through their official search APIs, JLCPCB through a local mirror of the JLCPCB parts library. A vendor that is switched off is simply not queried; its column stays on the page and says so, so a missing column never looks like a vendor outage. The status beside each name is read live from the backend's own health endpoint, never cached from an earlier claim.</p>+ <p class="card-desc">Every search goes to the Adom wiki, which forwards it to Component Ocean; Component Ocean answers each vendor from its cache or asks Mouser, DigiKey and JLCPCB itself, so this page never calls a distributor and holds no vendor key. A vendor that is switched off is simply not asked for; its column stays on the page and says so, so a missing column never looks like a vendor outage. The light beside each name shows how that vendor answered in the last search (live, or from the cache and how old).</p> <div class="wrapper"> <h4 class="name" title="vendorMouser vendorDigikey vendorJlcpcb"><span class="prefix">Vendors: </span><span class="title">Query these vendors</span></h4> <div class="setting-row">@@ -818,7 +836,7 @@ function renderColumn(v,block){ } function skeleton(n){let h='';for(let i=0;i<Math.min(n||3,5);i++)h+='<div class="skel"><div class="b img"></div><div><div class="b l" style="width:60%"></div><div class="b l" style="width:40%"></div><div class="b l" style="width:85%"></div><div class="b l" style="width:50%;margin:0"></div></div></div>';return h;} function renderIdle(){- const idle={mouser:'Run a search to see Mouser results.',digikey:'1 to 3 day ground shipping; the alternative when Mouser is out.',jlcpcb:'Parts library for JLCPCB-assembled boards.'};+ $('#wiki').innerHTML='';const idle={mouser:'Run a search to see Mouser results.',digikey:'1 to 3 day ground shipping; the alternative when Mouser is out.',jlcpcb:'Parts library for JLCPCB-assembled boards.'}; for(const v of VENDORS){$('#body-'+v).innerHTML='<div class="col-empty">'+ICON_CHIP+'<span>'+idle[v]+'</span></div>';$('#meta-'+v).textContent='';} } function renderRecommendation(rec,emptyState,policy){@@ -834,14 +852,51 @@ function renderRecommendation(rec,emptyState,policy){ if(emptyState){el.innerHTML='<div class="recommendation empty"><svg class="ricon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M12 8v5M12 16h.01"/></svg><div style="flex:1;min-width:0"><div class="label">No source found</div><div class="main">'+escape(emptyState.title)+'</div><div class="reason">'+escape(emptyState.explanation)+'</div><div class="es-hint">'+escape(emptyState.hint)+'</div></div></div>';return;} el.innerHTML=''; }+function renderWiki(w,q){+ const el=$('#wiki');if(!w||w.skipped){el.innerHTML='';return;}+ if(!w.ok){el.innerHTML='<div class="wikibox"><div class="wlabel">Adom wiki</div><div class="wmain">The wiki did not answer</div><div class="wsub">'+escape(w.error||'')+' Retry in a minute.</div></div>';return;}+ const ex=(w.hits||[]).find(h=>h.exact);+ const chip=(on,t,cls)=>'<span class="chip'+(on?' on':'')+(cls?' '+cls:'')+'">'+escape(t)+'</span>';+ const others=(w.hits||[]).filter(h=>h!==ex).slice(0,4).map(h=>'<li><a href="'+escape(h.url)+'" target="_blank" rel="noopener">'+escape(h.mpn||h.ref)+'</a> '+escape(h.manufacturer||'')+(h.verified==='verified'?' · Verified':'')+'</li>').join('');+ if(ex){+ const c=ex.cad||{},a=ex.adom||null;+ el.innerHTML='<div class="wikibox ready"><div class="wlabel">Ready-made CAD on the Adom wiki</div>'+ +'<div class="wmain"><a href="'+escape(ex.url)+'" target="_blank" rel="noopener">'+escape(ex.mpn||ex.title)+'</a>'+(ex.manufacturer?' · '+escape(ex.manufacturer):'')+'</div>'+ +'<div class="chips">'+chip(c.symbol,'Symbol')+chip(c.footprint,'Footprint')+chip(c['3d'],'3D')+chip(c.step,'STEP')+chip(c.lbr,'.lbr')+ +(ex.verified==='verified'?chip(false,'Verified','ver'):ex.verified==='stale'?chip(false,'Verification out of date','stale'):'')+ +(ex.lifecycle&&ex.lifecycle!=='active'?chip(false,ex.lifecycle,'tag'):'')+ +(a?chip(false,'Adom # '+(a.part_number||'')+' · '+(a.stock==null?(a.kind==='adom-basic'?'Stocked by Adom':'not tracked'):a.stock+' at Adom'),'on'):'')+'</div>'+ +'<div class="wact"><a class="btn primary" href="'+escape(ex.url)+'" target="_blank" rel="noopener" data-tooltip="Open the component page: symbol, footprint, 3D model, STEP, Eagle library and datasheet, ready to download.">Open on the wiki '+ICON_EXT+'</a></div>'+ +(others?'<div class="wsub">Related pages</div><ul class="wlist">'+others+'</ul>':'')+'</div>';+ return;+ }+ const req=w.request;+ const cands=(w.candidates||[]).slice(0,8).map(c=>'<li>'+(c.page_url?'<a href="https://wiki.adom.inc'+escape(c.page_url)+'" target="_blank" rel="noopener">'+escape(c.mpn)+'</a> (page)':escape(c.mpn))+(c.manufacturer?' · '+escape(c.manufacturer):'')+(c.package?' · '+escape(c.package):'')+(c.lifecycle?' · <span class="chip tag">'+escape(c.lifecycle)+'</span>':'')+'</li>').join('');+ el.innerHTML='<div class="wikibox"><div class="wlabel">Adom wiki</div>'+ +'<div class="wmain">'+(req?'No page for '+escape(req.mpn)+' yet':'No exact page for "'+escape(q||'')+'"')+'</div>'+ +(req?'<div class="wsub">'+escape(req.message)+'</div><div class="wact"><button class="btn primary" id="btnRequest" data-mpn="'+escape(req.mpn)+'" data-tooltip="Asks Adom\'s factory to build the page, through the wiki\'s own request flow (needs a wiki sign-in). You get a status link and the place in the queue.">Request '+escape(req.mpn)+'</button><span class="wnote" id="reqStatus"></span></div>':'')+ +(cands?'<div class="wsub">Part numbers behind it</div><ul class="wlist">'+cands+'</ul>':'')+ +(others?'<div class="wsub">Related pages</div><ul class="wlist">'+others+'</ul>':'')+ +(w.miss_note?'<div class="wnote">Search miss '+escape(w.miss_note)+'</div>':(w.miss_recorded?'<div class="wnote">This search was counted, so popular parts get built first.</div>':''))+'</div>';+}+document.addEventListener('click',async e=>{const b=e.target.closest('#btnRequest');if(!b)return;+ b.disabled=true;const st=$('#reqStatus');st.textContent='Requesting...';+ try{const r=await fetch('api/request',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({mpn:b.dataset.mpn})});const v=await r.json();+ if(!r.ok){st.textContent=v.error||('Request failed: '+r.statusText);b.disabled=false;toast(v.error||'Request failed','error');return;}+ const q=v.request||{},link=v.status_url||'';+ st.innerHTML=(v.already==='built'?'Already has a page. ':escape(q.state||'requested')+(v.position?', position '+v.position:'')+'. ')+(link?'<a href="'+escape(link)+'" target="_blank" rel="noopener">Follow it '+ICON_EXT+'</a>':'');+ toast('Requested '+b.dataset.mpn,'success');+ }catch(err){st.textContent='Request failed: '+(err.message||err);b.disabled=false;}+}); function renderResults(r){ lastResults=r;+ renderWiki(r.wiki,r.query); for(const v of VENDORS)renderColumn(v,r[v]); renderRecommendation(r.recommendation,r.empty_state,r.policy); const n=VENDORS.reduce((a,v)=>a+((r[v]&&r[v].hits)||[]).length,0); $('#subject').textContent=r.query||''; $('#meta').textContent=n+' hits, '+fmtMs(r.elapsed_ms||0)+(r.source==='ai'?', from your AI':'');- const st=$('#status');st.textContent='Done: Mouser '+((r.mouser&&r.mouser.hits)||[]).length+', DigiKey '+((r.digikey&&r.digikey.hits)||[]).length+', JLCPCB '+((r.jlcpcb&&r.jlcpcb.hits)||[]).length+' in '+fmtMs(r.elapsed_ms||0);st.className='statusline ok';+ const st=$('#status');const wx=r.wiki&&(r.wiki.hits||[]).find(h=>h.exact);st.textContent='Done: '+(wx?'wiki page with ready-made CAD, ':(r.wiki&&r.wiki.ok?'no wiki page yet, ':''))+'Mouser '+((r.mouser&&r.mouser.hits)||[]).length+', DigiKey '+((r.digikey&&r.digikey.hits)||[]).length+', JLCPCB '+((r.jlcpcb&&r.jlcpcb.hits)||[]).length+' in '+fmtMs(r.elapsed_ms||0);st.className='statusline ok'; } // ---- Search (state lives on the server; the poll renders) ----@@ -865,6 +920,8 @@ async function doSearch(keyword){ if(!r.ok){const st=$('#status');st.textContent='Search failed: '+(v.error||r.statusText);st.className='statusline error';toast('Search failed: '+(v.error||r.statusText),'error');renderIdle();return;} renderResults(v);lastSig=v.query+':'+(v.elapsed_ms||0); const n=VENDORS.reduce((a,v2)=>a+((v[v2]&&v[v2].hits)||[]).length,0);+ const wx=v.wiki&&(v.wiki.hits||[]).find(h=>h.exact);+ if(wx)toast('Ready-made CAD on the Adom wiki for '+(wx.mpn||keyword),'success'); if(v.recommendation)toast('Recommended: '+v.recommendation.winner+' for '+v.recommendation.mpn,'success');else if(!n)toast('No matches for "'+keyword+'"','info'); }catch(e){console.error('search failed: '+(e.message||e));const st=$('#status');st.textContent='Search failed: '+(e.message||e);st.className='statusline error';toast('Search failed: '+(e.message||e),'error');renderIdle();} finally{setBusy(null);}
src/cli.rs+37−1@@ -19,8 +19,14 @@ pub fn run_search(args: SearchArgs) -> Result<(), String> { &opts, ); // OK: line to stderr so stdout stays pure JSON for jq.+ let wiki_line = match (&agg.wiki.hits.iter().find(|h| h.exact), agg.wiki.ok) {+ (Some(h), _) => format!("wiki: {} (ready-made CAD)", h.r#ref),+ (None, true) => format!("wiki: no page for {}{}", args.keyword, if agg.wiki.miss_recorded { " (miss recorded)" } else { "" }),+ (None, false) => "wiki: unreachable".into(),+ }; let ok_line = format!(- "Mouser: {} hit(s) | DigiKey: {} hit(s) | JLCPCB: {} hit(s) | recommendation: {}",+ "{} | Mouser: {} hit(s) | DigiKey: {} hit(s) | JLCPCB: {} hit(s) | recommendation: {}",+ wiki_line, agg.mouser.hits.len(), agg.digikey.hits.len(), agg.jlcpcb.hits.len(),@@ -43,6 +49,7 @@ pub fn run_search(args: SearchArgs) -> Result<(), String> { if let Some(note) = agg.recommendation.as_ref().and_then(|r| r.substitution.as_ref()) { eprintln!("Hint: {}", note); }+ if let Some(h) = &agg.wiki_hint { eprintln!("Hint: {}", h); } if crate::stderr_is_tty() { eprintln!("{}{}OK:{} {}", crate::GREEN, crate::BOLD, crate::RESET, ok_line); } else {@@ -313,3 +320,32 @@ fn format_stock(n: u64) -> String { else if n < 1000 { format!("{}", n) } else { format!("{}k", n / 1000) } }++/// `request <MPN>`: the wiki's own request flow (POST /api/part-request), so a part with no page gets built.+pub fn run_request(a: crate::RequestArgs) -> Result<(), String> {+ if a.urgency != "now" && a.urgency != "later" { return Err("--urgency is now or later".into()); }+ let r = crate::wiki::request(&a.mpn, &a.urgency, None)?;+ let req = r.get("request").cloned().unwrap_or(serde_json::Value::Null);+ let state = req.get("state").and_then(|v| v.as_str()).unwrap_or("?");+ let status = r.get("status_url").and_then(|v| v.as_str()).unwrap_or("");+ let line = match (r.get("already").and_then(|v| v.as_str()), state) {+ (Some("built"), _) => format!("{} already has a page: {}", a.mpn, req.get("page_url").or(r.get("outcome_url")).and_then(|v| v.as_str()).unwrap_or("")),+ (Some("building"), _) => format!("{} is already being built; follow it: {}", a.mpn, status),+ _ => format!("{} requested ({}{}); follow it: {}", a.mpn, state,+ r.get("position").and_then(|v| v.as_u64()).map(|p| format!(", position {}", p)).unwrap_or_default(), status),+ };+ crate::ok(&line);+ println!("{}", serde_json::to_string_pretty(&r).unwrap_or_default());+ Ok(())+}++/// `request-status <id|status link>`: where a request stands (GET /api/part-request/status/<id>).+pub fn run_request_status(id: &str) -> Result<(), String> {+ let id = id.trim_end_matches('/').rsplit('/').next().unwrap_or(id);+ let r = crate::wiki::request_status(id, None)?;+ let req = r.get("request").cloned().unwrap_or(serde_json::Value::Null);+ crate::ok(format!("request {}: {}{}", id, req.get("state").and_then(|v| v.as_str()).unwrap_or("?"),+ req.get("public_reason").and_then(|v| v.as_str()).map(|x| format!(" ({})", x)).unwrap_or_default()));+ println!("{}", serde_json::to_string_pretty(&r).unwrap_or_default());+ Ok(())+}
src/main.rs+20−2@@ -16,6 +16,7 @@ mod serve; mod settings; mod taskbar; mod vendors;+mod wiki; use clap::{CommandFactory, Parser, Subcommand}; use std::io::IsTerminal;@@ -68,7 +69,7 @@ macro_rules! note { } #[derive(Parser)]-#[command(name = "adom-parts-search", version, about = "Parts Search: one query across Mouser, DigiKey, and JLCPCB, with a Mouser-preferred best-source recommendation")]+#[command(name = "adom-parts-search", version, about = "Parts Search: one query across the Adom wiki (ready-made CAD), Mouser, DigiKey, and JLCPCB, with a Mouser-preferred best-source recommendation")] pub struct Cli { #[command(subcommand)] cmd: Cmd,@@ -76,9 +77,17 @@ pub struct Cli { #[derive(Subcommand)] enum Cmd {- /// Search all three vendors in parallel; print unified JSON to stdout.+ /// Search the Adom wiki and all three vendors in parallel; print unified JSON to stdout. A part with no wiki page is+ /// offered for a request (adom-parts-search request <MPN>). Search(SearchArgs), + /// Request a part with no wiki page: Adom's factory builds it (symbol, footprint, 3D, datasheet). Same flow as the+ /// wiki's "Request this part" box; prints the request, its status link and position.+ Request(RequestArgs),++ /// Where a part request stands now (the id or status link `request` printed).+ RequestStatus { id: String },+ /// Run the Parts Search page server in the foreground (3-column grid with product photos). App(AppArgs), @@ -169,6 +178,13 @@ pub struct SearchArgs { #[arg(long, env = "JLCPCB_API")] pub jlcpcb_api: Option<String>, } +#[derive(clap::Args)]+pub struct RequestArgs {+ pub mpn: String,+ /// now: built one at a time, soon; later: a cheaper batch wave, within hours.+ #[arg(long, default_value = "now")] pub urgency: String,+}+ #[derive(clap::Args)] pub struct ShowArgs { pub keyword: String,@@ -216,6 +232,8 @@ fn main() -> ExitCode { let args = Cli::parse(); let result = match args.cmd { Cmd::Search(a) => cli::run_search(a),+ Cmd::Request(a) => cli::run_request(a),+ Cmd::RequestStatus { id } => cli::run_request_status(&id), Cmd::Show(a) => cli::run_show(a), Cmd::App(a) => app::run(a), Cmd::Serve(a) => serve::run(a.port, a.print_url),
src/vendors.rs+147−198@@ -1,6 +1,6 @@-//! Parallel HTTP aggregator across the three Adom parts services-//! (adom-mouser, adom-digikey, adom-jlcpcb). This module has no API-//! credentials of its own — each vendor's backend already holds them.+//! The unified search result across Mouser, DigiKey and JLCPCB, fetched through the Adom wiki's parts-search route+//! (wiki.adom.inc -> Component Ocean -> the vendor services). This module calls no distributor and holds no+//! distributor credentials; Component Ocean answers each vendor's search from its cache or fetches it live. //! //! Output shape: a unified Vec<VendorHit> with the minimum fields the //! webview needs to render a comparison grid (MPN, image URL, price,@@ -9,9 +9,7 @@ use serde::{Deserialize, Serialize}; use serde_json::{json, Value};-use std::sync::mpsc; use std::thread;-use std::time::Duration; pub const DEFAULT_MOUSER: &str = "https://mouser-xr8t4f5d01bt.adom.cloud"; pub const DEFAULT_DIGIKEY: &str = "https://digikey-gjuu8l5t69uh.adom.cloud";@@ -73,6 +71,17 @@ pub struct AggregatedResults { pub mouser: VendorBlock, pub digikey: VendorBlock, pub jlcpcb: VendorBlock,+ /// The Adom wiki, asked in parallel with the vendors (src/wiki.rs): a component page with ready-made CAD+ /// (symbol, footprint, 3D, STEP, .lbr), its Verified state and Adom stock, or a request offer when there is none.+ #[serde(default)]+ pub wiki: crate::wiki::WikiBlock,+ /// One line for the person: ready-made CAD on the wiki, or how to request a page.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub wiki_hint: Option<String>,+ /// How the distributor columns were fetched: {via: "wiki" (the public route) or "test-route", url, live_calls (the+ /// distributor calls Component Ocean made for this search; 0 when every answer was cached), exact, demand}.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub parts_search: Option<Value>, pub recommendation: Option<Recommendation>, /// Populated when no vendor produced a usable hit. Tells the user /// why (no matches vs. all unreachable) and suggests a next step.@@ -105,6 +114,12 @@ pub struct VendorBlock { pub hits: Vec<VendorHit>, pub backend_url: String, pub elapsed_ms: u64,+ /// Served from Component Ocean's cache (true) or fetched live by CO for this search (false).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub from_cache: Option<bool>,+ /// Age of the vendor answer, seconds.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub age_s: Option<u64>, } #[derive(Debug, Clone, Serialize, Deserialize)]@@ -283,112 +298,6 @@ fn redact(raw: &str) -> String { s } -/// The key this app presents to the vendor backends, so its spend is-/// attributable instead of landing in the `anon` bucket with everything else.-/// File first (survives restarts, rotatable without a rebuild), env second.-/// Absent is NOT an error: the backends run in observe mode, so an un-keyed-/// build keeps working and simply shows up as anonymous — which is the whole-/// reason the rollout order is observe-then-enforce.-/// The credential this app presents to the vendor backends.-///-/// THIS IS THE CONTAINER'S ORDINARY ADOM API KEY, not a bespoke one. Every Adom-/// container already ships it at /var/run/adom/api-key, and the backends-/// validate it against Carbon — which means Parts Search works out of the box-/// on any Adom machine with nothing to install, and the vendor journals get a-/// PROVEN user identity rather than a header this app could have made up.-///-/// The earlier design minted its own key and required hand-placing a file on-/// every machine. That only worked where someone had configured it, which is-/// not a system.-fn adom_api_key() -> Option<String> {- if let Ok(k) = std::env::var("ADOM_API_KEY") {- if !k.trim().is_empty() { return Some(k.trim().to_string()); }- }- let home = std::env::var("HOME").unwrap_or_default();- for p in [- "/var/run/adom/api-key".to_string(),- format!("{}/.adom/api-key", home),- // Legacy path from the bespoke-key experiment; harmless if absent.- format!("{}/.adom/vendor-api-key", home),- ] {- if let Ok(k) = std::fs::read_to_string(&p) {- let k = k.trim().to_string();- if !k.is_empty() { return Some(k); }- }- }- None-}--/// The ADOM USER this process is acting for, resolved once and cached.-///-/// WHY: the API key identifies the APPLICATION. Every search from every person-/// running Parts Search looked identical in the vendors' journals, so "who is-/// spending the quota" could only ever be answered as "Parts Search" — true and-/// useless. This adds the person.-///-/// Resolved ONCE, not per search: `adom-cli carbon user get` is a network round-/// trip, and doing it per query would add its latency to every search and its-/// failure modes to every search's error path.-///-/// A failure here is NOT fatal. If identity cannot be resolved the searches-/// still run, unattributed — losing a metric is an acceptable outcome, losing-/// the feature is not.-fn adom_user() -> Option<String> {- use std::sync::OnceLock;- static USER: OnceLock<Option<String>> = OnceLock::new();- USER.get_or_init(|| {- if let Ok(u) = std::env::var("ADOM_USER") {- if !u.trim().is_empty() { return Some(u.trim().to_string()); }- }- let out = std::process::Command::new("adom-cli")- .args(["carbon", "user", "get"])- .output()- .ok()?;- if !out.status.success() { return None; }- let v: Value = serde_json::from_slice(&out.stdout).ok()?;- // The opaque id, not the email: these land in log files that get read,- // shipped and pasted, and an id is enough to group by.- v.get("id").and_then(|x| x.as_str()).map(|s| s.to_string())- })- .clone()-}--/// Identify every outbound call: the key when we have one, always a caller-/// label and User-Agent, and the Adom user when it can be resolved.-fn identify(req: ureq::Request) -> ureq::Request {- let req = req- .set("X-Adom-Caller", "parts-search")- .set("User-Agent", concat!("adom-parts-search/", env!("CARGO_PKG_VERSION")));- // No X-Adom-User: the backend derives the user from the validated token.- // A header we write about ourselves is a claim; the token is evidence.- match adom_api_key() {- Some(k) => req.set("X-Adom-Key", &k),- None => req,- }-}--fn post_action(url: &str, body: Value) -> Result<Value, String> {- let url = if url.ends_with('/') { url.to_string() } else { format!("{}/", url) };- let agent = ureq::AgentBuilder::new().timeout(Duration::from_secs(30)).build();- let res = match identify(agent.post(&url).set("Content-Type", "application/json")).send_json(body) {- Ok(r) => r,- // CARRY THE STATUS INTO THE ERROR STRING. Swallowing it is what made an- // authentication failure indistinguishable from a broken backend: the- // 401 body parsed as "some error", got the generic explanation, and told- // the user to contact an admin. A person reading that goes looking for a- // vendor API key, which is the one thing they must never need.- Err(ureq::Error::Status(code, r)) => {- let body = r.into_string().unwrap_or_default();- let hint = serde_json::from_str::<Value>(&body).ok()- .and_then(|v| v.get("_hint").and_then(|h| h.as_str()).map(|s| s.to_string()))- .unwrap_or_default();- return Err(format!("http {} {}", code, hint));- }- Err(e) => return Err(format!("{}", e)),- };- res.into_json().map_err(|e| format!("JSON: {}", e))-}- fn price_at_qty(tiers: Option<&Vec<Value>>, qty: u32) -> Option<String> { let tiers = tiers?; // Find the tier with the largest qty ≤ requested@@ -523,13 +432,39 @@ impl SearchOpts { } } +/// One vendor's part of the parts-search answer ({ok, error?, count, components, from_cache, age_s}) -> a column, with+/// the same normalising, relevance filter and stock order the direct calls used.+fn block_from_route(vendor: Vendor, v: Option<&Value>, q: &str, url: &str, elapsed: u64) -> VendorBlock {+ let mut block = VendorBlock { backend_url: url.to_string(), elapsed_ms: elapsed, ..Default::default() };+ let Some(v) = v else {+ let (t, expl, hint) = classify_error(vendor, "no answer for this vendor");+ block.error = Some(t); block.error_explanation = Some(expl); block.error_hint = Some(hint); return block;+ };+ block.from_cache = v.get("from_cache").and_then(|x| x.as_bool());+ block.age_s = v.get("age_s").and_then(|x| x.as_u64());+ if !v.get("ok").and_then(|x| x.as_bool()).unwrap_or(false) {+ let (t, expl, hint) = classify_error(vendor, v.get("error").and_then(|x| x.as_str()).unwrap_or("no answer"));+ block.error = Some(t); block.error_explanation = Some(expl); block.error_hint = Some(hint); return block;+ }+ block.ok = true;+ block.total = v.get("count").and_then(|n| n.as_u64()).unwrap_or(0);+ let components = v.get("components").and_then(|a| a.as_array()).cloned().unwrap_or_default();+ let raw: Vec<VendorHit> = components.iter().map(|c| match vendor {+ Vendor::Mouser => normalize_mouser(c), Vendor::DigiKey => normalize_digikey(c), Vendor::JLCPCB => normalize_jlcpcb(c),+ }).collect();+ block.hits = filter_relevant(&raw, q);+ block.hits.sort_by(|a, b| b.stock.cmp(&a.stock));+ if block.hits.is_empty() { block.total = 0; }+ block+}+ fn skipped_block(url: String) -> VendorBlock { VendorBlock { ok: false, skipped: true, error: Some("Switched off in Settings".into()), error_explanation: Some("This vendor was not queried because its toggle is off in Settings. Nothing is wrong with the backend.".into()), error_hint: Some("Open Settings (the cog, upper right) and turn the vendor back on.".into()),- total: 0, hits: vec![], backend_url: url, elapsed_ms: 0,+ total: 0, hits: vec![], backend_url: url, elapsed_ms: 0, from_cache: None, age_s: None, } } @@ -542,97 +477,43 @@ pub fn search_all( jlcpcb_api: Option<&str>, opts: &SearchOpts, ) -> AggregatedResults {- let m_url = mouser_api.unwrap_or(DEFAULT_MOUSER).to_string();- let d_url = digikey_api.unwrap_or(DEFAULT_DIGIKEY).to_string();- let j_url = jlcpcb_api.unwrap_or(DEFAULT_JLCPCB).to_string();+ // Ray, 2026-11-04: user / AI -> wiki.adom.inc -> Component Ocean -> Mouser / DigiKey / JLCPCB. One call to the+ // wiki's parts-search route replaces the three direct vendor calls: CO answers each vendor's full search from its+ // cache, or fetches it live when stale, under its own budget. Nothing here calls a distributor.+ let _ = (mouser_api, digikey_api, jlcpcb_api); let q = query.to_string();+ // the Adom wiki's component pages, beside it (John asked for native wiki search)+ let wiki_t = { let q = q.clone(); thread::spawn(move || crate::wiki::search(&q, None)) }; - let (tx, rx) = mpsc::channel::<(Vendor, VendorBlock)>();- let body_common = json!({"keyword": q, "limit": limit, "inStockOnly": in_stock_only});-- // Spawn three threads — one per vendor.- let enabled: Vec<(Vendor, String)> = [(Vendor::Mouser, m_url.clone(), opts.mouser), (Vendor::DigiKey, d_url.clone(), opts.digikey), (Vendor::JLCPCB, j_url.clone(), opts.jlcpcb)]- .into_iter().filter(|(_, _, on)| *on).map(|(v, u, _)| (v, u)).collect();- let n_enabled = enabled.len();- let jlc_basic = opts.jlcpcb_basic;- for (vendor, url) in enabled {- let tx = tx.clone();- let body = {- let mut b = body_common.clone();- b["action"] = Value::String("search".into());- if jlc_basic && vendor == Vendor::JLCPCB { b["is_basic"] = Value::Bool(true); }- b- };- let url_for_block = url.clone();- let q_for_thread = q.clone();- thread::spawn(move || {- let t0 = std::time::Instant::now();- let result = post_action(&url, body);- let elapsed = t0.elapsed().as_millis() as u64;- let mut block = VendorBlock {- ok: false, skipped: false, error: None, error_explanation: None, error_hint: None,- total: 0, hits: vec![],- backend_url: url_for_block, elapsed_ms: elapsed,- };- match result {- Ok(v) => {- if let Some(e) = v.get("error").and_then(|v| v.as_str()).or(- v.get("api_error").and_then(|v| v.as_str())- ) {- let (t, expl, hint) = classify_error(vendor, e);- block.error = Some(t);- block.error_explanation = Some(expl);- block.error_hint = Some(hint);- } else {- block.ok = true;- block.total = v.get("count").and_then(|n| n.as_u64()).unwrap_or(0);- let components = v.get("components").and_then(|a| a.as_array()).cloned().unwrap_or_default();- let raw: Vec<VendorHit> = components.iter().map(|c| match vendor {- Vendor::Mouser => normalize_mouser(c),- Vendor::DigiKey => normalize_digikey(c),- Vendor::JLCPCB => normalize_jlcpcb(c),- }).collect();- // Drop hits that don't contain the primary query- // token in the MPN or description. JLCPCB currently- // returns its default popular-parts list on no-match,- // so filter vendor-side. Safe for all vendors; vendor- // FTS that does match will keep its hits.- block.hits = filter_relevant(&raw, &q_for_thread);- // Sort by stock DESC so the most-useful variant is- // the first card a user sees. Mouser + DigiKey often- // return a stock=0 "parent" MPN before the stocked- // reel/cut-tape children; rendering that stock=0- // card first makes the whole column look empty.- block.hits.sort_by(|a, b| b.stock.cmp(&a.stock));- // If everything got filtered as irrelevant, reset- // `total` so the UI shows "0 matches".- if block.hits.is_empty() { block.total = 0; }- }- }- Err(e) => {- let (t, expl, hint) = classify_error(vendor, &e);- block.error = Some(t);- block.error_explanation = Some(expl);- block.error_hint = Some(hint);- }- }- let _ = tx.send((vendor, block));- });- }- drop(tx);+ let route = crate::wiki::parts_search_route();+ let vendors: Vec<&str> = [("mouser", opts.mouser), ("digikey", opts.digikey), ("jlcpcb", opts.jlcpcb)]+ .into_iter().filter(|(_, on)| *on).map(|(v, _)| v).collect();+ let t0 = std::time::Instant::now();+ let answer = if vendors.is_empty() { Err("every vendor is switched off in Settings".to_string()) }+ else { crate::wiki::post_route(&route, json!({"q": q, "limit": limit, "in_stock_only": in_stock_only, "jlcpcb_basic": opts.jlcpcb_basic, "vendors": vendors})) };+ let elapsed = t0.elapsed().as_millis() as u64; let mut agg = AggregatedResults { query: query.into(), ..Default::default() };- if !opts.mouser { agg.mouser = skipped_block(m_url.clone()); }- if !opts.digikey { agg.digikey = skipped_block(d_url.clone()); }- if !opts.jlcpcb { agg.jlcpcb = skipped_block(j_url.clone()); }- for _ in 0..n_enabled {- match rx.recv() {- Ok((Vendor::Mouser, b)) => agg.mouser = b,- Ok((Vendor::DigiKey, b)) => agg.digikey = b,- Ok((Vendor::JLCPCB, b)) => agg.jlcpcb = b,- Err(_) => break,- }+ for (vendor, key, on) in [(Vendor::Mouser, "mouser", opts.mouser), (Vendor::DigiKey, "digikey", opts.digikey), (Vendor::JLCPCB, "jlcpcb", opts.jlcpcb)] {+ let block = if !on { skipped_block(route.url.clone()) } else {+ match &answer {+ Ok(v) => block_from_route(vendor, v.get(key), &q, &route.url, elapsed),+ // the wiki call itself failed (down, rate-limited, or Component Ocean slower than the wiki waits): one+ // plain explanation per column, not a vendor-backend error the person cannot act on+ Err(e) => VendorBlock { ok: false, skipped: false,+ error: Some(if e.contains("429") { "Too many searches just now".into() } else { "The Adom wiki did not return results".into() }),+ error_explanation: Some(format!("{} results come through the Adom wiki and Component Ocean, and that request failed ({}).", vendor.display(), e.chars().take(120).collect::<String>())),+ error_hint: Some(if e.contains("429") { "Wait a minute and search again; signed in to the wiki the limit is higher (adom-wiki auth login).".into() }+ else { "Search again in a minute; a repeat is usually answered from Component Ocean's cache.".into() }),+ total: 0, hits: vec![], backend_url: route.url.clone(), elapsed_ms: elapsed, ..Default::default() },+ }+ };+ match vendor { Vendor::Mouser => agg.mouser = block, Vendor::DigiKey => agg.digikey = block, Vendor::JLCPCB => agg.jlcpcb = block } }+ agg.parts_search = Some(match &answer {+ Ok(v) => json!({"via": route.via, "url": route.url, "live_calls": v.get("live_calls"), "exact": v.get("exact"), "demand": v.get("demand"), "elapsed_ms": elapsed}),+ Err(e) => json!({"via": route.via, "url": route.url, "error": e, "elapsed_ms": elapsed}),+ }); // Cross-vendor CAD fallback: DigiKey is the only backend that // exposes CAD links today. For any Mouser or JLCPCB hit whose MPN // matches a DigiKey hit with a cad_3d_url, copy that URL onto@@ -654,6 +535,8 @@ pub fn search_all( } } + agg.wiki = wiki_t.join().unwrap_or_default();+ agg.wiki_hint = wiki_hint(&agg.wiki); agg.recommendation = if opts.policy == "cheapest" { pick_cheapest(&agg, &agg.query) } else { pick_winner(&agg, &agg.query) }; if agg.recommendation.is_none() { agg.empty_state = Some(build_empty_state(&agg));@@ -702,6 +585,20 @@ fn build_empty_state(agg: &AggregatedResults) -> EmptyState { }; } + // Every vendor answered and some have the part, but none is eligible: Mouser and DigiKey out of stock or on a+ // long lead, and JLCPCB is never recommended (its parts are for JLCPCB-assembled boards). The old fall-through+ // said "returned zero hits ... are currently erroring" with nothing erroring.+ if m_ok && d_ok && j_ok && (m_hits + d_hits + j_hits) > 0 {+ let jlc_stock: u64 = agg.jlcpcb.hits.iter().map(|h| h.stock).max().unwrap_or(0);+ return EmptyState {+ title: format!("No distributor has \"{q}\" in stock right now."),+ explanation: format!(+ "Mouser and DigiKey list it, but with no stock or a long lead time.{}",+ if jlc_stock > 0 { format!(" JLCPCB has {} for boards it assembles.", jlc_stock) } else { String::new() }),+ hint: "Check the lead times on the cards, ask for an alternate part, or have JLCPCB assemble the board.".into(),+ };+ }+ // Mixed: some vendors OK with 0 hits, others errored — partial visibility. let live_vendors: Vec<&str> = [ (m_ok, "Mouser"), (d_ok, "DigiKey"), (j_ok, "JLCPCB"),@@ -1016,3 +913,55 @@ mod recommendation_tests { assert_eq!(pick_winner(&a, &a.query).unwrap().mpn, "TPS389001DSER"); } }+++/// One line about the wiki for the banner and the CLI: ready-made CAD, or how to request a page.+pub fn wiki_hint(w: &crate::wiki::WikiBlock) -> Option<String> {+ if let Some(h) = w.hits.iter().find(|h| h.exact && (h.cad.symbol || h.cad.footprint)) {+ let mut have = vec![];+ if h.cad.symbol { have.push("symbol"); } if h.cad.footprint { have.push("footprint"); } if h.cad.model_3d { have.push("3D"); }+ if h.cad.step { have.push("STEP"); } if h.cad.lbr { have.push(".lbr"); }+ let v = match h.verified.as_str() { "verified" => ", Verified", "stale" => ", verification out of date", _ => "" };+ return Some(format!("Ready-made CAD on the Adom wiki: {} ({}{}).", h.url, have.join(", "), v));+ }+ w.request.as_ref().map(|r| format!("{} Run: {}", r["message"].as_str().unwrap_or(""), r["cli"].as_str().unwrap_or("")))+}++#[cfg(test)]+mod wiki_hint_tests {+ use super::*;+ use crate::wiki::{Cad, WikiBlock, WikiHit};++ #[test]+ fn an_exact_page_with_cad_is_ready_made_and_a_miss_points_at_request() {+ let page = WikiHit { r#ref: "adom/lm358dr".into(), url: "https://wiki.adom.inc/adom/lm358dr".into(), exact: true, verified: "verified".into(),+ cad: Cad { symbol: true, footprint: true, model_3d: true, step: true, lbr: true }, ..Default::default() };+ let w = WikiBlock { ok: true, ready_made: true, hits: vec![page], ..Default::default() };+ assert_eq!(wiki_hint(&w).unwrap(), "Ready-made CAD on the Adom wiki: https://wiki.adom.inc/adom/lm358dr (symbol, footprint, 3D, STEP, .lbr, Verified).");+ let miss = WikiBlock { ok: true, request: Some(crate::wiki::request_offer("LM2903L-Q1")), ..Default::default() };+ assert!(wiki_hint(&miss).unwrap().ends_with("Run: adom-parts-search request LM2903L-Q1"));+ // a related page is not the part: no "ready-made" claim for it+ let related = WikiHit { exact: false, cad: Cad { symbol: true, footprint: true, ..Default::default() }, ..Default::default() };+ assert!(wiki_hint(&WikiBlock { ok: true, hits: vec![related], ..Default::default() }).is_none());+ }+}++#[cfg(test)]+mod empty_state_tests {+ use super::*;+ fn hit(v: Vendor, stock: u64) -> VendorHit {+ VendorHit { vendor: v, vendor_pn: "x".into(), mpn: "TPS62840DLCR".into(), manufacturer: String::new(), description: String::new(), stock,+ unit_price: None, price_100: None, lead_time: String::new(), image_url: None, datasheet_url: None, product_url: None, flags: vec![],+ cad_3d_url: None, cad_3d_format: None, cad_3d_source: None }+ }+ #[test]+ fn listed_but_out_of_stock_is_not_called_zero_hits_or_erroring() {+ let ok = |h: Vec<VendorHit>| VendorBlock { ok: true, total: h.len() as u64, hits: h, ..Default::default() };+ let agg = AggregatedResults { query: "TPS62840DLCR".into(), mouser: ok(vec![hit(Vendor::Mouser, 0)]), digikey: ok(vec![hit(Vendor::DigiKey, 0)]),+ jlcpcb: ok(vec![hit(Vendor::JLCPCB, 3700)]), ..Default::default() };+ let e = build_empty_state(&agg);+ assert_eq!(e.title, "No distributor has \"TPS62840DLCR\" in stock right now.");+ assert!(e.explanation.contains("JLCPCB has 3700"));+ assert!(!e.explanation.contains("erroring"));+ }+}
uninstall.sh