← Commit history
v2.1.11: A part request is answered in the thread that asked, not by email (the wiki thread's handoff; John's report that an AI's request was answered by email to the person).
15 files changed
+606−319
Cargo.lock+1−1@@ -10,7 +10,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "adom-parts-search"-version = "2.1.10"+version = "2.1.11" dependencies = [ "base64", "clap",
Cargo.toml+1−1@@ -1,6 +1,6 @@ [package] name = "adom-parts-search"-version = "2.1.10"+version = "2.1.11" 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.10+2.1.11
install.shpackage.json+1−40@@ -34,44 +34,5 @@ "SKILL.md", "BUILD-SKILL.md", "CHANGELOG.md"- ],- "changelog": "A part request is answered in the thread that asked, not by email (the wiki thread's handoff; John's report that an AI's request was answered by email to the person).",- "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+7−44@@ -36,22 +36,10 @@ "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": "A part request is answered in the thread that asked, not by email (the wiki thread's handoff; John's report that an AI's request was answered by email to the person)."+ "org": "adom" }
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/host.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/deadline.rs src/request.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+65−1@@ -191,6 +191,29 @@ fn probe_wiki() -> Value { } } +/// One query parameter of a request URL, %XX and + decoded.+fn query_param(url: &str, key: &str) -> Option<String> {+ let q = url.split_once('?')?.1;+ q.split('&').filter_map(|kv| kv.split_once('=')).find(|(k, _)| *k == key).map(|(_, v)| {+ let b = v.as_bytes();+ let mut out = Vec::with_capacity(b.len());+ let mut i = 0;+ while i < b.len() {+ match b[i] {+ b'+' => { out.push(b' '); i += 1; }+ b'%' if i + 2 < b.len() => {+ match u8::from_str_radix(std::str::from_utf8(&b[i + 1..i + 3]).unwrap_or(""), 16) {+ Ok(x) => { out.push(x); i += 3; }+ Err(_) => { out.push(b'%'); i += 1; }+ }+ }+ c => { out.push(c); i += 1; }+ }+ }+ String::from_utf8_lossy(&out).into_owned()+ })+}+ /// 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 {@@ -754,10 +777,36 @@ fn handle(mut req: Request, state: Arc<AppState>, no_tab: bool, tab_name: &str) 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) {+ else {+ // the page answers in the app; "Email me when it's ready" sends notify: "email" for someone closing it+ let opts = crate::wiki::RequestOpts {+ notify: body.get("notify").and_then(|v| v.as_str()).filter(|n| *n == "email" || *n == "thread").map(String::from),+ deadline_minutes: body.get("deadline_minutes").and_then(|v| v.as_u64()).filter(|m| (1..=1440).contains(m)).map(|m| m as u32),+ };+ match crate::wiki::request(&mpn, body.get("urgency").and_then(|v| v.as_str()).unwrap_or("now"), &opts) { Ok(v) => (200, v), Err(e) => (if e.starts_with("not signed in") { 401 } else { 502 }, json!({"error": e})), } }+ } else if method == Method::Get && ends("/api/request-status") {+ // the page follows its request: the wiki holds the answer (wait, at most 50 s) until the state moves on+ let q = |k: &str| query_param(&url, k);+ match q("id").filter(|i| !i.is_empty()) {+ None => (400, json!({"error": "id is required", "_hint": "GET /api/request-status?id=<id>&wait=50&since=queued"})),+ Some(id) => {+ let wait = q("wait").and_then(|w| w.parse::<u64>().ok()).filter(|w| *w > 0).map(|w| w.min(50));+ let since = q("since").filter(|s| !s.is_empty());+ match crate::wiki::request_status(&id, wait.map(|w| (w, since.as_deref()))) {+ Ok(mut v) => {+ let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0);+ v["_follow"] = json!({"line": crate::request::status_line(&id, &v, now),+ "held": crate::deadline::wiki_keeps_the_clock(&v), "late": crate::deadline::wiki_says_late(&v),+ "state": crate::deadline::state(&v)});+ (200, v)+ }+ Err(e) => (502, json!({"error": e})),+ }+ }+ } } else if method == Method::Post && (ends("/search") || ends("/api/search")) { match read_body(&mut req) { Ok(body) => {@@ -811,3 +860,18 @@ fn handle(mut req: Request, state: Arc<AppState>, no_tab: bool, tab_name: &str) }; let _ = req.respond(json_resp(result.0, result.1)); }++#[cfg(test)]+mod query_tests {+ #[test]+ fn query_params_decode() {+ let u = "/x/api/request-status?id=uAEq_M3E&wait=50&since=in%20review&n=a+b&bad=%G1&end=%4";+ assert_eq!(super::query_param(u, "id").as_deref(), Some("uAEq_M3E"));+ assert_eq!(super::query_param(u, "since").as_deref(), Some("in review"));+ assert_eq!(super::query_param(u, "n").as_deref(), Some("a b"));+ assert_eq!(super::query_param(u, "bad").as_deref(), Some("%G1"));+ assert_eq!(super::query_param(u, "end").as_deref(), Some("%4"));+ assert_eq!(super::query_param(u, "missing"), None);+ assert_eq!(super::query_param("/no-query", "id"), None);+ }+}
src/app/ui.html+52−7@@ -199,6 +199,11 @@ main>:first-child{margin-top:0} .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}+.wikibox .wmail{display:inline-flex;align-items:center;gap:6px;font-size:12px;color:var(--text-2);cursor:pointer}+.wikibox .wmail input{accent-color:var(--accent);margin:0}+.wikibox .wnote.late{color:var(--yellow)}+.wikibox .wnote svg{width:12px;height:12px;vertical-align:-1px;margin-left:2px}+.wikibox .wact .wnote{margin-top:0} .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 */@@ -860,6 +865,7 @@ function renderRecommendation(rec,emptyState,policy){ el.innerHTML=''; } function renderWiki(w,q){+ reqFollow=null; 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);@@ -881,19 +887,58 @@ function renderWiki(w,q){ 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>':'')+ +(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><label class="wmail" data-tooltip="Off: this page follows the request and shows when the part is built. On: the wiki emails you instead, for when you will close the app."><input type="checkbox" id="reqEmail">Email me when it\'s ready</label><span class="wnote" id="reqStatus" aria-live="polite"></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>'; }+// A request made here is followed here: the wiki holds each status answer (wait=50) until it changes, so the page+// shows queued -> building -> built without polling. "Email me when it's ready" sends notify:"email" instead.+let reqFollow=null;+const REQ_DONE=['built','done','published','public','cancelled','canceled','failed','error','rejected'];+function reqTime(x){if(!x)return '';const s=String(x);const d=new Date(s.replace(' ','T')+(/[zZ]$|[+-]\d\d:?\d\d$/.test(s)?'':'Z'));+ return isNaN(d)?s:d.toLocaleString([],{hour:'2-digit',minute:'2-digit',month:'short',day:'numeric'});}+function reqPaint(st,v,link){+ const q=v.request||{},f=v._follow||{},state=f.state||q.state||'requested',pos=q.position??v.position,dl=v.deadline_at||q.deadline_at;+ const page=q.page_url||v.page_url||'',url=page.startsWith('/')?'https://wiki.adom.inc'+page:page;+ let t;+ if(state==='built')t='Built: the page is ready. '+(url?'<a href="'+escape(url)+'" target="_blank" rel="noopener">Open it '+ICON_EXT+'</a>':'');+ else{t=escape(state.charAt(0).toUpperCase()+state.slice(1))+(pos?', position '+escape(String(pos)):'')+'.';+ if(state==='review')t+=' A person reviews it next.';+ else if(f.late)t+=' Late'+(dl?': was due '+escape(reqTime(dl)):'')+'.';+ else if(dl)t+=' Due by '+escape(reqTime(dl))+'.';+ t+=link?' <a href="'+escape(link)+'" target="_blank" rel="noopener">Status '+ICON_EXT+'</a>':'';}+ st.innerHTML=t;st.classList.toggle('late',!!f.late&&state!=='built');+ return state;+}+async function reqFollowLoop(id,st,state,link,mpn){+ const me={};reqFollow=me;let errors=0;+ while(reqFollow===me){+ const t0=Date.now();let v;+ try{const r=await fetch('api/request-status?id='+encodeURIComponent(id)+'&wait=50&since='+encodeURIComponent(state));v=await r.json();+ if(!r.ok)throw new Error(v.error||r.statusText);errors=0;}+ catch(err){if(++errors>=3){if(reqFollow===me)st.innerHTML=escape('Stopped following: '+(err.message||err)+'. ')+(link?'<a href="'+escape(link)+'" target="_blank" rel="noopener">Status '+ICON_EXT+'</a>':'');return;}+ await new Promise(r=>setTimeout(r,15000));continue;}+ if(reqFollow!==me)return;+ const prev=state;state=reqPaint(st,v,link);const f=v._follow||{};+ if(state!==prev&&state==='built')toast(mpn+' is built: its page is ready','success');+ if(!f.held||REQ_DONE.includes(state)||state==='review'||f.late){if(f.late)toast(mpn+' is late at the factory','info');reqFollow=null;return;}+ if(Date.now()-t0<5000)await new Promise(r=>setTimeout(r,10000)); // a wiki that answers at once is not asked again sooner+ }+} 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;}+ b.disabled=true;const st=$('#reqStatus'),em=$('#reqEmail'),email=!!(em&&em.checked);if(em)em.disabled=true;st.textContent='Requesting...';+ try{const r=await fetch('api/request',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({mpn:b.dataset.mpn,notify:email?'email':'thread'})});const v=await r.json();+ if(!r.ok){st.textContent=v.error||('Request failed: '+r.statusText);b.disabled=false;if(em)em.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;}+ if(v.already==='built'){st.innerHTML='Already has a page. '+(link?'<a href="'+escape(link)+'" target="_blank" rel="noopener">Open it '+ICON_EXT+'</a>':'');toast(b.dataset.mpn+' already has a page','info');return;}+ const state=reqPaint(st,v,link);+ const id=q.id!=null?String(q.id):(String(v.status_api||link).replace(/\/+$/,'').split('/').pop()||'');+ if(v.notify==='email'){st.insertAdjacentHTML('afterbegin','The wiki emails you when it is ready. ');toast('Requested '+b.dataset.mpn+': you will get an email','success');return;}+ if(!v.notify){st.insertAdjacentHTML('afterbegin','The wiki emails you when it is ready. ');toast('Requested '+b.dataset.mpn,'success');return;}+ toast('Requested '+b.dataset.mpn+': this page follows it','success');+ if(id&&!REQ_DONE.includes(state))reqFollowLoop(id,st,state,link,b.dataset.mpn);+ }catch(err){st.textContent='Request failed: '+(err.message||err);b.disabled=false;if(em)em.disabled=false;} }); function renderResults(r){ lastResults=r;
src/cli.rs−210@@ -330,213 +330,3 @@ 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>), the time it is due,-/// and once that has passed, a Hint that the calling AI may build the part itself (adom/build-a-component-page).-pub fn run_request_status(id: &str) -> Result<(), String> {- let id = id.trim_end_matches('/').rsplit('/').next().unwrap_or(id);- let mut r = crate::wiki::request_status(id, None)?;- let req = r.get("request").cloned().unwrap_or(serde_json::Value::Null);- let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0);- let due = deadline(&req, now);- crate::ok(format!("request {}: {}{}{}", id, req.get("state").and_then(|v| v.as_str()).unwrap_or("?"),- req.get("public_reason").or(req.get("reason")).and_then(|v| v.as_str()).map(|x| format!(" ({})", x)).unwrap_or_default(),- due.as_ref().map(|d| format!("; {}", d.line())).unwrap_or_default()));- let mut late_hint = None;- if let Some(d) = &due {- // CO's eta_text is not quoted when it contradicts the deadline (a retry hours away, or already late)- if let Some(t) = d.eta_text.clone() { r["request"]["eta_text"] = serde_json::Value::String(t); }- r["deadline"] = serde_json::json!({"at": fmt_utc(d.at), "source": d.source, "passed": d.passed});- if d.passed {- let slug = page_slug(&req);- late_hint = Some(late_hint_text(&slug, &fmt_utc(d.at), &crate::wiki::page_state("adom", &slug, None)));- }- }- println!("{}", serde_json::to_string_pretty(&r).unwrap_or_default());- if let Some(h) = late_hint { crate::hint(h); }- Ok(())-}--/// Service limits quoted when Component Ocean gives no retry time (component-factory#3: 20 minutes for an urgent part,-/// an hour for one in review); a `later` request is due within a day.-const LIMIT_NOW_SECS: i64 = 20 * 60;-const LIMIT_REVIEW_SECS: i64 = 60 * 60;-const LIMIT_LATER_SECS: i64 = 24 * 60 * 60;-const SKILL_BUILD_PAGE: &str = "build-a-component-page skill (https://wiki.adom.inc/adom/build-a-component-page)";--#[derive(Debug)]-pub struct Deadline { pub at: i64, pub source: String, pub passed: bool, pub eta_text: Option<String> }--impl Deadline {- fn line(&self) -> String {- if self.passed { format!("LATE: was due {} ({})", fmt_utc(self.at), self.source) }- else { format!("due by {} ({})", fmt_utc(self.at), self.source) }- }-}--/// When the request is due. Component Ocean's `not_before` (its next retry) plus `eta_seconds` when CO gives one,-/// otherwise `requested_at` plus the service limit. None once the request is built or finished.-pub fn deadline(req: &serde_json::Value, now: i64) -> Option<Deadline> {- let state = req.get("state").and_then(|v| v.as_str()).unwrap_or("");- if matches!(state, "built" | "done" | "published" | "public" | "cancelled" | "canceled" | "") { return None; }- let eta = req.get("eta_seconds").and_then(|v| v.as_i64()).unwrap_or(0).max(0);- let (at, source) = if let Some(nb) = req.get("not_before").and_then(epoch) {- (nb + eta, format!("Component Ocean not_before: next retry {}{}", fmt_utc(nb),- if eta > 0 { format!(", plus its {} s ETA", eta) } else { String::new() }))- } else if let Some(t0) = req.get("requested_at").and_then(epoch) {- let (lim, what) = if state == "review" { (LIMIT_REVIEW_SECS, "in review") }- else if req.get("urgency").and_then(|v| v.as_str()) == Some("later") { (LIMIT_LATER_SECS, "a `later` request") }- else { (LIMIT_NOW_SECS, "an urgent request") };- (t0 + lim, format!("service limit: {} min for {} from requested_at", lim / 60, what))- } else if eta > 0 {- (now + eta, "Component Ocean eta_seconds".to_string())- } else { return None; };- let passed = now > at || matches!(state, "failed" | "error" | "rejected");- let eta_text = if passed { Some(format!("late: was due {}", fmt_utc(at))) }- else if at - now > eta + 120 || req.get("not_before").is_some() { Some(format!("due by {}", fmt_utc(at))) }- else { None };- Some(Deadline { at, source, passed, eta_text })-}--/// The Hint once the deadline has passed: use a verified page, finish an existing one, or build the part yourself.-pub fn late_hint_text(slug: &str, due: &str, page: &crate::wiki::PageState) -> String {- use crate::wiki::PageState::*;- let r = format!("adom/{}", slug);- match page {- Exists { verified: true } => format!("The factory is late (due {}), but {} already exists and is verified: use it \- (https://wiki.adom.inc/{}). Do not build this part yourself and do not overwrite that page.", due, r, r),- Exists { verified: false } => format!("The factory is late (due {}). {} already exists: finish that page with the {} \- instead of creating a second one, and keep anything a person edited or verified on it.", due, r, SKILL_BUILD_PAGE),- Missing | Unknown(_) => format!("The factory is late (due {}). You may build this part yourself with the {}, publishing \- to {}.{} Never create a duplicate page and never overwrite a page that has a verification record or a person's edit; \- if the factory finishes later, its build does not replace yours.", due, SKILL_BUILD_PAGE, r,- if let Unknown(e) = page { format!(" Could not check whether {} exists ({}): check it before you publish.", r, e) }- else { format!(" {} does not exist yet; check again right before you publish.", r) }),- }-}--/// The page the request will fill: CO's page_url when set, else the MPN as a wiki slug (LTST-C19HE1WT -> ltst-c19he1wt).-pub fn page_slug(req: &serde_json::Value) -> String {- if let Some(u) = req.get("page_url").and_then(|v| v.as_str()).filter(|u| !u.is_empty()) {- return u.trim_end_matches('/').rsplit('/').next().unwrap_or(u).to_string();- }- let s: String = req.get("mpn").and_then(|v| v.as_str()).unwrap_or("").to_lowercase().chars()- .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect();- s.trim_matches('-').to_string()-}--/// Seconds since the epoch, UTC: "2026-11-26 04:15:13" (CO's form), RFC 3339 with Z or an offset, or a number.-fn epoch(v: &serde_json::Value) -> Option<i64> {- if let Some(n) = v.as_i64() { return Some(if n > 100_000_000_000 { n / 1000 } else { n }); }- let s = v.as_str()?.trim();- if let Ok(n) = s.parse::<i64>() { return epoch(&serde_json::json!(n)); }- let n = |a: usize, b: usize| s.get(a..b).and_then(|x| x.parse::<i64>().ok());- let t = days_from_civil(n(0, 4)?, n(5, 7)?, n(8, 10)?) * 86400 + n(11, 13)? * 3600 + n(14, 16)? * 60 + n(17, 19)?;- let tail = s.get(19..).unwrap_or("").trim_start_matches(|c: char| c == '.' || c.is_ascii_digit());- let off = match tail.as_bytes().first() {- Some(b'+') | Some(b'-') => {- let sign = if tail.starts_with('-') { -1 } else { 1 };- let h = tail.get(1..3)?.parse::<i64>().ok()?;- let m = tail.get(4..6).or(tail.get(3..5)).and_then(|x| x.parse::<i64>().ok()).unwrap_or(0);- sign * (h * 3600 + m * 60)- }- _ => 0,- };- Some(t - off)-}--fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {- let y = if m <= 2 { y - 1 } else { y };- let era = if y >= 0 { y } else { y - 399 } / 400;- let yoe = y - era * 400;- let doy = (153 * ((m + 9) % 12) + 2) / 5 + d - 1;- era * 146097 + yoe * 365 + yoe / 4 - yoe / 100 + doy - 719468-}--pub fn fmt_utc(t: i64) -> String {- let (days, secs) = (t.div_euclid(86400), t.rem_euclid(86400));- let z = days + 719468;- let era = if z >= 0 { z } else { z - 146096 } / 146097;- let doe = z - era * 146097;- let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;- let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);- let mp = (5 * doy + 2) / 153;- let d = doy - (153 * mp + 2) / 5 + 1;- let m = if mp < 10 { mp + 3 } else { mp - 9 };- let y = yoe + era * 400 + if m <= 2 { 1 } else { 0 };- format!("{:04}-{:02}-{:02} {:02}:{:02} UTC", y, m, d, secs / 3600, secs % 3600 / 60)-}--#[cfg(test)]-mod request_status_tests {- use super::*;- use crate::wiki::PageState;- use serde_json::json;-- fn at(s: &str) -> i64 { epoch(&json!(s)).unwrap() }-- #[test]- fn retry_hours_away_quotes_the_deadline_not_about_a_minute() {- let now = at("2026-11-26 14:30:00");- let req = json!({"mpn": "LTST-C19HE1WT", "state": "queued", "position": 1, "eta_seconds": 0,- "eta_text": "about a minute", "urgency": "now", "requested_at": "2026-11-26 14:25:00",- "not_before": "2026-11-26T18:00:00Z"});- let d = deadline(&req, now).unwrap();- assert_eq!(fmt_utc(d.at), "2026-11-26 18:00 UTC");- assert!(!d.passed);- assert!(d.source.contains("not_before"), "{}", d.source);- assert!(d.line().contains("due by 2026-11-26 18:00 UTC"));- let t = d.eta_text.unwrap();- assert!(!t.contains("minute"), "{}", t);- }-- #[test]- fn deadline_passed_gives_the_build_it_yourself_hint() {- // the LTST-C19HE1WT stall: queued at 04:15, eta 0 "about a minute", still there 10 hours later- let req = json!({"mpn": "LTST-C19HE1WT", "state": "queued", "position": 1, "eta_seconds": 0,- "eta_text": "about a minute", "urgency": "now", "requested_at": "2026-11-26 04:15:13"});- let d = deadline(&req, at("2026-11-26 14:30:00")).unwrap();- assert!(d.passed);- assert_eq!(fmt_utc(d.at), "2026-11-26 04:35 UTC");- assert!(d.source.starts_with("service limit"));- assert!(!d.eta_text.as_deref().unwrap().contains("minute"));- assert_eq!(page_slug(&req), "ltst-c19he1wt");- let h = late_hint_text(&page_slug(&req), &fmt_utc(d.at), &PageState::Missing);- assert!(h.contains("factory is late") && h.contains("build-a-component-page") && h.contains("adom/ltst-c19he1wt"), "{}", h);- assert!(h.contains("duplicate") && h.contains("verification record"), "{}", h);- // not yet due: no deadline passed- assert!(!deadline(&req, at("2026-11-26 04:20:00")).unwrap().passed);- }-- #[test]- fn verified_page_exists_hint_says_use_it_do_not_build() {- let h = late_hint_text("ltst-c19he1wt", "2026-11-26 04:35 UTC", &PageState::Exists { verified: true });- assert!(h.contains("use it") && h.contains("Do not build") && h.contains("do not overwrite"), "{}", h);- assert!(!h.contains("build-a-component-page"), "{}", h);- assert!(crate::wiki::has_verification(&json!({"verification": {"entries": [{"status": "verified"}]}})));- assert!(!crate::wiki::has_verification(&json!({"verification": {"entries": []}})));- }-- #[test]- fn built_request_has_no_deadline() {- assert!(deadline(&json!({"state": "built", "requested_at": "2026-11-26 04:15:13"}), at("2026-11-27 00:00:00")).is_none());- }-}
src/deadline.rsadded+254@@ -0,0 +1,254 @@+//! When a part request is due, and what to do once it is late.+//!+//! The wiki answers with its own clock from 2026-12-04 on (`deadline_at`, `deadline_passed`), so the CLI, AI Flow and+//! Parts Search agree on one time. Older wikis do not, so the time is then worked out here as PR #6 did: Component+//! Ocean's next retry, or a stated service limit from the time the part was requested.++/// Service limits quoted when Component Ocean gives no retry time (component-factory#3: 20 minutes for an urgent part,+/// an hour for one in review); a `later` request is due within a day.+const LIMIT_NOW_SECS: i64 = 20 * 60;+const LIMIT_REVIEW_SECS: i64 = 60 * 60;+const LIMIT_LATER_SECS: i64 = 24 * 60 * 60;+const SKILL_BUILD_PAGE: &str = "build-a-component-page skill (https://wiki.adom.inc/adom/build-a-component-page)";++#[derive(Debug)]+pub struct Deadline { pub at: i64, pub source: String, pub passed: bool, pub eta_text: Option<String> }++impl Deadline {+ pub fn line(&self) -> String {+ if self.passed { format!("LATE: was due {} ({})", fmt_utc(self.at), self.source) }+ else { format!("due by {} ({})", fmt_utc(self.at), self.source) }+ }+}++/// When the request is due. Component Ocean's `not_before` (its next retry) plus `eta_seconds` when CO gives one,+/// otherwise `requested_at` plus the service limit. None once the request is built or finished.+pub fn deadline(req: &serde_json::Value, now: i64) -> Option<Deadline> {+ let state = req.get("state").and_then(|v| v.as_str()).unwrap_or("");+ if matches!(state, "built" | "done" | "published" | "public" | "cancelled" | "canceled" | "") { return None; }+ let eta = req.get("eta_seconds").and_then(|v| v.as_i64()).unwrap_or(0).max(0);+ let (at, source) = if let Some(nb) = req.get("not_before").and_then(epoch) {+ (nb + eta, format!("Component Ocean not_before: next retry {}{}", fmt_utc(nb),+ if eta > 0 { format!(", plus its {} s ETA", eta) } else { String::new() }))+ } else if let Some(t0) = req.get("requested_at").and_then(epoch) {+ let (lim, what) = if state == "review" { (LIMIT_REVIEW_SECS, "in review") }+ else if req.get("urgency").and_then(|v| v.as_str()) == Some("later") { (LIMIT_LATER_SECS, "a `later` request") }+ else { (LIMIT_NOW_SECS, "an urgent request") };+ (t0 + lim, format!("service limit: {} min for {} from requested_at", lim / 60, what))+ } else if eta > 0 {+ (now + eta, "Component Ocean eta_seconds".to_string())+ } else { return None; };+ let passed = now > at || matches!(state, "failed" | "error" | "rejected");+ let eta_text = if passed { Some(format!("late: was due {}", fmt_utc(at))) }+ else if at - now > eta + 120 || req.get("not_before").is_some() { Some(format!("due by {}", fmt_utc(at))) }+ else { None };+ Some(Deadline { at, source, passed, eta_text })+}++/// The wiki's hint code once a request is past its deadline with the part unbuilt.+pub const LATE_CODE: &str = "PART_REQUEST_DEADLINE_PASSED";++/// A field of a status or request answer, read at the top level first, then inside `request`.+pub fn field<'a>(r: &'a serde_json::Value, k: &str) -> Option<&'a serde_json::Value> {+ r.get(k).filter(|v| !v.is_null()).or_else(|| r.get("request").and_then(|q| q.get(k)).filter(|v| !v.is_null()))+}++/// The request's state ("queued", "building", "review", "built", ...), "?" when the answer has none.+pub fn state(r: &serde_json::Value) -> &str {+ r.get("request").and_then(|q| q.get("state")).or(r.get("state")).and_then(|v| v.as_str()).unwrap_or("?")+}++/// Nothing more will happen on its own: the part is built, or the request ended.+pub fn is_final(state: &str) -> bool {+ matches!(state, "built" | "done" | "published" | "public" | "cancelled" | "canceled" | "failed" | "error" | "rejected")+}++/// The wiki keeps the clock and holds status answers (`?wait`): it sends `deadline_at` or `deadline_passed`.+pub fn wiki_keeps_the_clock(r: &serde_json::Value) -> bool {+ field(r, "deadline_at").is_some() || field(r, "deadline_passed").is_some()+}++/// The wiki says the request is late: `deadline_passed`, or its PART_REQUEST_DEADLINE_PASSED hint.+pub fn wiki_says_late(r: &serde_json::Value) -> bool {+ if field(r, "deadline_passed").and_then(|v| v.as_bool()) == Some(true) { return true; }+ let is_late = |v: &serde_json::Value| v.as_str() == Some(LATE_CODE)+ || v.get("code").and_then(|c| c.as_str()) == Some(LATE_CODE);+ ["code", "hint_code", "hint"].iter().any(|k| field(r, k).map(is_late).unwrap_or(false))+ || field(r, "hints").and_then(|h| h.as_array()).map(|a| a.iter().any(is_late)).unwrap_or(false)+}++/// When the request is due: the wiki's own `deadline_at` and `deadline_passed` when it sends them, else the time+/// worked out here from Component Ocean's answer (older wikis). None once the part is built or the request ended.+pub fn due(r: &serde_json::Value, now: i64) -> Option<Deadline> {+ let req = r.get("request").cloned().unwrap_or(serde_json::Value::Null);+ if is_final(state(r)) { return None; }+ if wiki_keeps_the_clock(r) {+ let at = field(r, "deadline_at").and_then(epoch);+ let passed = wiki_says_late(r);+ return at.map(|at| Deadline { at, source: "the wiki's deadline".into(), passed,+ eta_text: Some(if passed { format!("late: was due {}", fmt_utc(at)) } else { format!("due by {}", fmt_utc(at)) }) })+ .or_else(|| passed.then(|| Deadline { at: now, source: "the wiki says the deadline passed".into(), passed, eta_text: None }));+ }+ deadline(&req, now)+}++/// The Hint once the deadline has passed: use a verified page, finish an existing one, or build the part yourself.+pub fn late_hint_text(slug: &str, due: &str, page: &crate::wiki::PageState) -> String {+ use crate::wiki::PageState::*;+ let r = format!("adom/{}", slug);+ match page {+ Exists { verified: true } => format!("The factory is late (due {}), but {} already exists and is verified: use it \+ (https://wiki.adom.inc/{}). Do not build this part yourself and do not overwrite that page.", due, r, r),+ Exists { verified: false } => format!("The factory is late (due {}). {} already exists: finish that page with the {} \+ instead of creating a second one, and keep anything a person edited or verified on it.", due, r, SKILL_BUILD_PAGE),+ Missing | Unknown(_) => format!("The factory is late (due {}). You may build this part yourself with the {}, publishing \+ to {}.{} Never create a duplicate page and never overwrite a page that has a verification record or a person's edit; \+ if the factory finishes later, its build does not replace yours.", due, SKILL_BUILD_PAGE, r,+ if let Unknown(e) = page { format!(" Could not check whether {} exists ({}): check it before you publish.", r, e) }+ else { format!(" {} does not exist yet; check again right before you publish.", r) }),+ }+}++/// The page the request will fill: CO's page_url when set, else the MPN as a wiki slug (LTST-C19HE1WT -> ltst-c19he1wt).+pub fn page_slug(req: &serde_json::Value) -> String {+ if let Some(u) = req.get("page_url").and_then(|v| v.as_str()).filter(|u| !u.is_empty()) {+ return u.trim_end_matches('/').rsplit('/').next().unwrap_or(u).to_string();+ }+ let s: String = req.get("mpn").and_then(|v| v.as_str()).unwrap_or("").to_lowercase().chars()+ .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect();+ s.trim_matches('-').to_string()+}++/// Seconds since the epoch, UTC: "2026-11-26 04:15:13" (CO's form), RFC 3339 with Z or an offset, or a number.+pub fn epoch(v: &serde_json::Value) -> Option<i64> {+ if let Some(n) = v.as_i64() { return Some(if n > 100_000_000_000 { n / 1000 } else { n }); }+ let s = v.as_str()?.trim();+ if let Ok(n) = s.parse::<i64>() { return epoch(&serde_json::json!(n)); }+ let n = |a: usize, b: usize| s.get(a..b).and_then(|x| x.parse::<i64>().ok());+ let t = days_from_civil(n(0, 4)?, n(5, 7)?, n(8, 10)?) * 86400 + n(11, 13)? * 3600 + n(14, 16)? * 60 + n(17, 19)?;+ let tail = s.get(19..).unwrap_or("").trim_start_matches(|c: char| c == '.' || c.is_ascii_digit());+ let off = match tail.as_bytes().first() {+ Some(b'+') | Some(b'-') => {+ let sign = if tail.starts_with('-') { -1 } else { 1 };+ let h = tail.get(1..3)?.parse::<i64>().ok()?;+ let m = tail.get(4..6).or(tail.get(3..5)).and_then(|x| x.parse::<i64>().ok()).unwrap_or(0);+ sign * (h * 3600 + m * 60)+ }+ _ => 0,+ };+ Some(t - off)+}++fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {+ let y = if m <= 2 { y - 1 } else { y };+ let era = if y >= 0 { y } else { y - 399 } / 400;+ let yoe = y - era * 400;+ let doy = (153 * ((m + 9) % 12) + 2) / 5 + d - 1;+ era * 146097 + yoe * 365 + yoe / 4 - yoe / 100 + doy - 719468+}++pub fn fmt_utc(t: i64) -> String {+ let (days, secs) = (t.div_euclid(86400), t.rem_euclid(86400));+ let z = days + 719468;+ let era = if z >= 0 { z } else { z - 146096 } / 146097;+ let doe = z - era * 146097;+ let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);+ let mp = (5 * doy + 2) / 153;+ let d = doy - (153 * mp + 2) / 5 + 1;+ let m = if mp < 10 { mp + 3 } else { mp - 9 };+ let y = yoe + era * 400 + if m <= 2 { 1 } else { 0 };+ format!("{:04}-{:02}-{:02} {:02}:{:02} UTC", y, m, d, secs / 3600, secs % 3600 / 60)+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::wiki::PageState;+ use serde_json::json;++ fn at(s: &str) -> i64 { epoch(&json!(s)).unwrap() }++ #[test]+ fn retry_hours_away_quotes_the_deadline_not_about_a_minute() {+ let now = at("2026-11-26 14:30:00");+ let req = json!({"mpn": "LTST-C19HE1WT", "state": "queued", "position": 1, "eta_seconds": 0,+ "eta_text": "about a minute", "urgency": "now", "requested_at": "2026-11-26 14:25:00",+ "not_before": "2026-11-26T18:00:00Z"});+ let d = deadline(&req, now).unwrap();+ assert_eq!(fmt_utc(d.at), "2026-11-26 18:00 UTC");+ assert!(!d.passed);+ assert!(d.source.contains("not_before"), "{}", d.source);+ assert!(d.line().contains("due by 2026-11-26 18:00 UTC"));+ let t = d.eta_text.unwrap();+ assert!(!t.contains("minute"), "{}", t);+ }++ #[test]+ fn deadline_passed_gives_the_build_it_yourself_hint() {+ // the LTST-C19HE1WT stall: queued at 04:15, eta 0 "about a minute", still there 10 hours later+ let req = json!({"mpn": "LTST-C19HE1WT", "state": "queued", "position": 1, "eta_seconds": 0,+ "eta_text": "about a minute", "urgency": "now", "requested_at": "2026-11-26 04:15:13"});+ let d = deadline(&req, at("2026-11-26 14:30:00")).unwrap();+ assert!(d.passed);+ assert_eq!(fmt_utc(d.at), "2026-11-26 04:35 UTC");+ assert!(d.source.starts_with("service limit"));+ assert!(!d.eta_text.as_deref().unwrap().contains("minute"));+ assert_eq!(page_slug(&req), "ltst-c19he1wt");+ let h = late_hint_text(&page_slug(&req), &fmt_utc(d.at), &PageState::Missing);+ assert!(h.contains("factory is late") && h.contains("build-a-component-page") && h.contains("adom/ltst-c19he1wt"), "{}", h);+ assert!(h.contains("duplicate") && h.contains("verification record"), "{}", h);+ // not yet due: no deadline passed+ assert!(!deadline(&req, at("2026-11-26 04:20:00")).unwrap().passed);+ }++ #[test]+ fn verified_page_exists_hint_says_use_it_do_not_build() {+ let h = late_hint_text("ltst-c19he1wt", "2026-11-26 04:35 UTC", &PageState::Exists { verified: true });+ assert!(h.contains("use it") && h.contains("Do not build") && h.contains("do not overwrite"), "{}", h);+ assert!(!h.contains("build-a-component-page"), "{}", h);+ assert!(crate::wiki::has_verification(&json!({"verification": {"entries": [{"status": "verified"}]}})));+ assert!(!crate::wiki::has_verification(&json!({"verification": {"entries": []}})));+ }++ #[test]+ fn the_wikis_deadline_wins_over_the_local_estimate() {+ // the wiki says 04:35 and not late, though Component Ocean's not_before would say 18:00+ let r = json!({"request": {"mpn": "LM358", "state": "queued", "requested_at": "2026-12-04 04:15:00",+ "not_before": "2026-12-04T18:00:00Z"}, "deadline_at": "2026-12-04T04:35:00Z", "deadline_passed": false});+ let d = due(&r, at("2026-12-04 04:20:00")).unwrap();+ assert_eq!(fmt_utc(d.at), "2026-12-04 04:35 UTC");+ assert!(!d.passed && d.source == "the wiki's deadline");+ assert!(wiki_keeps_the_clock(&r));+ // the wiki's word decides late, not this machine's clock+ let d = due(&r, at("2026-12-04 09:00:00")).unwrap();+ assert!(!d.passed, "local clock must not override deadline_passed: false");+ }++ #[test]+ fn late_from_deadline_passed_or_the_hint_code() {+ let r = json!({"request": {"state": "queued", "deadline_at": "2026-12-04 04:35:00", "deadline_passed": true}});+ let d = due(&r, at("2026-12-04 05:00:00")).unwrap();+ assert!(d.passed && d.line().starts_with("LATE: was due 2026-12-04 04:35 UTC"), "{}", d.line());+ let r = json!({"request": {"state": "queued"}, "deadline_at": "2026-12-04T04:35:00Z",+ "hint": {"code": "PART_REQUEST_DEADLINE_PASSED", "text": "late"}});+ assert!(wiki_says_late(&r) && due(&r, 0).unwrap().passed);+ let r = json!({"request": {"state": "queued"}, "deadline_passed": true});+ assert!(due(&r, 100).unwrap().passed, "late with no deadline_at still reads late");+ }++ #[test]+ fn an_older_wiki_falls_back_to_the_local_estimate() {+ let r = json!({"request": {"mpn": "LTST-C19HE1WT", "state": "queued", "urgency": "now", "requested_at": "2026-11-26 04:15:13"}});+ assert!(!wiki_keeps_the_clock(&r));+ let d = due(&r, at("2026-11-26 14:30:00")).unwrap();+ assert!(d.passed && d.source.starts_with("service limit"));+ // built: nothing is due, whatever the wiki sends+ assert!(due(&json!({"request": {"state": "built"}, "deadline_passed": true}), 0).is_none());+ }++ #[test]+ fn built_request_has_no_deadline() {+ assert!(deadline(&json!({"state": "built", "requested_at": "2026-11-26 04:15:13"}), at("2026-11-27 00:00:00")).is_none());+ }+}
src/main.rs+14−3@@ -11,8 +11,10 @@ mod app; mod cli;+mod deadline; mod host; mod install;+mod request; mod serve; mod settings; mod taskbar;@@ -87,7 +89,12 @@ enum Cmd { Request(RequestArgs), /// Where a part request stands now (the id or status link `request` printed).- RequestStatus { id: String },+ RequestStatus {+ id: String,+ /// Follow it: the wiki holds each answer until something changes; one line per change, until the part is+ /// built, goes to review or passes its deadline.+ #[arg(long)] wait: bool,+ }, /// Run the Parts Search page server in the foreground (3-column grid with product photos). App(AppArgs),@@ -184,6 +191,10 @@ 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,+ /// Email me when it is ready, instead of this thread following it (the default for a signed-in request).+ #[arg(long)] pub email: bool,+ /// Minutes until the request is due (1 to 1440); the wiki's default is 20.+ #[arg(long)] pub deadline: Option<u32>, } #[derive(clap::Args)]@@ -233,8 +244,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::Request(a) => request::run_request(a),+ Cmd::RequestStatus { id, wait } => request::run_request_status(&id, wait), Cmd::Show(a) => cli::run_show(a), Cmd::App(a) => app::run(a), Cmd::Serve(a) => serve::run(a.port, a.print_url),
src/request.rsadded+173@@ -0,0 +1,173 @@+//! `request <MPN>` and `request-status <id> [--wait]`: the wiki's own part-request flow.+//!+//! A signed-in request is answered in the thread that asked (wikis from 2026-12-04 on): no email, a status to follow+//! and a deadline. `--email` asks for the email instead. `request-status --wait` lets the wiki hold each answer until+//! something changes, so a thread follows its request without polling.++use crate::deadline::{self, due, fmt_utc, is_final, late_hint_text, page_slug, state, wiki_keeps_the_clock, wiki_says_late};+use serde_json::Value;+use std::time::{Duration, Instant};++/// Seconds the wiki is asked to hold one status answer (it allows 55).+const WAIT_SECS: u64 = 50;+/// The longest `--wait` follows a request: past the longest deadline the wiki accepts (1440 minutes).+const FOLLOW_MAX: Duration = Duration::from_secs(25 * 3600);+/// A wiki that answers at once with nothing new is not asked again sooner than this.+const MIN_GAP: Duration = Duration::from_secs(10);++fn now() -> i64 {+ std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0)+}++/// The request id from an answer: `request.id`, else the last part of its status link.+pub fn request_id(r: &Value) -> Option<String> {+ if let Some(i) = r.pointer("/request/id").filter(|v| !v.is_null()) {+ return Some(i.as_str().map(String::from).unwrap_or_else(|| i.to_string()));+ }+ ["status_api", "status_url"].iter().filter_map(|k| deadline::field(r, k).and_then(|v| v.as_str()))+ .filter_map(|u| u.trim_end_matches('/').rsplit('/').next().map(String::from)).find(|s| !s.is_empty())+}++/// Where the answer goes, in words: this thread (no email), or an email. None when the part already has a page.+pub fn notify_line(r: &Value, id: Option<&str>) -> Option<String> {+ if r.get("already").and_then(|v| v.as_str()) == Some("built") { return None; }+ let due = deadline::field(r, "deadline_at").and_then(|v| deadline::epoch(v)).map(|t| format!(", due by {}", fmt_utc(t)))+ .unwrap_or_default();+ let follow = id.map(|i| format!("`adom-parts-search request-status {} --wait`", i)).unwrap_or_else(|| "request-status --wait".into());+ match r.get("notify").and_then(|v| v.as_str()) {+ Some("thread") => Some(format!("No email: this thread follows it with {}{}", follow, due)),+ Some("email") => Some(format!("The wiki emails you when it is ready{}", due)),+ Some(other) => Some(format!("Answered by {}{}", other, due)),+ None => Some("The wiki emails you when it is ready (this wiki does not answer in the thread yet)".into()),+ }+}++pub fn run_request(a: crate::RequestArgs) -> Result<(), String> {+ if a.urgency != "now" && a.urgency != "later" { return Err("--urgency is now or later".into()); }+ if let Some(m) = a.deadline { if !(1..=1440).contains(&m) { return Err("--deadline is 1 to 1440 minutes".into()); } }+ let opts = crate::wiki::RequestOpts { notify: a.email.then(|| "email".to_string()), deadline_minutes: a.deadline };+ let r = crate::wiki::request(&a.mpn, &a.urgency, &opts)?;+ let req = r.get("request").cloned().unwrap_or(Value::Null);+ let status = r.get("status_url").and_then(|v| v.as_str()).unwrap_or("");+ let id = request_id(&r);+ let head = match (r.get("already").and_then(|v| v.as_str()), state(&r)) {+ (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),+ (_, st) => format!("{} requested ({}{}); status: {}", a.mpn, st,+ r.get("position").and_then(|v| v.as_u64()).map(|p| format!(", position {}", p)).unwrap_or_default(), status),+ };+ crate::ok(match notify_line(&r, id.as_deref()) { Some(n) => format!("{}. {}", head, n), None => head });+ println!("{}", serde_json::to_string_pretty(&r).unwrap_or_default());+ if r.get("notify").and_then(|v| v.as_str()) == Some("thread") {+ if let Some(i) = &id {+ crate::hint(format!("Follow it with `adom-parts-search request-status {} --wait`: one line per change, until the part \+ is built, goes to review or passes its deadline. Do not loop request-status yourself.", i));+ }+ }+ Ok(())+}++/// One line for where a request stands: state, reason, position, and when it is due.+pub fn status_line(id: &str, r: &Value, now: i64) -> String {+ let reason = deadline::field(r, "public_reason").or(deadline::field(r, "reason")).and_then(|v| v.as_str())+ .map(|x| format!(" ({})", x)).unwrap_or_default();+ let pos = deadline::field(r, "position").and_then(|v| v.as_u64()).map(|p| format!(", position {}", p)).unwrap_or_default();+ let d = due(r, now).map(|d| format!("; {}", d.line())).unwrap_or_default();+ format!("request {}: {}{}{}{}", id, state(r), reason, pos, d)+}++/// Following stops once the part is built or the request ended, it went to a person's review, or it is late.+fn settled(r: &Value) -> bool { is_final(state(r)) || state(r) == "review" || wiki_says_late(r) }++pub fn run_request_status(id: &str, wait: bool) -> Result<(), String> {+ let id = id.trim_end_matches('/').rsplit('/').next().unwrap_or(id).to_string();+ let mut r = crate::wiki::request_status(&id, None)?;+ let mut last = status_line(&id, &r, now());+ crate::ok(&last);+ if wait && !settled(&r) {+ if !wiki_keeps_the_clock(&r) {+ crate::warn("this wiki does not hold status answers yet (its answer has no deadline_at), so --wait cannot \+ follow the request; run request-status again later");+ } else {+ r = follow(&id, r, &mut last)?;+ }+ }+ finish(r)+}++/// Long-poll the wiki (`?wait=50&since=<state>`) and print a line each time something changes.+fn follow(id: &str, mut r: Value, last: &mut String) -> Result<Value, String> {+ let started = Instant::now();+ let mut errors = 0;+ while !settled(&r) && started.elapsed() < FOLLOW_MAX {+ let t0 = Instant::now();+ let since = state(&r).to_string();+ match crate::wiki::request_status(id, Some((WAIT_SECS, Some(&since)))) {+ Ok(n) => { errors = 0; r = n; }+ Err(e) => {+ errors += 1;+ if errors >= 3 { return Err(format!("lost the wiki while following request {}: {}", id, e)); }+ std::thread::sleep(Duration::from_secs(15));+ continue;+ }+ }+ let line = status_line(id, &r, now());+ if line != *last { crate::ok(&line); *last = line; }+ else if t0.elapsed() < Duration::from_secs(5) { std::thread::sleep(MIN_GAP); }+ }+ Ok(r)+}++/// The full answer on stdout with the deadline written in, and once late, the Hint to build the part.+fn finish(mut r: Value) -> Result<(), String> {+ let req = r.get("request").cloned().unwrap_or(Value::Null);+ let mut late_hint = None;+ if let Some(d) = due(&r, now()) {+ // CO's eta_text is not quoted when it contradicts the deadline (a retry hours away, or already late)+ if let Some(t) = d.eta_text.clone() { if r["request"].is_object() { r["request"]["eta_text"] = Value::String(t); } }+ r["deadline"] = serde_json::json!({"at": fmt_utc(d.at), "source": d.source, "passed": d.passed});+ if d.passed {+ let slug = page_slug(&req);+ late_hint = Some(late_hint_text(&slug, &fmt_utc(d.at), &crate::wiki::page_state("adom", &slug, Some(&crate::wiki::request_base()))));+ }+ }+ println!("{}", serde_json::to_string_pretty(&r).unwrap_or_default());+ if let Some(h) = late_hint { crate::hint(h); }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn a_thread_request_says_no_email_and_how_to_follow() {+ let r = json!({"request": {"id": "abc123", "state": "queued"}, "notify": "thread",+ "deadline_at": "2026-12-04T04:35:00Z", "status_api": "https://wiki.adom.inc/api/part-request/status/abc123"});+ let id = request_id(&r);+ assert_eq!(id.as_deref(), Some("abc123"));+ let l = notify_line(&r, id.as_deref()).unwrap();+ assert!(l.starts_with("No email") && l.contains("request-status abc123 --wait") && l.contains("due by 2026-12-04 04:35 UTC"), "{}", l);+ }++ #[test]+ fn email_and_older_wikis_say_email() {+ assert!(notify_line(&json!({"notify": "email"}), None).unwrap().starts_with("The wiki emails you"));+ assert!(notify_line(&json!({"request": {"state": "queued"}}), None).unwrap().contains("does not answer in the thread yet"));+ assert!(notify_line(&json!({"already": "built"}), None).is_none());+ // the id from a status link when the request has none+ assert_eq!(request_id(&json!({"status_url": "https://wiki.adom.inc/part-request/41zd/"})).as_deref(), Some("41zd"));+ }++ #[test]+ fn following_stops_at_built_review_or_late() {+ assert!(settled(&json!({"request": {"state": "built"}})));+ assert!(settled(&json!({"request": {"state": "review"}})));+ assert!(settled(&json!({"request": {"state": "queued"}, "deadline_passed": true})));+ assert!(!settled(&json!({"request": {"state": "queued"}, "deadline_passed": false})));+ let l = status_line("abc", &json!({"request": {"state": "queued", "position": 2}, "deadline_at": "2026-12-04T04:35:00Z",+ "deadline_passed": false}), 0);+ assert_eq!(l, "request abc: queued, position 2; due by 2026-12-04 04:35 UTC (the wiki's deadline)");+ }+}
src/wiki.rs+36−10@@ -241,23 +241,49 @@ fn post(base: &str, path: &str, body: Value, tok: &Option<String>, secs: u64) -> } } +/// Where part requests go: the wiki, or ADOM_PARTS_SEARCH_WIKI (a test wiki or a local mock) when set.+pub fn request_base() -> String {+ std::env::var("ADOM_PARTS_SEARCH_WIKI").ok().map(|u| u.trim().trim_end_matches('/').to_string())+ .filter(|u| !u.is_empty()).unwrap_or_else(|| DEFAULT_WIKI.to_string())+}++/// How a request is answered. `notify: None` leaves it to the wiki, which answers a signed-in (token) request in the+/// thread that asked: no email, a status to follow and a deadline. `Some("email")` asks for the email instead.+#[derive(Debug, Clone, Default)]+pub struct RequestOpts { pub notify: Option<String>, pub deadline_minutes: Option<u32> }+ /// Have Adom's factory build a page for this part, through the wiki's own request flow (the "Request this part"-/// button posts the same call). The answer carries the request, its status_url and its position or ETA.-pub fn request(mpn: &str, urgency: &str, base: Option<&str>) -> Result<Value, String> {+/// button posts the same call). The answer carries the request, its status link, `status_api`, `notify` and+/// `deadline_at` (wikis from 2026-12-04 on), and its position or ETA.+pub fn request(mpn: &str, urgency: &str, opts: &RequestOpts) -> Result<Value, String> { let tok = token(); if tok.is_none() { return Err("not signed in to the wiki: run `adom-wiki auth login` (or set ADOM_WIKI_TOKEN), then request again".into()); }- let base = base.unwrap_or(DEFAULT_WIKI);- let mut r = post(base, "/api/part-request", serde_json::json!({"mpn": mpn.trim(), "urgency": urgency}), &tok, 60)?;- // the wiki answers a site-relative status link; a CLI or another app needs the full one- if let Some(u) = r.get("status_url").and_then(|v| v.as_str()).filter(|u| u.starts_with('/')).map(String::from) {- r["status_url"] = Value::String(format!("{}{}", base.trim_end_matches('/'), u));+ let base = request_base();+ let mut body = serde_json::json!({"mpn": mpn.trim(), "urgency": urgency});+ if let Some(n) = &opts.notify { body["notify"] = Value::String(n.clone()); }+ if let Some(m) = opts.deadline_minutes { body["deadline_minutes"] = Value::from(m); }+ let mut r = post(&base, "/api/part-request", body, &tok, 60)?;+ // the wiki answers site-relative links; a CLI or another app needs the full ones+ for k in ["status_url", "status_api"] {+ if let Some(u) = r.get(k).and_then(|v| v.as_str()).filter(|u| u.starts_with('/')).map(String::from) {+ r[k] = Value::String(format!("{}{}", base, u));+ } } Ok(r) } -/// Where a request stands now (GET /api/part-request/status/<id>).-pub fn request_status(id: &str, base: Option<&str>) -> Result<Value, String> {- get(base.unwrap_or(DEFAULT_WIKI), &format!("/api/part-request/status/{}", urlencode(id)), &token(), 20)+/// Where a request stands now (GET /api/part-request/status/<id>). With `wait`, the wiki holds the answer (at most+/// 55 s) until the state moves on from `since`, the deadline passes, or the wait runs out.+pub fn request_status(id: &str, wait: Option<(u64, Option<&str>)>) -> Result<Value, String> {+ let mut path = format!("/api/part-request/status/{}", urlencode(id));+ let mut secs = 20;+ if let Some((w, since)) = wait {+ let w = w.min(55);+ path.push_str(&format!("?wait={}", w));+ if let Some(s) = since { path.push_str(&format!("&since={}", urlencode(s))); }+ secs = w + 20;+ }+ get(&request_base(), &path, &token(), secs) } /// Whether adom/<slug> exists and carries a verification record (checked before an AI builds a late part itself).
uninstall.sh