From 50cd0275e7d80a47cd5f5bdee08d49085580ee42 Mon Sep 17 00:00:00 2001 From: root Date: Wed, 18 Nov 2026 10:19:43 -0500 Subject: [PATCH 1/6] Reports stop waiting on slow manufacturer recall lookups The maker's VIN recall lookup now starts right after the decode, beside NHTSA's calls, and a report waits for it at most 2 s (website, REST) or 6 s (MCP decode_vin), counted from its start. Past that, recall_status is {pending: true, reason: 'lookup_in_progress', status_url} (unknown, never 'no open recalls') and the lookup finishes in the background, filling its 15-minute cache. Concurrent requests share one lookup; a background failure is contained. ?recall_wait=full (REST) and recall_wait 'full' (MCP) wait for it; comparisons always wait. /api/vin/{vin}/recall-status and MCP vin_recall_status resolve the make from the decode when the WMI alone does not name the maker, so they join the lookup a report started. Also: related-name recall lookups start beside the exact one and run three at a time; safety-rating details three at a time; the Transport Canada generation check asks all years at once. Co-Authored-By: Claude Opus 5.5 --- lib/mcp/research-tools.mjs | 4 +- lib/mcp/vehicle-tools.mjs | 11 +-- lib/nhtsa.mjs | 49 +++++++---- lib/recall-status.mjs | 40 +++++++-- lib/reports.mjs | 170 ++++++++++++++++++++++++++++++++----- lib/tire-placards.mjs | 10 ++- public/index.html | 4 +- server.mjs | 12 ++- 8 files changed, 239 insertions(+), 61 deletions(-) diff --git a/lib/mcp/research-tools.mjs b/lib/mcp/research-tools.mjs index dbefb25..ddc6525 100644 --- a/lib/mcp/research-tools.mjs +++ b/lib/mcp/research-tools.mjs @@ -5,7 +5,7 @@ import { rateBenchmarks } from '../rate-benchmarks.mjs'; import { scenario } from '../scenario.mjs'; import { communications } from '../communications.mjs'; import { capabilities } from '../capabilities.mjs'; -import { vinRecallStatus } from '../recall-status.mjs'; +import { vinRecallStatusFor } from '../reports.mjs'; import { compareVehicles } from '../reports.mjs'; export function researchTools(add) { @@ -15,7 +15,7 @@ export function researchTools(add) { }); const vehicleQuery={year:z.number().int(),make:z.string().min(1).max(100),model:z.string().min(1).max(100)}; researchTool('explore_capabilities','Discover supported features and explicit coverage gaps.',{},()=>capabilities); - researchTool('vin_recall_status','VIN-specific manufacturer-reported open and completed recall status. Tesla and Ford open/completed states; GM completed/closed states with explicit repair dates where supplied; Honda and Acura active safety recalls; Subaru completed/incomplete safety recalls; Volkswagen, Audi, Land Rover and Jaguar recalls as reported by each maker; Nissan positive open safety recalls; Mopar positive open records matched to the full VIN. Service programs are separate. Toyota, Hyundai and Kia require interactive official verification. Unknowns are never zero. Not a complete service history. Where the maker\'s reply describes the VIN (Volkswagen, Audi, Land Rover, Jaguar, Subaru, Honda/Acura), manufacturer_description gives the raw text and only the fields it states.',{vin:z.string()},({vin})=>vinRecallStatus(vin)); + researchTool('vin_recall_status','VIN-specific manufacturer-reported open and completed recall status. Tesla and Ford open/completed states; GM completed/closed states with explicit repair dates where supplied; Honda and Acura active safety recalls; Subaru completed/incomplete safety recalls; Volkswagen, Audi, Land Rover and Jaguar recalls as reported by each maker; Nissan positive open safety recalls; Mopar positive open records matched to the full VIN. Service programs are separate. Toyota, Hyundai and Kia require interactive official verification. Unknowns are never zero. Not a complete service history. Where the maker\'s reply describes the VIN (Volkswagen, Audi, Land Rover, Jaguar, Subaru, Honda/Acura), manufacturer_description gives the raw text and only the fields it states. When a decode_vin report has recall_status.pending, this waits for that same lookup (up to about 15 s).',{vin:z.string()},({vin})=>vinRecallStatusFor(vin)); researchTool('vehicle_catalog','Browse EPA year, make, model and configuration menus. Not sale listings.',{level:z.enum(['year','make','model','options']),year:z.number().int().optional(),make:z.string().optional(),model:z.string().optional()},({level,...query})=>catalog(level,query)); researchTool('epa_vehicle','Get an explicitly selected EPA test configuration; not an exact VIN match.',{id:z.string()},({id})=>epaRecord(id)); researchTool('vehicle_emissions','Get EPA emissions for an explicit EPA vehicle ID.',{id:z.string()},({id})=>emissions(id)); diff --git a/lib/mcp/vehicle-tools.mjs b/lib/mcp/vehicle-tools.mjs index 0a2c944..d984dff 100644 --- a/lib/mcp/vehicle-tools.mjs +++ b/lib/mcp/vehicle-tools.mjs @@ -1,16 +1,17 @@ import * as z from 'zod/v4'; import { validateVin, normalizeVin } from '../validate.mjs'; import { decodeVin as nhtsaDecode, batchDecode } from '../nhtsa.mjs'; -import { fullReport, mcpReport, modelYearRecalls } from '../reports.mjs'; +import { fullReport, mcpReport, modelYearRecalls, RECALL_WAIT_MS } from '../reports.mjs'; import { applyOwnerDetails } from '../transmission-choice.mjs'; export function vehicleTools(add) { add('decode_vin', - 'Decode a VIN and return a vehicle report: specs, recalls (with manufacturer build-date ranges), a complaint summary with the most recent complaints, safety ratings, fuel economy, EPA test-vehicle data, parts content and origin (MY2020+), historical production and theft (MY1998-2012), and photo URLs. decode_checks checks the official decode field by field (drive, engine, electrification, transmission, speeds, seats, GVWR) against the manufacturer\'s description of this VIN, NHTSA test vehicles with the same VIN pattern and EPA\'s configurations: confirmed, corrected, doubtful or filled, with vPIC\'s original value kept.', + 'Decode a VIN and return a vehicle report: specs, recalls (with manufacturer build-date ranges), a complaint summary with the most recent complaints, safety ratings, fuel economy, EPA test-vehicle data, parts content and origin (MY2020+), historical production and theft (MY1998-2012), and photo URLs. decode_checks checks the official decode field by field (drive, engine, electrification, transmission, speeds, seats, GVWR) against the manufacturer\'s description of this VIN, NHTSA test vehicles with the same VIN pattern and EPA\'s configurations: confirmed, corrected, doubtful or filled, with vPIC\'s original value kept. recall_status is the manufacturer\'s VIN-specific recall status; a maker that has not answered within about 6 s (Ford\'s lookup takes 10 s or more) gives recall_status.pending true: unknown, not "no open recalls"; call vin_recall_status with the VIN for the complete answer, or pass recall_wait "full".', { vin: z.string().describe('17-character Vehicle Identification Number'), - transmission: z.optional(z.enum(['automatic', 'manual'])).describe('Transmission, when the owner knows it and the VIN does not say. Applies to fuel economy only when EPA lists the model with both; without it an automatic is assumed and marked (fuel_economy.assumed, alternatives).') }, - async ({ vin, transmission }) => { - const report = mcpReport(applyOwnerDetails(await fullReport(vin), { transmission }, { by: 'request' })); + transmission: z.optional(z.enum(['automatic', 'manual'])).describe('Transmission, when the owner knows it and the VIN does not say. Applies to fuel economy only when EPA lists the model with both; without it an automatic is assumed and marked (fuel_economy.assumed, alternatives).'), + recall_wait: z.optional(z.enum(['full'])).describe('"full": wait for the manufacturer\'s VIN recall lookup (up to about 15 s) instead of returning recall_status.pending after about 6 s.') }, + async ({ vin, transmission, recall_wait }) => { + const report = mcpReport(applyOwnerDetails(await fullReport(vin, { recallWaitMs: recall_wait === 'full' ? Infinity : RECALL_WAIT_MS.mcp }), { transmission }, { by: 'request' })); return { content: [{ type: 'text', text: JSON.stringify(report, null, 2) }] }; } ); diff --git a/lib/nhtsa.mjs b/lib/nhtsa.mjs index edb2681..49a0197 100644 --- a/lib/nhtsa.mjs +++ b/lib/nhtsa.mjs @@ -369,6 +369,23 @@ const RELATED_NOTE = 'Campaigns NHTSA files for the same make and year under ano * Labels come from NHTSA's /products/vehicle/models reply, which lists only part of a make's * labels (checked 2026-11-16), and from the local flat-file label index when it is installed. */ +/** Run `fn` over `items`, at most `limit` at a time; results in input order. */ +export async function mapLimit(items, limit, fn) { + const out = new Array(items.length); + let next = 0; + const worker = async () => { while (next < items.length) { const i = next++; out[i] = await fn(items[i], i); } }; + await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker)); + return out; +} + +// Related-name campaign lookups in flight at once (one recallsByVehicle call each; results cached 6 hours per +// make/model/year by lib/reports.mjs). Was one at a time; three keeps the same requests gentle and cuts the wait. +const RELATED_CONCURRENCY = 3; + +/** + * `exactRecalls`: the exact-name campaigns, or a promise of them (the label search then runs while the exact lookup + * is still out); null (or a promise of null) when the exact lookup failed: no per-name lookup is made then. + */ export async function getRelatedModelRecalls(make, model, year, exactRecalls = [], { labelIndex = lookupRecallLabels } = {}) { const unavailable = { available: false, scope: 'make_related_model_year', vin_specific: false, count: null, models: [] }; try { @@ -386,14 +403,11 @@ export async function getRelatedModelRecalls(make, model, year, exactRecalls = [ const decodedNameUsed = index?.available ? decodedNameForms(model).some(n => index.used_names.has(n)) : true; const matches = relatedModelMatches(model, labels, { make, decodedNameUsed }); const checked = matches.slice(0, MAX_RELATED_LABELS), unchecked = matches.slice(MAX_RELATED_LABELS); - const known = new Set(exactRecalls.map(r => r?.campaign_number).filter(Boolean)); - // One label at a time, as before: gentle on api.nhtsa.gov, and the result is cached per make/model/year. - const results = []; - for (const m of checked) { - const r = await getRecalls(make, m.label, year); - if (r.available === false) return unavailable; - results.push(r); - } + const exact = await exactRecalls; + if (!Array.isArray(exact)) return unavailable; + const known = new Set(exact.map(r => r?.campaign_number).filter(Boolean)); + const results = await mapLimit(checked, RELATED_CONCURRENCY, m => getRecalls(make, m.label, year)); + if (results.some(r => r.available === false)) return unavailable; const models = [], seen = new Set(); checked.forEach((m, i) => { const extra = results[i].recalls.filter(c => c.campaign_number && !known.has(c.campaign_number) && !seen.has(c.campaign_number)); @@ -538,23 +552,22 @@ export async function getSafetyRatings(make, model, year) { return empty; } - // Step 2: Fetch details for each variant - const detailedVariants = []; - for (const variant of variants) { + // Step 2: Fetch details for each variant, three at a time (was one after another), kept in NHTSA's order + const details = await mapLimit(variants, 3, async variant => { const vehicleId = variant.VehicleId; - if (!vehicleId) continue; + if (!vehicleId) return null; try { const detailUrl = `${SAFETY_BASE}/VehicleId/${vehicleId}?format=json`; const detailRes = await fetch(detailUrl, { signal: timeoutSignal() }); - if (!detailRes.ok) continue; + if (!detailRes.ok) return null; const detailData = await detailRes.json(); const r = detailData?.Results?.[0]; - if (!r) continue; + if (!r) return null; - detailedVariants.push({ + return { vehicle_id: vehicleId, description: clean(r.VehicleDescription), overall: num(r.OverallRating), @@ -564,11 +577,13 @@ export async function getSafetyRatings(make, model, year) { side_passenger: num(r.SideCrashPassengersideRating), rollover: num(r.RolloverRating), side_pole: num(r.SidePoleCrashRating), - }); + }; } catch (innerErr) { console.error(`[nhtsa] getSafetyRatings detail error for ${vehicleId}:`, innerErr.message); + return null; } - } + }); + const detailedVariants = details.filter(Boolean); if (detailedVariants.length === 0) { return empty; diff --git a/lib/recall-status.mjs b/lib/recall-status.mjs index 2fd9271..c3e1b00 100644 --- a/lib/recall-status.mjs +++ b/lib/recall-status.mjs @@ -32,6 +32,37 @@ function documentUrl(value) { catch { return null; } } +const BY_WMI=[[TESLA_WMIS,'tesla'],[MOPAR_WMIS,'mopar'],[TOYOTA_WMIS,'toyota'],[FORD_WMIS,'ford'],[GM_WMIS,'gm'],[HONDA_WMIS,'honda'],[NISSAN_WMIS,'nissan'],[HYUNDAI_WMIS,'hyundai'],[KIA_WMIS,'kia'],[SUBARU_WMIS,'subaru'],[VW_WMIS,'vw'],[AUDI_WMIS,'audi'],[LAND_ROVER_WMIS,'landrover'],[JAGUAR_WMIS,'jaguar']]; +const BY_BRAND={TESLA:'tesla',CHRYSLER:'mopar',DODGE:'mopar',JEEP:'mopar',RAM:'mopar',FIAT:'mopar','ALFA ROMEO':'mopar',PLYMOUTH:'mopar',TOYOTA:'toyota',LEXUS:'toyota',SCION:'toyota',FORD:'ford',LINCOLN:'ford',MERCURY:'ford',CHEVROLET:'gm',BUICK:'gm',GMC:'gm',CADILLAC:'gm',PONTIAC:'gm',OLDSMOBILE:'gm',SATURN:'gm',HUMMER:'gm',SAAB:'gm',GEO:'gm',BRIGHTDROP:'gm',HONDA:'honda', + NISSAN:'nissan',HYUNDAI:'hyundai',KIA:'kia',ACURA:'honda',SUBARU:'subaru',VOLKSWAGEN:'vw',AUDI:'audi','LAND ROVER':'landrover',JAGUAR:'jaguar'}; +const OFFICIAL={nissan:NISSAN_LOOKUP,hyundai:HYUNDAI_LOOKUP,kia:KIA_LOOKUP,subaru:SUBARU_LOOKUP,vw:VW_LOOKUP,audi:AUDI_LOOKUP,landrover:LAND_ROVER_LOOKUP,jaguar:JAGUAR_LOOKUP}; +// Lookups that make a request to the maker (the others answer at once: interactive verification or not supported). +const NETWORK=new Set(['tesla','mopar','ford','gm','honda','nissan','subaru','vw','audi','landrover','jaguar']); +const MAKER={tesla:'Tesla',mopar:'Mopar',ford:'Ford',gm:'GM',honda:'Honda',nissan:'Nissan',subaru:'Subaru',vw:'Volkswagen',audi:'Audi',landrover:'Land Rover',jaguar:'Jaguar',toyota:'Toyota',hyundai:'Hyundai',kia:'Kia'}; +const PROVIDER_NAME={nissan:'Nissan U.S. VIN Recall Search',mopar:'Mopar Fleet Recall/Rapid Response Inquiry',tesla:'Tesla Service VIN Recall Search',ford:'Ford Owner Support VIN Recalls',gm:'GM Recall and Warranty Center',honda:'Honda MyGarage VIN Recall Search', + subaru:'Subaru U.S. VIN Recall Lookup',vw:'Volkswagen U.S. VIN Recall Lookup',audi:'Audi U.S. VIN Recall Lookup',landrover:'Land Rover U.S. Product Recall Search',jaguar:'Jaguar U.S. Product Recall Search'}; + +/** Which maker lookup serves a VIN: by its WMI first, else by the decoded make. No request is made. */ +function resolveProvider(vin,make=''){ + const brand=String(make||'').toUpperCase(); + const provider=BY_WMI.find(([set])=>set.has(vin.slice(0,3)))?.[1]||(Object.hasOwn(BY_BRAND,brand)?BY_BRAND[brand]:null); + const verification_url = provider==='tesla' ? `${LOOKUP}?VIN=${encodeURIComponent(vin)}` : provider==='mopar' ? MOPAR_LOOKUP : provider==='toyota' ? 'https://www.toyota.com/recall/' : provider==='ford'?FORD_LOOKUP+vin+'/':provider==='gm'?GM_LOOKUP+'?vin='+vin:provider==='honda'?HONDA_LOOKUP:'https://www.nhtsa.gov/recalls'; + return {provider,verification_url}; +} + +/** + * The maker lookup for a VIN without making it: `provider` (null when no maker is supported), `maker` (short name for + * "Checking with Ford…"), `name` (the lookup, as recall_status.source.provider names it), `verification_url` (as + * recall_status gives it), `network` (true when the lookup asks the maker; false when it answers at once) and + * `by_wmi` (the WMI alone names the maker, so the decoded make is not needed). + */ +export function recallLookupInfo(input,make=''){ + const vin=normalizeVin(input); + const {provider,verification_url}=resolveProvider(vin,make); + return {provider,maker:provider?MAKER[provider]:null,name:provider?PROVIDER_NAME[provider]??null:null,verification_url:OFFICIAL[provider]||verification_url, + network:NETWORK.has(provider),by_wmi:BY_WMI.some(([set])=>set.has(vin.slice(0,3)))}; +} + // The upstream returns an application error to Node fetch; its public endpoint // works with the standard HTTPS client. Bound response size and request duration. function manufacturerRequest(url, {signal,method='GET',headers={},body}) { @@ -67,14 +98,7 @@ export function createRecallStatusLookup(request=manufacturerRequest) { return async function vinRecallStatus(input, make = '') { const vin = normalizeVin(input); if (!validateVin(vin).valid) throw new InputError('Provide a valid 17-character VIN including checksum'); - const brand=String(make).toUpperCase(),wmi=vin.slice(0,3); - const byWmi=[[TESLA_WMIS,'tesla'],[MOPAR_WMIS,'mopar'],[TOYOTA_WMIS,'toyota'],[FORD_WMIS,'ford'],[GM_WMIS,'gm'],[HONDA_WMIS,'honda'],[NISSAN_WMIS,'nissan'],[HYUNDAI_WMIS,'hyundai'],[KIA_WMIS,'kia'],[SUBARU_WMIS,'subaru'],[VW_WMIS,'vw'],[AUDI_WMIS,'audi'],[LAND_ROVER_WMIS,'landrover'],[JAGUAR_WMIS,'jaguar']].find(([set])=>set.has(wmi))?.[1]; - const byBrand={TESLA:'tesla',CHRYSLER:'mopar',DODGE:'mopar',JEEP:'mopar',RAM:'mopar',FIAT:'mopar','ALFA ROMEO':'mopar',PLYMOUTH:'mopar',TOYOTA:'toyota',LEXUS:'toyota',SCION:'toyota',FORD:'ford',LINCOLN:'ford',MERCURY:'ford',CHEVROLET:'gm',BUICK:'gm',GMC:'gm',CADILLAC:'gm',PONTIAC:'gm',OLDSMOBILE:'gm',SATURN:'gm',HUMMER:'gm',SAAB:'gm',GEO:'gm',BRIGHTDROP:'gm',HONDA:'honda'}; - Object.assign(byBrand,{NISSAN:'nissan',HYUNDAI:'hyundai',KIA:'kia'}); - Object.assign(byBrand,{ACURA:'honda',SUBARU:'subaru',VOLKSWAGEN:'vw',AUDI:'audi','LAND ROVER':'landrover',JAGUAR:'jaguar'}); - const provider=byWmi||(Object.hasOwn(byBrand,brand)?byBrand[brand]:null); - const verification_url = provider==='tesla' ? `${LOOKUP}?VIN=${encodeURIComponent(vin)}` : provider==='mopar' ? MOPAR_LOOKUP : provider==='toyota' ? 'https://www.toyota.com/recall/' : provider==='ford'?FORD_LOOKUP+vin+'/':provider==='gm'?GM_LOOKUP+'?vin='+vin:provider==='honda'?HONDA_LOOKUP:'https://www.nhtsa.gov/recalls'; - const official={nissan:NISSAN_LOOKUP,hyundai:HYUNDAI_LOOKUP,kia:KIA_LOOKUP,subaru:SUBARU_LOOKUP,vw:VW_LOOKUP,audi:AUDI_LOOKUP,landrover:LAND_ROVER_LOOKUP,jaguar:JAGUAR_LOOKUP}; + const {provider,verification_url}=resolveProvider(vin,make),official=OFFICIAL; const added={subaru:{name:'Subaru U.S. VIN Recall Lookup',url:SUBARU_API+vin,parse:b=>parseSubaru(b,vin)},vw:{name:'Volkswagen U.S. VIN Recall Lookup',url:VW_API+vin,parse:b=>parseVw(b,vin)},audi:{name:'Audi U.S. VIN Recall Lookup',url:AUDI_API,options:()=>audiRequest(vin),parse:b=>parseAudi(b)},landrover:{name:'Land Rover U.S. Product Recall Search',url:LAND_ROVER_API+vin,parse:b=>parseLandRover(b,vin)},jaguar:{name:'Jaguar U.S. Product Recall Search',url:JAGUAR_API+vin,parse:b=>parseLandRover(b,vin,'Jaguar')}}[provider]; const base = {vin, scope:'vin', vin_specific:true, verification_url:official[provider]||verification_url, note}; if (provider==='toyota') return {...base,available:false,reason:'interactive_verification_required',open_count:null,completed_count:null,recalls:[], diff --git a/lib/reports.mjs b/lib/reports.mjs index 932bfa6..a4545e1 100644 --- a/lib/reports.mjs +++ b/lib/reports.mjs @@ -4,7 +4,7 @@ import { decodeVin as nhtsaDecode, getRecalls, getComplaints, getSafetyRatings, import { getFuelEconomy } from './epa.mjs'; import { getPhotoUrls } from './photo.mjs'; import { vinCache, recallCache, ratingCache, fuelCache } from './cache.mjs'; -import { vinRecallStatus } from './recall-status.mjs'; +import { vinRecallStatus as defaultRecallLookup, recallLookupInfo } from './recall-status.mjs'; import { InputError } from './research.mjs'; import { withBuildDates } from './recall-build-dates.mjs'; import { extraReportBlocks, compactExtraBlocks } from './more-sources.mjs'; @@ -21,13 +21,20 @@ import { withManufacturerRecord, compactDecodeChecks } from './decode-report.mjs */ export async function modelYearRecalls(make, model, year) { const cacheKey = `${make}|${model}|${year}`; - const recalls = recallCache.has(cacheKey) ? recallCache.get(cacheKey) - : await getRecalls(make, model, year).then(r => { if (r?.available !== false) recallCache.set(cacheKey, r); return r; }); - if (!recalls || recalls.available === false || !make || !model || !year) return recalls; + const exact = recallCache.has(cacheKey) ? Promise.resolve(recallCache.get(cacheKey)) + : getRecalls(make, model, year).then(r => { if (r?.available !== false) recallCache.set(cacheKey, r); return r; }); + if (!make || !model || !year) return exact; const relatedKey = cacheKey + '|related'; - let related = recallCache.get(relatedKey); + // The related-name search starts beside the exact lookup: it needs the exact campaigns only before its per-name + // lookups (to skip them when the exact lookup failed) and to drop duplicates. It never rejects. + const cachedRelated = recallCache.get(relatedKey); + const relatedTask = cachedRelated ? null + : getRelatedModelRecalls(make, model, year, exact.then(r => (!r || r.available === false ? null : r.recalls))); + const recalls = await exact; + if (!recalls || recalls.available === false) return recalls; + let related = cachedRelated; if (!related) { - related = await getRelatedModelRecalls(make, model, year, recalls.recalls); + related = await relatedTask; if (related.available) recallCache.set(relatedKey, related); } return withBuildDates(withRelatedRecalls(recalls, related), make, model, year); @@ -53,32 +60,147 @@ export function withRelatedRecalls(recalls, related) { return { ...recalls, related_models: related, related_campaigns_found: found, count_note: parts.length ? parts.join(' ') : null }; } +/** + * How long a report waits for the manufacturer's VIN recall lookup, counted from the moment the lookup starts (right + * after the decode, beside NHTSA's calls). Some makers' lookups are slow: Ford's CDN holds every request ~9-10 s + * (measured 2026-11-18, research notes fast-first-report-2026-11-18). Past the wait the report goes out with + * recall_status {pending: true} and the lookup keeps running; its result is cached (lib/recall-status.mjs, 15 minutes) + * for the next request, GET /api/vin/{vin}/recall-status and MCP vin_recall_status, which wait for the same lookup. + * report: the website and REST /api/vin/{vin}; mcp: MCP decode_vin (agents rarely come back for a second call). + * `recallWaitMs: Infinity` waits for the lookup's own end (REST ?recall_wait=full, MCP recall_wait "full"). + */ +export const RECALL_WAIT_MS = Object.freeze({ report: 2000, mcp: 6000 }); + +let recallLookup = defaultRecallLookup; +/** + * Tests and scripts: the recall-status lookup reports use, e.g. createRecallStatusLookup(stubRequest), so no live + * maker request is made. Returns the previous one; no argument restores the default. + */ +export function useRecallStatusLookup(lookup) { + const previous = recallLookup; + recallLookup = lookup || defaultRecallLookup; + return previous; +} + +/** + * The manufacturer's VIN recall status for a VIN (REST /api/vin/{vin}/recall-status, MCP vin_recall_status). When + * the WMI alone does not name the maker, the decoded make does (the cached report's, else a decode), as in reports, + * so this joins a lookup a report started. Throws InputError for an invalid VIN. + */ +export async function vinRecallStatusFor(input) { + const vin = normalizeVin(input); + if (!validateVin(vin).valid) return recallLookup(vin); // the lookup's own InputError + let make = ''; + if (!recallLookupInfo(vin).by_wmi) { + make = vinCache.get(vin)?.vehicle?.make || ''; + if (!make) { try { make = (await nhtsaDecode(vin))?.vehicle?.make || ''; } catch { make = ''; } } + } + return recallLookup(vin, make); +} + +/** + * Start (or join) the maker's lookup. The returned promise never rejects, so a lookup that outlives the report and + * then fails is contained (no unhandled rejection): a failure becomes recall status unknown, never "no recalls". + */ +function startRecallLookup(vin, make) { + const at = Date.now(); + let promise; + try { promise = Promise.resolve(recallLookup(vin, make)); } catch (err) { promise = Promise.reject(err); } + promise = promise.catch(err => { + console.error('[reports] manufacturer recall lookup failed:', err?.message || err); + const info = recallLookupInfo(vin, make); + return { vin, scope: 'vin', vin_specific: true, verification_url: info.verification_url, available: false, reason: 'upstream_unavailable', + open_count: null, completed_count: null, recalls: [], note: 'The manufacturer recall lookup failed. Repair status for this VIN is unknown. Check the official source.' }; + }); + return { at, promise }; +} + +const WAITED = Symbol('waited'); +/** The promise's value if it settles within `ms`, else WAITED. Infinity waits for it. */ +function within(promise, ms) { + if (ms === Infinity) return promise; + let timer; + const timeout = new Promise(resolve => { timer = setTimeout(resolve, Math.max(0, ms), WAITED); }); + return Promise.race([promise, timeout]).finally(() => clearTimeout(timer)); +} + +/** + * recall_status while the maker's lookup is still running: unknown, never "no open recalls" (open_count and + * completed_count null, available false), with where to get the answer. + */ +export function pendingRecallStatus(vin, make, waitedMs) { + const info = recallLookupInfo(vin, make), maker = info.maker || 'The manufacturer'; + return { vin, scope: 'vin', vin_specific: true, verification_url: info.verification_url, + available: false, pending: true, reason: 'lookup_in_progress', maker: info.maker, waited_ms: waitedMs, + source: { provider: info.name, reference_url: info.verification_url }, + open_count: null, completed_count: null, recalls: [], + status_url: `/api/vin/${vin}/recall-status`, + note: `${maker}'s VIN recall lookup had not answered after ${(waitedMs / 1000).toFixed(1)} s, so this VIN's repair status is unknown in this response; it is not "no open recalls". The lookup keeps running: GET status_url waits for it, and this report includes it once it has answered (add ?recall_wait=full to wait for it).` }; +} + +/** The decode checks while the maker's record is still loading (the base report's checks, record marked pending). */ +function pendingDecodeChecks(dc, maker) { + if (!dc?.sources) return dc; + return { ...dc, sources: { ...dc.sources, manufacturer_record: { status: 'pending', reason: 'lookup_in_progress', maker: maker || null, + note: 'The manufacturer\'s record of this VIN comes from its recall lookup, which had not answered when this report was sent; the checks ran without it.' } } }; +} + +// The report with a given recall status, computed once per base report, status result and owner values: the +// lookup caches its result object for 15 minutes, so repeated requests reuse the decode checks and any re-match. +const withStatusMemo = new WeakMap(); +function reportWithStatus(base, status, owner) { + const ownerKey = JSON.stringify(owner ?? null), hit = withStatusMemo.get(base); + if (hit && hit.status === status && hit.ownerKey === ownerKey) return hit.report; + const report = withManufacturerRecord({ ...base, recall_status: status }, { owner }); + withStatusMemo.set(base, { status, ownerKey, report }); + return report; +} + /** * The report with the manufacturer's VIN recall status. The decode checks then run again with the manufacturer's * own description of the VIN when its reply carries one (lib/decode-report.mjs). `owner`: values the reader states - * about their own vehicle ({transmission: 'manual'}), the top tier of the decode checks. + * about their own vehicle ({transmission: 'manual'}), the top tier of the decode checks. `recallWaitMs`: see + * RECALL_WAIT_MS; past it, recall_status is {pending: true} (pendingRecallStatus) and the lookup finishes in the + * background. */ -export async function fullReport(vin, {owner = null} = {}) { - const report = await fullReportBase(vin); +export async function fullReport(vin, {owner = null, recallWaitMs = RECALL_WAIT_MS.report} = {}) { + const entry = reportEntry(vin); + // The maker's lookup starts as soon as the decode names the make, in parallel with NHTSA's calls. + const early = entry.decoded.then(d => d?.vehicle ? { make: d.vehicle.make, ...startRecallLookup(entry.vin, d.vehicle.make) } : null); + const report = await entry.report; if (!report.vehicle) return report; - return withManufacturerRecord({...report, recall_status: await vinRecallStatus(report.vin, report.vehicle.make)}, {owner}); + let lookup = await early; + if (!lookup || lookup.make !== report.vehicle.make) lookup = { make: report.vehicle.make, ...startRecallLookup(report.vin, report.vehicle.make) }; + const status = await within(lookup.promise, lookup.at + recallWaitMs - Date.now()); + if (status === WAITED) { + const pending = pendingRecallStatus(report.vin, report.vehicle.make, recallWaitMs); + return { ...report, recall_status: pending, decode_checks: pendingDecodeChecks(report.decode_checks, pending.maker) }; + } + return reportWithStatus(report, status, owner); } const pendingReports = new Map(); /** The report without manufacturer VIN recall lookups; shares the cache with fullReport. */ -export function baseReport(vin) { return fullReportBase(vin); } -function fullReportBase(vin) { +export function baseReport(vin) { return reportEntry(vin).report; } +/** + * One assembly per VIN at a time, shared by concurrent callers: `report`, and `decoded`, which resolves with + * {vehicle} as soon as the decode (or the cache) names the vehicle, or null when there is none. + */ +function reportEntry(vin) { const key = normalizeVin(vin); if (pendingReports.has(key)) return pendingReports.get(key); - const pending = assembleReport(key).finally(() => pendingReports.delete(key)); - pendingReports.set(key, pending); - return pending; + let named; + const decoded = new Promise(resolve => { named = resolve; }); + const report = assembleReport(key, named).finally(() => { named(null); pendingReports.delete(key); }); + const entry = { vin: key, report, decoded }; + pendingReports.set(key, entry); + return entry; } -async function assembleReport(vin) { +async function assembleReport(vin, named = () => {}) { vin = normalizeVin(vin); const cached = vinCache.get(vin); - if (cached) return cached; + if (cached) { named(cached.vehicle ? { vehicle: cached.vehicle } : null); return cached; } const validation = validateVin(vin); if (!validation.valid) { @@ -89,6 +211,7 @@ async function assembleReport(vin) { if (!decoded) { return { valid: true, vin, validation, vehicle: null, engine: null, error: 'NHTSA decode failed', recalls: null, complaints: null, safety_ratings: null, fuel_economy: null, photos: null }; } + named({ vehicle: decoded.vehicle }); const { year, make, model } = decoded.vehicle; const cacheKey = `${make}|${model}|${year}`; @@ -215,7 +338,15 @@ export function restReport(report, { allComplaints = false } = {}) { export function mcpReport(report) { if (!report?.vehicle) return report; const { raw_nhtsa, ...rest } = report; - return { ...rest, ...compactExtraBlocks(rest), complaints: compactComplaints(report.complaints), ...(rest.decode_checks ? { decode_checks: compactDecodeChecks(rest.decode_checks) } : {}) }; + return { ...rest, ...compactExtraBlocks(rest), complaints: compactComplaints(report.complaints), ...(rest.decode_checks ? { decode_checks: compactDecodeChecks(rest.decode_checks) } : {}), + ...(rest.recall_status?.pending ? { recall_status: mcpPendingStatus(rest.recall_status) } : {}) }; +} + +/** The pending recall status for MCP clients: the next step is a tool call, not a URL. */ +function mcpPendingStatus(s) { + const maker = s.maker || 'The manufacturer'; + return { ...s, next_step: { tool: 'vin_recall_status', arguments: { vin: s.vin } }, + note: `${maker}'s VIN recall lookup had not answered after ${((s.waited_ms || 0) / 1000).toFixed(1)} s, so this VIN's repair status is unknown in this result; it is not "no open recalls". For the complete answer call vin_recall_status with this VIN (it waits for the same lookup), or call decode_vin again with recall_wait "full".` }; } export async function compareVehicles(vins) { @@ -223,7 +354,8 @@ export async function compareVehicles(vins) { const normalized=vins.map(normalizeVin); if (new Set(normalized).size !== normalized.length) throw new InputError('Choose distinct VINs'); const results=await Promise.all(normalized.map(async vin=>{ - try {return {vin,report:mcpReport(await fullReport(vin))};} + // A comparison waits for every maker's lookup (no pending status): it is printed and exported as one table. + try {return {vin,report:mcpReport(await fullReport(vin,{recallWaitMs:Infinity}))};} catch {return {vin,error:'Report unavailable; retry later'};} })); return {results,note:'Recall and complaint counts are model-year data, not a ranking of individual vehicle safety. Missing data is not zero.'}; diff --git a/lib/tire-placards.mjs b/lib/tire-placards.mjs index bb62c7f..533335c 100644 --- a/lib/tire-placards.mjs +++ b/lib/tire-placards.mjs @@ -387,11 +387,13 @@ async function lookup(vin, {file = TIRE_PLACARDS_FILE, dims = transportCanadaDim const generations = new Map(); if (needs(placards, rules.tires) || needs(specsPool, rules.specs) || needs(specsPool, rules.tank)) { const years = [...new Set([...placards, ...specsPool].filter(r => r.year !== year && inReach(r)).map(r => r.year))]; - const vinWb = await wheelbases(vin.make, vin.model, year, dims); - await Promise.all(years.map(async y => { + // The VIN's year and the tested years are asked at once (was the VIN's year first): one round trip instead of two. + // A tested year's record is used only when the VIN's year has one; wheelbases() never rejects. + const [vinWb, ...testedWb] = await Promise.all([year, ...years].map(y => wheelbases(vin.make, vin.model, y, dims))); + years.forEach((y, i) => { const measured = (data.specs || []).filter(r => r.year === y && r.data.wheelbase_mm).map(r => r.data.wheelbase_mm); - generations.set(y, compareWheelbases(vinWb, vinWb?.length ? await wheelbases(vin.make, vin.model, y, dims) : null, measured)); - })); + generations.set(y, compareWheelbases(vinWb, vinWb?.length ? testedWb[i] : null, measured)); + }); } const source = {provider: 'NHTSA vehicle crash-test and compliance test reports', indexed_at: data.source.indexed_at ?? null, dataset_generated_at: data.source.dataset_generated_at ?? null}; diff --git a/public/index.html b/public/index.html index 6d5abd1..a15d0a5 100644 --- a/public/index.html +++ b/public/index.html @@ -333,14 +333,14 @@

Claude Code stdio

Complete MCP tool directory

Generated from the server’s registered tools; the same list is served as JSON at /api/tools. Public research is available without an account; saved vehicles and preferences require authentication.

Vehicle reports · 4 tools

-
decode_vin (vin, transmission)

Decode a VIN and return a vehicle report: specs, recalls (with manufacturer build-date ranges), a complaint summary with the most recent complaints, safety ratings, fuel economy, EPA test-vehicle data, parts content and origin (MY2020+), historical production and theft (MY1998-2012), and photo URLs. decode_checks checks the official decode field by field (drive, engine, electrification, transmission, speeds, seats, GVWR) against the manufacturer's description of this VIN, NHTSA test vehicles with the same VIN pattern and EPA's configurations: confirmed, corrected, doubtful or filled, with vPIC's original value kept.

+
decode_vin (vin, transmission, recall_wait)

Decode a VIN and return a vehicle report: specs, recalls (with manufacturer build-date ranges), a complaint summary with the most recent complaints, safety ratings, fuel economy, EPA test-vehicle data, parts content and origin (MY2020+), historical production and theft (MY1998-2012), and photo URLs. decode_checks checks the official decode field by field (drive, engine, electrification, transmission, speeds, seats, GVWR) against the manufacturer's description of this VIN, NHTSA test vehicles with the same VIN pattern and EPA's configurations: confirmed, corrected, doubtful or filled, with vPIC's original value kept. recall_status is the manufacturer's VIN-specific recall status; a maker that has not answered within about 6 s (Ford's lookup takes 10 s or more) gives recall_status.pending true: unknown, not "no open recalls"; call vin_recall_status with the VIN for the complete answer, or pass recall_wait "full".

validate_vin (vin)

Quickly validate a VIN without calling any external APIs.

lookup_recalls (vin, make, model, year)

Look up recalls for a vehicle. Provide either a VIN or make/model/year.

batch_decode (vins)

Decode multiple VINs at once (up to 50).

Research and analysis · 13 tools

explore_capabilities

Discover supported features and explicit coverage gaps.

-
vin_recall_status (vin)

VIN-specific manufacturer-reported open and completed recall status. Tesla and Ford open/completed states; GM completed/closed states with explicit repair dates where supplied; Honda and Acura active safety recalls; Subaru completed/incomplete safety recalls; Volkswagen, Audi, Land Rover and Jaguar recalls as reported by each maker; Nissan positive open safety recalls; Mopar positive open records matched to the full VIN. Service programs are separate. Toyota, Hyundai and Kia require interactive official verification. Unknowns are never zero. Not a complete service history. Where the maker's reply describes the VIN (Volkswagen, Audi, Land Rover, Jaguar, Subaru, Honda/Acura), manufacturer_description gives the raw text and only the fields it states.

+
vin_recall_status (vin)

VIN-specific manufacturer-reported open and completed recall status. Tesla and Ford open/completed states; GM completed/closed states with explicit repair dates where supplied; Honda and Acura active safety recalls; Subaru completed/incomplete safety recalls; Volkswagen, Audi, Land Rover and Jaguar recalls as reported by each maker; Nissan positive open safety recalls; Mopar positive open records matched to the full VIN. Service programs are separate. Toyota, Hyundai and Kia require interactive official verification. Unknowns are never zero. Not a complete service history. Where the maker's reply describes the VIN (Volkswagen, Audi, Land Rover, Jaguar, Subaru, Honda/Acura), manufacturer_description gives the raw text and only the fields it states. When a decode_vin report has recall_status.pending, this waits for that same lookup (up to about 15 s).

vehicle_catalog (level, year, make, model)

Browse EPA year, make, model and configuration menus. Not sale listings.

epa_vehicle (id)

Get an explicitly selected EPA test configuration; not an exact VIN match.

vehicle_emissions (id)

Get EPA emissions for an explicit EPA vehicle ID.

diff --git a/server.mjs b/server.mjs index 94e2bbf..1d091d5 100644 --- a/server.mjs +++ b/server.mjs @@ -20,8 +20,7 @@ import { rateBenchmarks } from './lib/rate-benchmarks.mjs'; import { scenario } from './lib/scenario.mjs'; import { communications } from './lib/communications.mjs'; import { capabilities } from './lib/capabilities.mjs'; -import { vinRecallStatus } from './lib/recall-status.mjs'; -import { fullReport, baseReport, restReport, compareVehicles, modelYearRecalls } from './lib/reports.mjs'; +import { fullReport, baseReport, restReport, compareVehicles, modelYearRecalls, vinRecallStatusFor, RECALL_WAIT_MS } from './lib/reports.mjs'; import { normalizeTransmission, applyOwnerDetails } from './lib/transmission-choice.mjs'; import { validateOwnerDetails, parseOwnerDetails, serializeOwnerDetails, OwnerDetailsError } from './lib/owner-details.mjs'; import { renderVinPage, renderUnknownVinPage } from './lib/vin-page.mjs'; @@ -483,16 +482,21 @@ button{padding:.75rem 2rem;border:none;border-radius:10px;font-size:1rem;font-we } catch (err) { safeError(res, err); } }); + // ?recall_wait=full: wait for the manufacturer's VIN recall lookup instead of answering with recall_status.pending + // after RECALL_WAIT_MS.report (lib/reports.mjs). The website asks again with it when a report comes back pending. app.get('/api/vin/:vin', rateGuard(30), async (req, res) => { const t = transmissionParam(req, res); if (!t.ok) return; - try { res.json(restReport(applyOwnerDetails(await fullReport(req.params.vin), { transmission: t.value }, { by: 'request' }), { allComplaints: req.query.complaints === 'all' })); } catch (err) { safeError(res, err); } + const wait = req.query.recall_wait; + if (wait !== undefined && wait !== 'full') return res.status(400).json({ error: 'recall_wait must be "full"' }); + try { res.json(restReport(applyOwnerDetails(await fullReport(req.params.vin, { recallWaitMs: wait === 'full' ? Infinity : RECALL_WAIT_MS.report }), { transmission: t.value }, { by: 'request' }), { allComplaints: req.query.complaints === 'all' })); } catch (err) { safeError(res, err); } }); app.get('/api/vin/:vin/validate', rateGuard(60), (req, res) => { res.json(validateVin(req.params.vin)); }); - app.get('/api/vin/:vin/recall-status',rateGuard(30),researchHandler(req=>vinRecallStatus(req.params.vin))); + // Waits for a lookup a report already started (recall_status.status_url of a pending report). + app.get('/api/vin/:vin/recall-status',rateGuard(30),researchHandler(req=>vinRecallStatusFor(req.params.vin))); app.use('/api/vin/:vin', (req, res, next) => { if (!validateVin(req.params.vin).valid) return res.status(400).json({error:'Provide a valid VIN (format and checksum)'}); From b28e68ab1f0566cb5a1686b91394d8586feaa0b2 Mon Sep 17 00:00:00 2001 From: root Date: Wed, 18 Nov 2026 10:29:29 -0500 Subject: [PATCH 2/6] Website fills in a late manufacturer recall status in place When a report arrives with recall_status.pending, the recall card, the car sheet's recall row and the decode-checks source line say "Checking with ..." on screen. The page then asks /api/vin/{vin}?recall_wait=full (the same running lookup) and redraws only what changed: the status block, the sheet's recall section and footer, and the decode-check line (or the decode, engine, fuel and test-vehicle blocks if the maker's record changed a checked value). keep-state.js keeps typed text, open forms, focus, the transmission choice and the place on screen. Printed while pending, the sheet says the maker had not answered when it was printed (never a "checking" placeholder, never "no recalls"). If the follow-up fails twice, the status reads as not loaded (unknown). Tests: pure-function budget tests with a gated stub maker lookup, a server test with Ford's mock page delayed 2.6 s (REST, status_url, recall_wait, MCP 6 s), and the page's pending, follow-up and print text. Co-Authored-By: Claude Opus 5.5 --- public/app.js | 82 ++++++++++- public/car-sheet.js | 66 +++++++-- public/decode-checks.js | 15 +- public/index.html | 4 +- public/keep-state.js | 101 +++++++++++++ public/style.css | 3 + tests/fast-first-report.test.mjs | 210 +++++++++++++++++++++++++++ tests/mock-upstream.mjs | 5 +- tests/pending-recall-status.test.mjs | 129 ++++++++++++++++ tests/slow-maker.test.mjs | 77 ++++++++++ 10 files changed, 671 insertions(+), 21 deletions(-) create mode 100644 public/keep-state.js create mode 100644 tests/fast-first-report.test.mjs create mode 100644 tests/pending-recall-status.test.mjs create mode 100644 tests/slow-maker.test.mjs diff --git a/public/app.js b/public/app.js index 4bd2f39..9a07883 100644 --- a/public/app.js +++ b/public/app.js @@ -106,7 +106,9 @@ form.addEventListener('submit', async (e) => { // Compact hero hero.classList.add('compact'); results.hidden = false; - $('#decode-status').textContent = 'Report ready. Review source coverage in each section.'; + const pendingMaker = report.recall_status?.pending ? (report.recall_status.maker || 'The manufacturer') : null; + $('#decode-status').textContent = pendingMaker ? `Report ready. ${pendingMaker}’s VIN recall status is still loading; it fills in by itself.` : 'Report ready. Review source coverage in each section.'; + if (pendingMaker) followRecallStatus(report); if (!location.hash || location.hash === '#report') { history.replaceState(null, '', '/' + encodeURIComponent(vin) + location.search + '#report'); results.scrollIntoView({ behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'instant' : 'smooth', block: 'start' }); @@ -326,7 +328,7 @@ function renderFuel(r) { function rerenderOwnerView(focusChoice) { if (!currentReport) return; const view = window.OwnerDetails?.applyToReport(currentReport) || currentReport; - renderFuel(view); window.CarSheet?.render(view); window.VinWorkspace?.reportUpdated(view); + renderFuel(view); window.CarSheet?.update ? CarSheet.update(view) : window.CarSheet?.render(view); window.VinWorkspace?.reportUpdated(view); if (focusChoice) $('#fuel-body [data-owner-transmission]')?.focus(); } $('#fuel-body').addEventListener('click', async e => { @@ -381,19 +383,90 @@ function renderFuelBody(r) { } // ── Recalls Card ── +// The VIN-specific status is its own block (#recall-status-block), so it can be filled in alone when the maker's +// lookup answers after the report is drawn (followRecallStatus). function renderRecalls(r) { renderCampaigns(r); + $('#recalls-body').innerHTML = `
${recallStatusHtml(r)}

Model-year recall campaigns

` + $('#recalls-body').innerHTML; +} +function recallStatusHtml(r) { const s = r.recall_status; const link = s?.verification_url || 'https://www.nhtsa.gov/recalls'; const renderStatusRecords = records => records.map(x => `
${esc(x.campaign_number)} · ${esc(x.manufacturer_status)}${x.record_kind ? `

${esc(x.record_kind.replaceAll('_',' '))}

` : ''}

${esc(x.summary || x.title || '')}

${x.completion_description ? `

Completion basis: ${esc(x.completion_description)}

` : ''}${x.repair_completed_at ? `

Reported repair date: ${esc(x.repair_completed_at)}

` : ''}${x.manufacturer_closed_at ? `

Manufacturer closing date: ${esc(x.manufacturer_closed_at)}

` : ''}${x.remedy ? `

Remedy: ${esc(x.remedy)}

` : ''}${x.document_url ? `Manufacturer bulletin` : ''}
`).join(''); - const content = s?.available + const maker = esc(s?.maker || 'the manufacturer'); + // Still answering: unknown, never "no open recalls"; on paper it says the status had not loaded. + const content = s?.pending + ? `

Checking with ${maker}… Its VIN lookup is still answering; this part fills in by itself.

Not loaded: ${maker} had not answered when this page was printed, so this VIN’s repair status is unknown here.

` + : s?.available ? `

${s.open_record_count!==undefined ? esc(s.open_record_count)+' open recall/campaign records · '+esc(s.open_count ?? 'Unknown')+' verified safety-recall count' : esc(s.open_count ?? 'Unknown')+' open recalls'} · ${esc(s.completed_count ?? 'Unknown')} manufacturer-reported completed/closed${s.unknown_count ? ' · '+esc(s.unknown_count)+' unknown status' : ''}

Checked ${esc(s.source.retrieved_at)} · ${esc(s.source.provider)}

${renderStatusRecords(s.campaigns || s.recalls)} ${!s.campaigns && s.service_campaigns?.length ? `

Other manufacturer programs · ${esc(s.service_campaigns.length)}

${renderStatusRecords(s.service_campaigns)}` : ''}

${esc(s.note)}

` : `

VIN-specific repair status is unavailable. ${esc(s?.note || 'Check the official source. Model-year campaigns do not establish completed repairs.')}

`; - $('#recalls-body').innerHTML = `

VIN-specific recall repair status

${content}

Verify this VIN with the official source

Model-year recall campaigns

` + $('#recalls-body').innerHTML; + return `

VIN-specific recall repair status

${content}

Verify this VIN with the official source

`; +} + +// ── The maker's VIN recall status, when it answers after the report ── +// A report can arrive with recall_status.pending (lib/reports.mjs: the maker's lookup was still answering). The page +// asks again with ?recall_wait=full, which waits for that same lookup, and fills in only what it changes: the status +// block, the car sheet's recall row and footer, and, when the maker's description of the VIN changed the decode checks +// or the fuel and tire matches, those blocks. Typed text, open forms, focus, the transmission choice and the place on +// screen are kept (public/keep-state.js). +const MAKER_BLOCKS = ['recall_status', 'decode_checks', 'fuel_economy', 'tire_placard', 'test_vehicle_specs', 'epa_test_vehicles', 'parts_content', 'production_theft']; +let recallFollow = 0; +async function followRecallStatus(report) { + // Still wanted while this VIN's report is shown with the status pending (typing the same VIN again keeps it). + const token = ++recallFollow, vin = report.vin; + const live = () => token === recallFollow && currentReport?.vin === vin && currentReport.recall_status?.pending === true; + let next = null; + for (let attempt = 0; attempt < 2 && !next; attempt++) { + if (attempt) await new Promise(resolve => setTimeout(resolve, 3000)); + if (!live()) return; + try { + const res = await apiFetch(`/api/vin/${encodeURIComponent(vin)}?recall_wait=full`); + const data = res.ok ? await res.json() : null; + if (data?.vehicle && data.recall_status && !data.recall_status.pending) next = data; + } catch { /* tried again once, then shown as not loaded */ } + } + if (!live()) return; + if (!next) { + const s = currentReport.recall_status || {}; + next = {...currentReport, recall_status: {...s, pending: false, available: false, reason: 'lookup_not_loaded', + note: `${s.maker || 'The manufacturer'}’s answer could not be loaded. VIN-specific repair status is unknown; reload the report or check the official source.`}}; + } + applyMakerUpdate(next); +} + +function applyMakerUpdate(next) { + const prev = currentReport; + if (!prev || prev.vin !== next.vin) return; + const same = (a, b) => JSON.stringify(a) === JSON.stringify(b); + const merged = {...prev}; + for (const k of MAKER_BLOCKS) { if (k in next) merged[k] = next[k]; else delete merged[k]; } + // The maker's record only changes the "checked against" line, unless it changed a checked value (then the + // fuel-economy, tire and test-car matches may have changed too). + const checks = dc => dc && dc.sources ? {...dc, sources: {...dc.sources, manufacturer_record: null}} : dc; + const valuesChanged = !same(checks(prev.decode_checks), checks(next.decode_checks)) || MAKER_BLOCKS.slice(2).some(k => !same(prev[k], next[k])); + currentReport = merged; + const view = window.OwnerDetails?.applyToReport(merged) || merged; + const statusBlock = $('#recall-status-block'); + const cards = valuesChanged ? ['#overview-body', '#engine-body', '#decode-checks-body', '#safety-ratings-body', '#fuel-body'].map(id => $(id)) : []; + const around = window.KeepState ? KeepState.around : (roots, fn) => fn(); + around([statusBlock, ...cards], () => { + if (statusBlock) statusBlock.innerHTML = recallStatusHtml(view); + if (valuesChanged) { + renderOverview(view); renderEngine(view); renderDecodeChecks(view); renderSafetyRatings(view); + window.TestVehicle?.render(view); renderFuel(view); window.MoreSources?.render(view); + } else if (!same(prev.decode_checks, next.decode_checks)) { + const line = $('#decode-checks-body .dc-sources'); + if (line && window.DecodeChecks?.sourcesHtml) line.outerHTML = DecodeChecks.sourcesHtml(view); + } + window.CarSheet?.update ? CarSheet.update(view) : window.CarSheet?.render(view); + window.VinWorkspace?.reportUpdated(view); + }, [$('#sheet-body'), $('#sheet-foot')]); + const s = merged.recall_status || {}, maker = prev.recall_status?.maker || s.maker || 'The manufacturer'; + $('#decode-status').textContent = s.available ? `${maker}’s VIN recall status has loaded.` : `${maker}’s VIN recall status is not available; see the recall section.`; } function renderCampaigns(r) { @@ -1104,6 +1177,7 @@ if (typeof navigator !== 'undefined' && navigator.modelContext) { updateSaveButton(vin); hero.classList.add('compact'); results.hidden = false; + if (report.recall_status?.pending) followRecallStatus(report); } return report; }, diff --git a/public/car-sheet.js b/public/car-sheet.js index 5e25387..076b038 100644 --- a/public/car-sheet.js +++ b/public/car-sheet.js @@ -448,7 +448,13 @@ const CarSheet = (() => { const v = r.vehicle || {}, s = r.recall_status, rec = r.recalls, c = r.complaints, rat = r.safety_ratings || {}; const name = [v.year, makeName(v.make), v.model].filter(present).join(' '); let status; - if (s && s.available) { + if (s && s.pending) { + // The maker's lookup is still answering (lib/reports.mjs pendingRecallStatus): on screen "Checking with Ford…", + // filled in when it answers; on paper never a placeholder: the status had not loaded, so it is unknown. + const maker = s.maker || 'the manufacturer'; + status = `Checking with ${esc(maker)}…The maker’s VIN lookup is still answering; this row fills in by itself.` + + `Unknown: ${esc(maker)} had not answered when this sheet was printed.`; + } else if (s && s.available) { const provider = (s.source && s.source.provider) || 'the manufacturer'; const checked = fmtDate(s.source && s.source.retrieved_at); const unk = x => (x === null || x === undefined ? 'unknown' : fmt(x)); @@ -461,7 +467,8 @@ const CarSheet = (() => { const alert = Number(s.open_count) > 0 || Number(s.open_record_count) > 0; status = `${esc(parts.join(' · '))}Reported by ${esc(provider)}${checked ? `, checked ${esc(checked)}` : ''}.`; } else { - const why = s && s.reason === 'interactive_verification_required' ? 'The maker’s check needs a person to verify.' : 'Not available for this vehicle here.'; + const why = s && s.reason === 'interactive_verification_required' ? 'The maker’s check needs a person to verify.' + : s && s.reason === 'lookup_not_loaded' ? 'The maker’s answer could not be loaded here; reload the report.' : 'Not available for this vehicle here.'; status = `Unknown. ${esc(why)}`; } const verify = (s && s.verification_url) || 'https://www.nhtsa.gov/recalls'; @@ -511,12 +518,15 @@ const CarSheet = (() => { return `

Sources: ${esc(sources.join('; '))}.${assembled ? ` Data gathered ${esc(assembled)}.` : ''}

Decoded from the VIN and public records; options, repairs and later changes are not shown. Check the placard, the manual and the official recall links.

Live report: ${url}${dagger}

${qr ? `
${qr}
` : ''}`; } + /** The sheet's sections in order, as [class name, html]; html is '' for a section with nothing to show. */ + function sections(r) { + return [['sheet-vehicle', vehicleSection(r)], ['sheet-power', powerSection(r)], ['sheet-recalls', recallSection(r)], ['sheet-size', sizeSection(r)], + ['sheet-tires', tireSection(r)], ['sheet-manual', manualSection(r)], ['sheet-vin', vinSection(r)]]; + } + /** Sheet HTML for a report: {body, foot}. Pure; used by render() and the tests. */ function html(r) { - return { - body: [vehicleSection(r), powerSection(r), recallSection(r), sizeSection(r), tireSection(r), manualSection(r), vinSection(r)].join(''), - foot: footer(r), - }; + return { body: sections(r).map(x => x[1]).join(''), foot: footer(r) }; } /** Summarize Transport Canada variants (metric). Values all variants agree on are single; others are ranges. */ @@ -550,9 +560,13 @@ const CarSheet = (() => { return `${list(rows)}

Transport Canada model data, ${esc(which)}. Not specific to this VIN.

`; } - let current = null; + // current: the report drawn; drawn: its sections and footer as drawn, so update() can swap only what changed; + // dimsToken: the Transport Canada request in flight belongs to the vehicle drawn last by render(). + let current = null, drawn = null, dimsToken = 0; async function loadDimensions(r) { - const target = typeof document !== 'undefined' && document.querySelector('#sheet-body [data-dims]'); + const token = ++dimsToken; + const dimsTarget = () => typeof document !== 'undefined' && document.querySelector('#sheet-body [data-dims]'); + const target = dimsTarget(); const v = r.vehicle || {}; if (!target || !present(v.year) || !present(v.make) || !present(v.model)) { if (target) target.innerHTML = ''; return; } const ask = async model => { @@ -565,10 +579,11 @@ const CarSheet = (() => { // vPIC and Transport Canada name some models differently ("Bolt EV" / "BOLT 4DR HATCHBACK"). // Retry with the first word only; the matched record names are printed so the reader can judge. if (data.available && !data.data.length && /\s/.test(String(v.model).trim())) data = await ask(String(v.model).trim().split(/\s+/)[0]); - if (current !== r) return; - target.innerHTML = data.available ? dimensionsHtml(dimensionSummary(data.data), r) : '

Transport Canada dimensions are unavailable right now.

'; + // update() may have swapped the size section meanwhile: write into the one on the page now + if (token !== dimsToken || !dimsTarget()) return; + dimsTarget().innerHTML = data.available ? dimensionsHtml(dimensionSummary(data.data), current || r) : '

Transport Canada dimensions are unavailable right now.

'; } catch { - if (current === r) target.innerHTML = '

Transport Canada dimensions are unavailable right now.

'; + if (token === dimsToken && dimsTarget()) dimsTarget().innerHTML = '

Transport Canada dimensions are unavailable right now.

'; } } @@ -581,11 +596,38 @@ const CarSheet = (() => { if (title) title.textContent = [v.year, makeName(v.make), v.model, v.trim].filter(present).join(' '); body.innerHTML = out.body; if (foot) foot.innerHTML = out.foot; + drawn = { vin: r.vin, sections: sections(r), foot: out.foot }; const assembled = fmtDate(r.provenance && r.provenance.assembled_at), prepared = document.querySelector('#sheet-prepared'); if (prepared) prepared.textContent = assembled ? `Data gathered ${assembled} from public NHTSA, EPA, Transport Canada and maker records.` : 'From public NHTSA, EPA, Transport Canada and maker records.'; loadDimensions(r); } + /** + * Redraw only the sections of the drawn sheet whose HTML changed for `r` (the same vehicle, e.g. once the maker's + * recall status arrives or the owner states the transmission). Copied-in values, open forms, focus and the Transport + * Canada dimensions already loaded are kept (public/keep-state.js). Falls back to render() for another vehicle. + */ + function update(r) { + const body = typeof document !== 'undefined' && document.querySelector('#sheet-body'), foot = document.querySelector('#sheet-foot'); + if (!body || !r || !r.vehicle) return; + if (!drawn || drawn.vin !== r.vin || typeof KeepState === 'undefined') { render(r); return; } + const next = sections(r); + for (const [i, [name, h]] of next.entries()) { + if (h === drawn.sections[i][1]) continue; + const old = drawn.sections[i][1] ? body.querySelector(`:scope > .${name}`) : null; + if (!old || !h) { render(r); return; } // a section appeared or went away: draw the sheet again + const dims = old.querySelector('[data-dims]'); + const swapped = KeepState.replace(old, h); + if (!swapped) { render(r); return; } + const newDims = swapped.querySelector('[data-dims]'); + if (dims && newDims) newDims.replaceWith(dims); // vehicle dimensions do not depend on what changed + } + const f = footer(r); + if (foot && f !== drawn.foot) foot.innerHTML = f; + drawn = { vin: r.vin, sections: next, foot: f }; + current = r; + } + // "Print this sheet" prints one page; the toolbar's "Print view" prints the sheet followed by the full report. if (typeof document !== 'undefined' && document.addEventListener) { const root = document.documentElement; @@ -632,6 +674,6 @@ const CarSheet = (() => { }); } - return { manualFor, html, dimensionSummary, dimensionsHtml, fmtDate, render, testedPlacards, testedSpecs, matchText }; + return { manualFor, html, dimensionSummary, dimensionsHtml, fmtDate, render, update, testedPlacards, testedSpecs, matchText }; })(); if (typeof window !== 'undefined') window.CarSheet = CarSheet; diff --git a/public/decode-checks.js b/public/decode-checks.js index 5bdc0f9..72b8028 100644 --- a/public/decode-checks.js +++ b/public/decode-checks.js @@ -104,15 +104,26 @@ const DecodeChecks = (() => { return `
  • ${esc(WORD[f.status] || f.status)} ${esc(f.label)}: ${value}` + `${f.note ? `${esc(f.note)}${tests ? ` NHTSA ${tests}.` : ''}` : ''}
  • `; }).join(''); + return `
      ${rows}
    ${sourcesHtml(r)}${formHtml(r)}`; + } + + /** + * "Checked against …": the sources line of the card. While the maker's recall lookup is still answering + * (manufacturer_record pending) it says so on screen, and on paper that the record had not loaded. + */ + function sourcesHtml(r) { + const dc = r && r.decode_checks; + if (!dc || !Array.isArray(dc.fields)) return ''; const s = dc.sources || {}; const mfr = s.manufacturer_record || {}; const mfrText = mfr.status === 'used' ? `the manufacturer’s description of this VIN (“${esc(mfr.text)}”, ${esc(mfr.source || 'recall lookup')})` + : mfr.status === 'pending' ? `the manufacturer’s record (checking with ${esc(mfr.maker || 'the manufacturer')}…not loaded when printed)` : mfr.status === 'not_checked' ? 'the manufacturer’s record (not yet loaded)' : mfr.status === 'not_supported' ? null : 'the manufacturer’s record (not available for this VIN)'; const tv = s.test_vehicle_pattern || {}; const tvText = tv.status === 'used' ? `${esc(tv.vehicles)} NHTSA test vehicle${tv.vehicles === 1 ? '' : 's'} with VIN pattern ${esc(dc.pattern)}` : `NHTSA test vehicles (none with VIN pattern ${esc(dc.pattern || '?')})`; const fixText = s.rule_fixes && s.rule_fixes.status === 'used' ? `mcp.vin’s reviewed fixes of NHTSA’s vPIC rules (${esc((s.rule_fixes.ids || []).join(', '))}${s.rule_fixes.release ? `, vPIC release ${esc(s.rule_fixes.release)}` : ''})` : null; const used = [mfrText, fixText, tvText, s.epa && s.epa.status === 'used' ? 'EPA’s configurations for this model year' : null].filter(Boolean).join('; '); - return `
      ${rows}

    Checked against ${used}. ${esc(dc.note || '')}

    ${formHtml(r)}`; + return `

    Checked against ${used}. ${esc(dc.note || '')}

    `; } /** "Report a decode error": screen only, for review, never applied. */ @@ -156,6 +167,6 @@ const DecodeChecks = (() => { }); } - return { check, marker, shown, valueHtml, checkedValue, combinedHtml, cardHtml, formHtml, fields }; + return { check, marker, shown, valueHtml, checkedValue, combinedHtml, cardHtml, sourcesHtml, formHtml, fields }; })(); if (typeof window !== 'undefined') window.DecodeChecks = DecodeChecks; diff --git a/public/index.html b/public/index.html index a15d0a5..600d2b4 100644 --- a/public/index.html +++ b/public/index.html @@ -95,7 +95,7 @@ } - + @@ -442,4 +442,4 @@
    -
    +
    diff --git a/public/keep-state.js b/public/keep-state.js new file mode 100644 index 0000000..dedfffb --- /dev/null +++ b/public/keep-state.js @@ -0,0 +1,101 @@ +/* Redraw part of a page in place without losing what the reader is doing there: typed text, choices, disabled + * (already sent) forms and their status lines, open
    , focus and caret, and the place on screen. + * + * Used when the manufacturer's VIN recall status arrives after the report is drawn (public/app.js, car-sheet.js): + * only the blocks whose data changed are redrawn, through these helpers. + * - Form controls are matched by kind (tag, type, name) and their order within the redrawn element. + * - The place on screen: an element at the top of the viewport that is not redrawn keeps its position; browsers + * with scroll anchoring already do this, and then the correction measured here is zero. + */ +const KeepState = (() => { + const CONTROLS = 'input,select,textarea,button'; + const FOCUSABLE = 'input,select,textarea,button,a[href],summary,[tabindex]'; + const kindOf = el => `${el.tagName}|${el.type || ''}|${el.name || ''}`; + + /** What the reader has done inside `root`. */ + function snapshot(root) { + if (!root || !root.querySelectorAll) return null; + const controls = [...root.querySelectorAll(CONTROLS)].map(el => ({kind: kindOf(el), value: el.value, checked: el.checked, disabled: el.disabled})); + const details = [...root.querySelectorAll('details')].map(d => d.open); + const statuses = [...root.querySelectorAll('[role=status]')].map(s => s.textContent); + const active = typeof document !== 'undefined' ? document.activeElement : null; + let focus = null; + if (active && active !== root && root.contains(active)) { + const list = [...root.querySelectorAll(FOCUSABLE)]; + let start = null, end = null; + try { start = active.selectionStart; end = active.selectionEnd; } catch { /* not a text control */ } + focus = {index: list.indexOf(active), kind: kindOf(active), start, end}; + } + return {controls, details, statuses, focus}; + } + + /** Put a snapshot back onto the redrawn `root`. */ + function restore(root, snap) { + if (!root || !snap) return; + const seen = new Map(), byKind = new Map(); + for (const c of snap.controls) byKind.set(c.kind, [...(byKind.get(c.kind) || []), c]); + for (const el of root.querySelectorAll(CONTROLS)) { + const kind = kindOf(el), n = seen.get(kind) || 0, old = (byKind.get(kind) || [])[n]; + seen.set(kind, n + 1); + if (!old) continue; + if (el.tagName !== 'BUTTON') { + if (el.type === 'checkbox' || el.type === 'radio') el.checked = old.checked; + else if (el.value !== old.value && (el.tagName !== 'SELECT' || [...el.options].some(o => o.value === old.value))) el.value = old.value; + } + el.disabled = old.disabled; + } + [...root.querySelectorAll('details')].forEach((d, i) => { if (i < snap.details.length) d.open = snap.details[i]; }); + [...root.querySelectorAll('[role=status]')].forEach((s, i) => { if (i < snap.statuses.length && snap.statuses[i]) s.textContent = snap.statuses[i]; }); + if (snap.focus && snap.focus.index >= 0) { + const el = [...root.querySelectorAll(FOCUSABLE)][snap.focus.index]; + if (el && kindOf(el) === snap.focus.kind && typeof el.focus === 'function') { + el.focus({preventScroll: true}); + if (snap.focus.start !== null && typeof el.setSelectionRange === 'function') { try { el.setSelectionRange(snap.focus.start, snap.focus.end); } catch { /* not a text control */ } } + } + } + } + + /** The element at the top of the viewport that lies outside every element in `roots`, with its position. */ + function anchor(roots) { + if (typeof document === 'undefined' || typeof innerWidth === 'undefined' || !document.elementFromPoint) return null; + for (const y of [8, 48, 120, Math.round(innerHeight / 2)]) { + let el = document.elementFromPoint(Math.round(innerWidth / 2), y); + // inside a redrawn element: anchor on that element itself, which stays in the page + const host = el && roots.find(r => r && r.contains(el)); + if (host) el = host; + if (el && el !== document.body && el !== document.documentElement) return {el, top: el.getBoundingClientRect().top}; + } + return null; + } + + /** + * Run `redraw`, which replaces the contents of the `roots` elements, keeping their form state and focus, and the + * place on screen. `moving`: more elements `redraw` changes that keep their own state (e.g. the car sheet, whose + * sections are swapped with replace()); they only count for the place on screen. + */ + function around(roots, redraw, moving = []) { + roots = roots.filter(Boolean); + const snaps = roots.map(snapshot), mark = anchor([...roots, ...moving.filter(Boolean)]); + redraw(); + roots.forEach((root, i) => restore(root, snaps[i])); + if (mark && mark.el.isConnected) { + const delta = mark.el.getBoundingClientRect().top - mark.top; + if (Math.abs(delta) >= 1) scrollBy({top: delta, behavior: 'instant'}); // html has scroll-behavior: smooth + } + } + + /** Replace `oldEl` with the element `html` describes, keeping what the reader did in it. Returns the new element. */ + function replace(oldEl, html) { + const t = document.createElement('template'); + t.innerHTML = html.trim(); + const next = t.content.firstElementChild; + if (!next || t.content.childElementCount !== 1) return null; + const snap = snapshot(oldEl); + oldEl.replaceWith(next); + restore(next, snap); + return next; + } + + return {snapshot, restore, anchor, around, replace}; +})(); +if (typeof window !== 'undefined') window.KeepState = KeepState; diff --git a/public/style.css b/public/style.css index 6a234be..2e7cacc 100644 --- a/public/style.css +++ b/public/style.css @@ -48,3 +48,6 @@ html.print-sheet-only #results>:not(#car-sheet),html.print-sheet-only #print-met .dc-mark,.dc-print-only{display:none} .dc{display:inline-block;font-size:9.5px;font-weight:700;letter-spacing:.3px;text-transform:uppercase;padding:1px 5px;border-radius:3px;margin-left:5px;vertical-align:1px;line-height:1.5}.dc-corrected{color:var(--blue);background:#e5eff5}.dc-doubtful{color:var(--orange);background:var(--orange-dim)}.dc-filled{color:var(--green);background:var(--green-dim)}.dc-confirmed{color:var(--green);background:var(--green-dim)}.dc-unverified,.dc-unknown{color:var(--text-muted);background:#eef1ed}.dc-detail{display:block;font-size:11px;font-weight:400;color:var(--text-muted);margin-top:2px}.dc-list{list-style:none;margin:0;padding:0}.dc-item{padding:8px 0;border-bottom:1px solid #edf0eb;font-size:12px;line-height:1.55;overflow-wrap:anywhere}.dc-item:last-child{border-bottom:0}.dc-item .dc{margin:0 4px 0 0}.dc-was{color:var(--text-muted);font-size:11px}.dc-why{display:block;font-size:11px;color:var(--text-dim);margin-top:2px}.dc-note{font-size:11px;line-height:1.55;color:var(--text-muted);margin:10px 0 0}.decode-fix{margin:14px 0 0;font-size:12px}.decode-fix>summary{cursor:pointer;color:var(--accent);font-weight:600;min-height:32px;display:flex;align-items:center}.decode-fix-form{margin-top:6px}.decode-fix-form .dc-note{margin:0 0 8px}.decode-fix-form button{margin-top:10px;min-height:38px;font-size:12px}.decode-fix-status{font-size:12px;margin:8px 0 0;color:var(--text)}.decode-fix-status:empty{display:none} @media print{.decode-fix{display:none!important}.car-sheet .dc{font-size:5.5pt;padding:0 1.5pt;margin-left:2pt;border:.5pt solid #000;background:none!important;color:#000!important;line-height:1.2;vertical-align:.5pt}.car-sheet .dc-detail{display:inline;font-size:6.5pt;margin:0 0 0 2pt;color:#000!important;font-weight:400}.car-sheet .dc-detail-filled,.car-sheet .dc-filled{display:none!important}.car-sheet .dc-mark,.car-sheet .dc-print-only{display:inline!important}.car-sheet .sheet-row{padding:1.2pt 0;line-height:1.2}.car-sheet .dc-detail-corrected,.car-sheet .dc-detail-doubtful{font-size:6pt}} +/* The maker's VIN recall status while its lookup is still answering (public/app.js, car-sheet.js, decode-checks.js): "Checking with Ford…" on screen, never printed as if final */ +.pending-print{display:none}.recall-pending{color:var(--text-dim)}.pending-dot{display:inline-block;width:8px;height:8px;margin-right:8px;border-radius:50%;background:var(--accent);vertical-align:1px;animation:pending-pulse 1.2s ease-in-out infinite}@keyframes pending-pulse{0%,100%{opacity:.25}50%{opacity:1}}@media(prefers-reduced-motion:reduce){.pending-dot{animation:none}} +@media print{.pending-screen{display:none!important}span.pending-print{display:inline!important}p.pending-print,div.pending-print{display:block!important}} diff --git a/tests/fast-first-report.test.mjs b/tests/fast-first-report.test.mjs new file mode 100644 index 0000000..8af4a8e --- /dev/null +++ b/tests/fast-first-report.test.mjs @@ -0,0 +1,210 @@ +// A first-time report must not wait on a slow manufacturer recall lookup (lib/reports.mjs RECALL_WAIT_MS). +// The maker's lookup is a stub request passed to createRecallStatusLookup: no live maker request is made. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { fullReport, mcpReport, useRecallStatusLookup, vinRecallStatusFor, pendingRecallStatus, RECALL_WAIT_MS } from '../lib/reports.mjs'; +import { createRecallStatusLookup, recallLookupInfo } from '../lib/recall-status.mjs'; +import { vehicleTools } from '../lib/mcp/vehicle-tools.mjs'; +import { vinCache, recallCache, ratingCache, fuelCache } from '../lib/cache.mjs'; +import { validateVin } from '../lib/validate.mjs'; +import { fordPage, fordState } from './manufacturer-fixtures.mjs'; + +const withCheck = v => v.slice(0, 8) + validateVin(v).checksum.expected + v.slice(9); +let serial = 100; +const nextFordVin = () => withCheck(`1FTEX1EP0FFD06${serial++}`); +const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); + +// NHTSA, EPA and Transport Canada answer at once with a Ford decode and no campaigns. +function stubNhtsa() { + const original = globalThis.fetch; + globalThis.fetch = async url => { + const u = String(url); + if (u.includes('DecodeVinValues')) { + const vin = decodeURIComponent(u.split('/').at(-1).split('?')[0]); + return Response.json({Results: [{VIN: vin, Make: 'FORD', Model: 'F-150', ModelYear: '2015'}]}); + } + if (u.includes('SafetyRatings')) return Response.json({Results: []}); + if (u.includes('fueleconomy')) return Response.json(null); + return Response.json({results: []}); + }; + return () => { globalThis.fetch = original; }; +} + +/** + * A Ford lookup counting its requests. Its page answers after `delay` ms, or, without a delay, when the test calls + * release(): a gate, so the outcome does not depend on how busy the machine is. `fail`: the request fails instead. + * `requested`: resolves when the first request is made; `answered`: when the stub has answered (or failed). + */ +function slowFord({delay = null, fail = false} = {}) { + const calls = []; + let open, started, finished; + const gate = delay === null ? new Promise(resolve => { open = resolve; }) : null; + const requested = new Promise(resolve => { started = resolve; }), answered = new Promise(resolve => { finished = resolve; }); + const lookup = createRecallStatusLookup(async url => { + calls.push(url); started(Date.now()); + try { + await (gate || sleep(delay)); + if (fail) throw new Error('socket hang up'); + const vin = new URL(url).pathname.split('/').filter(Boolean).at(-1); + const page = fordPage(fordState(vin)); + return {ok: true, text: async () => page, json: async () => JSON.parse(page)}; + } finally { finished(); } + }); + return {lookup, calls, release: () => open(), requested, answered}; +} +const settle = () => new Promise(resolve => setTimeout(resolve, 20)); // let catch handlers and unhandledRejection run + +function setup(t, lookup) { + [vinCache, recallCache, ratingCache, fuelCache].forEach(c => c.clear()); + const restoreFetch = stubNhtsa(), previous = useRecallStatusLookup(lookup); + t.after(() => { restoreFetch(); useRecallStatusLookup(previous); [vinCache, recallCache, ratingCache, fuelCache].forEach(c => c.clear()); }); +} + +test('the website and REST budget is 2 s and MCP\'s 6 s, counted from the lookup start', () => { + assert.equal(RECALL_WAIT_MS.report, 2000); + assert.equal(RECALL_WAIT_MS.mcp, 6000); + const info = recallLookupInfo('1FTEX1EP4FFD06976'); + assert.deepEqual([info.provider, info.maker, info.name, info.network, info.by_wmi], ['ford', 'Ford', 'Ford Owner Support VIN Recalls', true, true]); + assert.equal(recallLookupInfo(withCheck('1ZVFT80N055124042'), 'FORD').by_wmi, false); // Mustang (AutoAlliance WMI): by make + assert.equal(recallLookupInfo(withCheck('1ZVFT80N055124042'), 'FORD').provider, 'ford'); +}); + +test('a slow maker lookup: the report answers with recall_status pending, then the background lookup fills the cache', async t => { + const ford = slowFord(); + setup(t, ford.lookup); + const vin = nextFordVin(); + const first = await fullReport(vin, {recallWaitMs: 150}); // the maker has not answered (gate closed) + const s = first.recall_status; + assert.equal(s.pending, true); + assert.equal(s.available, false); + assert.equal(s.reason, 'lookup_in_progress'); + assert.equal(s.open_count, null, 'unknown, never "no open recalls"'); + assert.equal(s.completed_count, null); + assert.deepEqual(s.recalls, []); + assert.equal(s.maker, 'Ford'); + assert.equal(s.source.provider, 'Ford Owner Support VIN Recalls'); + assert.equal(s.status_url, `/api/vin/${vin}/recall-status`); + assert.equal(s.waited_ms, 150); + assert.match(s.verification_url, /^https:\/\/www\.ford\.com\/support\/recalls-details\//); + assert.match(s.note, /not "no open recalls"/); + assert.equal(first.decode_checks.sources.manufacturer_record.status, 'pending'); + assert.equal(first.decode_checks.sources.manufacturer_record.maker, 'Ford'); + assert.equal(ford.calls.length, 1, 'the lookup started once'); + // The lookup keeps running in the background and fills the 15-minute cache. + ford.release(); + await ford.answered; await settle(); + const second = await fullReport(vin, {recallWaitMs: 0}); + assert.equal(second.recall_status.available, true); + assert.equal(second.recall_status.pending, undefined); + assert.equal(second.recall_status.open_count, 1); + assert.equal(second.decode_checks.sources.manufacturer_record.status, 'not_available'); + assert.equal(ford.calls.length, 1, 'no second request to the maker'); + // The same full report object is reused while the base report and the maker's result are cached. + assert.equal(await fullReport(vin, {recallWaitMs: 0}), second); +}); + +test('the lookup starts right after the decode, beside NHTSA\'s calls (not after them)', async t => { + const ford = slowFord({delay: 50}); + setup(t, ford.lookup); + // NHTSA's recall lookup answers only once the maker's request has started (or after 3 s): in the old order (maker + // after the NHTSA calls) the maker's request would start after NHTSA answered. + const restore = globalThis.fetch; + let recallsAnswered = null; + globalThis.fetch = async url => { + if (String(url).includes('recallsByVehicle')) { await Promise.race([ford.requested, sleep(3000)]); recallsAnswered ??= Date.now(); } + return restore(url); + }; + const r = await fullReport(nextFordVin(), {recallWaitMs: Infinity}); + const makerStarted = await ford.requested; + assert.equal(r.recall_status.available, true); + assert.ok(recallsAnswered !== null && makerStarted <= recallsAnswered, `maker request at ${makerStarted}, NHTSA recalls answered at ${recallsAnswered}`); +}); + +test('concurrent reports share one maker lookup, and the recall-status endpoint joins it', async t => { + const ford = slowFord(); + setup(t, ford.lookup); + const vin = nextFordVin(); + const [a, b] = await Promise.all([fullReport(vin, {recallWaitMs: 50}), fullReport(vin.toLowerCase(), {recallWaitMs: 50})]); + assert.equal(a.recall_status.pending, true); + assert.equal(b.recall_status.pending, true); + const joined = vinRecallStatusFor(vin); // what GET status_url and MCP vin_recall_status run + ford.release(); + const status = await joined; + assert.equal(status.available, true); + assert.equal(status.open_count, 1); + assert.equal(ford.calls.length, 1); + const full = await fullReport(vin, {recallWaitMs: Infinity}); + assert.equal(full.recall_status, status); + assert.equal(ford.calls.length, 1); +}); + +test('a background lookup that fails is contained: no unhandled rejection, then unknown (not pending, not zero)', async t => { + const ford = slowFord({fail: true}); + setup(t, ford.lookup); + const unhandled = []; + const onUnhandled = err => unhandled.push(err); + process.on('unhandledRejection', onUnhandled); + t.after(() => process.off('unhandledRejection', onUnhandled)); + const vin = nextFordVin(); + const first = await fullReport(vin, {recallWaitMs: 20}); + assert.equal(first.recall_status.pending, true); + ford.release(); + await ford.answered; await settle(); + assert.deepEqual(unhandled, []); + const second = await fullReport(vin, {recallWaitMs: Infinity}); + assert.equal(second.recall_status.available, false); + assert.equal(second.recall_status.reason, 'upstream_unavailable'); + assert.equal(second.recall_status.open_count, null); + assert.equal(second.recall_status.pending, undefined); + assert.equal(ford.calls.length, 2, 'a failure is not cached: the next report asks again'); + + // A lookup function that throws (not only one that returns a failure) is contained the same way. + let open; + const gate = new Promise(resolve => { open = resolve; }); + useRecallStatusLookup(async () => { await gate; throw new Error('boom'); }); + const thrown = await fullReport(nextFordVin(), {recallWaitMs: 10}); + assert.equal(thrown.recall_status.pending, true); + open(); await settle(); + assert.deepEqual(unhandled, []); + const after = await fullReport(nextFordVin(), {recallWaitMs: Infinity}); + assert.equal(after.recall_status.available, false); + assert.equal(after.recall_status.reason, 'upstream_unavailable'); +}); + +test('makers that answer at once never show pending', async t => { + const calls = []; + setup(t, createRecallStatusLookup(async url => { calls.push(url); throw new Error('no request expected'); })); + const toyota = withCheck('4T1BF1FK0CU123456'); + const restore = globalThis.fetch; + globalThis.fetch = async url => String(url).includes('DecodeVinValues') + ? Response.json({Results: [{VIN: toyota, Make: 'TOYOTA', Model: 'Camry', ModelYear: '2012'}]}) : restore(url); + const r = await fullReport(toyota, {recallWaitMs: 0}); + assert.equal(r.recall_status.reason, 'interactive_verification_required'); + assert.equal(r.recall_status.pending, undefined); + assert.deepEqual(calls, []); +}); + +test('MCP decode_vin waits longer (6 s) than the website, offers recall_wait "full", and points to vin_recall_status', async t => { + // 3 s: past the website's 2 s, within MCP's 6 s. + const {lookup, calls} = slowFord({delay: 3000}); + setup(t, lookup); + let decodeVin, schema; + vehicleTools((name, description, inputSchema, handler) => { if (name === 'decode_vin') { decodeVin = handler; schema = {description, inputSchema}; } }); + assert.ok(schema.inputSchema.recall_wait, 'recall_wait argument'); + assert.match(schema.description, /recall_status\.pending/); + assert.match(schema.description, /vin_recall_status/); + const vin = nextFordVin(); + // The website's budget (2 s) runs out; MCP's 6 s does not. + const [site, mcp] = await Promise.all([fullReport(vin), decodeVin({vin}).then(r => JSON.parse(r.content[0].text))]); + assert.equal(site.recall_status.pending, true); + assert.equal(mcp.recall_status.available, true); + assert.equal(mcp.recall_status.open_count, 1); + assert.equal(calls.length, 1); + // A pending status in MCP output names the next tool call. + const pending = mcpReport({...site, recall_status: pendingRecallStatus(vin, 'FORD', RECALL_WAIT_MS.mcp)}); + assert.equal(pending.recall_status.pending, true); + assert.deepEqual(pending.recall_status.next_step, {tool: 'vin_recall_status', arguments: {vin}}); + assert.match(pending.recall_status.note, /call vin_recall_status/); + assert.match(pending.recall_status.note, /after 6\.0 s/); + assert.equal(pending.decode_checks.sources.manufacturer_record, 'pending'); +}); diff --git a/tests/mock-upstream.mjs b/tests/mock-upstream.mjs index a7adac0..d84a93b 100644 --- a/tests/mock-upstream.mjs +++ b/tests/mock-upstream.mjs @@ -5,12 +5,15 @@ import https from 'node:https'; import {Readable} from 'node:stream'; import {EventEmitter} from 'node:events'; const nativeGet=https.get; +// MOCK_FORD_DELAY_MS: Ford's page answers after that long (its CDN holds real requests ~9-10 s; tests/slow-maker.test.mjs). +const fordDelay=Number(process.env.MOCK_FORD_DELAY_MS)||0; https.get=(url,opts,callback)=>{ if(String(url)==='https://www.nissanusa.com/owners/recalls-vin.html'){ const response=Readable.from([Buffer.from(nissanPage)]);response.statusCode=200;queueMicrotask(()=>callback(response));return new EventEmitter(); } if(String(url).includes('ford.com/support/recalls-details/')){ - const vin=new URL(url).pathname.split('/').filter(Boolean).at(-1);const response=Readable.from([Buffer.from(fordPage(fordState(vin)))]);response.statusCode=200;queueMicrotask(()=>callback(response));return new EventEmitter(); + const vin=new URL(url).pathname.split('/').filter(Boolean).at(-1);const response=Readable.from([Buffer.from(fordPage(fordState(vin)))]);response.statusCode=200; + if(fordDelay)setTimeout(()=>callback(response),fordDelay);else queueMicrotask(()=>callback(response));return new EventEmitter(); } if(String(url).includes('experience.gm.com/ownercenter/api/')){ const vin=new URL(url).pathname.split('/').at(-2);const response=Readable.from([Buffer.from(JSON.stringify(gmFixture(vin)))]);response.statusCode=200;queueMicrotask(()=>callback(response));return new EventEmitter(); diff --git a/tests/pending-recall-status.test.mjs b/tests/pending-recall-status.test.mjs new file mode 100644 index 0000000..2e4311a --- /dev/null +++ b/tests/pending-recall-status.test.mjs @@ -0,0 +1,129 @@ +// The website while the maker's VIN recall lookup is still answering (recall_status.pending, lib/reports.mjs): +// "Checking with Ford…" on screen, never printed as if final, then filled in place. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import vm from 'node:vm'; +import {readFileSync} from 'node:fs'; + +const pending = {vin: '1FTEX1EP4FFD06976', scope: 'vin', vin_specific: true, available: false, pending: true, reason: 'lookup_in_progress', maker: 'Ford', + waited_ms: 2000, source: {provider: 'Ford Owner Support VIN Recalls', reference_url: 'https://www.ford.com/support/recalls-details/1FTEX1EP4FFD06976/'}, + verification_url: 'https://www.ford.com/support/recalls-details/1FTEX1EP4FFD06976/', open_count: null, completed_count: null, recalls: [], + status_url: '/api/vin/1FTEX1EP4FFD06976/recall-status', note: 'Ford\'s VIN recall lookup had not answered after 2.0 s.'}; +const complete = {vin: '1FTEX1EP4FFD06976', available: true, open_count: 2, completed_count: 1, unknown_count: 0, service_campaign_count: 1, + verification_url: 'https://www.ford.com/support/recalls-details/1FTEX1EP4FFD06976/', note: 'Official Ford VIN page.', + source: {provider: 'Ford Owner Support VIN Recalls', retrieved_at: '2026-11-18T15:10:00Z'}, + recalls: [{campaign_number: '22S41', manufacturer_status: 'Recall incomplete (O)', record_kind: 'safety_recall', summary: 'Brake hose'}], service_campaigns: []}; +const report = (recall_status, extra = {}) => ({valid: true, vin: '1FTEX1EP4FFD06976', validation: {checksum: {valid: true}}, + vehicle: {year: 2015, make: 'FORD', model: 'F-150', body_class: 'Pickup'}, engine: {displacement_l: 3.5, cylinders: 6}, transmission: {}, raw_nhtsa: {}, + dimensions: {}, recalls: {available: true, count: 3, recalls: []}, complaints: {available: true, count: 0, complaints: []}, safety_ratings: {rated: false}, + fuel_economy: {available: false, reason: 'no_matching_variant'}, provenance: {assembled_at: '2026-11-18T15:09:58Z'}, + decode_checks: {pattern: '1FTEX1EP*FF', fields: [], counts: {}, sources: {manufacturer_record: recall_status.pending ? {status: 'pending', maker: 'Ford'} : {status: 'not_available'}, test_vehicle_pattern: {status: 'none_for_pattern'}}, note: ''}, + recall_status, ...extra}); + +function loadSheet() { + const ctx = {console, URLSearchParams, setTimeout}; + vm.createContext(ctx); + for (const file of ['qr.js', 'decode-checks.js', 'car-sheet.js']) vm.runInContext(readFileSync(new URL('../public/' + file, import.meta.url), 'utf8'), ctx); + return {sheet: vm.runInContext('CarSheet', ctx), dc: vm.runInContext('DecodeChecks', ctx)}; +} +const recallRow = html => html.match(/This VIN’s recall status<\/dt>
    (.*?)<\/dd>/)[1]; +// What reaches paper: screen-only parts (pending-screen, sheet-screen-only) removed; pending-print shown. +const paper = html => html.replace(/(?:[^<]|[^<]*<\/span>)*<\/span>/g, '') + .replace(/[^<]*<\/span>/g, '').replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim(); +const screen = html => html.replace(/[^<]*<\/span>/g, '').replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim(); + +test('car sheet: pending shows "Checking with Ford…" on screen and prints that Ford had not answered, never a status', () => { + const {sheet} = loadSheet(); + const row = recallRow(sheet.html(report(pending)).body); + assert.match(screen(row), /^Checking with Ford…/); + assert.match(paper(row), /^Unknown: Ford had not answered when this sheet was printed\./); + assert.doesNotMatch(paper(row), /Checking/); + assert.doesNotMatch(paper(row), /\b0 open\b|no open/i); + assert.match(paper(row), /Check this VIN with the official source/); + // The footer names the maker as a source only once it has answered. + assert.doesNotMatch(sheet.html(report(pending)).foot, /Ford Owner Support/); + const done = sheet.html(report(complete)); + assert.match(recallRow(done.body), /2 open · 1 completed or closed/); + assert.match(done.foot, /Ford Owner Support VIN Recalls/); + // Only the recall section differs between the two (the sheet redraws only that one). + const sections = h => h.match(/
    '), b = done.body.split('
    '); + assert.deepEqual(sections(sheet.html(report(pending)).body), sections(done.body)); + assert.deepEqual(a.map((x, i) => x === b[i]), a.map(x => !x.includes('sheet-recalls'))); + // The page could not load the answer: unknown, with why. + const lost = recallRow(sheet.html(report({...pending, pending: false, reason: 'lookup_not_loaded'})).body); + assert.match(lost, /^Unknown\. The maker’s answer could not be loaded here; reload the report\./); +}); + +test('decode checks card: the manufacturer record is "checking with Ford…" on screen and "not loaded when printed" on paper', () => { + const {dc} = loadSheet(); + const line = dc.sourcesHtml(report(pending)); + assert.match(line, /^

    /); + assert.match(screen(line), /the manufacturer’s record \(\s*checking with Ford…\s*\)/); + assert.match(line, /not loaded when printed<\/span>/); + assert.match(dc.sourcesHtml(report(complete)), /the manufacturer’s record \(not available for this VIN\)/); + assert.ok(dc.cardHtml(report(pending)).includes(line), 'the card carries the same line'); +}); + +// app.js with a minimal DOM (as tests/regression.test.mjs): render, then the follow-up request fills the status in. +function frontend() { + const els = new Map(); + const element = () => ({style: {}, dataset: {}, handlers: {}, value: '', classList: {add() {}, remove() {}, toggle() {}}, addEventListener(k, fn) { this.handlers[k] = fn; }, dispatchEvent(e) { return this.handlers[e.type]?.(e); }, setAttribute() {}, focus() {}, setSelectionRange() {}, querySelector() { return element(); }, querySelectorAll() { return []; }, replaceChildren() { this.innerHTML = ''; }, innerHTML: '', textContent: '', hidden: false}); + const document = {createElement: () => ({set textContent(v) { this.innerHTML = String(v).replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>'); }}), querySelector: s => { if (!els.has(s)) els.set(s, element()); return els.get(s); }, querySelectorAll: () => [], addEventListener() {}}; + const requests = []; + const ctx = {document, window: {location: {pathname: '/'}}, navigator: {}, localStorage: {getItem() { return null; }}, console, setTimeout: fn => fn(), addEventListener() {}, requests}; + ctx.fetch = async url => { requests.push(url); return ctx.reply(url); }; + vm.createContext(ctx); + vm.runInContext(readFileSync(new URL('../public/app.js', import.meta.url), 'utf8'), ctx); + return {ctx, els, run: script => vm.runInContext(script, ctx)}; +} + +test('web report: pending shows "Checking with Ford…", then the follow-up fills only the status block', async () => { + const {ctx, els, run} = frontend(); + ctx.first = report(pending); + run('currentReport = first; renderRecalls(first)'); + const body = els.get('#recalls-body').innerHTML; + assert.match(body, /

    /); + assert.match(body, /Checking with Ford… Its VIN lookup is still answering/); + assert.match(body, /

    Not loaded: Ford had not answered when this page was printed/); + assert.doesNotMatch(body, /0 open recalls/); + ctx.reply = () => Response.json(report(complete)); + await run('followRecallStatus(currentReport)'); + assert.deepEqual(ctx.requests, ['/api/vin/1FTEX1EP4FFD06976?recall_wait=full']); + const block = els.get('#recall-status-block').innerHTML; + assert.match(block, /2 open recalls · 1 manufacturer-reported completed\/closed/); + assert.match(block, /Ford Owner Support VIN Recalls/); + assert.equal(els.get('#recalls-body').innerHTML, body, 'the campaign list is not redrawn'); + assert.equal(run('currentReport.recall_status.available'), true); + assert.equal(run('currentReport.complaints.count'), 0, 'blocks the maker does not touch are kept from the first report'); + assert.match(els.get('#decode-status').textContent, /Ford’s VIN recall status has loaded/); +}); + +test('web report: if the follow-up fails twice the status says it could not be loaded (unknown), never pending forever', async () => { + const {ctx, els, run} = frontend(); + ctx.first = report(pending); + run('currentReport = first; renderRecalls(first)'); + ctx.reply = () => { throw new TypeError('network down'); }; + await run('followRecallStatus(currentReport)'); + assert.equal(ctx.requests.length, 2, 'asked twice'); + const block = els.get('#recall-status-block').innerHTML; + assert.match(block, /VIN-specific repair status is unavailable\. Ford’s answer could not be loaded/); + assert.doesNotMatch(block, /Checking/); + assert.equal(run('currentReport.recall_status.pending'), false); + assert.match(els.get('#decode-status').textContent, /not available/); +}); + +test('web report: a follow-up for a VIN no longer shown changes nothing', async () => { + const {ctx, els, run} = frontend(); + ctx.first = report(pending); + run('currentReport = first; renderRecalls(first)'); + let release; + ctx.reply = () => new Promise(resolve => { release = () => resolve(Response.json(report(complete))); }); + const follow = run('followRecallStatus(currentReport)'); + await new Promise(r => setImmediate(r)); + run('currentReport = null'); + release(); + await follow; + assert.ok(!els.has('#recall-status-block'), 'nothing was redrawn'); + assert.ok(!els.has('#decode-status')); +}); diff --git a/tests/slow-maker.test.mjs b/tests/slow-maker.test.mjs new file mode 100644 index 0000000..1b7cdec --- /dev/null +++ b/tests/slow-maker.test.mjs @@ -0,0 +1,77 @@ +// The real server with a slow manufacturer lookup: Ford's page answers after 2.6 s (tests/mock-upstream.mjs, +// MOCK_FORD_DELAY_MS), longer than the website/REST wait (2 s) and shorter than MCP's (6 s). Own server and port, +// so its rate limits and caches are apart from tests/integration.test.mjs. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtemp, cp, symlink, rm, mkdir } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { spawn } from 'node:child_process'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'; +import { validateVin } from '../lib/validate.mjs'; + +const root = fileURLToPath(new URL('../', import.meta.url)); +const stage = await mkdtemp(path.join(tmpdir(), 'vin-mcp-slow-maker-')); +for (const f of ['server.mjs', 'package.json', 'lib', 'public', 'tests/mock-upstream.mjs', 'tests/mopar-fixture.mjs', 'tests/manufacturer-fixtures.mjs']) await cp(path.join(root, f), path.join(stage, f), {recursive: true}); +await symlink(path.join(root, 'node_modules'), path.join(stage, 'node_modules'), 'dir'); +await mkdir(path.join(stage, 'data'), {recursive: true}); +const port = 23292, base = `http://127.0.0.1:${port}`, FORD_DELAY = 2600; +const env = {...process.env, JWT_SECRET: 'isolated-test-secret', ADMIN_KEY: 'b'.repeat(64), NODE_ENV: 'production', MOCK_FORD_DELAY_MS: String(FORD_DELAY)}; +const child = spawn(process.execPath, ['--import', path.join(stage, 'tests/mock-upstream.mjs'), path.join(stage, 'server.mjs'), '--http', '--port', String(port)], {cwd: stage, env, stdio: ['ignore', 'ignore', 'pipe']}); +let stderr = ''; child.stderr.on('data', b => stderr += b); +test.after(async () => { child.kill(); await new Promise(resolve => child.once('exit', resolve)); await rm(stage, {recursive: true, force: true}); }); +for (let i = 0; i < 100; i++) { try { if ((await fetch(base + '/health')).ok) break; } catch {} await new Promise(r => setTimeout(r, 50)); if (i === 99) throw Error(stderr); } + +const withCheck = v => v.slice(0, 8) + validateVin(v).checksum.expected + v.slice(9); +const timed = async url => { const t = Date.now(); const res = await fetch(base + url); return {res, body: await res.json(), ms: Date.now() - t}; }; + +test('REST: a first report answers before the slow maker, pending with status_url; the status and the next report are complete', async () => { + const vin = withCheck('1FTEX1EP0FFD06901'); + const first = await timed('/api/vin/' + vin); + assert.equal(first.res.status, 200); + assert.ok(first.ms < FORD_DELAY - 200, `first report in ${first.ms} ms`); + const s = first.body.recall_status; + assert.deepEqual([s.pending, s.available, s.reason, s.open_count, s.completed_count, s.maker], [true, false, 'lookup_in_progress', null, null, 'Ford']); + assert.equal(s.status_url, `/api/vin/${vin}/recall-status`); + assert.equal(first.body.decode_checks.sources.manufacturer_record.status, 'pending'); + // status_url waits for the same lookup (no new 2.6 s wait from the start) + const status = await timed(s.status_url); + assert.equal(status.res.status, 200); + assert.equal(status.body.available, true); + assert.equal(status.body.open_count, 1); + assert.ok(first.ms + status.ms < FORD_DELAY + 1500, `status after ${first.ms + status.ms} ms in all`); + const again = await timed('/api/vin/' + vin); + assert.equal(again.body.recall_status.available, true); + assert.equal(again.body.recall_status.pending, undefined); + assert.ok(again.ms < 1000, `cached report in ${again.ms} ms`); +}); + +test('REST: ?recall_wait=full waits for the maker; other values are refused', async () => { + const vin = withCheck('1FTEX1EP0FFD06902'); + assert.equal((await fetch(base + '/api/vin/' + vin + '?recall_wait=later')).status, 400); + const full = await timed('/api/vin/' + vin + '?recall_wait=full'); + assert.equal(full.body.recall_status.available, true); + assert.equal(full.body.recall_status.completed_count, 1); + assert.ok(full.ms >= FORD_DELAY - 100, `waited ${full.ms} ms`); +}); + +test('MCP: decode_vin waits up to 6 s, so this maker is complete; vin_recall_status joins a running lookup', async () => { + const client = new Client({name: 'slow-maker-test', version: '1'}), transport = new StreamableHTTPClientTransport(new URL(base + '/mcp')); + try { + await client.connect(transport); + const vin = withCheck('1FTEX1EP0FFD06903'); + const r = JSON.parse((await client.callTool({name: 'decode_vin', arguments: {vin}})).content[0].text); + assert.equal(r.recall_status.available, true); + assert.equal(r.recall_status.open_count, 1); + // A website report leaves the lookup running; vin_recall_status gets its answer. + const other = withCheck('1FTEX1EP0FFD06904'); + const site = await timed('/api/vin/' + other); + assert.equal(site.body.recall_status.pending, true); + const t = Date.now(); + const status = JSON.parse((await client.callTool({name: 'vin_recall_status', arguments: {vin: other}})).content[0].text); + assert.equal(status.available, true); + assert.ok(Date.now() - t < FORD_DELAY, 'joined the running lookup'); + } finally { await transport.terminateSession(); await client.close(); } +}); From fa6c31ad22aeb15895f57b6267a62bdb5a7b7ed2 Mon Sep 17 00:00:00 2001 From: root Date: Wed, 18 Nov 2026 10:31:00 -0500 Subject: [PATCH 3/6] Document pending recall status; VinClient.decode recallWait option docs/data-sources.md: the budget, the pending shape, status_url, the shared background lookup, recall_wait, the website's in-place update and print wording, and why Ford's lookup is slow (Akamai holds each request about 9-10 s). llms-full.txt: recall_status and recall_wait for REST and MCP, the recall-status endpoint, manufacturer_record "pending", caching. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- docs/data-sources.md | 22 +++++++++++++++++++++- public/client.mjs | 3 ++- public/index.html | 4 ++-- public/llms-full.txt | 12 ++++++++++-- public/research/research.js | 2 +- tests/pending-recall-status.test.mjs | 9 +++++++++ 7 files changed, 46 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index ab43a02..0927b5b 100644 --- a/README.md +++ b/README.md @@ -239,7 +239,7 @@ charting or document tools to create figures and analysis. Custom chart renderin in the agent's tools. The API supplies comparisons, scenario calculations, provenance and JSON. Configuration/model-year data and VIN-specific facts retain their distinct scopes. -VIN recall repair status: Tesla and Ford open/completed statuses, GM open/completed or administratively closed records, Honda and Acura active safety recalls, Subaru completed/incomplete safety recalls, Volkswagen, Audi, Land Rover and Jaguar recalls as reported by each maker, positive Nissan open safety recalls, and Mopar VIN-matched open recall/campaign records are included in reports and comparisons, with `vin_recall_status`, `GET /api/vin/{vin}/recall-status` and `VinClient.recallStatus(vin)`. Mopar safety-recall count and completed history remain unknown because its feed mixes campaign types. GM repair dates are shown only when explicitly supplied; administrative closing dates remain separate. Ford customer-satisfaction and GM non-recall programs stay separate from recall counts. Honda covers active safety recalls from the past 15 calendar years and does not supply completed history. Nissan requires matching full VINs and verified safety classifications; empty results remain unknown. Toyota/Lexus/Scion, Hyundai and Kia require interactive official verification. Other makes remain unknown. See the [source and coverage notes](docs/data-sources.md#vin-specific-recall-repair-status). +VIN recall repair status: Tesla and Ford open/completed statuses, GM open/completed or administratively closed records, Honda and Acura active safety recalls, Subaru completed/incomplete safety recalls, Volkswagen, Audi, Land Rover and Jaguar recalls as reported by each maker, positive Nissan open safety recalls, and Mopar VIN-matched open recall/campaign records are included in reports and comparisons, with `vin_recall_status`, `GET /api/vin/{vin}/recall-status` and `VinClient.recallStatus(vin)`. Mopar safety-recall count and completed history remain unknown because its feed mixes campaign types. GM repair dates are shown only when explicitly supplied; administrative closing dates remain separate. Ford customer-satisfaction and GM non-recall programs stay separate from recall counts. Honda covers active safety recalls from the past 15 calendar years and does not supply completed history. Nissan requires matching full VINs and verified safety classifications; empty results remain unknown. Toyota/Lexus/Scion, Hyundai and Kia require interactive official verification. Other makes remain unknown. A report waits up to 2 s for the maker's lookup (MCP `decode_vin`: 6 s); a slower maker (Ford's lookup usually takes about 10 s) gives `recall_status.pending: true`, unknown rather than zero, with `status_url` to fetch the complete status from the same running lookup, or ask with `?recall_wait=full` (`VinClient.decode(vin, {recallWait: 'full'})`). See the [source and coverage notes](docs/data-sources.md#vin-specific-recall-repair-status). Deployment caching: HTML must revalidate, API responses must not be stored by shared caches, and changed JavaScript/PDF links use a content-hash query version generated by `node scripts/version-assets.mjs`. API clients also bypass stored browser responses. Preserve these policies in any reverse proxy so updated recall records are rendered by the matching client code. diff --git a/docs/data-sources.md b/docs/data-sources.md index 1a2bb85..338929c 100644 --- a/docs/data-sources.md +++ b/docs/data-sources.md @@ -187,6 +187,25 @@ Tesla Service's [official VIN recall search](https://service.tesla.com/en-US/vin `GET /api/vin/{vin}/recall-status`, `VinClient.recallStatus(vin)` and MCP `vin_recall_status` expose this data. VIN reports and printable comparisons include the summary. Tesla and Ford supply open/completed states. Subaru supplies completed and incomplete safety recalls, with emissions campaigns listed separately. Volkswagen, Audi and Land Rover report open recalls, and completed ones only where their lookup returns them. Acura is covered through the Honda lookup. (Added 2026-11-16 in `lib/more-manufacturer-recalls.mjs`; open records have been seen live for Volkswagen and Audi; completed records for those two, and any Land Rover or Jaguar record, have only been read from the makers' page code. Jaguar shares Land Rover's lookup. BMW's lookup did not answer plain requests and is not used.) GM supplies open/completed or administratively closed records, and explicit repair dates where supplied. Honda supplies active safety recalls; Nissan supplies positive open safety recalls and Mopar supplies VIN-matched open recall/campaign records, with the limitations below. Toyota, Lexus, Scion, Hyundai and Kia require interactive verification; other manufacturers return unknown with an official lookup link. Unknown response statuses never count as zero open recalls; recall dates never become repair completion dates. Results are not a complete service history or a guarantee of safety. Successful results are cached for up to 15 minutes; failures are retried. Public manufacturer interfaces are undocumented for third-party integration and can change. +#### When the maker answers slowly: `pending` + +A report does not wait the whole time for a slow maker. The lookup starts as soon as the VIN is decoded, beside NHTSA's calls, and the report waits for it up to a budget counted from that start: 2 s for the website and `GET /api/vin/{vin}` (`RECALL_WAIT_MS.report` in `lib/reports.mjs`), 6 s for MCP `decode_vin` (`RECALL_WAIT_MS.mcp`). Comparisons wait for the full answer (they are printed and exported). A maker still answering after the budget gives: + +```json +"recall_status": {"vin": "1FMCU0G61LUA27504", "scope": "vin", "vin_specific": true, "available": false, + "pending": true, "reason": "lookup_in_progress", "maker": "Ford", "waited_ms": 2000, + "open_count": null, "completed_count": null, "recalls": [], + "source": {"provider": "Ford Owner Support VIN Recalls", "reference_url": "https://www.ford.com/support/recalls-details/..."}, + "verification_url": "https://www.ford.com/support/recalls-details/...", + "status_url": "/api/vin/1FMCU0G61LUA27504/recall-status", "note": "..."} +``` + +Pending is unknown, never "no open recalls" (`available: false`, counts null). The lookup keeps running in the background and fills the 15-minute cache; one lookup per VIN runs at a time and every request for that VIN shares it (`createRecallStatusLookup`). `GET status_url`, MCP `vin_recall_status` and `GET /api/vin/{vin}?recall_wait=full` (MCP: `recall_wait: "full"`) wait for that same lookup. A background lookup that fails is caught: nothing is cached and the next request asks the maker again. In MCP output a pending status also carries `next_step: {tool: "vin_recall_status", arguments: {vin}}`. `decode_checks.sources.manufacturer_record.status` is `pending` meanwhile; the checks that use the maker's description of the VIN run when the status arrives. + +The website shows "Checking with Ford…" in the recall card, the car sheet's recall row and the decode-checks source line, then requests the report again with `?recall_wait=full` and redraws only the blocks that changed (the status block, the car sheet's recall section and footer, and the decode checks, fuel economy and test-vehicle blocks only if the maker's record changed a checked value), keeping typed text, open forms, focus, the transmission choice and the scroll position (`public/keep-state.js`). Printed while pending, the car sheet's row reads "Unknown: Ford had not answered when this sheet was printed" and the recall card "Not loaded: Ford had not answered when this page was printed"; printing does not wait. If the second request fails twice, the status reads as not loaded (unknown). + +Why Ford is slow (measured 2026-11-18 from the web server, 4 requests): Ford's CDN (Akamai) holds each request about 9-10 s before answering (`server-timing` edge duration 9,000-10,002 ms; origin about 120 ms), even for a no-VIN page, a cached redirect and a reused connection, so the delay is per request and a client cannot shorten it. The VIN page is also about 1.3 MB, with the recall data about 81% of the way through. Reports for other makes took 0.4-2 s in all before this change. + ### Ford: open/completed recalls and separate programs The [official Ford VIN page](https://www.ford.com/support/recalls/) serves its VIN-specific status in the same public page used by the browser. The adapter parses the serialized data as JSON; it never executes downloaded JavaScript. Both the page VIN and the returned vehicle VIN must match. The success flag, validation flag, arrays and declared record counts must agree. `O` means open and `C` means completed; other values remain unknown. Safety/environmental recall records and customer-satisfaction programs are separate. Coverage begins January 1, 2004. No repair date is supplied, so `repair_completed_at` remains null. The same official checker accepts Ford, Lincoln and Mercury; upstream confirmation still controls availability. @@ -674,7 +693,8 @@ tires and capacities) use the checked values. Code: `lib/decode-checks.mjs`, `li disagree leave the field unset; "e-tron", "PZEV", "FED", a lone "A" and Subaru's "2.5X" are never read as powertrain, transmission or drive. The VIN page is drawn before the maker replies and never waits for it (`sources.manufacturer_record.status: "not_checked"`); the REST report, MCP `decode_vin` and comparisons - re-run the checks with it (`used`, `not_available` or `not_supported`). In a gentle sample of 16 NHTSA test + re-run the checks with it (`used`, `not_available` or `not_supported`), or say `pending` when the maker had not + answered within the report's wait (see "When the maker answers slowly" above; the website then fills them in). In a gentle sample of 16 NHTSA test vehicles the description agreed with vPIC on every stated field except drive on both 2018 Atlases (vPIC AWD, Volkswagen "FWD", both test reports FWD), and named "MULTITRONIC" (a CVT) where vPIC said "Automatic". - **NHTSA test-vehicle evidence.** `data-src/decode-evidence.jsonl` (built offline by the audit, imported with diff --git a/public/client.mjs b/public/client.mjs index ffe423c..1552285 100644 --- a/public/client.mjs +++ b/public/client.mjs @@ -1,7 +1,8 @@ export class VinClient { constructor({baseUrl='http://127.0.0.1:3200',fetchImpl=globalThis.fetch,timeout=45000}={}){this.baseUrl=baseUrl.replace(/\/$/,'');this.fetch=(...args)=>fetchImpl(...args);this.timeout=timeout;} async request(path,body){const r=await this.fetch(this.baseUrl+path,{cache:'no-store',method:body===undefined?'GET':'POST',headers:body===undefined?{}:{'Content-Type':'application/json'},...(body===undefined?{}:{body:JSON.stringify(body)}),signal:AbortSignal.timeout(this.timeout)});const data=await r.json();if(!r.ok){const e=new Error(data.error||data.reason||`HTTP ${r.status}`);e.status=r.status;e.data=data;throw e;}return data;} - decode(vin){return this.request('/api/vin/'+encodeURIComponent(vin));} + // recallWait 'full': wait for the maker's VIN recall lookup instead of getting recall_status.pending after 2 s. + decode(vin,{recallWait}={}){return this.request('/api/vin/'+encodeURIComponent(vin)+(recallWait?'?recall_wait='+encodeURIComponent(recallWait):''));} recallStatus(vin){return this.request('/api/vin/'+encodeURIComponent(vin)+'/recall-status');} validate(vin){return this.request('/api/vin/'+encodeURIComponent(vin)+'/validate');} batch(vins){return this.request('/api/batch',{vins});} diff --git a/public/index.html b/public/index.html index 600d2b4..54d812c 100644 --- a/public/index.html +++ b/public/index.html @@ -396,7 +396,7 @@

    REST API

    node cli.mjs decode 1HGCM82633A004352 node cli.mjs catalog options '{"year":2003, "make":"Honda","model":"Accord"}'
    -

    API request console

    The response will appear here.

    Download JavaScript client · Machine-readable endpoint guide

    +

    API request console

    The response will appear here.

    Download JavaScript client · Machine-readable endpoint guide

    -
    +
    diff --git a/public/llms-full.txt b/public/llms-full.txt index eb236e7..b3f9ed4 100644 --- a/public/llms-full.txt +++ b/public/llms-full.txt @@ -46,6 +46,7 @@ Aggregates all 6 data sources into a single JSON response. Parameters: - `vin` (path, required): 17-character Vehicle Identification Number - `transmission` (query, optional): `automatic` or `manual`, when the owner knows it and the VIN does not say. It applies only when EPA lists the model with both; otherwise the answer is unchanged. Any other value returns 400. Without it, an automatic is assumed and marked (see `fuel_economy.assumed` below). +- `recall_wait` (query, optional): `full` waits for the manufacturer's VIN recall lookup (up to about 15 s) instead of answering with `recall_status.pending` after 2 s. Any other value returns 400. Response fields: - `valid` (boolean): Whether the VIN passed validation @@ -66,7 +67,8 @@ Response fields: - `fuel_economy` (object): FuelEconomy.gov configuration match: city/highway/combined MPG (MPGe for EVs, see unit), annual fuel cost, CO2 tailpipe g/mi, EV range (all-electric range; for plug-in hybrids total_range is gas plus electric), charge time; match: exact, closest (summary and match_basis say what differs), same_rating (several configurations fit and share one combined figure, which is given; city/highway only when they agree; configurations[] and separated_by say what differs) or multiple_configurations (available false, reason ambiguous_variant, with mpg_range, configurations[] each with its own figures and a plain-words label, separated_by, configuration_count; the VIN does not say which); not matched: not_found, no_matching_variant, heavy_duty_not_rated.. Transmission choice: when the configurations the VIN fits differ only partly by transmission (EPA lists both an automatic and a manual), the VIN does not say which, and the ratings differ, the automatic configuration's figures are given (one, or several by the usual rules) and marked: `assumed: {transmission: 'automatic'}`, `summary` starting "Assuming an automatic transmission (the VIN does not say)", `transmission_choice` {chosen, basis: assumed | request | owner_stated, label, options, classified, configuration_counts, efids_all}, and `alternatives` [{for_transmission: 'manual', ...the manual configuration's figures}]. CVT, dual-clutch and automated-manual transmissions count as automatic. With `?transmission=manual` (or the MCP `transmission` argument) the manual figures are given instead, with `stated: {transmission, by: 'request'}` and the automatic in `alternatives`. The decode's own transmission always wins. Saved vehicles carry `owner_details` ({transmission} or null), set with PUT /api/user/vins/{id}/details EPA rates configurations, not individual cars - `tire_placard` (object): Tire size (with load index and speed symbol) and front/rear recommended cold pressure (psi and kPa) printed in NHTSA crash-test reports or FMVSS 110/138/537 compliance test reports for a vehicle NHTSA tested, same vPIC make and model, closest match. `scope: "nhtsa_test_vehicle"`, `vin_specific: false`, `match_kind`, `max_year_gap` (2). `vehicles` lists the closest tested vehicles with `tested_as`, `tires`, `cold_pressure_psi`, `cold_pressure_kpa`, `source` (`nhtsa_crash_test` or `nhtsa_compliance_test`), `report_url`, `report_label`, `test_no` (null for a compliance report), `report_number` and `fmvss` (compliance reports), `other_reports`, `confidence` (`high` = two reports agree, `normal` = one report) and `match {kind, tested_model_year, vin_model_year, year_gap, differences, generation_check}`. Kinds, closest first: `exact` (same model year, no visible difference in trim, series, body, drive or electrification), `nearest_model_year` (another tested year within 2; both years on a tie; `generation_check` compares Transport Canada wheelbases: `same_wheelbase` or `unknown`; a year with a different wheelbase, likely another generation, is never used, and when only such years were tested `reason: "other_generation_only"`), `different_variant` (same year, differences listed; also `engine`, `wheel_size`, `gvwr_class`, `cab` from the two vPIC decodes). Only the closest kind present is returned; among equally close vehicles those that match the VIN's vPIC wheel size, engine and cab are kept, else all of them (the set). `accuracy {kind, tire_size_right_pct, cold_pressure_right_pct, basis}`: how often this kind of match gave the vehicle's own value in mcp.vin's leave-one-out test (each of 2,382 NHTSA test vehicles held out and looked up). An empty list means not tested or not indexed within reach (`reason: "no_close_match"`), never zero; `available: false` means the index was not checked. A test vehicle whose known powertrain class (battery-electric or not, from vPIC) differs from the VIN's is never used (`reason: "other_powertrain_only"`). Values are never estimated, blended or averaged. A vehicle may carry `corrections`: a misprint in NHTSA's report corrected because it has a clear mechanical cause (psi printed under a kPa heading, the tire's sidewall maximum printed in the pressure row, a digit glitch in a tire size, front and rear swapped) and an independent check confirmed the corrected value (the same report prints it elsewhere, or another report of the same test vehicle or of the same model generation and version does). Each is `{corrected: true, field, rule, printed, value, note, confirmed_by: [{check, detail, report, report_url}]}`; the vehicle's `tires` and `cold_pressure_*` are the corrected values, `printed` is what the report shows. A placard pressure is corrected only to a value printed in that report or another report of the same vehicle, never computed. Misprints that could not be confirmed stay excluded. The owner's own door placard governs; it can differ by year, trim and tire size. - `test_vehicle_specs` (object): Capacities and weights printed in the same reports, same closest-match rule and `match` object, preferring a tested vehicle with the VIN's electrification. Each vehicle: `fuel_tank` (usable standard tank: `litres`, `gallons`, `printed`; with `correction` when the report printed US gallons under a litres heading and the gallons reading is confirmed by another tested vehicle of the same generation or the measured weight), `fuel_tank_optional`, `payload_vehicle_capacity_weight`, `seating`, `gvwr`, `gawr_front`, `gawr_rear` (kg and lb; `printed` keeps the label's unit as printed; with `correction` when the label value was printed under the wrong unit, pounds under a kg heading or the reverse, and the corrected reading fits the measured weight and the other label values while the printed one does not) and `curb_weight_as_delivered` (total, front, rear, `front_percent`). Compliance-tested vehicles give `seating` as `{total}` only and may combine several reports of one test vehicle (`other_reports`; `field_reports` names the report of each value). `fuel_tank` summary: `shown`, `best_guess` (true unless the match is exact), `values` (one entry per distinct tank of the closest tested vehicles; never averaged), `optional_tank_listed`, `model_tank_sizes` (when this model's tested vehicles list more than one tank), or `reason: "different_electrification"` when the closest tested vehicle is a hybrid, plug-in or not where the VIN differs (no tank shown). The tank comes from the closest tested vehicle that lists one, with its own `match` and `report_url`. `values_differ` (when equally close tested vehicles print different values: `payload`, `seating`, `gvwr`, each a list of `{value, tested_as, model_year, report_url}`; show all, do not pick one). GVWR and GAWR are given only from a tested vehicle of the same version; otherwise the vehicle has `withheld {fields, reason: "different_version", note}` (another version's GVWR was right in about 4 of 10 test cases). `accuracy` (block) and `fuel_tank.accuracy`: right-percentages of this kind of match in the same leave-one-out test. `stopping_distance`: FMVSS 135 brake compliance test of the closest tested vehicle with one: `lightly_loaded` and `fully_loaded_gvwr` stop from 100 km/h (`m` as printed, `ft` converted), `maximum_speed_kmh`, `match`, report link; one vehicle's compliance test, not a rating; `shown: false, reason: "no_brake_test_in_reach"` when none is indexed. NHTSA's test vehicle, not this VIN; the owner's own labels and manual govern. -- `decode_checks` (object): Checks on the official decode (NHTSA vPIC), which describes a VIN pattern, not this vehicle. `pattern` (VIN positions 1-8, 10, 11), `fields[]` with `field` (drive, engine_size, cylinders, powertrain, transmission, speeds, seats, gvwr_class), `original` (vPIC's text, never changed), `original_value`, `shown`, `shown_value`, `status` (`confirmed`, `corrected`, `doubtful`, `filled`, `unverified`, `unknown`), `basis` (evidence tier), `rule`, `note`, `evidence` (`test_vehicles[]` with `test_no`, `report_url`, `value`, `source`; `epa` with `lists_decoded_value`, `model_names`), `candidates[]` (each tier's value, for doubts) and `matching` (`checked_value`, `widened` = the matchers return the range, `official_value`). `precedence`: `owner` > `manufacturer_vin_record` > `mcp_vin_rule_fix` > `nhtsa_test_vehicle_pattern` > `vpic_decode` > `assumption`. A field an mcp.vin rule fix changed is `corrected` with basis `mcp_vin_rule_fix`, `original` = NHTSA's official value, and `evidence.rule_fix` (`changed`, `fixes` with reason and NHTSA report links); `sources.rule_fixes.status`: `used`, `none_for_vin` or `not_applied` (a live-API decode). `sources.manufacturer_record.status`: `used`, `not_checked` (the VIN page, drawn before the maker replies), `not_available`, `not_supported`. Corrected = the manufacturer's record of this VIN, two or more NHTSA test vehicles with the same pattern that agree, or one test vehicle plus EPA listing its value and not vPIC's. Doubtful = a source disagrees without settling it, EPA lists no such value or combination for the model year, vPIC says "2WD/4WD", or an impossible combination. Filled = vPIC blank; from a test vehicle or from EPA's only value for the model year. vPIC error rates measured on 2,454 NHTSA test vehicles: drive 0.8%, displacement 0.2%, cylinders 0.3%, electrification 0.3%, transmission 0.1-0.6%, speeds 3.4%, seats 4.8%, GVWR class 0.7%. MCP `decode_vin` returns a shorter form (per field status, official, checked, basis, rule, note, matching, up to two report links). +- `decode_checks` (object): Checks on the official decode (NHTSA vPIC), which describes a VIN pattern, not this vehicle. `pattern` (VIN positions 1-8, 10, 11), `fields[]` with `field` (drive, engine_size, cylinders, powertrain, transmission, speeds, seats, gvwr_class), `original` (vPIC's text, never changed), `original_value`, `shown`, `shown_value`, `status` (`confirmed`, `corrected`, `doubtful`, `filled`, `unverified`, `unknown`), `basis` (evidence tier), `rule`, `note`, `evidence` (`test_vehicles[]` with `test_no`, `report_url`, `value`, `source`; `epa` with `lists_decoded_value`, `model_names`), `candidates[]` (each tier's value, for doubts) and `matching` (`checked_value`, `widened` = the matchers return the range, `official_value`). `precedence`: `owner` > `manufacturer_vin_record` > `mcp_vin_rule_fix` > `nhtsa_test_vehicle_pattern` > `vpic_decode` > `assumption`. A field an mcp.vin rule fix changed is `corrected` with basis `mcp_vin_rule_fix`, `original` = NHTSA's official value, and `evidence.rule_fix` (`changed`, `fixes` with reason and NHTSA report links); `sources.rule_fixes.status`: `used`, `none_for_vin` or `not_applied` (a live-API decode). `sources.manufacturer_record.status`: `used`, `not_checked` (the VIN page, drawn before the maker replies), `pending` (the maker's lookup was still answering; see `recall_status.pending`), `not_available`, `not_supported`. Corrected = the manufacturer's record of this VIN, two or more NHTSA test vehicles with the same pattern that agree, or one test vehicle plus EPA listing its value and not vPIC's. Doubtful = a source disagrees without settling it, EPA lists no such value or combination for the model year, vPIC says "2WD/4WD", or an impossible combination. Filled = vPIC blank; from a test vehicle or from EPA's only value for the model year. vPIC error rates measured on 2,454 NHTSA test vehicles: drive 0.8%, displacement 0.2%, cylinders 0.3%, electrification 0.3%, transmission 0.1-0.6%, speeds 3.4%, seats 4.8%, GVWR class 0.7%. MCP `decode_vin` returns a shorter form (per field status, official, checked, basis, rule, note, matching, up to two report links). +- `recall_status` (object): The manufacturer's VIN-specific recall repair status (see GET /api/vin/:vin/recall-status): `available`, `open_count`, `completed_count`, `recalls[]`, `source`, `verification_url`, `note`; `available: false` with `reason` when the maker gives none. The maker's lookup starts as soon as the VIN is decoded and the report waits up to 2 s for it (MCP `decode_vin`: 6 s). A maker that has not answered by then (Ford's lookup usually takes 10 s or more) gives `pending: true`, `available: false`, `reason: "lookup_in_progress"`, `open_count: null`, `completed_count: null`, `recalls: []`, `maker`, `waited_ms`, `note` and `status_url` (`/api/vin/{vin}/recall-status`). Pending means unknown, never "no open recalls". The lookup keeps running: GET `status_url` waits for that same lookup and returns the complete status, and the next report for the VIN (within 15 minutes) includes it. `decode_checks.sources.manufacturer_record.status` is `pending` meanwhile. - `recall_status.manufacturer_description` (object): Where the maker's VIN recall reply names the vehicle (Volkswagen, Audi, Land Rover, Jaguar, Subaru, Honda/Acura): `text` (raw), `reply_field`, `model_year`, `truncated` (Land Rover and Jaguar cut at 40 characters), `parsed` (only what the text states: `engine_size_l`, `cylinders`, `powertrain`, `transmission`, `drive`, `body`, `doors`, `trim`), `not_parsed`, `source {provider, url, retrieved_at}`. `available: false` with `reason` (`not_in_reply`, `not_supplied_by_manufacturer`) otherwise. No extra request: the same reply as the recall status. - `photos` (object): URLs for front, rear, side, interior, and detail vehicle photos - `raw_nhtsa` (object): Full 140+ field NHTSA decode: NHTSA's official values (NHTSA's own rules), even where an mcp.vin rule fix changed a value in `vehicle`, `engine` or `transmission` @@ -80,6 +82,10 @@ Example: curl https://mcp.vin/api/vin/1HGCM82633A004352 ``` +### GET /api/vin/:vin/recall-status — VIN Recall Repair Status + +The manufacturer's VIN-specific recall repair status alone (the `recall_status` of the full report), waiting for the maker's lookup. If a report for the VIN started that lookup (a report that returned `recall_status.pending`), this joins it rather than starting another. Successful answers are cached for 15 minutes; failures are not cached and return `available: false` with `reason: "upstream_unavailable"`. + ### GET /api/vin/:vin/validate — Quick Validation Local-only validation (no external API calls). Checks checksum, format, WMI decode, and model year. @@ -228,8 +234,9 @@ Decode a VIN and return a comprehensive vehicle report with specs, recalls, comp Parameters: - `vin` (string, required): 17-character Vehicle Identification Number - `transmission` (string, optional): `automatic` or `manual`, when the owner knows it and the VIN does not say. Applies to fuel economy only, and only when EPA lists the model with both; without it an automatic is assumed and marked (`fuel_economy.assumed`, `fuel_economy.alternatives`). +- `recall_wait` (string, optional): `full` waits for the manufacturer's VIN recall lookup (up to about 15 s). -Returns: Full JSON report with all data sources aggregated +Returns: Full JSON report with all data sources aggregated. `recall_status` is the manufacturer's VIN-specific recall status; a maker that has not answered within about 6 s gives `recall_status.pending: true` (unknown, not "no open recalls") with `next_step: {tool: "vin_recall_status", arguments: {vin}}`: that tool waits for the same lookup and returns the complete status. #### validate_vin Quickly validate a VIN without calling any external APIs. Checks checksum, format, WMI, and model year. @@ -330,6 +337,7 @@ The server uses in-memory LRU caching with TTL: - Recalls: 6 hours - Safety ratings: 24 hours - Fuel economy: 24 hours +- Manufacturer VIN recall status: 15 minutes (successful answers only); one lookup per VIN at a time, shared by every request that asks ## Articles diff --git a/public/research/research.js b/public/research/research.js index b0a77bf..4e4e4be 100644 --- a/public/research/research.js +++ b/public/research/research.js @@ -1,4 +1,4 @@ -import {VinClient} from '/client.mjs?v=2a80830879a9'; +import {VinClient} from '/client.mjs?v=d2b27f93e7db'; const api=new VinClient({baseUrl:location.origin}), $=s=>document.querySelector(s); const esc=s=>String(s??'Unknown').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); const money=n=>new Intl.NumberFormat('en-US',{style:'currency',currency:'USD',minimumFractionDigits:2,maximumFractionDigits:2}).format(n); diff --git a/tests/pending-recall-status.test.mjs b/tests/pending-recall-status.test.mjs index 2e4311a..ae1d0ca 100644 --- a/tests/pending-recall-status.test.mjs +++ b/tests/pending-recall-status.test.mjs @@ -4,6 +4,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import vm from 'node:vm'; import {readFileSync} from 'node:fs'; +import {VinClient} from '../public/client.mjs'; const pending = {vin: '1FTEX1EP4FFD06976', scope: 'vin', vin_specific: true, available: false, pending: true, reason: 'lookup_in_progress', maker: 'Ford', waited_ms: 2000, source: {provider: 'Ford Owner Support VIN Recalls', reference_url: 'https://www.ford.com/support/recalls-details/1FTEX1EP4FFD06976/'}, @@ -127,3 +128,11 @@ test('web report: a follow-up for a VIN no longer shown changes nothing', async assert.ok(!els.has('#recall-status-block'), 'nothing was redrawn'); assert.ok(!els.has('#decode-status')); }); + +test('VinClient.decode asks for the full wait only when told to', async () => { + const seen = []; + const client = new VinClient({baseUrl: 'http://localhost:3298', fetchImpl: async url => { seen.push(url); return new Response('{}'); }}); + await client.decode('1FTEX1EP4FFD06976'); + await client.decode('1FTEX1EP4FFD06976', {recallWait: 'full'}); + assert.deepEqual(seen, ['http://localhost:3298/api/vin/1FTEX1EP4FFD06976', 'http://localhost:3298/api/vin/1FTEX1EP4FFD06976?recall_wait=full']); +}); From c520758e3b02f6d247228ee8d4116458644d2b54 Mon Sep 17 00:00:00 2001 From: root Date: Wed, 18 Nov 2026 10:47:12 -0500 Subject: [PATCH 4/6] Reports stop waiting on NHTSA's complaint list too NHTSA's complaintsByVehicle is the next slowest part of a first report: measured from the web server on 2026-11-18, a 2020 Ford Escape took 17.3 s, a 2017 Honda CR-V 5.0 s and a 2003 Accord 6.4 s (1.4-2.0 MB). With the 10 s timeout the Escape's list always failed, so its report was never cached and every visit waited 10 s again. - modelYearComplaints: one request per make/model/year at a time, shared by reports and /api/vin/{vin}/complaints; successes cached 6 h; the request may run 30 s (COMPLAINTS_TIMEOUT_MS). - The report is assembled without waiting for it. If the list has not arrived within the caller's budget (2 s website/REST, 6 s MCP; compare waits), complaints is {pending: true, available: false, count: null, status_url: /api/vin/{vin}/complaints} - unknown, never zero. The complete report is built and cached when the list arrives. The VIN page (server-rendered) no longer waits for it either. - Website: "Loading NHTSA's owner complaints..." then fills the card and the car sheet row in place; printed while pending it says the list had not arrived. MCP: a note to call decode_vin again. Co-Authored-By: Claude Opus 5.5 --- lib/cache.mjs | 1 + lib/mcp/vehicle-tools.mjs | 4 +- lib/nhtsa.mjs | 7 +- lib/reports.mjs | 88 ++++++++++++++++--- public/app.js | 78 +++++++++++++---- public/car-sheet.js | 9 +- public/index.html | 4 +- server.mjs | 6 +- tests/fast-first-report.test.mjs | 123 +++++++++++++++++++++++++-- tests/mock-upstream.mjs | 4 +- tests/pending-recall-status.test.mjs | 48 +++++++++++ tests/slow-maker.test.mjs | 20 +++-- 12 files changed, 340 insertions(+), 52 deletions(-) diff --git a/lib/cache.mjs b/lib/cache.mjs index 26f1943..c4572ca 100644 --- a/lib/cache.mjs +++ b/lib/cache.mjs @@ -63,3 +63,4 @@ export const vinCache = new LRUCache(1000, 60 * 60 * 1000); // 1hr for full export const recallCache = new LRUCache(500, 6 * 60 * 60 * 1000); // 6hr for recalls (change less often) export const ratingCache = new LRUCache(500, 24 * 60 * 60 * 1000); // 24hr for safety ratings (static) export const fuelCache = new LRUCache(500, 24 * 60 * 60 * 1000); // 24hr for fuel economy (static) +export const complaintCache = new LRUCache(200, 6 * 60 * 60 * 1000); // 6hr for NHTSA complaints (1-2 MB for a common model) diff --git a/lib/mcp/vehicle-tools.mjs b/lib/mcp/vehicle-tools.mjs index d984dff..c763fee 100644 --- a/lib/mcp/vehicle-tools.mjs +++ b/lib/mcp/vehicle-tools.mjs @@ -6,12 +6,12 @@ import { applyOwnerDetails } from '../transmission-choice.mjs'; export function vehicleTools(add) { add('decode_vin', - 'Decode a VIN and return a vehicle report: specs, recalls (with manufacturer build-date ranges), a complaint summary with the most recent complaints, safety ratings, fuel economy, EPA test-vehicle data, parts content and origin (MY2020+), historical production and theft (MY1998-2012), and photo URLs. decode_checks checks the official decode field by field (drive, engine, electrification, transmission, speeds, seats, GVWR) against the manufacturer\'s description of this VIN, NHTSA test vehicles with the same VIN pattern and EPA\'s configurations: confirmed, corrected, doubtful or filled, with vPIC\'s original value kept. recall_status is the manufacturer\'s VIN-specific recall status; a maker that has not answered within about 6 s (Ford\'s lookup takes 10 s or more) gives recall_status.pending true: unknown, not "no open recalls"; call vin_recall_status with the VIN for the complete answer, or pass recall_wait "full".', + 'Decode a VIN and return a vehicle report: specs, recalls (with manufacturer build-date ranges), a complaint summary with the most recent complaints, safety ratings, fuel economy, EPA test-vehicle data, parts content and origin (MY2020+), historical production and theft (MY1998-2012), and photo URLs. decode_checks checks the official decode field by field (drive, engine, electrification, transmission, speeds, seats, GVWR) against the manufacturer\'s description of this VIN, NHTSA test vehicles with the same VIN pattern and EPA\'s configurations: confirmed, corrected, doubtful or filled, with vPIC\'s original value kept. recall_status is the manufacturer\'s VIN-specific recall status; a maker that has not answered within about 6 s (Ford\'s lookup takes 10 s or more) gives recall_status.pending true: unknown, not "no open recalls"; call vin_recall_status with the VIN for the complete answer, or pass recall_wait "full". NHTSA\'s complaint list for a common model can take 15 s or more: complaints.pending true is unknown, not zero; call decode_vin again in a minute (cached once it arrives).', { vin: z.string().describe('17-character Vehicle Identification Number'), transmission: z.optional(z.enum(['automatic', 'manual'])).describe('Transmission, when the owner knows it and the VIN does not say. Applies to fuel economy only when EPA lists the model with both; without it an automatic is assumed and marked (fuel_economy.assumed, alternatives).'), recall_wait: z.optional(z.enum(['full'])).describe('"full": wait for the manufacturer\'s VIN recall lookup (up to about 15 s) instead of returning recall_status.pending after about 6 s.') }, async ({ vin, transmission, recall_wait }) => { - const report = mcpReport(applyOwnerDetails(await fullReport(vin, { recallWaitMs: recall_wait === 'full' ? Infinity : RECALL_WAIT_MS.mcp }), { transmission }, { by: 'request' })); + const report = mcpReport(applyOwnerDetails(await fullReport(vin, { recallWaitMs: recall_wait === 'full' ? Infinity : RECALL_WAIT_MS.mcp, complaintsWaitMs: RECALL_WAIT_MS.mcp }), { transmission }, { by: 'request' })); return { content: [{ type: 'text', text: JSON.stringify(report, null, 2) }] }; } ); diff --git a/lib/nhtsa.mjs b/lib/nhtsa.mjs index 49a0197..1a21bd3 100644 --- a/lib/nhtsa.mjs +++ b/lib/nhtsa.mjs @@ -451,9 +451,12 @@ export async function getRelatedModelRecalls(make, model, year, exactRecalls = [ * @param {string} make * @param {string} model * @param {number|string} year + * @param {{timeoutMs?: number}} [options] NHTSA can take 5-17 s to send a common model's list (1-2 MB); + * reports ask through modelYearComplaints (lib/reports.mjs) with COMPLAINTS_TIMEOUT_MS. * @returns {object} { count, complaints, summary } */ -export async function getComplaints(make, model, year) { +export const COMPLAINTS_TIMEOUT_MS = 30_000; +export async function getComplaints(make, model, year, { timeoutMs = FETCH_TIMEOUT } = {}) { try { const params = new URLSearchParams({ make: String(make), @@ -461,7 +464,7 @@ export async function getComplaints(make, model, year) { modelYear: String(year), }); const url = `${COMPLAINTS_BASE}?${params}`; - const res = await fetch(url, { signal: timeoutSignal() }); + const res = await fetch(url, { signal: timeoutSignal(timeoutMs) }); if (!res.ok) { console.error(`[nhtsa] getComplaints HTTP ${res.status}`); diff --git a/lib/reports.mjs b/lib/reports.mjs index a4545e1..7d03ce1 100644 --- a/lib/reports.mjs +++ b/lib/reports.mjs @@ -1,9 +1,9 @@ /** Shared vehicle reports for REST, MCP and comparisons. */ import { validateVin, normalizeVin } from './validate.mjs'; -import { decodeVin as nhtsaDecode, getRecalls, getComplaints, getSafetyRatings, getRelatedModelRecalls } from './nhtsa.mjs'; +import { decodeVin as nhtsaDecode, getRecalls, getComplaints, getSafetyRatings, getRelatedModelRecalls, COMPLAINTS_TIMEOUT_MS } from './nhtsa.mjs'; import { getFuelEconomy } from './epa.mjs'; import { getPhotoUrls } from './photo.mjs'; -import { vinCache, recallCache, ratingCache, fuelCache } from './cache.mjs'; +import { vinCache, recallCache, ratingCache, fuelCache, complaintCache } from './cache.mjs'; import { vinRecallStatus as defaultRecallLookup, recallLookupInfo } from './recall-status.mjs'; import { InputError } from './research.mjs'; import { withBuildDates } from './recall-build-dates.mjs'; @@ -40,6 +40,37 @@ export async function modelYearRecalls(make, model, year) { return withBuildDates(withRelatedRecalls(recalls, related), make, model, year); } +/** + * NHTSA's owner complaints for a make, model and year: one request per model at a time, shared by every caller + * (reports, /api/vin/{vin}/complaints), and successful answers cached 6 hours. NHTSA can take 5-17 s to send a + * common model's list (1-2 MB of JSON; a 2020 Ford Escape took 17 s from the web server on 2026-11-18), so the + * request may run COMPLAINTS_TIMEOUT_MS (30 s); reports wait for it only up to their budget (fullReport). Never rejects. + */ +const complaintLookups = new Map(); +export function modelYearComplaints(make, model, year) { + const key = `${make}|${model}|${year}`; + if (complaintCache.has(key)) return Promise.resolve(complaintCache.get(key)); + if (complaintLookups.has(key)) return complaintLookups.get(key); + const lookup = Promise.resolve() + .then(() => getComplaints(make, model, year, { timeoutMs: COMPLAINTS_TIMEOUT_MS })) + .catch(err => { console.error('[reports] complaint lookup failed:', err?.message || err); return null; }) + .then(c => c || { available: false, count: null, complaints: [], summary: null, error: 'Complaint lookup unavailable' }) + .then(c => { if (c.available !== false) complaintCache.set(key, c); return c; }) + .finally(() => complaintLookups.delete(key)); + complaintLookups.set(key, lookup); + return lookup; +} + +/** + * complaints while NHTSA's list is still arriving: unknown, never zero (count null, available false), with where + * to get it. + */ +export function pendingComplaints(vin) { + return { available: false, pending: true, reason: 'lookup_in_progress', scope: 'make_model_year', count: null, complaints: [], summary: null, + status_url: `/api/vin/${vin}/complaints`, + note: 'NHTSA had not sent its owner-complaint list for this make, model and year when this report was sent (a common model\'s list is 1-2 MB and can take 15 s or more), so the count is unknown here; it is not zero. The request keeps running: GET status_url waits for it, and the next report includes it.' }; +} + /** Attach related-label campaigns without changing the exact-label count. */ export function withRelatedRecalls(recalls, related) { const flatOnly = related?.flat_file_only?.count || 0; @@ -163,15 +194,18 @@ function reportWithStatus(base, status, owner) { * RECALL_WAIT_MS; past it, recall_status is {pending: true} (pendingRecallStatus) and the lookup finishes in the * background. */ -export async function fullReport(vin, {owner = null, recallWaitMs = RECALL_WAIT_MS.report} = {}) { +export async function fullReport(vin, {owner = null, recallWaitMs = RECALL_WAIT_MS.report, complaintsWaitMs = RECALL_WAIT_MS.report} = {}) { const entry = reportEntry(vin); // The maker's lookup starts as soon as the decode names the make, in parallel with NHTSA's calls. const early = entry.decoded.then(d => d?.vehicle ? { make: d.vehicle.make, ...startRecallLookup(entry.vin, d.vehicle.make) } : null); - const report = await entry.report; - if (!report.vehicle) return report; + const base = await entry.report; + if (!base.vehicle) return base; let lookup = await early; - if (!lookup || lookup.make !== report.vehicle.make) lookup = { make: report.vehicle.make, ...startRecallLookup(report.vin, report.vehicle.make) }; + if (!lookup || lookup.make !== base.vehicle.make) lookup = { make: base.vehicle.make, ...startRecallLookup(base.vin, base.vehicle.make) }; const status = await within(lookup.promise, lookup.at + recallWaitMs - Date.now()); + // Both waits run against deadlines counted from each request's start, so waiting for one after the other takes + // as long as the later deadline; complaints that arrived while the recall status was awaited are included. + const report = await withComplaints(base, complaintsWaitMs); if (status === WAITED) { const pending = pendingRecallStatus(report.vin, report.vehicle.make, recallWaitMs); return { ...report, recall_status: pending, decode_checks: pendingDecodeChecks(report.decode_checks, pending.maker) }; @@ -179,8 +213,22 @@ export async function fullReport(vin, {owner = null, recallWaitMs = RECALL_WAIT_ return reportWithStatus(report, status, owner); } +// A report assembled before NHTSA's complaints arrived (complaints pending) → {at, promise}: the request's start +// and the complete report it becomes (the same object for every caller; null if it could not be built). +const completions = new WeakMap(); +/** `report` with NHTSA's complaints if they arrive within `ms` of their request's start; else as given (pending). */ +async function withComplaints(report, ms) { + const completion = completions.get(report); + if (!completion) return report; + const complete = await within(completion.promise, completion.at + ms - Date.now()); + return complete === WAITED || !complete ? report : complete; +} + const pendingReports = new Map(); -/** The report without manufacturer VIN recall lookups; shares the cache with fullReport. */ +/** + * The report without manufacturer VIN recall lookups; shares the cache with fullReport. It does not wait for NHTSA's + * complaints: when they had not arrived with the rest, `complaints` is pending (pendingComplaints). + */ export function baseReport(vin) { return reportEntry(vin).report; } /** * One assembly per VIN at a time, shared by concurrent callers: `report`, and `decoded`, which resolves with @@ -221,9 +269,11 @@ async function assembleReport(vin, named = () => {}) { const raw = used.raw || {}; const fuelKey = `${cacheKey}|${JSON.stringify([used.engine, used.transmission, used.vehicle, used.dimensions?.gvwr, raw.Series, raw.Series2, raw.Trim2, raw.Doors, raw.BatteryKWh, raw.BatteryKWh_to, raw.FuelTypeSecondary])}`; - const [recalls, complaints, ratings, fuel, testVehicle] = await Promise.all([ + // NHTSA's complaints can take much longer than the rest (modelYearComplaints): the report is assembled without + // waiting for them, and completes when they arrive (completions). + const complaintsAt = Date.now(), complaintsTask = modelYearComplaints(make, model, year); + const [recalls, ratings, fuel, testVehicle] = await Promise.all([ modelYearRecalls(make, model, year), - getComplaints(make, model, year), ratingCache.has(cacheKey) ? ratingCache.get(cacheKey) : getSafetyRatings(make, model, year).then(r => { if (r) ratingCache.set(cacheKey, r); return r; }), fuelCache.has(fuelKey) ? fuelCache.get(fuelKey) : getFuelEconomy(year, make, model, used).then(r => { if (r?.available || (r?.match === 'multiple_configurations' && !r.incomplete)) fuelCache.set(fuelKey, r); return r; }), // Local index of NHTSA's crash-test vehicles: closest match, never this VIN's own values (lib/tire-placards.mjs). @@ -239,7 +289,7 @@ async function assembleReport(vin, named = () => {}) { vehicle: decoded.vehicle, engine: decoded.engine, transmission: decoded.transmission, dimensions: decoded.dimensions, plant: decoded.plant, safety_equipment: decoded.safety, recalls: recallBlock || { count: 0, recalls: [] }, - complaints: complaints || { count: 0, complaints: [], summary: { crashes: 0, fires: 0, injuries: 0, deaths: 0 } }, + complaints: null, // set below (complete) or pending safety_ratings: ratings || { rated: false }, fuel_economy: fuel || { available: false }, tire_placard: testVehicle.tire_placard, @@ -255,8 +305,18 @@ async function assembleReport(vin, named = () => {}) { }; const transientFuelFailure = ['upstream_error', 'invalid_response'].includes(fuel?.reason) || fuel?.incomplete === true; - if (recalls?.available !== false && complaints?.available !== false && !transientFuelFailure) vinCache.set(vin, report); - return report; + const complete = complaints => { + const done = { ...report, complaints: complaints || { count: 0, complaints: [], summary: { crashes: 0, fires: 0, injuries: 0, deaths: 0 } } }; + if (recalls?.available !== false && complaints?.available !== false && !transientFuelFailure) vinCache.set(vin, done); + return done; + }; + const arrived = await within(complaintsTask, 0); + if (arrived !== WAITED) return complete(arrived); + // Still arriving: a report with complaints pending now; the complete one is built (and cached) when they arrive. + const partial = { ...report, complaints: pendingComplaints(vin) }; + completions.set(partial, { at: complaintsAt, promise: complaintsTask.then(complete).catch(err => { + console.error('[reports] completing report with complaints failed:', err?.message || err); return null; }) }); + return partial; } /** Where the specifications came from: the local decoder (vPIC release, rule fixes) or NHTSA's live API. */ @@ -301,6 +361,8 @@ function compactComplaints(complaints) { ...c, summary: c.summary && c.summary.length > MCP_SUMMARY_CHARS ? c.summary.slice(0, MCP_SUMMARY_CHARS) + '...' : c.summary, })); + if (complaints?.pending) return { ...complaints, complaints: undefined, recent: [], top_components: [], + note: 'NHTSA had not sent its owner-complaint list for this make, model and year in time (a common model\'s list can take 15 s or more), so the count is unknown here, not zero. The request keeps running; call decode_vin again in a minute for the list (cached once it arrives).' }; return { ...complaints, complaints: undefined, @@ -355,7 +417,7 @@ export async function compareVehicles(vins) { if (new Set(normalized).size !== normalized.length) throw new InputError('Choose distinct VINs'); const results=await Promise.all(normalized.map(async vin=>{ // A comparison waits for every maker's lookup (no pending status): it is printed and exported as one table. - try {return {vin,report:mcpReport(await fullReport(vin,{recallWaitMs:Infinity}))};} + try {return {vin,report:mcpReport(await fullReport(vin,{recallWaitMs:Infinity,complaintsWaitMs:Infinity}))};} catch {return {vin,error:'Report unavailable; retry later'};} })); return {results,note:'Recall and complaint counts are model-year data, not a ranking of individual vehicle safety. Missing data is not zero.'}; diff --git a/public/app.js b/public/app.js index 9a07883..ae79d1a 100644 --- a/public/app.js +++ b/public/app.js @@ -106,9 +106,8 @@ form.addEventListener('submit', async (e) => { // Compact hero hero.classList.add('compact'); results.hidden = false; - const pendingMaker = report.recall_status?.pending ? (report.recall_status.maker || 'The manufacturer') : null; - $('#decode-status').textContent = pendingMaker ? `Report ready. ${pendingMaker}’s VIN recall status is still loading; it fills in by itself.` : 'Report ready. Review source coverage in each section.'; - if (pendingMaker) followRecallStatus(report); + $('#decode-status').textContent = readyMessage(report); + followPending(report); if (!location.hash || location.hash === '#report') { history.replaceState(null, '', '/' + encodeURIComponent(vin) + location.search + '#report'); results.scrollIntoView({ behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'instant' : 'smooth', block: 'start' }); @@ -407,6 +406,55 @@ function recallStatusHtml(r) { return `

    VIN-specific recall repair status

    ${content}

    Verify this VIN with the official source

    `; } +// ── Parts that arrive after the report ── +// The server does not hold a report back for its two slow sources (lib/reports.mjs): the maker's VIN recall status +// (recall_status.pending) and NHTSA's complaint list (complaints.pending). The page asks for each again and fills it +// in place. +function readyMessage(report) { + const later = []; + if (report.recall_status?.pending) later.push(`${report.recall_status.maker || 'The manufacturer'}’s VIN recall status`); + if (report.complaints?.pending) later.push('NHTSA’s complaint list'); + if (!later.length) return 'Report ready. Review source coverage in each section.'; + return later.length > 1 ? `Report ready. ${later.join(' and ')} are still loading; they fill in by themselves.` : `Report ready. ${later[0]} is still loading; it fills in by itself.`; +} +function followPending(report) { + if (report.recall_status?.pending) followRecallStatus(report); + if (report.complaints?.pending) followComplaints(report); +} +// Fetch `url` as JSON until `done(data)` accepts it, at most twice (3 s apart), while `live()` holds; null if not. +async function fetchFollowUp(url, done, live) { + for (let attempt = 0; attempt < 2; attempt++) { + if (attempt) await new Promise(resolve => setTimeout(resolve, 3000)); + if (!live()) return null; + try { + const res = await apiFetch(url); + const data = res.ok ? await res.json() : null; + if (done(data)) return data; + } catch { /* tried again once, then shown as not loaded */ } + } + return null; +} + +// NHTSA's complaint list: /api/vin/{vin}/complaints joins the request the report started (cached once it arrives). +let complaintsFollow = 0; +async function followComplaints(report) { + const token = ++complaintsFollow, vin = report.vin; + const live = () => token === complaintsFollow && currentReport?.vin === vin && currentReport.complaints?.pending === true; + let next = await fetchFollowUp(`/api/vin/${encodeURIComponent(vin)}/complaints`, data => data && typeof data.available === 'boolean' && !data.pending, live); + if (!live()) return; + if (!next) next = {...currentReport.complaints, pending: false, available: false, reason: 'lookup_not_loaded', + note: 'NHTSA’s complaint list could not be loaded here. The count is unknown; reload the report.'}; + currentReport = {...currentReport, complaints: next}; + const view = window.OwnerDetails?.applyToReport(currentReport) || currentReport; + const around = window.KeepState ? KeepState.around : (roots, fn) => fn(); + around([$('#complaints-body')], () => { + renderComplaints(view); + window.CarSheet?.update ? CarSheet.update(view) : window.CarSheet?.render(view); + window.VinWorkspace?.reportUpdated(view); + }, [$('#sheet-body'), $('#sheet-foot')]); + $('#decode-status').textContent = next.available ? 'NHTSA’s owner complaints have loaded.' : 'NHTSA’s owner complaints could not be loaded; see the complaints section.'; +} + // ── The maker's VIN recall status, when it answers after the report ── // A report can arrive with recall_status.pending (lib/reports.mjs: the maker's lookup was still answering). The page // asks again with ?recall_wait=full, which waits for that same lookup, and fills in only what it changes: the status @@ -419,16 +467,7 @@ async function followRecallStatus(report) { // Still wanted while this VIN's report is shown with the status pending (typing the same VIN again keeps it). const token = ++recallFollow, vin = report.vin; const live = () => token === recallFollow && currentReport?.vin === vin && currentReport.recall_status?.pending === true; - let next = null; - for (let attempt = 0; attempt < 2 && !next; attempt++) { - if (attempt) await new Promise(resolve => setTimeout(resolve, 3000)); - if (!live()) return; - try { - const res = await apiFetch(`/api/vin/${encodeURIComponent(vin)}?recall_wait=full`); - const data = res.ok ? await res.json() : null; - if (data?.vehicle && data.recall_status && !data.recall_status.pending) next = data; - } catch { /* tried again once, then shown as not loaded */ } - } + let next = await fetchFollowUp(`/api/vin/${encodeURIComponent(vin)}?recall_wait=full`, data => data?.vehicle && data.recall_status && !data.recall_status.pending, live); if (!live()) return; if (!next) { const s = currentReport.recall_status || {}; @@ -565,10 +604,19 @@ function renderComplaints(r) { const count = c?.count || 0; const badge = $('#complaint-count'); + if (c?.pending) { + // Still arriving (followComplaints fills it in): unknown, never zero; on paper it was not loaded. + badge.textContent = '…'; + badge.className = 'count-badge'; + $('#complaints-body').innerHTML = '

    Loading NHTSA’s owner complaints… The list for a common model is large and can take 15 seconds or more; this card fills in by itself.

    Not loaded: NHTSA’s complaint list had not arrived when this page was printed.

    '; + return; + } if (c?.available === false) { badge.textContent = '?'; badge.className = 'count-badge'; - $('#complaints-body').innerHTML = '
    Complaint lookup is temporarily unavailable. Please try again.
    '; + $('#complaints-body').innerHTML = c.reason === 'lookup_not_loaded' + ? '
    NHTSA’s complaint list could not be loaded here. The count is unknown; reload the report.
    ' + : '
    Complaint lookup is temporarily unavailable. Please try again.
    '; return; } if (count === 0) { @@ -1177,7 +1225,7 @@ if (typeof navigator !== 'undefined' && navigator.modelContext) { updateSaveButton(vin); hero.classList.add('compact'); results.hidden = false; - if (report.recall_status?.pending) followRecallStatus(report); + followPending(report); } return report; }, diff --git a/public/car-sheet.js b/public/car-sheet.js index 076b038..8a9df3c 100644 --- a/public/car-sheet.js +++ b/public/car-sheet.js @@ -478,12 +478,17 @@ const CarSheet = (() => { const related = rec && rec.related_models && rec.related_models.available && rec.related_models.count > 0 ? ` (plus ${fmt(rec.related_models.count)} filed under related model names; they may not apply)` : ''; const otherName = rec && rec.count === 0 && !related && (rec.related_campaigns_found === null || (rec.related_models && rec.related_models.decoded_name_in_recall_data === false)) ? ' (NHTSA may file campaigns for this vehicle under another model name)' : ''; - const complaints = !c || c.available === false || typeof c.count !== 'number' ? 'Unknown (lookup unavailable)' : `${fmt(c.count)} for this model year`; + // Still arriving from NHTSA (complaints.pending): on screen it fills in by itself; on paper it was not loaded. + const complaints = c && c.pending + ? `Loading from NHTSA…Unknown: NHTSA's list had not arrived when this sheet was printed.` + : esc(!c || c.available === false || typeof c.count !== 'number' + ? (c && c.reason === 'lookup_not_loaded' ? 'Unknown (could not be loaded here; reload the report)' : 'Unknown (lookup unavailable)') + : `${fmt(c.count)} for this model year`); const stars = rat.rated && num(rat.overall) ? `${rat.overall} of 5 stars overall` : rat.rated ? 'Rated, but no overall score published' : 'No NHTSA rating found'; const rows = [ rowHtml('This VIN’s recall status', status), rowHtml('Model-year recall campaigns', `${esc(campaigns + related + otherName)}NHTSA campaigns for the make, model and year. Not this car’s repair status.`), - rowHtml('Owner complaints to NHTSA', `${esc(complaints)}Reports, not confirmed defects.`), + rowHtml('Owner complaints to NHTSA', `${complaints}Reports, not confirmed defects.`), row('NHTSA crash rating', stars), ]; return section('recalls', 'Recalls and safety', list(rows)); diff --git a/public/index.html b/public/index.html index 54d812c..c73c0eb 100644 --- a/public/index.html +++ b/public/index.html @@ -333,7 +333,7 @@

    Claude Code stdio

    Complete MCP tool directory

    Generated from the server’s registered tools; the same list is served as JSON at /api/tools. Public research is available without an account; saved vehicles and preferences require authentication.

    Vehicle reports · 4 tools

    -
    decode_vin (vin, transmission, recall_wait)

    Decode a VIN and return a vehicle report: specs, recalls (with manufacturer build-date ranges), a complaint summary with the most recent complaints, safety ratings, fuel economy, EPA test-vehicle data, parts content and origin (MY2020+), historical production and theft (MY1998-2012), and photo URLs. decode_checks checks the official decode field by field (drive, engine, electrification, transmission, speeds, seats, GVWR) against the manufacturer's description of this VIN, NHTSA test vehicles with the same VIN pattern and EPA's configurations: confirmed, corrected, doubtful or filled, with vPIC's original value kept. recall_status is the manufacturer's VIN-specific recall status; a maker that has not answered within about 6 s (Ford's lookup takes 10 s or more) gives recall_status.pending true: unknown, not "no open recalls"; call vin_recall_status with the VIN for the complete answer, or pass recall_wait "full".

    +
    decode_vin (vin, transmission, recall_wait)

    Decode a VIN and return a vehicle report: specs, recalls (with manufacturer build-date ranges), a complaint summary with the most recent complaints, safety ratings, fuel economy, EPA test-vehicle data, parts content and origin (MY2020+), historical production and theft (MY1998-2012), and photo URLs. decode_checks checks the official decode field by field (drive, engine, electrification, transmission, speeds, seats, GVWR) against the manufacturer's description of this VIN, NHTSA test vehicles with the same VIN pattern and EPA's configurations: confirmed, corrected, doubtful or filled, with vPIC's original value kept. recall_status is the manufacturer's VIN-specific recall status; a maker that has not answered within about 6 s (Ford's lookup takes 10 s or more) gives recall_status.pending true: unknown, not "no open recalls"; call vin_recall_status with the VIN for the complete answer, or pass recall_wait "full". NHTSA's complaint list for a common model can take 15 s or more: complaints.pending true is unknown, not zero; call decode_vin again in a minute (cached once it arrives).

    validate_vin (vin)

    Quickly validate a VIN without calling any external APIs.

    lookup_recalls (vin, make, model, year)

    Look up recalls for a vehicle. Provide either a VIN or make/model/year.

    batch_decode (vins)

    Decode multiple VINs at once (up to 50).

    @@ -442,4 +442,4 @@
    -
    +
    diff --git a/server.mjs b/server.mjs index 1d091d5..8f3c9ff 100644 --- a/server.mjs +++ b/server.mjs @@ -6,7 +6,7 @@ import { fileURLToPath } from 'node:url'; import path from 'node:path'; import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; import { validateVin, normalizeVin } from './lib/validate.mjs'; -import { decodeVin as nhtsaDecode, batchDecode, getComplaints, getSafetyRatings } from './lib/nhtsa.mjs'; +import { decodeVin as nhtsaDecode, batchDecode, getSafetyRatings } from './lib/nhtsa.mjs'; import { getFuelEconomy } from './lib/epa.mjs'; import { getPhotoUrl } from './lib/photo.mjs'; import { vinCache } from './lib/cache.mjs'; @@ -20,7 +20,7 @@ import { rateBenchmarks } from './lib/rate-benchmarks.mjs'; import { scenario } from './lib/scenario.mjs'; import { communications } from './lib/communications.mjs'; import { capabilities } from './lib/capabilities.mjs'; -import { fullReport, baseReport, restReport, compareVehicles, modelYearRecalls, vinRecallStatusFor, RECALL_WAIT_MS } from './lib/reports.mjs'; +import { fullReport, baseReport, restReport, compareVehicles, modelYearRecalls, modelYearComplaints, vinRecallStatusFor, RECALL_WAIT_MS } from './lib/reports.mjs'; import { normalizeTransmission, applyOwnerDetails } from './lib/transmission-choice.mjs'; import { validateOwnerDetails, parseOwnerDetails, serializeOwnerDetails, OwnerDetailsError } from './lib/owner-details.mjs'; import { renderVinPage, renderUnknownVinPage } from './lib/vin-page.mjs'; @@ -517,7 +517,7 @@ button{padding:.75rem 2rem;border:none;border-radius:10px;font-size:1rem;font-we const decoded = await nhtsaDecode(normalizeVin(req.params.vin)); if (!decoded) return res.status(400).json({ error: 'Could not decode VIN' }); const { make, model, year } = decoded.vehicle; - res.json(await getComplaints(make, model, year) || { count: 0, complaints: [], summary: {} }); + res.json(await modelYearComplaints(make, model, year)); // joins a report's running request } catch (err) { safeError(res, err); } }); diff --git a/tests/fast-first-report.test.mjs b/tests/fast-first-report.test.mjs index 8af4a8e..8cfa328 100644 --- a/tests/fast-first-report.test.mjs +++ b/tests/fast-first-report.test.mjs @@ -1,11 +1,12 @@ -// A first-time report must not wait on a slow manufacturer recall lookup (lib/reports.mjs RECALL_WAIT_MS). -// The maker's lookup is a stub request passed to createRecallStatusLookup: no live maker request is made. +// A first-time report must not wait on a slow manufacturer recall lookup or on NHTSA's complaint list +// (lib/reports.mjs RECALL_WAIT_MS). The maker's lookup is a stub request passed to createRecallStatusLookup and +// NHTSA is a stubbed fetch: no live request is made. import test from 'node:test'; import assert from 'node:assert/strict'; -import { fullReport, mcpReport, useRecallStatusLookup, vinRecallStatusFor, pendingRecallStatus, RECALL_WAIT_MS } from '../lib/reports.mjs'; +import { fullReport, baseReport, mcpReport, useRecallStatusLookup, vinRecallStatusFor, pendingRecallStatus, modelYearComplaints, RECALL_WAIT_MS } from '../lib/reports.mjs'; import { createRecallStatusLookup, recallLookupInfo } from '../lib/recall-status.mjs'; import { vehicleTools } from '../lib/mcp/vehicle-tools.mjs'; -import { vinCache, recallCache, ratingCache, fuelCache } from '../lib/cache.mjs'; +import { vinCache, recallCache, ratingCache, fuelCache, complaintCache } from '../lib/cache.mjs'; import { validateVin } from '../lib/validate.mjs'; import { fordPage, fordState } from './manufacturer-fixtures.mjs'; @@ -55,9 +56,9 @@ function slowFord({delay = null, fail = false} = {}) { const settle = () => new Promise(resolve => setTimeout(resolve, 20)); // let catch handlers and unhandledRejection run function setup(t, lookup) { - [vinCache, recallCache, ratingCache, fuelCache].forEach(c => c.clear()); + [vinCache, recallCache, ratingCache, fuelCache, complaintCache].forEach(c => c.clear()); const restoreFetch = stubNhtsa(), previous = useRecallStatusLookup(lookup); - t.after(() => { restoreFetch(); useRecallStatusLookup(previous); [vinCache, recallCache, ratingCache, fuelCache].forEach(c => c.clear()); }); + t.after(() => { restoreFetch(); useRecallStatusLookup(previous); [vinCache, recallCache, ratingCache, fuelCache, complaintCache].forEach(c => c.clear()); }); } test('the website and REST budget is 2 s and MCP\'s 6 s, counted from the lookup start', () => { @@ -208,3 +209,113 @@ test('MCP decode_vin waits longer (6 s) than the website, offers recall_wait "fu assert.match(pending.recall_status.note, /after 6\.0 s/); assert.equal(pending.decode_checks.sources.manufacturer_record, 'pending'); }); + +// ---- NHTSA's complaint list (a common model's takes 5-17 s) ---- + +/** NHTSA's complaints answer when the test calls release() (or fail when `fail`); everything else at once. */ +function gatedComplaints(t, {fail = false} = {}) { + const calls = []; + let open; + const gate = new Promise(resolve => { open = resolve; }); + const before = globalThis.fetch; + globalThis.fetch = async (url, opts) => { + if (!String(url).includes('complaintsByVehicle')) return before(url, opts); + calls.push(String(url)); + await gate; + if (fail) throw new Error('The operation was aborted due to timeout'); + return Response.json({results: [ + {odiNumber: 11000001, dateComplaintFiled: '03/02/2024', components: 'ENGINE', summary: 'Stalled', crash: 'NO', fire: 'NO', numberOfInjuries: 0, numberOfDeaths: 0}, + {odiNumber: 11000002, dateComplaintFiled: '04/05/2024', components: 'BRAKES', summary: 'Long stop', crash: 'YES', fire: 'NO', numberOfInjuries: 1, numberOfDeaths: 0}]}); + }; + // A request still held at the end is let go (and settles) before the next test clears the caches. + t.after(async () => { open(); await new Promise(resolve => setTimeout(resolve, 20)); globalThis.fetch = before; }); + return {calls, release: () => open()}; +} + +test('slow NHTSA complaints: the report answers with complaints pending (unknown, not zero); the next report has them', async t => { + const ford = slowFord({delay: 0}); + setup(t, ford.lookup); + const nhtsa = gatedComplaints(t); + const vin = nextFordVin(); + const first = await fullReport(vin, {complaintsWaitMs: 100}); + const c = first.complaints; + assert.deepEqual([c.pending, c.available, c.reason, c.count, c.summary], [true, false, 'lookup_in_progress', null, null]); + assert.deepEqual(c.complaints, []); + assert.equal(c.status_url, `/api/vin/${vin}/complaints`); + assert.match(c.note, /it is not zero/); + assert.equal(first.recall_status.available, true, 'the rest of the report is complete'); + assert.equal(vinCache.get(vin), undefined, 'a report without its complaints is not cached'); + // The server-rendered VIN page (baseReport) does not wait for the complaints either. + const page = await baseReport(vin); + assert.equal(page.complaints.pending, true); + // The request keeps running; /api/vin/{vin}/complaints (modelYearComplaints) joins it. + const joined = modelYearComplaints('FORD', 'F-150', '2015'); + nhtsa.release(); + const list = await joined; + assert.equal(list.count, 2); + assert.equal(nhtsa.calls.length, 1, 'one request to NHTSA for every caller'); + await new Promise(resolve => setTimeout(resolve, 20)); + const cached = vinCache.get(vin); + assert.equal(cached?.complaints, list, 'the complete report is cached once the complaints arrive'); + const second = await fullReport(vin, {complaintsWaitMs: 0}); + assert.equal(second.complaints.count, 2); + assert.equal(second.complaints.summary.crashes, 1); + assert.equal(second.complaints.pending, undefined); + assert.equal(nhtsa.calls.length, 1); + assert.equal(Object.keys(second).indexOf('complaints'), Object.keys(second).indexOf('recalls') + 1, 'the block keeps its place in the report'); +}); + +test('complaints that arrive within the budget are in the report; a longer recall wait picks up later ones', async t => { + const ford = slowFord({delay: 0}); + setup(t, ford.lookup); + const nhtsa = gatedComplaints(t); + const vin = nextFordVin(); + setTimeout(() => nhtsa.release(), 150); + const r = await fullReport(vin, {complaintsWaitMs: 2000}); + assert.equal(r.complaints.available, true); + assert.equal(r.complaints.count, 2); + // Waiting past the complaints budget for the recall status includes complaints that arrived meanwhile. + [vinCache, complaintCache].forEach(c => c.clear()); + const late = gatedComplaints(t), slow = slowFord(); + useRecallStatusLookup(slow.lookup); + const report = fullReport(nextFordVin(), {recallWaitMs: Infinity, complaintsWaitMs: 0}); + await slow.requested; late.release(); await new Promise(resolve => setTimeout(resolve, 20)); slow.release(); + const both = await report; + assert.equal(both.recall_status.available, true); + assert.equal(both.complaints.count, 2); +}); + +test('a complaint request that fails in the background is contained and not cached; the next report asks again', async t => { + const ford = slowFord({delay: 0}); + setup(t, ford.lookup); + const unhandled = []; + const onUnhandled = err => unhandled.push(err); + process.on('unhandledRejection', onUnhandled); + t.after(() => process.off('unhandledRejection', onUnhandled)); + const nhtsa = gatedComplaints(t, {fail: true}); + const vin = nextFordVin(); + const first = await fullReport(vin, {complaintsWaitMs: 20}); + assert.equal(first.complaints.pending, true); + nhtsa.release(); + await new Promise(resolve => setTimeout(resolve, 30)); + assert.deepEqual(unhandled, []); + assert.equal(vinCache.get(vin), undefined); + const second = await fullReport(vin, {complaintsWaitMs: Infinity}); + assert.equal(second.complaints.available, false); + assert.equal(second.complaints.pending, undefined); + assert.equal(second.complaints.count, null); + assert.equal(nhtsa.calls.length, 2, 'a failure is not cached'); +}); + +test('MCP: pending complaints say unknown, not zero, and how to get them', async t => { + const ford = slowFord({delay: 0}); + setup(t, ford.lookup); + gatedComplaints(t); + const r = mcpReport(await fullReport(nextFordVin(), {complaintsWaitMs: 10})); + assert.equal(r.complaints.pending, true); + assert.equal(r.complaints.count, null); + assert.deepEqual(r.complaints.recent, []); + assert.equal(r.complaints.complaints, undefined); + assert.match(r.complaints.note, /unknown here, not zero/); + assert.match(r.complaints.note, /call decode_vin again/); +}); diff --git a/tests/mock-upstream.mjs b/tests/mock-upstream.mjs index d84a93b..0235f37 100644 --- a/tests/mock-upstream.mjs +++ b/tests/mock-upstream.mjs @@ -7,6 +7,8 @@ import {EventEmitter} from 'node:events'; const nativeGet=https.get; // MOCK_FORD_DELAY_MS: Ford's page answers after that long (its CDN holds real requests ~9-10 s; tests/slow-maker.test.mjs). const fordDelay=Number(process.env.MOCK_FORD_DELAY_MS)||0; +// MOCK_COMPLAINTS_DELAY_MS: NHTSA's complaint list answers after that long (5-17 s for a common model live). +const complaintsDelay=Number(process.env.MOCK_COMPLAINTS_DELAY_MS)||0; https.get=(url,opts,callback)=>{ if(String(url)==='https://www.nissanusa.com/owners/recalls-vin.html'){ const response=Readable.from([Buffer.from(nissanPage)]);response.statusCode=200;queueMicrotask(()=>callback(response));return new EventEmitter(); @@ -54,7 +56,7 @@ globalThis.fetch=async (input,opts)=>{ } if(u.includes('api.nhtsa.gov/recalls'))return json({results:[]}); if(u.includes('api.nhtsa.gov/products/vehicle/models'))return json({results:[]}); - if(u.includes('api.nhtsa.gov/complaints'))return json({results:[]}); + if(u.includes('api.nhtsa.gov/complaints')){if(complaintsDelay)await new Promise(r=>setTimeout(r,complaintsDelay));return json({results:[]});} if(u.includes('api.nhtsa.gov/SafetyRatings'))return json({Results:[]}); if(u.includes('fueleconomy.gov')){ const url=new URL(u),model=url.searchParams.get('model'); diff --git a/tests/pending-recall-status.test.mjs b/tests/pending-recall-status.test.mjs index ae1d0ca..ec4d5e8 100644 --- a/tests/pending-recall-status.test.mjs +++ b/tests/pending-recall-status.test.mjs @@ -136,3 +136,51 @@ test('VinClient.decode asks for the full wait only when told to', async () => { await client.decode('1FTEX1EP4FFD06976', {recallWait: 'full'}); assert.deepEqual(seen, ['http://localhost:3298/api/vin/1FTEX1EP4FFD06976', 'http://localhost:3298/api/vin/1FTEX1EP4FFD06976?recall_wait=full']); }); + +// ---- NHTSA's complaint list arriving after the report (complaints.pending) ---- +const pendingComplaints = {available: false, pending: true, reason: 'lookup_in_progress', scope: 'make_model_year', count: null, complaints: [], summary: null, + status_url: '/api/vin/1FTEX1EP4FFD06976/complaints', note: 'not zero'}; +const complaintList = {available: true, scope: 'make_model_year', count: 2, summary: {crashes: 1, fires: 0, injuries: 1, deaths: 0}, + complaints: [{odi_number: '1', date_complaint_filed: '03/02/2024', component: 'ENGINE', summary: 'Stalled'}, {odi_number: '2', date_complaint_filed: '04/05/2024', component: 'BRAKES', summary: 'Long stop', crash: true}]}; + +test('car sheet and complaints card: pending complaints are "loading" on screen and "not loaded" on paper, never zero', () => { + const {sheet} = loadSheet(); + const row = html => html.match(/Owner complaints to NHTSA<\/dt>
    (.*?)<\/dd>/)[1]; + const pendingRow = row(sheet.html(report(complete, {complaints: pendingComplaints})).body); + assert.match(screen(pendingRow), /^Loading from NHTSA…/); + assert.match(paper(pendingRow), /^Unknown: NHTSA's list had not arrived when this sheet was printed\./); + assert.doesNotMatch(paper(pendingRow), /\b0\b|Loading/); + assert.match(row(sheet.html(report(complete, {complaints: complaintList})).body), /^2 for this model year/); + assert.match(row(sheet.html(report(complete, {complaints: {...pendingComplaints, pending: false, reason: 'lookup_not_loaded'}})).body), /^Unknown \(could not be loaded here; reload the report\)/); +}); + +test('web report: pending complaints show "Loading…", then /complaints fills the card in place', async () => { + const {ctx, els, run} = frontend(); + ctx.first = report(complete, {complaints: pendingComplaints}); + run('currentReport = first; renderComplaints(first)'); + assert.equal(els.get('#complaint-count').textContent, '…'); + assert.match(els.get('#complaints-body').innerHTML, /Loading NHTSA’s owner complaints…/); + assert.match(els.get('#complaints-body').innerHTML, /

    Not loaded: NHTSA’s complaint list had not arrived when this page was printed\.<\/p>/); + assert.equal(run('readyMessage(first)'), 'Report ready. NHTSA’s complaint list is still loading; it fills in by itself.'); + assert.equal(run('readyMessage({...first, recall_status: ' + JSON.stringify(pending) + '})'), 'Report ready. Ford’s VIN recall status and NHTSA’s complaint list are still loading; they fill in by themselves.'); + ctx.reply = () => Response.json(complaintList); + await run('followComplaints(currentReport)'); + assert.deepEqual(ctx.requests, ['/api/vin/1FTEX1EP4FFD06976/complaints']); + assert.equal(els.get('#complaint-count').textContent, 2); + assert.match(els.get('#complaints-body').innerHTML, /Long stop/); + assert.equal(run('currentReport.complaints.count'), 2); + assert.equal(run('currentReport.recall_status.open_count'), 2, 'the recall status is kept'); + assert.match(els.get('#decode-status').textContent, /owner complaints have loaded/); +}); + +test('web report: complaints that cannot be loaded read as unknown (could not be loaded), never zero', async () => { + const {ctx, els, run} = frontend(); + ctx.first = report(complete, {complaints: pendingComplaints}); + run('currentReport = first; renderComplaints(first)'); + ctx.reply = () => new Response('{}', {status: 502}); + await run('followComplaints(currentReport)'); + assert.equal(ctx.requests.length, 2, 'asked twice'); + assert.equal(els.get('#complaint-count').textContent, '?'); + assert.match(els.get('#complaints-body').innerHTML, /could not be loaded here\. The count is unknown/); + assert.equal(run('currentReport.complaints.pending'), false); +}); diff --git a/tests/slow-maker.test.mjs b/tests/slow-maker.test.mjs index 1b7cdec..fbb75f5 100644 --- a/tests/slow-maker.test.mjs +++ b/tests/slow-maker.test.mjs @@ -1,6 +1,7 @@ -// The real server with a slow manufacturer lookup: Ford's page answers after 2.6 s (tests/mock-upstream.mjs, -// MOCK_FORD_DELAY_MS), longer than the website/REST wait (2 s) and shorter than MCP's (6 s). Own server and port, -// so its rate limits and caches are apart from tests/integration.test.mjs. +// The real server with a slow manufacturer lookup and slow NHTSA complaints: Ford's page and NHTSA's complaint list +// answer after 2.6 s (tests/mock-upstream.mjs, MOCK_FORD_DELAY_MS, MOCK_COMPLAINTS_DELAY_MS), longer than the +// website/REST wait (2 s) and shorter than MCP's (6 s). Own server and port, so its rate limits and caches are apart +// from tests/integration.test.mjs. import test from 'node:test'; import assert from 'node:assert/strict'; import { mkdtemp, cp, symlink, rm, mkdir } from 'node:fs/promises'; @@ -18,7 +19,7 @@ for (const f of ['server.mjs', 'package.json', 'lib', 'public', 'tests/mock-upst await symlink(path.join(root, 'node_modules'), path.join(stage, 'node_modules'), 'dir'); await mkdir(path.join(stage, 'data'), {recursive: true}); const port = 23292, base = `http://127.0.0.1:${port}`, FORD_DELAY = 2600; -const env = {...process.env, JWT_SECRET: 'isolated-test-secret', ADMIN_KEY: 'b'.repeat(64), NODE_ENV: 'production', MOCK_FORD_DELAY_MS: String(FORD_DELAY)}; +const env = {...process.env, JWT_SECRET: 'isolated-test-secret', ADMIN_KEY: 'b'.repeat(64), NODE_ENV: 'production', MOCK_FORD_DELAY_MS: String(FORD_DELAY), MOCK_COMPLAINTS_DELAY_MS: String(FORD_DELAY)}; const child = spawn(process.execPath, ['--import', path.join(stage, 'tests/mock-upstream.mjs'), path.join(stage, 'server.mjs'), '--http', '--port', String(port)], {cwd: stage, env, stdio: ['ignore', 'ignore', 'pipe']}); let stderr = ''; child.stderr.on('data', b => stderr += b); test.after(async () => { child.kill(); await new Promise(resolve => child.once('exit', resolve)); await rm(stage, {recursive: true, force: true}); }); @@ -36,8 +37,13 @@ test('REST: a first report answers before the slow maker, pending with status_ur assert.deepEqual([s.pending, s.available, s.reason, s.open_count, s.completed_count, s.maker], [true, false, 'lookup_in_progress', null, null, 'Ford']); assert.equal(s.status_url, `/api/vin/${vin}/recall-status`); assert.equal(first.body.decode_checks.sources.manufacturer_record.status, 'pending'); - // status_url waits for the same lookup (no new 2.6 s wait from the start) - const status = await timed(s.status_url); + const c = first.body.complaints; + assert.deepEqual([c.pending, c.available, c.count, c.status_url], [true, false, null, `/api/vin/${vin}/complaints`]); + // Each status_url waits for the request already running (no new 2.6 s wait from the start). + const [status, complaints] = await Promise.all([timed(s.status_url), timed(c.status_url)]); + assert.equal(complaints.res.status, 200); + assert.deepEqual([complaints.body.available, complaints.body.count, complaints.body.pending], [true, 0, undefined]); + assert.ok(first.ms + complaints.ms < FORD_DELAY + 1500, `complaints after ${first.ms + complaints.ms} ms in all`); assert.equal(status.res.status, 200); assert.equal(status.body.available, true); assert.equal(status.body.open_count, 1); @@ -45,6 +51,7 @@ test('REST: a first report answers before the slow maker, pending with status_ur const again = await timed('/api/vin/' + vin); assert.equal(again.body.recall_status.available, true); assert.equal(again.body.recall_status.pending, undefined); + assert.equal(again.body.complaints.available, true); assert.ok(again.ms < 1000, `cached report in ${again.ms} ms`); }); @@ -65,6 +72,7 @@ test('MCP: decode_vin waits up to 6 s, so this maker is complete; vin_recall_sta const r = JSON.parse((await client.callTool({name: 'decode_vin', arguments: {vin}})).content[0].text); assert.equal(r.recall_status.available, true); assert.equal(r.recall_status.open_count, 1); + assert.equal(r.complaints.available, true, 'the complaint list arrived within the 6 s too'); // A website report leaves the lookup running; vin_recall_status gets its answer. const other = withCheck('1FTEX1EP0FFD06904'); const site = await timed('/api/vin/' + other); From 5094958353077cce736e4469e2bc8ce784b6fc96 Mon Sep 17 00:00:00 2001 From: root Date: Wed, 18 Nov 2026 10:47:45 -0500 Subject: [PATCH 5/6] Document pending NHTSA complaints Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- docs/data-sources.md | 4 ++++ public/llms-full.txt | 7 ++++--- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 0927b5b..6f3c2a4 100644 --- a/README.md +++ b/README.md @@ -239,7 +239,7 @@ charting or document tools to create figures and analysis. Custom chart renderin in the agent's tools. The API supplies comparisons, scenario calculations, provenance and JSON. Configuration/model-year data and VIN-specific facts retain their distinct scopes. -VIN recall repair status: Tesla and Ford open/completed statuses, GM open/completed or administratively closed records, Honda and Acura active safety recalls, Subaru completed/incomplete safety recalls, Volkswagen, Audi, Land Rover and Jaguar recalls as reported by each maker, positive Nissan open safety recalls, and Mopar VIN-matched open recall/campaign records are included in reports and comparisons, with `vin_recall_status`, `GET /api/vin/{vin}/recall-status` and `VinClient.recallStatus(vin)`. Mopar safety-recall count and completed history remain unknown because its feed mixes campaign types. GM repair dates are shown only when explicitly supplied; administrative closing dates remain separate. Ford customer-satisfaction and GM non-recall programs stay separate from recall counts. Honda covers active safety recalls from the past 15 calendar years and does not supply completed history. Nissan requires matching full VINs and verified safety classifications; empty results remain unknown. Toyota/Lexus/Scion, Hyundai and Kia require interactive official verification. Other makes remain unknown. A report waits up to 2 s for the maker's lookup (MCP `decode_vin`: 6 s); a slower maker (Ford's lookup usually takes about 10 s) gives `recall_status.pending: true`, unknown rather than zero, with `status_url` to fetch the complete status from the same running lookup, or ask with `?recall_wait=full` (`VinClient.decode(vin, {recallWait: 'full'})`). See the [source and coverage notes](docs/data-sources.md#vin-specific-recall-repair-status). +VIN recall repair status: Tesla and Ford open/completed statuses, GM open/completed or administratively closed records, Honda and Acura active safety recalls, Subaru completed/incomplete safety recalls, Volkswagen, Audi, Land Rover and Jaguar recalls as reported by each maker, positive Nissan open safety recalls, and Mopar VIN-matched open recall/campaign records are included in reports and comparisons, with `vin_recall_status`, `GET /api/vin/{vin}/recall-status` and `VinClient.recallStatus(vin)`. Mopar safety-recall count and completed history remain unknown because its feed mixes campaign types. GM repair dates are shown only when explicitly supplied; administrative closing dates remain separate. Ford customer-satisfaction and GM non-recall programs stay separate from recall counts. Honda covers active safety recalls from the past 15 calendar years and does not supply completed history. Nissan requires matching full VINs and verified safety classifications; empty results remain unknown. Toyota/Lexus/Scion, Hyundai and Kia require interactive official verification. Other makes remain unknown. A report waits up to 2 s for the maker's lookup (MCP `decode_vin`: 6 s); a slower maker (Ford's lookup usually takes about 10 s) gives `recall_status.pending: true`, unknown rather than zero, with `status_url` to fetch the complete status from the same running lookup, or ask with `?recall_wait=full` (`VinClient.decode(vin, {recallWait: 'full'})`). NHTSA's complaint list (5-17 s for a common model) arrives the same way: `complaints.pending: true` with `status_url` `/api/vin/{vin}/complaints`. See the [source and coverage notes](docs/data-sources.md#vin-specific-recall-repair-status). Deployment caching: HTML must revalidate, API responses must not be stored by shared caches, and changed JavaScript/PDF links use a content-hash query version generated by `node scripts/version-assets.mjs`. API clients also bypass stored browser responses. Preserve these policies in any reverse proxy so updated recall records are rendered by the matching client code. diff --git a/docs/data-sources.md b/docs/data-sources.md index 338929c..9f64869 100644 --- a/docs/data-sources.md +++ b/docs/data-sources.md @@ -206,6 +206,10 @@ The website shows "Checking with Ford…" in the recall card, the car sheet's re Why Ford is slow (measured 2026-11-18 from the web server, 4 requests): Ford's CDN (Akamai) holds each request about 9-10 s before answering (`server-timing` edge duration 9,000-10,002 ms; origin about 120 ms), even for a no-VIN page, a cached redirect and a reused connection, so the delay is per request and a client cannot shorten it. The VIN page is also about 1.3 MB, with the recall data about 81% of the way through. Reports for other makes took 0.4-2 s in all before this change. +#### NHTSA's complaint list: `pending` the same way + +NHTSA's `complaintsByVehicle` sends a model year's whole list at once: 1-2 MB of JSON for a common model, which took 17.3 s for a 2020 Ford Escape, 5.0 s for a 2017 Honda CR-V and 6.4 s for a 2003 Honda Accord (from the web server, 2026-11-18; time to first byte, so NHTSA's own time). It used to be awaited with the rest under a 10 s timeout, so the Escape's list always failed and its report was never cached. Now (`modelYearComplaints` in `lib/reports.mjs`) one request per make, model and year runs at a time, shared by every report and `GET /api/vin/{vin}/complaints`, for up to 30 s; successful lists are cached 6 hours. The report is assembled without waiting for it and waits up to the same budgets (2 s website and REST, 6 s MCP; comparisons wait). Still arriving, `complaints` is `{"available": false, "pending": true, "reason": "lookup_in_progress", "count": null, "complaints": [], "summary": null, "status_url": "/api/vin/{vin}/complaints", "note": ...}`: unknown, never zero. When the list arrives the complete report is built and cached for the next request. The server-rendered VIN page (`/{vin}`) no longer waits for the list (it leaves the complaint count out of its description while pending). The website shows "Loading NHTSA's owner complaints…" and fills the card and the car sheet's row in place from `status_url`; printed while pending they say the list had not arrived. In MCP output a pending list says to call `decode_vin` again (there is no complaints tool). + ### Ford: open/completed recalls and separate programs The [official Ford VIN page](https://www.ford.com/support/recalls/) serves its VIN-specific status in the same public page used by the browser. The adapter parses the serialized data as JSON; it never executes downloaded JavaScript. Both the page VIN and the returned vehicle VIN must match. The success flag, validation flag, arrays and declared record counts must agree. `O` means open and `C` means completed; other values remain unknown. Safety/environmental recall records and customer-satisfaction programs are separate. Coverage begins January 1, 2004. No repair date is supplied, so `repair_completed_at` remains null. The same official checker accepts Ford, Lincoln and Mercury; upstream confirmation still controls availability. diff --git a/public/llms-full.txt b/public/llms-full.txt index b3f9ed4..6c4b0c4 100644 --- a/public/llms-full.txt +++ b/public/llms-full.txt @@ -62,7 +62,7 @@ Response fields: - `parts_content` (object): NHTSA Part 583 (AALA) parts content for the carline, model years 2020-2027 (available, match: carline or closest_carline, match_basis, rows[] with us_canada_parts_pct, other_major_sources, final_assembly, engine_origin, transmission_origin, unreadable, listed_times; rows_note when several fit; source); carline-level, not this car - `production_theft` (object): NHTSA final theft data for the vehicle line, model years 1998-2010 and 2012 (available, match: line_name or closest_line_name, match_basis, lines[] with production, thefts, thefts_per_1000_produced, rank, lines_ranked, source); figures for the whole line, not this car - `recalls` (object): Count and array of recall records (campaign number, component, summary, consequence, remedy, manufactured_from/manufactured_to: the manufacturer's build-date range for the campaign, null when none was filed; the VIN does not carry a build month, so this never says the vehicle is affected) -- `complaints` (object): Count, array of complaints, summary with crash/fire/injury/death counts +- `complaints` (object): Count, array of complaints, summary with crash/fire/injury/death counts. NHTSA can take 5-17 s to send a common model's list (1-2 MB); the report waits up to 2 s for it (MCP `decode_vin`: 6 s). Still arriving, it is `pending: true`, `available: false`, `reason: "lookup_in_progress"`, `count: null`, `complaints: []`, `summary: null`, with `status_url` (`/api/vin/{vin}/complaints`): unknown, never zero. The request keeps running; `status_url` waits for it and the next report includes it. - `safety_ratings` (object): NCAP star ratings — overall, frontal driver/passenger, side driver/passenger, rollover - `fuel_economy` (object): FuelEconomy.gov configuration match: city/highway/combined MPG (MPGe for EVs, see unit), annual fuel cost, CO2 tailpipe g/mi, EV range (all-electric range; for plug-in hybrids total_range is gas plus electric), charge time; match: exact, closest (summary and match_basis say what differs), same_rating (several configurations fit and share one combined figure, which is given; city/highway only when they agree; configurations[] and separated_by say what differs) or multiple_configurations (available false, reason ambiguous_variant, with mpg_range, configurations[] each with its own figures and a plain-words label, separated_by, configuration_count; the VIN does not say which); not matched: not_found, no_matching_variant, heavy_duty_not_rated.. Transmission choice: when the configurations the VIN fits differ only partly by transmission (EPA lists both an automatic and a manual), the VIN does not say which, and the ratings differ, the automatic configuration's figures are given (one, or several by the usual rules) and marked: `assumed: {transmission: 'automatic'}`, `summary` starting "Assuming an automatic transmission (the VIN does not say)", `transmission_choice` {chosen, basis: assumed | request | owner_stated, label, options, classified, configuration_counts, efids_all}, and `alternatives` [{for_transmission: 'manual', ...the manual configuration's figures}]. CVT, dual-clutch and automated-manual transmissions count as automatic. With `?transmission=manual` (or the MCP `transmission` argument) the manual figures are given instead, with `stated: {transmission, by: 'request'}` and the automatic in `alternatives`. The decode's own transmission always wins. Saved vehicles carry `owner_details` ({transmission} or null), set with PUT /api/user/vins/{id}/details EPA rates configurations, not individual cars - `tire_placard` (object): Tire size (with load index and speed symbol) and front/rear recommended cold pressure (psi and kPa) printed in NHTSA crash-test reports or FMVSS 110/138/537 compliance test reports for a vehicle NHTSA tested, same vPIC make and model, closest match. `scope: "nhtsa_test_vehicle"`, `vin_specific: false`, `match_kind`, `max_year_gap` (2). `vehicles` lists the closest tested vehicles with `tested_as`, `tires`, `cold_pressure_psi`, `cold_pressure_kpa`, `source` (`nhtsa_crash_test` or `nhtsa_compliance_test`), `report_url`, `report_label`, `test_no` (null for a compliance report), `report_number` and `fmvss` (compliance reports), `other_reports`, `confidence` (`high` = two reports agree, `normal` = one report) and `match {kind, tested_model_year, vin_model_year, year_gap, differences, generation_check}`. Kinds, closest first: `exact` (same model year, no visible difference in trim, series, body, drive or electrification), `nearest_model_year` (another tested year within 2; both years on a tie; `generation_check` compares Transport Canada wheelbases: `same_wheelbase` or `unknown`; a year with a different wheelbase, likely another generation, is never used, and when only such years were tested `reason: "other_generation_only"`), `different_variant` (same year, differences listed; also `engine`, `wheel_size`, `gvwr_class`, `cab` from the two vPIC decodes). Only the closest kind present is returned; among equally close vehicles those that match the VIN's vPIC wheel size, engine and cab are kept, else all of them (the set). `accuracy {kind, tire_size_right_pct, cold_pressure_right_pct, basis}`: how often this kind of match gave the vehicle's own value in mcp.vin's leave-one-out test (each of 2,382 NHTSA test vehicles held out and looked up). An empty list means not tested or not indexed within reach (`reason: "no_close_match"`), never zero; `available: false` means the index was not checked. A test vehicle whose known powertrain class (battery-electric or not, from vPIC) differs from the VIN's is never used (`reason: "other_powertrain_only"`). Values are never estimated, blended or averaged. A vehicle may carry `corrections`: a misprint in NHTSA's report corrected because it has a clear mechanical cause (psi printed under a kPa heading, the tire's sidewall maximum printed in the pressure row, a digit glitch in a tire size, front and rear swapped) and an independent check confirmed the corrected value (the same report prints it elsewhere, or another report of the same test vehicle or of the same model generation and version does). Each is `{corrected: true, field, rule, printed, value, note, confirmed_by: [{check, detail, report, report_url}]}`; the vehicle's `tires` and `cold_pressure_*` are the corrected values, `printed` is what the report shows. A placard pressure is corrected only to a value printed in that report or another report of the same vehicle, never computed. Misprints that could not be confirmed stay excluded. The owner's own door placard governs; it can differ by year, trim and tire size. @@ -116,7 +116,7 @@ Rate limit: 30 requests/minute per IP ### GET /api/vin/:vin/complaints — Complaints Only -Returns NHTSA consumer complaints for the decoded vehicle. +Returns NHTSA consumer complaints for the decoded vehicle: every complaint for the make, model and year. If a report started NHTSA's request for this model, this waits for that same request (up to 30 s). Successful lists are cached 6 hours; a failure returns `available: false`, `count: null`. Parameters: - `vin` (path, required): 17-character VIN @@ -236,7 +236,7 @@ Parameters: - `transmission` (string, optional): `automatic` or `manual`, when the owner knows it and the VIN does not say. Applies to fuel economy only, and only when EPA lists the model with both; without it an automatic is assumed and marked (`fuel_economy.assumed`, `fuel_economy.alternatives`). - `recall_wait` (string, optional): `full` waits for the manufacturer's VIN recall lookup (up to about 15 s). -Returns: Full JSON report with all data sources aggregated. `recall_status` is the manufacturer's VIN-specific recall status; a maker that has not answered within about 6 s gives `recall_status.pending: true` (unknown, not "no open recalls") with `next_step: {tool: "vin_recall_status", arguments: {vin}}`: that tool waits for the same lookup and returns the complete status. +Returns: Full JSON report with all data sources aggregated. `recall_status` is the manufacturer's VIN-specific recall status; a maker that has not answered within about 6 s gives `recall_status.pending: true` (unknown, not "no open recalls") with `next_step: {tool: "vin_recall_status", arguments: {vin}}`: that tool waits for the same lookup and returns the complete status. `complaints.pending: true` (NHTSA's complaint list had not arrived within about 6 s) is unknown, not zero; call `decode_vin` again in a minute (cached once it arrives). #### validate_vin Quickly validate a VIN without calling any external APIs. Checks checksum, format, WMI, and model year. @@ -338,6 +338,7 @@ The server uses in-memory LRU caching with TTL: - Safety ratings: 24 hours - Fuel economy: 24 hours - Manufacturer VIN recall status: 15 minutes (successful answers only); one lookup per VIN at a time, shared by every request that asks +- NHTSA complaints: 6 hours (successful answers only); one request per make, model and year at a time, shared by every request that asks ## Articles From 17f220334b37a797126b12bc13cd3b93b62e444b Mon Sep 17 00:00:00 2001 From: root Date: Wed, 18 Nov 2026 10:58:51 -0500 Subject: [PATCH 6/6] Set the status line inside the in-place redraw Without the browser's scroll anchoring (Safari), the shorter status line moved the page 19 px after Ford's status arrived; inside the redraw it is part of the measured correction (0 px in the 390 px check). Co-Authored-By: Claude Opus 5.5 --- public/app.js | 8 +++++--- public/index.html | 2 +- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/public/app.js b/public/app.js index ae79d1a..42abfb5 100644 --- a/public/app.js +++ b/public/app.js @@ -451,8 +451,9 @@ async function followComplaints(report) { renderComplaints(view); window.CarSheet?.update ? CarSheet.update(view) : window.CarSheet?.render(view); window.VinWorkspace?.reportUpdated(view); + // inside the redraw: a shorter status line moves the page too + $('#decode-status').textContent = next.available ? 'NHTSA’s owner complaints have loaded.' : 'NHTSA’s owner complaints could not be loaded; see the complaints section.'; }, [$('#sheet-body'), $('#sheet-foot')]); - $('#decode-status').textContent = next.available ? 'NHTSA’s owner complaints have loaded.' : 'NHTSA’s owner complaints could not be loaded; see the complaints section.'; } // ── The maker's VIN recall status, when it answers after the report ── @@ -503,9 +504,10 @@ function applyMakerUpdate(next) { } window.CarSheet?.update ? CarSheet.update(view) : window.CarSheet?.render(view); window.VinWorkspace?.reportUpdated(view); + // inside the redraw: a shorter status line moves the page too + const s = merged.recall_status || {}, maker = prev.recall_status?.maker || s.maker || 'The manufacturer'; + $('#decode-status').textContent = s.available ? `${maker}’s VIN recall status has loaded.` : `${maker}’s VIN recall status is not available; see the recall section.`; }, [$('#sheet-body'), $('#sheet-foot')]); - const s = merged.recall_status || {}, maker = prev.recall_status?.maker || s.maker || 'The manufacturer'; - $('#decode-status').textContent = s.available ? `${maker}’s VIN recall status has loaded.` : `${maker}’s VIN recall status is not available; see the recall section.`; } function renderCampaigns(r) { diff --git a/public/index.html b/public/index.html index c73c0eb..01818a4 100644 --- a/public/index.html +++ b/public/index.html @@ -442,4 +442,4 @@

    -
    +