LordOS — a free, fast and secure GNU/Linux distribution based on Debian, with its own desktop environment: display server and Wayland compositor in C, a React UI engine on QuickJS, and private native apps.
C cdebiandesktop-environmentebpffirewalllandlocklinuxlinux-distributionopen-sourceprivacyquickjsraspberry-pi-5reactsecuritywaylandwayland-compositor
Store: Suggested for your computer
Federico Pereira75f77daa28d2
diff --git a/apps/store/debian.js b/apps/store/debian.jsindex d0c7c5f..0bbfab0 100644--- a/apps/store/debian.js+++ b/apps/store/debian.js@@ -8,6 +8,7 @@ import {refreshApps, launchApp, useLauncherApps, LetterIcon, typeScale, spacing, direction, t, locale, errorText, statusText,Markdown, Toggle, LordOSLogo, session, lordosUpdate, restartNeeded, updatePrefs, setUpdatePrefs,} from '@lordos/sdk';+import { Suggested } from './suggested.js';const available = () => typeof lord.pkg !== 'undefined';const ready = () => available() && lord.pkg.available();@@ -224,6 +225,7 @@ function Discover({ query }) {const list = lord.pkg.apps({ category: cat, limit: 60, lang: lang2() });return h(View, { style: { gap: 16 } },h(Progress),+ h(Suggested, { deb: { state, runJob, PlanView, boxStyle } }),h(Text, { style: titleStyle(th) }, t('store.discover.title')),h(Chips, { items: CATS.filter((c) => counts[c]).map((c) => h(View, { key: c, onClick: () => setCat(c), style: {paddingHorizontal: 12, height: 26, justifyContent: 'center', borderRadius: 13, backgroundColor: c === cat ? th.accent : th.control } },diff --git a/apps/store/index.jsx b/apps/store/index.jsxindex 9206ef9..2e927fc 100644--- a/apps/store/index.jsx+++ b/apps/store/index.jsx@@ -3,6 +3,7 @@import {View, Text, Image, useTheme, useLocale, useAppWindow, useStore, Button, ScrollView, SidebarItem, SectionTitle, SearchField, Hairline, EmptyState, GroupBox,packages, packageList, refreshPackages, useLauncherApps, launchApp, fs, formatBytes, wm, direction, typeScale, spacing,+ suggestions, unseenSuggestions, refreshSuggestions,} from '@lordos/sdk';import { useEffect, useMemo, useState } from 'react';import { debian, useDebian } from './debian.js';@@ -310,8 +311,11 @@ export default function Store() {if (args?.page) setPage(args.page);if (args?.search) { setQuery(args.search); setPage('discover'); } // from Search}, [args?.nonce]);+ const sug = useStore(suggestions);+ useEffect(() => { refreshSuggestions(); }, []); // the hardware may have changed since the last look+ const unseen = page === 'discover' ? 0 : unseenSuggestions(sug.list).length; // new suggestions (Discover's badge)const pages = [- ['discover', tr('store.page.discover')],+ ['discover', tr('store.page.discover'), unseen || null],['lordos', tr('store.page.lordos')],['installed', tr('store.page.installed')],['updates', deb.upgrades?.length ? tr('store.page.updatesCount', { count: deb.upgrades.length }) : tr('store.page.updates')],@@ -323,7 +327,7 @@ export default function Store() {<Hairline edge="end" /><SearchField value={query} onChange={(v) => { setQuery(v); if (v && page !== 'discover' && page !== 'installed' && page !== 'lordos') setPage('discover'); }}placeholder={tr('store.search')} style={{ marginBottom: 10 }} />- {pages.map(([id, label]) => <SidebarItem key={id} label={label} selected={page === id} onClick={() => setPage(id)} />)}+ {pages.map(([id, label, detail]) => <SidebarItem key={id} label={label} detail={detail} selected={page === id} onClick={() => setPage(id)} />)}<View style={{ flex: 1 }} /><View style={{ paddingHorizontal: 10 }}><debian.Status /></View></View>diff --git a/apps/store/suggested.js b/apps/store/suggested.jsnew file mode 100644index 0000000..34c1257--- /dev/null+++ b/apps/store/suggested.js@@ -0,0 +1,139 @@+// suggested.js — Store → Discover, "Suggested for your computer": packages for the detected+// hardware (sdk/suggestions.js, assets/store/suggestions.json, docs/PACKAGES.md). Each card says+// why it appears, installs through the usual plan + pkg-install, and can be dismissed. Software+// that isn't free says so before anything is installed, and is never preselected.+import { createElement as h, useEffect, useState } from 'react';+import {+ View, Text, Button, useTheme, useStore, admin, typeScale, spacing, t, direction,+ suggestions, refreshSuggestions, reevaluateSuggestions, dismissSuggestion, markSuggestionsSeen,+} from '@lordos/sdk';++// ---- drawn glyphs (monochrome on a tinted tile) ----++const TINT = {+ vm: ['#5e8cff', '#3757d8'], gpu: ['#6fcf5b', '#2f9a3b'], board: ['#e2557a', '#b12c55'], printer: ['#8e8e93', '#5f5f66'],+ scanner: ['#8e8e93', '#5f5f66'], wifi: ['#36a3ff', '#1463d6'], bluetooth: ['#4f7dff', '#2448c9'], network: ['#2fb5a5', '#16867a'],+ graphics: ['#6fcf5b', '#2f9a3b'], other: ['#a07cff', '#6a45d6'], package: ['#a07cff', '#6a45d6'],+};++function Glyph({ kind, size: s = 40 }) {+ const [a, b] = TINT[kind] || TINT.package;+ const w = '#fff';+ const box = (style) => h(View, { style: { position: 'absolute', ...style } });+ let parts;+ switch (kind) {+ case 'vm': // a display with a stand+ parts = [box({ left: 9, top: 10, width: 22, height: 15, borderRadius: 2, border: `2px solid ${w}` }),+ box({ left: 18, top: 26, width: 4, height: 3, backgroundColor: w }), box({ left: 13, top: 29, width: 14, height: 2, borderRadius: 1, backgroundColor: w })];+ break;+ case 'gpu': case 'graphics': case 'board': // a chip with pins+ parts = [box({ left: 12, top: 12, width: 16, height: 16, borderRadius: 3, border: `2px solid ${w}` }), box({ left: 17, top: 17, width: 6, height: 6, borderRadius: 1, backgroundColor: w }),+ ...[14, 19, 24].flatMap((p) => [box({ left: p, top: 8, width: 2, height: 3, backgroundColor: w }), box({ left: p, top: 29, width: 2, height: 3, backgroundColor: w }),+ box({ left: 8, top: p, width: 3, height: 2, backgroundColor: w }), box({ left: 29, top: p, width: 3, height: 2, backgroundColor: w })])];+ break;+ case 'printer':+ parts = [box({ left: 14, top: 8, width: 12, height: 8, border: `2px solid ${w}`, borderRadius: 1 }), box({ left: 8, top: 15, width: 24, height: 11, borderRadius: 3, backgroundColor: w }),+ box({ left: 13, top: 23, width: 14, height: 9, borderRadius: 1, border: `2px solid ${w}`, backgroundColor: b })];+ break;+ case 'scanner':+ parts = [box({ left: 8, top: 17, width: 24, height: 11, borderRadius: 3, backgroundColor: w }), box({ left: 9, top: 13, width: 22, height: 3, borderRadius: 1.5, backgroundColor: w }),+ box({ left: 11, top: 21, width: 18, height: 2, backgroundColor: b })];+ break;+ case 'wifi': // a dot and two rings (top halves)+ parts = [h(View, { key: 'r', style: { position: 'absolute', left: 6, top: 9, width: 28, height: 14, overflow: 'hidden' } },+ box({ left: 0, top: 0, width: 28, height: 28, borderRadius: 14, border: `2.5px solid ${w}` }),+ box({ left: 6, top: 6, width: 16, height: 16, borderRadius: 8, border: `2.5px solid ${w}` })),+ box({ left: 17, top: 23, width: 6, height: 6, borderRadius: 3, backgroundColor: w })];+ break;+ case 'bluetooth':+ parts = [h(Text, { key: 'b', style: { position: 'absolute', left: 0, top: 6, width: s, textAlign: 'center', fontSize: 22, fontWeight: 700, color: w, lineHeight: 28 } }, 'B')];+ break;+ case 'network':+ parts = [box({ left: 8, top: 14, width: 24, height: 12, borderRadius: 2, border: `2px solid ${w}` }),+ ...[12, 17, 22, 27].map((x) => box({ left: x - 1, top: 18, width: 3, height: 4, backgroundColor: w }))];+ break;+ default: // a box+ parts = [box({ left: 10, top: 12, width: 20, height: 18, borderRadius: 3, border: `2px solid ${w}` }), box({ left: 10, top: 18, width: 20, height: 2, backgroundColor: w })];+ }+ return h(View, { style: { width: s, height: s, borderRadius: s * 0.24, background: `linear-gradient(180deg, ${a}, ${b})`, flexShrink: 0 } },+ ...parts.map((p, i) => (p.key ? p : { ...p, key: i })));+}++// ---- one card ----++const loc = (s, part, extra = {}) => t(`store.suggest.${s.text}.${part}`, { ...s.params, ...extra });++function Notes({ s, th }) {+ const lines = [+ !s.free && t('store.suggest.note.nonfree', { component: s.component || 'non-free' }),+ ...s.notes.filter((n) => n !== 'nonfree' && n !== 'firmware').map((n) => t(`store.suggest.${s.text}.note.${n}`)),+ s.notes.includes('firmware') && t('store.suggest.note.firmware'),+ ].filter(Boolean);+ if (!lines.length) return null;+ return h(View, { style: { gap: 4, marginTop: 2 } },+ ...lines.map((l, i) => h(Text, { key: i, style: { fontSize: typeScale.caption, color: th.textDim, lineHeight: 1.4, textAlign: 'start' } }, `• ${l}`)));+}++function Card({ s, deb }) {+ const th = useTheme();+ const { job } = useStore(deb.state);+ const [plan, setPlan] = useState(null);+ const [more, setMore] = useState(false);+ const isAdmin = admin.available();+ const nonfree = !s.free;+ const ask = () => setPlan(lord.pkg.plan({ install: s.install }));+ const confirm = () => {+ const extra = plan.items.some((i) => i.action === 'remove' && !i.requested);+ deb.runJob('pkg-install', `${s.install.join(' ')}${extra ? ' --allow-remove' : ''}`, t('store.suggest.job', { name: loc(s, 'title') }));+ setPlan(null);+ };+ const detailKey = s.state === 'unavailable' ? 'unavailable' : 'detail';+ const badge = s.state === 'installed'+ ? h(Text, { style: { fontSize: typeScale.caption, fontWeight: 500, color: '#30d158' } }, t('store.installedBadge'))+ : null;+ return h(View, { style: deb.boxStyle(th, { gap: spacing.s, padding: spacing.l }) },+ h(View, { style: { flexDirection: 'row', alignItems: 'flex-start', gap: spacing.m } },+ h(Glyph, { kind: s.icon }),+ h(View, { style: { flex: 1, minWidth: 0, gap: 3 } },+ h(View, { style: { flexDirection: 'row', alignItems: 'center', gap: spacing.s, flexWrap: 'wrap' } },+ h(Text, { style: { fontSize: typeScale.body, fontWeight: 600, color: th.text, textAlign: 'start' } }, loc(s, 'title')),+ nonfree ? h(View, { style: { paddingHorizontal: 6, height: 18, borderRadius: 9, justifyContent: 'center', backgroundColor: 'rgba(255,159,10,0.16)' } },+ h(Text, { style: { fontSize: 10.5, fontWeight: 600, color: '#ff9f0a' } }, t('store.suggest.nonfreeBadge'))) : null,+ badge),+ h(Text, { style: { fontSize: typeScale.callout, color: th.text, lineHeight: 1.4, textAlign: 'start' } }, loc(s, 'why')),+ h(Text, { style: { fontSize: typeScale.callout, color: th.textDim, lineHeight: 1.4, textAlign: 'start' } },+ loc(s, detailKey, { packages: (s.state === 'unavailable' ? s.missing : s.packages).join(', '), component: s.component || 'non-free' })),+ (nonfree || s.notes.length) && s.state !== 'installed'+ ? (more ? h(Notes, { s, th }) : h(Button, { plain: true, small: true, label: t('store.suggest.whatChanges'), onClick: () => setMore(true), style: { alignSelf: 'flex-start', [direction() === 'rtl' ? 'marginRight' : 'marginLeft']: -6 } }))+ : null),+ h(View, { style: { alignItems: 'flex-end', gap: 2 } },+ s.state === 'install' ? h(Button, { primary: !nonfree, label: nonfree ? t('store.suggest.installNonfree') : t('store.install'), disabled: !isAdmin || !!job,+ onClick: () => isAdmin && !job && ask() }) : null,+ s.state !== 'installed' ? h(Button, { plain: true, small: true, label: t('store.suggest.dismiss'), onClick: () => dismissSuggestion(s.id) }) : null)),+ !isAdmin && s.state === 'install' ? h(Text, { style: { fontSize: typeScale.caption, color: '#ff9f0a', textAlign: 'start' } }, t('store.debian.needAdmin')) : null,+ plan && h(View, { style: { gap: spacing.s, marginTop: spacing.xs, paddingTop: spacing.s, borderTop: `1px solid ${th.separator}` } },+ nonfree ? h(Text, { style: { fontSize: typeScale.caption, color: '#ff9f0a', lineHeight: 1.4, textAlign: 'start' } }, t('store.suggest.confirmNonfree')) : null,+ h(deb.PlanView, { plan }),+ h(View, { style: { flexDirection: 'row', gap: spacing.s, justifyContent: 'flex-end' } },+ h(Button, { label: t('store.cancel'), onClick: () => setPlan(null) }),+ plan.ok && h(Button, { primary: true, label: t('store.plan.confirm'), onClick: confirm }))));+}++// ---- the section ----++export function Suggested({ deb }) {+ const th = useTheme();+ const { list, fixture, ready } = useStore(suggestions);+ const { gen } = useStore(deb.state);+ useEffect(() => { if (!suggestions.get().ready) refreshSuggestions(); }, []);+ useEffect(() => { if (ready) markSuggestionsSeen(list); }, [ready, list]);+ useEffect(() => { if (gen) reevaluateSuggestions(); }, [gen]); // installed or removed something+ if (!ready || !list.length) return null;+ return h(View, { style: { gap: spacing.s, marginBottom: spacing.s } },+ h(View, { style: { flexDirection: 'row', alignItems: 'baseline', gap: spacing.s, flexWrap: 'wrap' } },+ h(Text, { style: { fontSize: typeScale.title, fontWeight: 600, color: th.text, textAlign: 'start' } }, t('store.suggest.title')),+ fixture ? h(View, { style: { paddingHorizontal: 8, height: 20, borderRadius: 10, justifyContent: 'center', backgroundColor: '#ff453a' } },+ h(Text, { style: { fontSize: 11, fontWeight: 700, color: '#fff' } }, t('store.suggest.fixture'))) : null),+ h(Text, { style: { fontSize: typeScale.callout, color: th.textDim, lineHeight: 1.4, textAlign: 'start', marginBottom: 2 } }, t('store.suggest.subtitle')),+ ...list.map((s) => h(Card, { key: s.id, s, deb })));+}diff --git a/assets/locales/en/errors.json b/assets/locales/en/errors.jsonindex c1886e6..20de9ca 100644--- a/assets/locales/en/errors.json+++ b/assets/locales/en/errors.json@@ -558,5 +558,6 @@"proc.denied": "Not allowed to stop this process","proc.failed": "Could not stop the process","proc.badArgument": "Invalid process request",- "proc.notOwn": "This process belongs to another user"+ "proc.notOwn": "This process belongs to another user",+ "hw.noKernelLog": "The kernel log could not be read"}diff --git a/assets/locales/en/status.json b/assets/locales/en/status.jsonindex c6d6945..c5ce8df 100644--- a/assets/locales/en/status.json+++ b/assets/locales/en/status.json@@ -119,5 +119,6 @@"hw.caseSet": "Case: {case}","ssh.off": "Remote login turned off","ssh.on": "Remote login turned on",- "ssh.saved": "Settings saved"+ "ssh.saved": "Settings saved",+ "hw.firmwareChecked": "Firmware checked"}diff --git a/assets/locales/en/store.json b/assets/locales/en/store.jsonindex 77d26b9..0290e4f 100644--- a/assets/locales/en/store.json+++ b/assets/locales/en/store.json@@ -148,5 +148,80 @@"other": "Debian updates ({count})"},"updates.auto": "Check for updates automatically",- "updates.autoHint": "Once a day, and only to tell you. Nothing is installed without asking."+ "updates.autoHint": "Once a day, and only to tell you. Nothing is installed without asking.",+ "suggest.confirmNonfree": "This is not free software: its source code isn't available, and Debian can't fix or audit it. You can remove it later like any other package.",+ "suggest.dismiss": "Don't suggest again",+ "suggest.firmware.bluetooth.detail": "{packages} has it. The device starts working after you install it and restart the computer (or unplug it and plug it back in).",+ "suggest.firmware.bluetooth.title": "Bluetooth firmware",+ "suggest.firmware.bluetooth.unavailable": "{packages} is in Debian's {component} component, which isn't enabled in this computer's package sources.",+ "suggest.firmware.bluetooth.why": "Your Bluetooth device asked for firmware that isn't installed ({files}).",+ "suggest.firmware.graphics.detail": "{packages} has it. The device starts working after you install it and restart the computer (or unplug it and plug it back in).",+ "suggest.firmware.graphics.title": "Graphics firmware",+ "suggest.firmware.graphics.unavailable": "{packages} is in Debian's {component} component, which isn't enabled in this computer's package sources.",+ "suggest.firmware.graphics.why": "Your graphics card asked for firmware that isn't installed ({files}).",+ "suggest.firmware.network.detail": "{packages} has it. The device starts working after you install it and restart the computer (or unplug it and plug it back in).",+ "suggest.firmware.network.title": "Network adapter firmware",+ "suggest.firmware.network.unavailable": "{packages} is in Debian's {component} component, which isn't enabled in this computer's package sources.",+ "suggest.firmware.network.why": "Your network adapter asked for firmware that isn't installed ({files}).",+ "suggest.firmware.other.detail": "{packages} has it. The device starts working after you install it and restart the computer (or unplug it and plug it back in).",+ "suggest.firmware.other.title": "Device firmware",+ "suggest.firmware.other.unavailable": "{packages} is in Debian's {component} component, which isn't enabled in this computer's package sources.",+ "suggest.firmware.other.why": "A device asked for firmware that isn't installed ({files}).",+ "suggest.firmware.wifi.detail": "{packages} has it. The device starts working after you install it and restart the computer (or unplug it and plug it back in).",+ "suggest.firmware.wifi.title": "Wi-Fi firmware",+ "suggest.firmware.wifi.unavailable": "{packages} is in Debian's {component} component, which isn't enabled in this computer's package sources.",+ "suggest.firmware.wifi.why": "Your Wi-Fi device asked for firmware that isn't installed ({files}).",+ "suggest.fixture": "Test data",+ "suggest.installNonfree": "Review and install",+ "suggest.ippUsb.detail": "{packages} makes it show up like a network printer and scanner.",+ "suggest.ippUsb.title": "Printing and scanning over USB without drivers",+ "suggest.ippUsb.unavailable": "{packages} isn't in this computer's package sources.",+ "suggest.ippUsb.why": "We detected a USB printer that can print and scan without a vendor driver (IPP over USB).",+ "suggest.job": "Installing {name}",+ "suggest.nonfreeBadge": "Not free software",+ "suggest.note.firmware": "Firmware is a small program that runs inside the device itself, not on the computer's processor; its license doesn't allow changing it.",+ "suggest.note.nonfree": "Not free software: it comes from Debian's {component} component, under its vendor's license.",+ "suggest.notify.body": {+ "one": "{name}, and {count} more. See them in the Store.",+ "other": "{name}, and {count} more. See them in the Store."+ },+ "suggest.notify.open": "Open the Store",+ "suggest.notify.title": {+ "one": "A suggestion for your computer",+ "other": "{count} suggestions for your computer"+ },+ "suggest.nvidiaDriver.detail": "Right now it uses nouveau, the free driver included with LordOS. The vendor's driver ({packages}) usually gives better 3D performance and power management.",+ "suggest.nvidiaDriver.note.nouveau": "Until you install it, the free nouveau driver stays in use; removing the package goes back to it.",+ "suggest.nvidiaDriver.note.older": "Cards older than about 2014 aren't supported by this driver version; keep the free driver on them. The LordOS desktop hasn't been tested with this driver yet.",+ "suggest.nvidiaDriver.note.secureBoot": "The driver is built for your kernel on this computer (DKMS) and again after every kernel update. With Secure Boot on, you have to enroll its signing key at the next restart, or the driver won't load.",+ "suggest.nvidiaDriver.title": "Proprietary graphics driver",+ "suggest.nvidiaDriver.unavailable": "The vendor's driver needs Debian's contrib and non-free components, and they aren't both enabled in this computer's package sources. The free driver, nouveau, keeps working.",+ "suggest.nvidiaDriver.why": "We detected an NVIDIA graphics card.",+ "suggest.printer.detail": "{packages} adds the {vendor} driver to the printing system. Many printers also work without it.",+ "suggest.printer.title": "{vendor} printer driver",+ "suggest.printer.unavailable": "{packages} isn't in this computer's package sources.",+ "suggest.printer.why": "We detected a printer from {vendor} connected by USB.",+ "suggest.qemuAgent.detail": "{packages} lets the host shut down LordOS cleanly, pause disk writes for consistent backups and see the network address.",+ "suggest.qemuAgent.title": "Guest agent for this virtual machine",+ "suggest.qemuAgent.unavailable": "{packages} isn't in this computer's package sources.",+ "suggest.qemuAgent.why": "We detected a virtual machine with a guest agent channel.",+ "suggest.rpi5Tools.detail": "{packages}: bootloader (EEPROM) updates, board tools such as vcgencmd and pinctrl, and command-line tools for the GPIO pins.",+ "suggest.rpi5Tools.title": "Raspberry Pi tools",+ "suggest.rpi5Tools.unavailable": "These tools aren't in this computer's package sources.",+ "suggest.rpi5Tools.why": "We detected a Raspberry Pi 5.",+ "suggest.scanner.detail": "{packages} lets scanning apps use it.",+ "suggest.scanner.title": "{vendor} scanner driver",+ "suggest.scanner.unavailable": "{packages} isn't in this computer's package sources.",+ "suggest.scanner.why": "We detected a scanner from {vendor} connected by USB.",+ "suggest.subtitle": "Packages for the hardware LordOS found in this computer. Detection happens only on this computer: nothing is sent anywhere.",+ "suggest.title": "Suggested for your computer",+ "suggest.virtualboxGuest.detail": "{packages} adds shared folders and time sync with the host.",+ "suggest.virtualboxGuest.title": "Guest utilities for this virtual machine",+ "suggest.virtualboxGuest.unavailable": "Its guest utilities ({packages}) aren't part of Debian 13, so LordOS can't offer them. The kernel already includes the guest drivers for the display and shared folders; for the best display, choose the VMSVGA graphics controller in the virtual machine's settings.",+ "suggest.virtualboxGuest.why": "We detected a VirtualBox virtual machine.",+ "suggest.vmwareTools.detail": "{packages} lets the host shut down or restart LordOS cleanly, keeps the clock in sync and reports the network address. Clipboard sharing and automatic resizing will be added when LordOS supports them.",+ "suggest.vmwareTools.title": "Guest tools for this virtual machine",+ "suggest.vmwareTools.unavailable": "{packages} isn't in this computer's package sources.",+ "suggest.vmwareTools.why": "We detected a VMware virtual machine.",+ "suggest.whatChanges": "What changes"}diff --git a/assets/locales/es/errors.json b/assets/locales/es/errors.jsonindex 51eb699..0a1a6d5 100644--- a/assets/locales/es/errors.json+++ b/assets/locales/es/errors.json@@ -558,5 +558,6 @@"proc.denied": "No tenés permiso para detener este proceso","proc.failed": "No se pudo detener el proceso","proc.badArgument": "Pedido de proceso no válido",- "proc.notOwn": "Este proceso es de otro usuario"+ "proc.notOwn": "Este proceso es de otro usuario",+ "hw.noKernelLog": "No se pudo leer el registro del kernel"}diff --git a/assets/locales/es/status.json b/assets/locales/es/status.jsonindex 9faf3b9..758426b 100644--- a/assets/locales/es/status.json+++ b/assets/locales/es/status.json@@ -119,5 +119,6 @@"hw.caseSet": "Caja: {case}","ssh.off": "Inicio de sesión remoto desactivado","ssh.on": "Inicio de sesión remoto activado",- "ssh.saved": "Ajustes guardados"+ "ssh.saved": "Ajustes guardados",+ "hw.firmwareChecked": "Firmware revisado"}diff --git a/assets/locales/es/store.json b/assets/locales/es/store.jsonindex d84d6b8..4c3eec2 100644--- a/assets/locales/es/store.json+++ b/assets/locales/es/store.json@@ -148,5 +148,80 @@"other": "Actualizaciones de Debian ({count})"},"updates.auto": "Buscar actualizaciones automáticamente",- "updates.autoHint": "Una vez por día, y solo para avisarte. No se instala nada sin preguntar."+ "updates.autoHint": "Una vez por día, y solo para avisarte. No se instala nada sin preguntar.",+ "suggest.confirmNonfree": "Esto no es software libre: su código fuente no está disponible y Debian no puede corregirlo ni auditarlo. Podés quitarlo después como cualquier otro paquete.",+ "suggest.dismiss": "No sugerir de nuevo",+ "suggest.firmware.bluetooth.detail": "{packages} lo trae. El dispositivo empieza a funcionar después de instalarlo y reiniciar el equipo (o desconectarlo y volver a conectarlo).",+ "suggest.firmware.bluetooth.title": "Firmware de Bluetooth",+ "suggest.firmware.bluetooth.unavailable": "{packages} está en el componente {component} de Debian, que no está habilitado en los orígenes de paquetes de este equipo.",+ "suggest.firmware.bluetooth.why": "Tu dispositivo Bluetooth pidió un firmware que no está instalado ({files}).",+ "suggest.firmware.graphics.detail": "{packages} lo trae. El dispositivo empieza a funcionar después de instalarlo y reiniciar el equipo (o desconectarlo y volver a conectarlo).",+ "suggest.firmware.graphics.title": "Firmware de gráficos",+ "suggest.firmware.graphics.unavailable": "{packages} está en el componente {component} de Debian, que no está habilitado en los orígenes de paquetes de este equipo.",+ "suggest.firmware.graphics.why": "Tu placa de video pidió un firmware que no está instalado ({files}).",+ "suggest.firmware.network.detail": "{packages} lo trae. El dispositivo empieza a funcionar después de instalarlo y reiniciar el equipo (o desconectarlo y volver a conectarlo).",+ "suggest.firmware.network.title": "Firmware del adaptador de red",+ "suggest.firmware.network.unavailable": "{packages} está en el componente {component} de Debian, que no está habilitado en los orígenes de paquetes de este equipo.",+ "suggest.firmware.network.why": "Tu adaptador de red pidió un firmware que no está instalado ({files}).",+ "suggest.firmware.other.detail": "{packages} lo trae. El dispositivo empieza a funcionar después de instalarlo y reiniciar el equipo (o desconectarlo y volver a conectarlo).",+ "suggest.firmware.other.title": "Firmware de un dispositivo",+ "suggest.firmware.other.unavailable": "{packages} está en el componente {component} de Debian, que no está habilitado en los orígenes de paquetes de este equipo.",+ "suggest.firmware.other.why": "Un dispositivo pidió un firmware que no está instalado ({files}).",+ "suggest.firmware.wifi.detail": "{packages} lo trae. El dispositivo empieza a funcionar después de instalarlo y reiniciar el equipo (o desconectarlo y volver a conectarlo).",+ "suggest.firmware.wifi.title": "Firmware de Wi-Fi",+ "suggest.firmware.wifi.unavailable": "{packages} está en el componente {component} de Debian, que no está habilitado en los orígenes de paquetes de este equipo.",+ "suggest.firmware.wifi.why": "Tu dispositivo Wi-Fi pidió un firmware que no está instalado ({files}).",+ "suggest.fixture": "Datos de prueba",+ "suggest.installNonfree": "Revisar e instalar",+ "suggest.ippUsb.detail": "{packages} hace que aparezca como una impresora y un escáner de red.",+ "suggest.ippUsb.title": "Imprimir y escanear por USB sin drivers",+ "suggest.ippUsb.unavailable": "{packages} no está en los orígenes de paquetes de este equipo.",+ "suggest.ippUsb.why": "Detectamos una impresora USB que puede imprimir y escanear sin driver del fabricante (IPP por USB).",+ "suggest.job": "Instalando {name}",+ "suggest.nonfreeBadge": "No es software libre",+ "suggest.note.firmware": "El firmware es un pequeño programa que corre dentro del propio dispositivo, no en el procesador del equipo; su licencia no permite modificarlo.",+ "suggest.note.nonfree": "No es software libre: viene del componente {component} de Debian, con la licencia de su fabricante.",+ "suggest.notify.body": {+ "one": "{name} y {count} más. Miralas en la Tienda.",+ "other": "{name} y {count} más. Miralas en la Tienda."+ },+ "suggest.notify.open": "Abrir la Tienda",+ "suggest.notify.title": {+ "one": "Una sugerencia para tu equipo",+ "other": "{count} sugerencias para tu equipo"+ },+ "suggest.nvidiaDriver.detail": "Ahora usa nouveau, el driver libre que viene con LordOS. El driver del fabricante ({packages}) suele dar mejor rendimiento 3D y mejor manejo de energía.",+ "suggest.nvidiaDriver.note.nouveau": "Hasta que lo instales se sigue usando el driver libre nouveau; si quitás el paquete, se vuelve a él.",+ "suggest.nvidiaDriver.note.older": "Las placas anteriores a 2014, aproximadamente, no son compatibles con esta versión del driver; en ellas conviene seguir con el driver libre. El escritorio de LordOS todavía no se probó con este driver.",+ "suggest.nvidiaDriver.note.secureBoot": "El driver se compila para tu kernel en este equipo (DKMS) y de nuevo después de cada actualización del kernel. Con el Arranque seguro activado, tenés que registrar su clave de firma en el próximo reinicio, o el driver no carga.",+ "suggest.nvidiaDriver.title": "Driver gráfico propietario",+ "suggest.nvidiaDriver.unavailable": "El driver del fabricante necesita los componentes contrib y non-free de Debian, y no están los dos habilitados en los orígenes de paquetes de este equipo. El driver libre, nouveau, sigue funcionando.",+ "suggest.nvidiaDriver.why": "Detectamos una placa de video NVIDIA.",+ "suggest.printer.detail": "{packages} agrega el driver de {vendor} al sistema de impresión. Muchas impresoras también funcionan sin él.",+ "suggest.printer.title": "Driver de impresora {vendor}",+ "suggest.printer.unavailable": "{packages} no está en los orígenes de paquetes de este equipo.",+ "suggest.printer.why": "Detectamos una impresora {vendor} conectada por USB.",+ "suggest.qemuAgent.detail": "{packages} permite que el anfitrión apague LordOS de forma ordenada, pause las escrituras en disco para copias de seguridad consistentes y vea la dirección de red.",+ "suggest.qemuAgent.title": "Agente de invitado para esta máquina virtual",+ "suggest.qemuAgent.unavailable": "{packages} no está en los orígenes de paquetes de este equipo.",+ "suggest.qemuAgent.why": "Detectamos una máquina virtual con un canal de agente de invitado.",+ "suggest.rpi5Tools.detail": "{packages}: actualizaciones del cargador de arranque (EEPROM), herramientas de la placa como vcgencmd y pinctrl, y herramientas de línea de comandos para los pines GPIO.",+ "suggest.rpi5Tools.title": "Herramientas de la Raspberry Pi",+ "suggest.rpi5Tools.unavailable": "Estas herramientas no están en los orígenes de paquetes de este equipo.",+ "suggest.rpi5Tools.why": "Detectamos una Raspberry Pi 5.",+ "suggest.scanner.detail": "{packages} permite que las apps de escaneo lo usen.",+ "suggest.scanner.title": "Driver de escáner {vendor}",+ "suggest.scanner.unavailable": "{packages} no está en los orígenes de paquetes de este equipo.",+ "suggest.scanner.why": "Detectamos un escáner {vendor} conectado por USB.",+ "suggest.subtitle": "Paquetes para el hardware que LordOS encontró en este equipo. La detección se hace solo en este equipo: no se envía nada a ningún lado.",+ "suggest.title": "Sugeridas para tu equipo",+ "suggest.virtualboxGuest.detail": "{packages} agrega carpetas compartidas y sincronización de la hora con el anfitrión.",+ "suggest.virtualboxGuest.title": "Utilidades de invitado para esta máquina virtual",+ "suggest.virtualboxGuest.unavailable": "Sus utilidades de invitado ({packages}) no forman parte de Debian 13, así que LordOS no puede ofrecerlas. El kernel ya incluye los drivers de invitado para la pantalla y las carpetas compartidas; para la mejor pantalla, elegí el controlador gráfico VMSVGA en la configuración de la máquina virtual.",+ "suggest.virtualboxGuest.why": "Detectamos una máquina virtual de VirtualBox.",+ "suggest.vmwareTools.detail": "{packages} permite que el anfitrión apague o reinicie LordOS de forma ordenada, mantiene la hora sincronizada e informa la dirección de red. El portapapeles compartido y el ajuste automático de la resolución llegarán cuando LordOS los admita.",+ "suggest.vmwareTools.title": "Herramientas de invitado para esta máquina virtual",+ "suggest.vmwareTools.unavailable": "{packages} no está en los orígenes de paquetes de este equipo.",+ "suggest.vmwareTools.why": "Detectamos una máquina virtual de VMware.",+ "suggest.whatChanges": "Qué cambia"}diff --git a/assets/locales/pt/errors.json b/assets/locales/pt/errors.jsonindex 0543704..fc7fe0e 100644--- a/assets/locales/pt/errors.json+++ b/assets/locales/pt/errors.json@@ -558,5 +558,6 @@"proc.denied": "Sem permissão para parar este processo","proc.failed": "Não foi possível parar o processo","proc.badArgument": "Pedido de processo inválido",- "proc.notOwn": "Este processo pertence a outro usuário"+ "proc.notOwn": "Este processo pertence a outro usuário",+ "hw.noKernelLog": "Não foi possível ler o registro do kernel"}diff --git a/assets/locales/pt/status.json b/assets/locales/pt/status.jsonindex 398472f..a4fac18 100644--- a/assets/locales/pt/status.json+++ b/assets/locales/pt/status.json@@ -119,5 +119,6 @@"hw.caseSet": "Gabinete: {case}","ssh.off": "Login remoto desativado","ssh.on": "Login remoto ativado",- "ssh.saved": "Configurações salvas"+ "ssh.saved": "Configurações salvas",+ "hw.firmwareChecked": "Firmware verificado"}diff --git a/assets/locales/pt/store.json b/assets/locales/pt/store.jsonindex a873f35..9e50c88 100644--- a/assets/locales/pt/store.json+++ b/assets/locales/pt/store.json@@ -148,5 +148,80 @@"other": "Atualizações do Debian ({count})"},"updates.auto": "Procurar atualizações automaticamente",- "updates.autoHint": "Uma vez por dia, e só para avisar. Nada é instalado sem perguntar."+ "updates.autoHint": "Uma vez por dia, e só para avisar. Nada é instalado sem perguntar.",+ "suggest.confirmNonfree": "Isto não é software livre: o código-fonte não está disponível e o Debian não pode corrigi-lo nem auditá-lo. Você pode removê-lo depois como qualquer outro pacote.",+ "suggest.dismiss": "Não sugerir de novo",+ "suggest.firmware.bluetooth.detail": "{packages} o contém. O dispositivo começa a funcionar depois de instalá-lo e reiniciar o computador (ou desconectá-lo e conectá-lo de novo).",+ "suggest.firmware.bluetooth.title": "Firmware de Bluetooth",+ "suggest.firmware.bluetooth.unavailable": "{packages} está no componente {component} do Debian, que não está habilitado nas fontes de pacotes deste computador.",+ "suggest.firmware.bluetooth.why": "Seu dispositivo Bluetooth pediu um firmware que não está instalado ({files}).",+ "suggest.firmware.graphics.detail": "{packages} o contém. O dispositivo começa a funcionar depois de instalá-lo e reiniciar o computador (ou desconectá-lo e conectá-lo de novo).",+ "suggest.firmware.graphics.title": "Firmware de gráficos",+ "suggest.firmware.graphics.unavailable": "{packages} está no componente {component} do Debian, que não está habilitado nas fontes de pacotes deste computador.",+ "suggest.firmware.graphics.why": "Sua placa de vídeo pediu um firmware que não está instalado ({files}).",+ "suggest.firmware.network.detail": "{packages} o contém. O dispositivo começa a funcionar depois de instalá-lo e reiniciar o computador (ou desconectá-lo e conectá-lo de novo).",+ "suggest.firmware.network.title": "Firmware do adaptador de rede",+ "suggest.firmware.network.unavailable": "{packages} está no componente {component} do Debian, que não está habilitado nas fontes de pacotes deste computador.",+ "suggest.firmware.network.why": "Seu adaptador de rede pediu um firmware que não está instalado ({files}).",+ "suggest.firmware.other.detail": "{packages} o contém. O dispositivo começa a funcionar depois de instalá-lo e reiniciar o computador (ou desconectá-lo e conectá-lo de novo).",+ "suggest.firmware.other.title": "Firmware de um dispositivo",+ "suggest.firmware.other.unavailable": "{packages} está no componente {component} do Debian, que não está habilitado nas fontes de pacotes deste computador.",+ "suggest.firmware.other.why": "Um dispositivo pediu um firmware que não está instalado ({files}).",+ "suggest.firmware.wifi.detail": "{packages} o contém. O dispositivo começa a funcionar depois de instalá-lo e reiniciar o computador (ou desconectá-lo e conectá-lo de novo).",+ "suggest.firmware.wifi.title": "Firmware de Wi-Fi",+ "suggest.firmware.wifi.unavailable": "{packages} está no componente {component} do Debian, que não está habilitado nas fontes de pacotes deste computador.",+ "suggest.firmware.wifi.why": "Seu dispositivo Wi-Fi pediu um firmware que não está instalado ({files}).",+ "suggest.fixture": "Dados de teste",+ "suggest.installNonfree": "Revisar e instalar",+ "suggest.ippUsb.detail": "{packages} faz com que ela apareça como uma impressora e um scanner de rede.",+ "suggest.ippUsb.title": "Imprimir e digitalizar por USB sem drivers",+ "suggest.ippUsb.unavailable": "{packages} não está nas fontes de pacotes deste computador.",+ "suggest.ippUsb.why": "Detectamos uma impressora USB que pode imprimir e digitalizar sem driver do fabricante (IPP por USB).",+ "suggest.job": "Instalando {name}",+ "suggest.nonfreeBadge": "Não é software livre",+ "suggest.note.firmware": "Firmware é um pequeno programa que roda dentro do próprio dispositivo, não no processador do computador; a licença não permite modificá-lo.",+ "suggest.note.nonfree": "Não é software livre: vem do componente {component} do Debian, com a licença do fabricante.",+ "suggest.notify.body": {+ "one": "{name} e mais {count}. Veja na Loja.",+ "other": "{name} e mais {count}. Veja na Loja."+ },+ "suggest.notify.open": "Abrir a Loja",+ "suggest.notify.title": {+ "one": "Uma sugestão para o seu computador",+ "other": "{count} sugestões para o seu computador"+ },+ "suggest.nvidiaDriver.detail": "Agora ela usa o nouveau, o driver livre incluído no LordOS. O driver do fabricante ({packages}) costuma dar melhor desempenho 3D e melhor gerenciamento de energia.",+ "suggest.nvidiaDriver.note.nouveau": "Até você instalá-lo, o driver livre nouveau continua em uso; remover o pacote volta para ele.",+ "suggest.nvidiaDriver.note.older": "Placas anteriores a cerca de 2014 não são suportadas por esta versão do driver; nelas, mantenha o driver livre. O desktop do LordOS ainda não foi testado com este driver.",+ "suggest.nvidiaDriver.note.secureBoot": "O driver é compilado para o seu kernel neste computador (DKMS) e de novo após cada atualização do kernel. Com a Inicialização segura ativada, você precisa registrar a chave de assinatura dele na próxima reinicialização, ou o driver não carrega.",+ "suggest.nvidiaDriver.title": "Driver gráfico proprietário",+ "suggest.nvidiaDriver.unavailable": "O driver do fabricante precisa dos componentes contrib e non-free do Debian, e os dois não estão habilitados nas fontes de pacotes deste computador. O driver livre, nouveau, continua funcionando.",+ "suggest.nvidiaDriver.why": "Detectamos uma placa de vídeo NVIDIA.",+ "suggest.printer.detail": "{packages} adiciona o driver da {vendor} ao sistema de impressão. Muitas impressoras também funcionam sem ele.",+ "suggest.printer.title": "Driver de impressora {vendor}",+ "suggest.printer.unavailable": "{packages} não está nas fontes de pacotes deste computador.",+ "suggest.printer.why": "Detectamos uma impressora {vendor} conectada por USB.",+ "suggest.qemuAgent.detail": "{packages} permite que o hospedeiro desligue o LordOS de forma limpa, pause as gravações em disco para backups consistentes e veja o endereço de rede.",+ "suggest.qemuAgent.title": "Agente de convidado para esta máquina virtual",+ "suggest.qemuAgent.unavailable": "{packages} não está nas fontes de pacotes deste computador.",+ "suggest.qemuAgent.why": "Detectamos uma máquina virtual com um canal de agente de convidado.",+ "suggest.rpi5Tools.detail": "{packages}: atualizações do carregador de inicialização (EEPROM), ferramentas da placa como vcgencmd e pinctrl, e ferramentas de linha de comando para os pinos GPIO.",+ "suggest.rpi5Tools.title": "Ferramentas do Raspberry Pi",+ "suggest.rpi5Tools.unavailable": "Estas ferramentas não estão nas fontes de pacotes deste computador.",+ "suggest.rpi5Tools.why": "Detectamos um Raspberry Pi 5.",+ "suggest.scanner.detail": "{packages} permite que os apps de digitalização o usem.",+ "suggest.scanner.title": "Driver de scanner {vendor}",+ "suggest.scanner.unavailable": "{packages} não está nas fontes de pacotes deste computador.",+ "suggest.scanner.why": "Detectamos um scanner {vendor} conectado por USB.",+ "suggest.subtitle": "Pacotes para o hardware que o LordOS encontrou neste computador. A detecção acontece só neste computador: nada é enviado para lugar nenhum.",+ "suggest.title": "Sugeridos para o seu computador",+ "suggest.virtualboxGuest.detail": "{packages} adiciona pastas compartilhadas e sincronização do relógio com o hospedeiro.",+ "suggest.virtualboxGuest.title": "Utilitários de convidado para esta máquina virtual",+ "suggest.virtualboxGuest.unavailable": "Os utilitários de convidado ({packages}) não fazem parte do Debian 13, então o LordOS não pode oferecê-los. O kernel já inclui os drivers de convidado para a tela e as pastas compartilhadas; para a melhor tela, escolha o controlador gráfico VMSVGA nas configurações da máquina virtual.",+ "suggest.virtualboxGuest.why": "Detectamos uma máquina virtual VirtualBox.",+ "suggest.vmwareTools.detail": "{packages} permite que o hospedeiro desligue ou reinicie o LordOS de forma limpa, mantém o relógio sincronizado e informa o endereço de rede. A área de transferência compartilhada e o redimensionamento automático virão quando o LordOS os suportar.",+ "suggest.vmwareTools.title": "Ferramentas de convidado para esta máquina virtual",+ "suggest.vmwareTools.unavailable": "{packages} não está nas fontes de pacotes deste computador.",+ "suggest.vmwareTools.why": "Detectamos uma máquina virtual VMware.",+ "suggest.whatChanges": "O que muda"}diff --git a/assets/store/suggestions.json b/assets/store/suggestions.jsonnew file mode 100644index 0000000..0862ad0--- /dev/null+++ b/assets/store/suggestions.json@@ -0,0 +1,90 @@+{+ "version": 1,+ "about": "Store -> Discover, 'Suggested for your computer': which Debian packages to offer for the detected hardware (sdk/suggestengine.js, docs/PACKAGES.md). Texts live in assets/locales/<lang>/store.json under suggest.<id>.*. Every package named here is checked against the package index before it is offered.",+ "rules": [+ {+ "id": "vmwareTools",+ "when": { "any": [ { "dmi": { "sysVendor": ["VMware, Inc."] } }, { "pci": { "vendor": ["15ad"] } } ] },+ "packages": ["open-vm-tools"],+ "free": true,+ "icon": "vm"+ },+ {+ "id": "qemuAgent",+ "when": { "virtio": ["org.qemu.guest_agent.0"] },+ "packages": ["qemu-guest-agent"],+ "free": true,+ "icon": "vm"+ },+ {+ "id": "virtualboxGuest",+ "when": { "any": [ { "dmi": { "productName": ["VirtualBox"] } }, { "pci": { "vendor": ["80ee"], "device": ["cafe"] } } ] },+ "packages": ["virtualbox-guest-utils"],+ "free": true,+ "icon": "vm",+ "ifUnavailable": "explain"+ },+ {+ "id": "nvidiaDriver",+ "when": { "all": [ { "arch": ["x86_64"] }, { "pci": { "vendor": ["10de"], "class": ["0300", "0302", "0380"] } } ] },+ "packages": ["linux-headers-amd64", "nvidia-driver", "firmware-misc-nonfree"],+ "installedWhen": ["nvidia-driver"],+ "free": false,+ "component": "non-free",+ "notes": ["nonfree", "nouveau", "secureBoot", "older"],+ "icon": "gpu",+ "ifUnavailable": "explain"+ },+ {+ "id": "rpi5Tools",+ "when": { "compatible": ["raspberrypi,5-model-b", "raspberrypi,500", "raspberrypi,5-compute-module"] },+ "packages": ["rpi-eeprom", "raspi-utils", "gpiod"],+ "require": "any",+ "free": true,+ "icon": "board"+ }+ ],+ "usb": {+ "about": "USB printers (an interface of class 07) and scanners (udev's libsane rules mark them) by vendor ID. Only drivers Debian ships; vendors not listed get nothing (most printers work driverless with CUPS).",+ "vendors": {+ "03f0": { "name": "HP", "printer": ["hplip"], "scanner": ["libsane-hpaio"] },+ "04b8": { "name": "Epson", "printer": ["printer-driver-escpr"] },+ "04f9": { "name": "Brother", "printer": ["printer-driver-brlaser"] },+ "04e8": { "name": "Samsung", "printer": ["printer-driver-splix"] },+ "04a9": { "name": "Canon", "printer": ["printer-driver-gutenprint"] }+ },+ "ippUsb": ["ipp-usb"]+ },+ "firmware": {+ "about": "Firmware files a driver asked for and the kernel didn't find, by path prefix, mapped to the Debian package that ships them (checked against trixie's non-free-firmware Contents). The first matching prefix wins; files no prefix matches get no suggestion.",+ "component": "non-free-firmware",+ "map": [+ { "prefix": "iwlwifi-", "package": "firmware-iwlwifi", "kind": "wifi" },+ { "prefix": "intel/ibt-", "package": "firmware-iwlwifi", "kind": "bluetooth" },+ { "prefix": "rtl_bt/", "package": "firmware-realtek", "kind": "bluetooth" },+ { "prefix": "rtw88/", "package": "firmware-realtek", "kind": "wifi" },+ { "prefix": "rtw89/", "package": "firmware-realtek", "kind": "wifi" },+ { "prefix": "rtlwifi/", "package": "firmware-realtek", "kind": "wifi" },+ { "prefix": "rtl_nic/", "package": "firmware-realtek", "kind": "network" },+ { "prefix": "ath10k/", "package": "firmware-atheros", "kind": "wifi" },+ { "prefix": "ath11k/", "package": "firmware-atheros", "kind": "wifi" },+ { "prefix": "ath12k/", "package": "firmware-atheros", "kind": "wifi" },+ { "prefix": "htc_", "package": "firmware-atheros", "kind": "wifi" },+ { "prefix": "ath6k/", "package": "firmware-atheros", "kind": "wifi" },+ { "prefix": "ar3k/", "package": "firmware-atheros", "kind": "bluetooth" },+ { "prefix": "qca/", "package": "firmware-atheros", "kind": "bluetooth" },+ { "prefix": "brcm/brcmfmac", "package": "firmware-brcm80211", "kind": "wifi" },+ { "prefix": "brcm/BCM-", "package": "firmware-misc-nonfree", "kind": "bluetooth" },+ { "prefix": "brcm/BCM", "package": "bluez-firmware", "kind": "bluetooth" },+ { "prefix": "mediatek/", "package": "firmware-mediatek", "kind": "wifi" },+ { "prefix": "mt76", "package": "firmware-mediatek", "kind": "wifi" },+ { "prefix": "mrvl/", "package": "firmware-libertas", "kind": "wifi" },+ { "prefix": "libertas/", "package": "firmware-libertas", "kind": "wifi" },+ { "prefix": "amdgpu/", "package": "firmware-amd-graphics", "kind": "graphics" },+ { "prefix": "radeon/", "package": "firmware-amd-graphics", "kind": "graphics" },+ { "prefix": "i915/", "package": "firmware-intel-graphics", "kind": "graphics" },+ { "prefix": "xe/", "package": "firmware-intel-graphics", "kind": "graphics" },+ { "prefix": "nvidia/", "package": "firmware-nvidia-graphics", "kind": "graphics" }+ ]+ }+}diff --git a/sdk/index.js b/sdk/index.jsindex 8827657..9c4bf58 100644--- a/sdk/index.js+++ b/sdk/index.js@@ -90,6 +90,8 @@ export { media, useMedia, usePlayer, nowPlaying, useNowPlaying, NowPlayingTile,export { disks, useDisks } from './disks.js';export { backup, useBackup, backupStatus } from './backup.js'; // Backups (docs/SYSTEM.md)export { lordosUpdate, restartNeeded, updatePrefs, setUpdatePrefs, UPDATE_DEFAULTS } from './updates.js'; // updating LordOS in place (docs/UPDATES.md)+// Store → Discover, "Suggested for your computer": packages for the detected hardware (docs/PACKAGES.md)+export { suggestions, refreshSuggestions, reevaluate as reevaluateSuggestions, dismissSuggestion, markSuggestionsSeen, unseenSuggestions } from './suggestions.js';export { vaultAvailable, vaultRequest, onVaultEvent, keyring, autofill, autofillReveal, KeyringPrompt, AutofillButton } from './vault.js'; // Passwords and keyring (docs/PASSWORDS.md)import { KeyringPrompt } from './vault.js';// Mail, Calendar, Contacts and Reminders through the sandboxed helper lord-maild (docs/MAIL.md)diff --git a/sdk/suggestengine.js b/sdk/suggestengine.jsnew file mode 100644index 0000000..74e10b3--- /dev/null+++ b/sdk/suggestengine.js@@ -0,0 +1,195 @@+// suggestengine.js — the rules of the Store's "Suggested for your computer" (pure functions, no+// `lord`, tested by server/tests/suggest_engine_test.mjs). The rules are data:+// assets/store/suggestions.json; the hardware facts come from lord.hwinfo.scan() (hw/hwscan.c) and+// the package state from lord.pkg.info(). See docs/PACKAGES.md, "Suggested for your computer".+//+// evaluate(data, facts, { info, dismissed, check }) → [Suggestion], most useful first+// firmwareFromLog(lines) → [{ file, driver }] from hw-firmware-missing's LOG lines+// fresh(list, notified) → the installable ones not notified yet+//+// Suggestion = { id, text, params, packages, install, state, free, component, notes, icon }+// id stable key ("nvidiaDriver", "printer:03f0", "firmware:firmware-realtek"), used to+// dismiss it and to notify once+// text the locale key under store.suggest.* for its title and reason ("nvidiaDriver",+// "printer", "firmware.wifi")+// state 'install' (install lists what is missing), 'installed', or 'unavailable' (the+// packages are not in the configured sources: the card explains why)+// Nothing here downloads, runs or sends anything.++const HEX4 = /^[0-9a-f]{4}$/;+const PKG = /^[a-z0-9][a-z0-9+.-]+$/;++const arr = (v) => (Array.isArray(v) ? v : []);+const str = (v) => (typeof v === 'string' ? v : '');++// ---- conditions ----++function matchPci(dev, want) {+ if (want.vendor && !arr(want.vendor).includes(str(dev.vendor))) return false;+ if (want.device && !arr(want.device).includes(str(dev.device))) return false;+ if (want.class && !arr(want.class).some((p) => str(dev.class).startsWith(p))) return false;+ return true;+}++// One condition of a rule's "when" against the facts.+export function matches(cond, facts) {+ if (!cond || typeof cond !== 'object') return false;+ const keys = Object.keys(cond);+ if (keys.length !== 1) return keys.length > 1 && keys.every((k) => matches({ [k]: cond[k] }, facts));+ const [k] = keys;+ const v = cond[k];+ switch (k) {+ case 'any': return arr(v).some((c) => matches(c, facts));+ case 'all': return arr(v).length > 0 && arr(v).every((c) => matches(c, facts));+ case 'dmi': return Object.entries(v || {}).every(([f, vals]) => arr(vals).includes(str(facts.dmi?.[f])));+ case 'pci': return arr(facts.pci).some((d) => matchPci(d, v || {}));+ case 'virtio': return arr(facts.virtio).some((n) => arr(v).includes(n));+ case 'compatible': return arr(facts.compatible).some((n) => arr(v).includes(n));+ case 'arch': return arr(v).includes(str(facts.arch));+ default: return false; // an unknown condition never matches+ }+}++// ---- package state ----++// state of a list of packages: which are known to the index, installed, and what to install.+function pkgState(names, info) {+ const known = [], missing = [], installed = [];+ for (const n of names) {+ const i = PKG.test(n) ? info(n) : null;+ if (!i) { missing.push(n); continue; }+ known.push(n);+ if (i.installed) installed.push(n);+ }+ return { known, missing, installed, install: known.filter((n) => !installed.includes(n)) };+}++// A suggestion from a list of packages: require 'all' (each must exist) or 'any' (those that exist).+function build(base, names, info, { require = 'all', installedWhen = null, ifUnavailable = 'hide', check = null } = {}) {+ const st = pkgState(names, info);+ const whenNames = installedWhen ? arr(installedWhen) : names;+ const doneByKey = installedWhen ? whenNames.every((n) => st.installed.includes(n)) : false;+ let state;+ if (doneByKey || (st.known.length && !st.install.length && (require === 'any' || !st.missing.length))) state = 'installed';+ else if (require === 'all' ? st.missing.length > 0 : st.known.length === 0) state = 'unavailable';+ else state = 'install';+ // every package exists, but the plan can't be made (a dependency in a component that isn't enabled)+ if (state === 'install' && check && !check(st.install)) state = 'unavailable';+ if (state === 'unavailable' && ifUnavailable !== 'explain') return null;+ return {+ ...base,+ packages: names,+ install: state === 'install' ? st.install : [],+ missing: st.missing.length || state !== 'unavailable' ? st.missing : st.install,+ state,+ };+}++// ---- the kinds of suggestion ----++function ruleSuggestions(data, facts, info, check) {+ const out = [];+ for (const r of arr(data.rules)) {+ if (!r || typeof r.id !== 'string' || !matches(r.when, facts)) continue;+ const s = build({+ id: r.id, text: r.id, params: {}, free: r.free !== false, component: str(r.component),+ notes: arr(r.notes), icon: str(r.icon) || 'package',+ }, arr(r.packages), info, { require: r.require, installedWhen: r.installedWhen, ifUnavailable: r.ifUnavailable, check });+ if (s) out.push(s);+ }+ return out;+}++const ifaceClass = (i) => str(i).slice(0, 2);++function usbSuggestions(data, facts, info, check) {+ const out = [];+ const vendors = data.usb?.vendors || {};+ const seen = new Set();+ let ipp = false;+ for (const d of arr(facts.usb)) {+ const vendor = str(d.vendor);+ if (!HEX4.test(vendor)) continue;+ const ifaces = arr(d.ifaces);+ const printer = ifaces.some((i) => ifaceClass(i) === '07');+ if (ifaces.includes('070104')) ipp = true; // IPP over USB (driverless printing and scanning)+ const v = vendors[vendor];+ if (!v) continue;+ const add = (kind, names) => {+ const id = `${kind}:${vendor}`;+ if (!arr(names).length || seen.has(id)) return;+ seen.add(id);+ const s = build({ id, text: kind, params: { vendor: str(v.name) }, free: true, component: '', notes: [], icon: kind },+ arr(names), info, { check });+ if (s) out.push(s);+ };+ if (printer) add('printer', v.printer);+ if (d.sane === true) add('scanner', v.scanner);+ }+ if (ipp && arr(data.usb?.ippUsb).length) {+ const s = build({ id: 'ippUsb', text: 'ippUsb', params: {}, free: true, component: '', notes: [], icon: 'printer' },+ arr(data.usb.ippUsb), info, { check });+ if (s) out.push(s);+ }+ return out;+}++function firmwarePackage(map, file) {+ return arr(map).find((m) => m && typeof m.prefix === 'string' && m.prefix && file.startsWith(m.prefix)) || null;+}++function firmwareSuggestions(data, facts, info, check) {+ const fw = data.firmware || {};+ const groups = new Map(); // package → { kind, files, drivers }+ for (const m of arr(facts.firmware?.missing)) {+ const file = str(m.file);+ const hit = file && firmwarePackage(fw.map, file);+ if (!hit || !PKG.test(hit.package)) continue;+ const g = groups.get(hit.package) || { kind: hit.kind, files: [], drivers: [] };+ if (!g.files.includes(file)) g.files.push(file);+ const drv = str(m.driver);+ if (drv && drv !== '-' && !g.drivers.includes(drv)) g.drivers.push(drv);+ groups.set(hit.package, g);+ }+ const out = [];+ for (const [pkg, g] of groups) {+ const i = info(pkg);+ if (i && i.installed) continue; // installed and still missing: nothing to offer+ const kind = ['wifi', 'bluetooth', 'network', 'graphics'].includes(g.kind) ? g.kind : 'other';+ const s = build({+ id: `firmware:${pkg}`, text: `firmware.${kind}`,+ params: { package: pkg, driver: g.drivers.join(', '), files: g.files.slice(0, 3).join(', '), count: g.files.length },+ free: false, component: str(fw.component) || 'non-free-firmware', notes: ['firmware'], icon: kind,+ }, [pkg], info, { ifUnavailable: 'explain', check });+ if (s) out.push(s);+ }+ return out;+}++const ORDER = { install: 0, unavailable: 1, installed: 2 };++// Every suggestion for these facts. info(name) → lord.pkg.info(name) (null: not in the index);+// check(names) → whether an install plan can be made (lord.pkg.plan(...).ok), optional.+export function evaluate(data, facts, { info = () => null, dismissed = [], check = null } = {}) {+ if (!data || !facts) return [];+ const no = new Set(arr(dismissed));+ const all = [...ruleSuggestions(data, facts, info, check), ...usbSuggestions(data, facts, info, check), ...firmwareSuggestions(data, facts, info, check)];+ return all.filter((s) => !no.has(s.id))+ .map((s, i) => [s, i]).sort((a, b) => ORDER[a[0].state] - ORDER[b[0].state] || a[1] - b[1]).map(([s]) => s);+}++// hw-firmware-missing's progress lines: "fw <file> <driver|->" (the root side already validated them).+export function firmwareFromLog(lines) {+ const out = [];+ for (const l of arr(lines)) {+ const m = /^fw ([A-Za-z0-9._+,\/-]{1,199}) ([A-Za-z0-9_-]{1,32})$/.exec(str(l));+ if (m && !m[1].includes('..') && !m[1].startsWith('/')) out.push({ file: m[1], driver: m[2] === '-' ? '' : m[2] });+ }+ return out;+}++// The installable suggestions not notified yet (the badge and the one-time notification).+export function fresh(list, notified = []) {+ const seen = new Set(arr(notified));+ return arr(list).filter((s) => s.state === 'install' && !seen.has(s.id));+}diff --git a/sdk/suggestions.js b/sdk/suggestions.jsnew file mode 100644index 0000000..08bd2df--- /dev/null+++ b/sdk/suggestions.js@@ -0,0 +1,113 @@+// suggestions.js — "Suggested for your computer" (Store → Discover; docs/PACKAGES.md).+//+// suggestions store { list, fixture, ready, scanning } (useStore(suggestions))+// refreshSuggestions({ firmware }) scans again (lord.hwinfo.scan; the kernel log through the+// read-only hw-firmware-missing action when the session can't read it)+// reevaluate() same facts, new package state (after an install)+// dismissSuggestion(id) "Don't suggest again"+// markSuggestionsSeen() the user has looked at Discover: the sidebar badge goes away+// unseenSuggestions() installable ones not looked at yet (the badge)+//+// Detection only reads the kernel's hardware files; the rules are data+// (assets/store/suggestions.json, sdk/suggestengine.js). Nothing is sent anywhere and nothing is+// installed without the user: Install goes through the Store's plan and pkg-install.+import { createStore } from './store.js';+import { settings } from './settings.js';+import { admin } from './admin.js';+import { notify } from './notify.js';+import { t } from './i18n.js';+import { wm } from './windows.js';+import { evaluate, firmwareFromLog, fresh } from './suggestengine.js';+import DATA from '../assets/store/suggestions.json';++const has = () => typeof lord !== 'undefined' && !!lord.hwinfo && !!lord.pkg;+const pkgReady = () => has() && lord.pkg.available();++export const SUGGEST_DEFAULTS = { dismissed: [], notified: [], seen: [] };+const prefs = (s = settings.get()) => ({ ...SUGGEST_DEFAULTS, ...(s.suggestions || {}) });+function setPrefs(patch) {+ settings.set((s) => ({ ...s, suggestions: { ...prefs(s), ...patch(prefs(s)) } }));+}++export const suggestions = createStore({ list: [], fixture: false, ready: false, scanning: false });+let facts = null;++const info = (name) => { try { return lord.pkg.info(name); } catch (e) { return null; } };+// an installable card only when its plan can be made (a dependency may live in a component that+// isn't enabled: nvidia-driver needs contrib as well as non-free)+const plannable = (names) => { try { return !!lord.pkg.plan({ install: names }).ok; } catch (e) { return true; } };++export function reevaluate() {+ if (!facts || !pkgReady()) { suggestions.set({ list: [], ready: !!facts }); return []; }+ const list = evaluate(DATA, facts, { info, check: plannable, dismissed: prefs().dismissed });+ suggestions.set({ list, fixture: !!facts.fixture, ready: true });+ return list;+}++// The kernel log through the root helper (only when the session can't read it, kernel.dmesg_restrict).+function firmwareViaHelper() {+ const lines = [];+ return admin.run('hw-firmware-missing', '', (l) => lines.push(l), { quiet: true })+ .then(() => firmwareFromLog(lines), () => null);+}++let running = null;+export function refreshSuggestions({ firmware = true } = {}) {+ if (!has()) return Promise.resolve([]);+ if (running) return running;+ suggestions.set({ scanning: true });+ running = (async () => {+ let f = null;+ try { f = lord.hwinfo.scan(); } catch (e) { f = null; }+ if (f && !f.fixture && f.firmware && !f.firmware.readable && firmware && admin.available()) {+ const missing = await firmwareViaHelper();+ if (missing) f.firmware = { readable: true, missing };+ }+ facts = f;+ return reevaluate();+ })().finally(() => { running = null; suggestions.set({ scanning: false }); });+ return running;+}++export function dismissSuggestion(id) {+ setPrefs((p) => ({ dismissed: [...new Set([...p.dismissed, String(id)])].slice(-200) }));+ reevaluate();+}++export function unseenSuggestions(list = suggestions.get().list) {+ return fresh(list, prefs().seen);+}++export function markSuggestionsSeen(list = suggestions.get().list) {+ const ids = list.filter((s) => s.state === 'install').map((s) => s.id);+ const p = prefs();+ if (ids.every((id) => p.seen.includes(id))) return;+ setPrefs((q) => ({ seen: [...new Set([...q.seen, ...ids])].slice(-200), notified: [...new Set([...q.notified, ...ids])].slice(-200) }));+}++// ---- once per new suggestion: a notification (only in a user's desktop session) ----++function maybeNotify(list) {+ const p = prefs();+ const news = fresh(list, p.notified);+ if (!news.length) return;+ setPrefs((q) => ({ notified: [...new Set([...q.notified, ...news.map((s) => s.id)])].slice(-200) }));+ const first = t(`store.suggest.${news[0].text}.title`, news[0].params);+ notify({+ app: 'store',+ title: t('store.suggest.notify.title', { count: news.length }),+ body: news.length === 1 ? first : t('store.suggest.notify.body', { name: first, count: news.length - 1 }),+ actions: [{ id: 'open', label: t('store.suggest.notify.open'), run: () => wm.open('store', { args: { page: 'discover' } }) }],+ });+}++function check() {+ if (!pkgReady()) return;+ refreshSuggestions().then(maybeNotify, () => {});+}++if (has() && typeof lord.admin !== 'undefined' && typeof lord.greeter === 'undefined') {+ // a while after login (the desktop first), then every 6 hours (a new device, firmware installed…)+ setTimeout(() => { check(); setInterval(check, 6 * 3600 * 1000); }, 3 * 60 * 1000);+ admin.onEvent((text) => { if (text === 'pkg changed' && facts) reevaluate(); });+}diff --git a/server/mk/settings.mk b/server/mk/settings.mkindex 7076245..9c708c0 100644--- a/server/mk/settings.mk+++ b/server/mk/settings.mk@@ -2,7 +2,7 @@# Bluetooth (BlueZ over our own D-Bus client), battery and power, date and time, default apps.# Objects are added to lord-server as extra prerequisites ($^ in its link rule takes them).HW_SRC := src/hw/edid.c src/hw/modes.c src/hw/night.c src/hw/mimeapps.c src/hw/power.c src/hw/jbuf.c src/hw/display.c \- src/hw/uevent.c src/hw/sysbus.c src/hw/bt.c src/hw/ppd.c src/hw/hw.c src/hw/hw_admin.c src/hw/defaults.c src/hw/notifyd.c src/ui/js_hw.c \+ src/hw/uevent.c src/hw/sysbus.c src/hw/bt.c src/hw/ppd.c src/hw/hw.c src/hw/hw_admin.c src/hw/defaults.c src/hw/notifyd.c src/hw/hwscan.c src/ui/js_hw.c \src/ui/js_fan.c src/fan/fancurve.cHW_HDR := $(wildcard src/hw/*.h) $(wildcard src/fan/*.h) src/ui/js_hw.h src/ui/js_fan.h src/kms.h src/vault/dbus.hHW_OBJ := $(HW_SRC:src/%.c=build/obj/%.o)@@ -11,9 +11,9 @@ build/lord-server: $(HW_OBJ)# pure parts: EDID, mode selection, gamma/temperature/sun math, mimeapps.list and globs2, power_supply,# and the admin actions' validatorstest: build/settings-hw-test-build/settings-hw-test: tests/settings_hw_test.c src/hw/edid.c src/hw/modes.c src/hw/night.c src/hw/mimeapps.c src/hw/power.c src/hw/hw_admin.c src/sec/json.c $(HW_HDR)+build/settings-hw-test: tests/settings_hw_test.c src/hw/edid.c src/hw/modes.c src/hw/night.c src/hw/mimeapps.c src/hw/power.c src/hw/hw_admin.c src/hw/hwscan.c src/hw/jbuf.c src/sec/json.c $(HW_HDR)@mkdir -p build- $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/settings_hw_test.c src/hw/edid.c src/hw/modes.c src/hw/night.c src/hw/mimeapps.c src/hw/power.c src/hw/hw_admin.c src/sec/json.c -lm+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/settings_hw_test.c src/hw/edid.c src/hw/modes.c src/hw/night.c src/hw/mimeapps.c src/hw/power.c src/hw/hw_admin.c src/hw/hwscan.c src/hw/jbuf.c src/sec/json.c -lm./$@ || { rm -f $@; exit 1; }# BlueZ parsing (GetManagedObjects, PropertiesChanged, Battery1, paths, state JSON) without a bustest: build/bt-test@@ -22,3 +22,10 @@ build/bt-test: $(BT_TEST_SRC) $(HW_HDR)@mkdir -p build$(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ $(BT_TEST_SRC)./$@ || { rm -f $@; exit 1; }+# hardware facts for the Store's suggestions (hwscan.c) over fake sysfs/DMI/PCI/USB/kmsg trees;+# `build/hwscan-test dump [root]` prints the facts JSON of a tree (or of this machine)+test: build/hwscan-test+build/hwscan-test: tests/hwscan_test.c src/hw/hwscan.c src/hw/jbuf.c src/sec/json.c $(HW_HDR)+ @mkdir -p build+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/hwscan_test.c src/hw/hwscan.c src/hw/jbuf.c src/sec/json.c+ ./$@ || { rm -f $@; exit 1; }diff --git a/server/src/hw/hw_admin.c b/server/src/hw/hw_admin.cindex 8dc5e26..2dfa5af 100644--- a/server/src/hw/hw_admin.c+++ b/server/src/hw/hw_admin.c@@ -1,5 +1,6 @@/* hw_admin.c — Settings' admin actions (see hw_admin.h). Runs as root in the admin helper. */#include "hw_admin.h"+#include "hwscan.h"#include <ctype.h>#include <dirent.h>@@ -258,3 +259,23 @@ void hw_act_rpi_case(const AdminReq *r, const char *arg, size_t len) {if (!ok || rename(tmp, dst)) { unlink(tmp); admin_err("hw.caseFailed", "errno", lerr_errno(errno), NULL); return; }admin_ok("hw.caseSet", "case", id, NULL);}++/* ---- missing firmware (the Store's suggestions, hwscan.c) ---- */++/* Read-only: the session can't read the kernel log when kernel.dmesg_restrict=1. Takes no+ * argument and returns only firmware file names that pass hwscan_fw_name_valid() and the driver+ * name parsed from the same line (letters, digits, '_' and '-'), never other log text. */+void hw_act_firmware_missing(const AdminReq *r, const char *arg, size_t len) {+ (void)r; (void)arg;+ if (len) { admin_err("admin.invalidArgument", NULL); return; }+ size_t n;+ int denied;+ char *log = hwscan_read_kmsg("", &n, &denied);+ if (!log) { admin_err("hw.noKernelLog", NULL); return; }+ HwFwMiss m[HWSCAN_FW_MAX];+ int k = hwscan_fw_missing("", log, n, m, HWSCAN_FW_MAX);+ free(log);+ for (int i = 0; i < k; i++)+ admin_say("LOG", "fw %s %s", m[i].file, m[i].driver[0] ? m[i].driver : "-"); /* i18n-ok: protocol line parsed by sdk/suggestengine.js */+ admin_ok("hw.firmwareChecked", NULL);+}diff --git a/server/src/hw/hw_admin.h b/server/src/hw/hw_admin.hindex e4b4476..c9af648 100644--- a/server/src/hw/hw_admin.h+++ b/server/src/hw/hw_admin.h@@ -13,6 +13,10 @@* rpi-case none|argon-one-v5 Raspberry Pi 5 only: writes /boot/firmware/lordos-case.txt* (fixed text, included from config.txt; takes effect* after a restart) admin+ * hw-firmware-missing (no arguments) reads the kernel log (/dev/kmsg) and returns+ * only the validated names of firmware files a driver asked+ * for and that are still missing, as "LOG fw <file> <driver>"+ * lines (the Store's suggestions, hwscan.c); read-only anyone*/#ifndef LORD_HW_ADMIN_H#define LORD_HW_ADMIN_H@@ -27,6 +31,7 @@ void hw_act_ntp(const AdminReq *r, const char *arg, size_t len);void hw_act_time_set(const AdminReq *r, const char *arg, size_t len);void hw_act_bt_unblock(const AdminReq *r, const char *arg, size_t len);void hw_act_rpi_case(const AdminReq *r, const char *arg, size_t len);+void hw_act_firmware_missing(const AdminReq *r, const char *arg, size_t len);const char *hw_rpi_case_text(const char *id); /* fixed file text of a known case, NULL otherwise *//* Validators, exposed for tests. */@@ -42,6 +47,7 @@ int hw_backlight_name_valid(const char *n);{ "time-ntp", hw_act_ntp, 0 }, \{ "time-set", hw_act_time_set, 0 }, \{ "bt-unblock", hw_act_bt_unblock, A_ANYONE }, \- { "rpi-case", hw_act_rpi_case, 0 },+ { "rpi-case", hw_act_rpi_case, 0 }, \+ { "hw-firmware-missing", hw_act_firmware_missing, A_ANYONE },#endifdiff --git a/server/src/hw/hwscan.c b/server/src/hw/hwscan.cnew file mode 100644index 0000000..e5334d5--- /dev/null+++ b/server/src/hw/hwscan.c@@ -0,0 +1,430 @@+/* hwscan.c — read-only hardware facts for the Store's suggestions (see hwscan.h). */+#include "hwscan.h"+#include "jbuf.h"++#include <ctype.h>+#include <dirent.h>+#include <errno.h>+#include <fcntl.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/stat.h>+#include <sys/utsname.h>+#include <unistd.h>++#define KMSG_MAX (4u << 20)++/* <root><path> into out. */+static void rpath(char *out, size_t size, const char *root, const char *path) {+ snprintf(out, size, "%s%s", root ? root : "", path);+}++/* A small sysfs/proc file: its first line, trimmed, printable ASCII only ('\0' inside a device+ * tree string ends it). "" when missing. */+static void read_attr(const char *path, char *out, size_t size) {+ out[0] = 0;+ int fd = open(path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);+ if (fd < 0) return;+ char buf[256];+ ssize_t n = read(fd, buf, sizeof buf - 1);+ close(fd);+ if (n <= 0) return;+ buf[n] = 0;+ size_t o = 0;+ for (ssize_t i = 0; i < n && buf[i] && buf[i] != '\n' && o + 1 < size; i++)+ out[o++] = (buf[i] >= 0x20 && buf[i] < 0x7f) ? buf[i] : '?';+ while (o && out[o - 1] == ' ') o--;+ out[o] = 0;+}++static void attr_at(const char *root, const char *dir, const char *name, char *out, size_t size) {+ char p[1024];+ snprintf(p, sizeof p, "%s%s/%s", root ? root : "", dir, name);+ read_attr(p, out, size);+}++/* A hex ID attribute ("0x10de" or "10de") as lowercase hex of `digits` digits; "" if not hex. */+static void hex_attr(const char *root, const char *dir, const char *name, int digits, char *out) {+ char v[32];+ attr_at(root, dir, name, v, sizeof v);+ const char *s = v;+ if (s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) s += 2;+ size_t n = strlen(s);+ out[0] = 0;+ if (!n || n > (size_t)digits) return;+ for (size_t i = 0; i < n; i++) if (!isxdigit((unsigned char)s[i])) return;+ size_t pad = (size_t)digits - n;+ for (size_t i = 0; i < pad; i++) out[i] = '0';+ for (size_t i = 0; i < n; i++) out[pad + i] = (char)tolower((unsigned char)s[i]);+ out[digits] = 0;+}++/* The driver bound to a device: the last component of its "driver" link. */+static void driver_of(const char *root, const char *dir, char *out, size_t size) {+ char p[1024], link[512];+ snprintf(p, sizeof p, "%s%s/driver", root ? root : "", dir);+ ssize_t n = readlink(p, link, sizeof link - 1);+ out[0] = 0;+ if (n <= 0) return;+ link[n] = 0;+ const char *b = strrchr(link, '/');+ b = b ? b + 1 : link;+ size_t o = 0;+ for (; *b && o + 1 < size; b++) if (isalnum((unsigned char)*b) || *b == '_' || *b == '-') out[o++] = *b;+ out[o] = 0;+}++static int skip_dirent(const struct dirent *e) { return e->d_name[0] == '.'; }++static int cmp_str(const void *a, const void *b) { return strcmp(*(char *const *)a, *(char *const *)b); }++/* The entries of a directory, sorted (so the JSON is stable). Caller frees each and the array. */+static char **list_dir(const char *path, int *count) {+ *count = 0;+ DIR *d = opendir(path);+ if (!d) return NULL;+ char **v = NULL;+ int n = 0, cap = 0;+ struct dirent *e;+ while ((e = readdir(d)) && n < 1024) {+ if (skip_dirent(e) || strlen(e->d_name) > 64) continue;+ if (n == cap) {+ int nc = cap ? cap * 2 : 32;+ char **nv = realloc(v, (size_t)nc * sizeof *v);+ if (!nv) break;+ v = nv;+ cap = nc;+ }+ if (!(v[n] = strdup(e->d_name))) break;+ n++;+ }+ closedir(d);+ if (v) qsort(v, (size_t)n, sizeof *v, cmp_str);+ *count = n;+ return v;+}++static void free_list(char **v, int n) {+ for (int i = 0; i < n; i++) free(v[i]);+ free(v);+}++/* ---- DMI and device tree ---- */++static void put_dmi(HBuf *b, const char *root) {+ static const struct { const char *key, *file; } f[] = {+ { "sysVendor", "sys_vendor" }, { "productName", "product_name" }, { "boardVendor", "board_vendor" },+ { "boardName", "board_name" }, { "chassisType", "chassis_type" },+ };+ hb_printf(b, "\"dmi\":{");+ for (size_t i = 0; i < sizeof f / sizeof f[0]; i++) {+ char v[96];+ attr_at(root, "/sys/class/dmi/id", f[i].file, v, sizeof v);+ hb_printf(b, "%s\"%s\":", i ? "," : "", f[i].key);+ hb_str(b, v);+ }+ hb_printf(b, "}");+}++static void put_devicetree(HBuf *b, const char *root) {+ char p[1024], model[128];+ rpath(p, sizeof p, root, "/proc/device-tree/model");+ read_attr(p, model, sizeof model);+ hb_printf(b, ",\"model\":");+ hb_str(b, model);+ /* compatible: NUL-separated strings */+ hb_printf(b, ",\"compatible\":[");+ rpath(p, sizeof p, root, "/proc/device-tree/compatible");+ int fd = open(p, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);+ if (fd >= 0) {+ char buf[512];+ ssize_t n = read(fd, buf, sizeof buf - 1);+ close(fd);+ int first = 1;+ for (ssize_t i = 0; n > 0 && i < n;) {+ char s[96];+ size_t o = 0;+ while (i < n && buf[i]) {+ char ch = buf[i++];+ if (o + 1 < sizeof s && (isalnum((unsigned char)ch) || strchr(",.-_+", ch))) s[o++] = ch;+ }+ i++;+ s[o] = 0;+ if (o) { hb_printf(b, "%s", first ? "" : ","); hb_str(b, s); first = 0; }+ }+ }+ hb_printf(b, "]");+}++/* ---- PCI ---- */++static void put_pci(HBuf *b, const char *root) {+ char p[1024];+ rpath(p, sizeof p, root, "/sys/bus/pci/devices");+ int n;+ char **v = list_dir(p, &n);+ hb_printf(b, ",\"pci\":[");+ int out = 0;+ for (int i = 0; i < n && out < 256; i++) {+ char dir[256], vendor[8], device[8], cls[8], drv[33];+ snprintf(dir, sizeof dir, "/sys/bus/pci/devices/%s", v[i]);+ hex_attr(root, dir, "vendor", 4, vendor);+ hex_attr(root, dir, "device", 4, device);+ hex_attr(root, dir, "class", 6, cls);+ if (!vendor[0] || !device[0]) continue;+ driver_of(root, dir, drv, sizeof drv);+ hb_printf(b, "%s{\"vendor\":\"%s\",\"device\":\"%s\",\"class\":\"%s\",\"driver\":", out++ ? "," : "", vendor, device, cls);+ hb_str(b, drv);+ hb_printf(b, "}");+ }+ hb_printf(b, "]");+ free_list(v, n);+}++/* ---- USB ---- */++/* udev's database entry for a character device ("189:3" → /run/udev/data/c189:3) has+ * "E:libsane_matched=yes" when libsane's udev rules know the device as a scanner. */+static int sane_matched(const char *root, const char *dir) {+ char dev[32];+ attr_at(root, dir, "dev", dev, sizeof dev);+ unsigned ma, mi;+ if (sscanf(dev, "%u:%u", &ma, &mi) != 2) return 0;+ char p[1024];+ snprintf(p, sizeof p, "%s/run/udev/data/c%u:%u", root ? root : "", ma, mi);+ int fd = open(p, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);+ if (fd < 0) return 0;+ char buf[8192];+ ssize_t n = read(fd, buf, sizeof buf - 1);+ close(fd);+ if (n <= 0) return 0;+ buf[n] = 0;+ for (char *l = buf; l && *l; l = strchr(l, '\n') ? strchr(l, '\n') + 1 : NULL)+ if (!strncmp(l, "E:libsane_matched=yes", 21) && (l[21] == '\n' || !l[21])) return 1;+ return 0;+}++static void put_usb(HBuf *b, const char *root) {+ char p[1024];+ rpath(p, sizeof p, root, "/sys/bus/usb/devices");+ int n;+ char **v = list_dir(p, &n);+ hb_printf(b, ",\"usb\":[");+ int out = 0;+ for (int i = 0; i < n && out < 256; i++) {+ if (strchr(v[i], ':')) continue; /* an interface, listed under its device */+ char dir[256], vendor[8], product[8], cls[4], drv[33];+ snprintf(dir, sizeof dir, "/sys/bus/usb/devices/%s", v[i]);+ hex_attr(root, dir, "idVendor", 4, vendor);+ hex_attr(root, dir, "idProduct", 4, product);+ if (!vendor[0] || !product[0] || !strcmp(vendor, "1d6b")) continue; /* no IDs, or a root hub */+ hex_attr(root, dir, "bDeviceClass", 2, cls);+ hb_printf(b, "%s{\"vendor\":\"%s\",\"product\":\"%s\",\"class\":\"%s\",\"ifaces\":[", out++ ? "," : "", vendor, product, cls);+ /* its interfaces: "<device>:<config>.<n>"; the first bound driver names the device */+ drv[0] = 0;+ size_t dl = strlen(v[i]);+ int fi = 0;+ for (int k = 0; k < n; k++) {+ if (strncmp(v[k], v[i], dl) || v[k][dl] != ':') continue;+ char idir[256], ic[4], is[4], ip[4];+ snprintf(idir, sizeof idir, "/sys/bus/usb/devices/%s", v[k]);+ hex_attr(root, idir, "bInterfaceClass", 2, ic);+ hex_attr(root, idir, "bInterfaceSubClass", 2, is);+ hex_attr(root, idir, "bInterfaceProtocol", 2, ip);+ if (!ic[0]) continue;+ hb_printf(b, "%s\"%s%s%s\"", fi++ ? "," : "", ic, is[0] ? is : "00", ip[0] ? ip : "00");+ if (!drv[0]) driver_of(root, idir, drv, sizeof drv);+ }+ hb_printf(b, "],\"driver\":");+ hb_str(b, drv);+ hb_printf(b, ",\"sane\":%s}", sane_matched(root, dir) ? "true" : "false");+ }+ hb_printf(b, "]");+ free_list(v, n);+}++/* ---- virtio serial ports (a QEMU guest agent channel is named "org.qemu.guest_agent.0") ---- */++static void put_virtio(HBuf *b, const char *root) {+ char p[1024];+ rpath(p, sizeof p, root, "/sys/class/virtio-ports");+ int n;+ char **v = list_dir(p, &n);+ hb_printf(b, ",\"virtio\":[");+ int out = 0;+ for (int i = 0; i < n && out < 32; i++) {+ char dir[256], name[96];+ snprintf(dir, sizeof dir, "/sys/class/virtio-ports/%s", v[i]);+ attr_at(root, dir, "name", name, sizeof name);+ int ok = name[0] != 0;+ for (const char *s = name; *s && ok; s++) ok = isalnum((unsigned char)*s) || strchr("._-", *s);+ if (!ok) continue;+ hb_printf(b, "%s", out++ ? "," : "");+ hb_str(b, name);+ }+ hb_printf(b, "]");+ free_list(v, n);+}++/* ---- firmware misses ---- */++int hwscan_fw_name_valid(const char *s) {+ size_t n = strlen(s);+ if (!n || n >= sizeof ((HwFwMiss *)0)->file || s[0] == '/' || s[0] == '.' || strstr(s, "..") || strstr(s, "//")) return 0;+ for (; *s; s++) if (!isalnum((unsigned char)*s) && !strchr("._+,-/", *s)) return 0;+ return 1;+}++int hwscan_fw_present(const char *root, const char *name) {+ static const char *const dirs[] = { "/lib/firmware/updates/", "/lib/firmware/", "/usr/lib/firmware/" };+ static const char *const ext[] = { "", ".xz", ".zst" };+ if (!hwscan_fw_name_valid(name)) return 0;+ for (size_t d = 0; d < sizeof dirs / sizeof dirs[0]; d++)+ for (size_t e = 0; e < sizeof ext / sizeof ext[0]; e++) {+ char p[1024];+ struct stat st;+ snprintf(p, sizeof p, "%s%s%s%s", root ? root : "", dirs[d], name, ext[e]);+ if (!stat(p, &st) && S_ISREG(st.st_mode)) return 1;+ }+ return 0;+}++/* The driver name at the start of a message: "iwlwifi 0000:00:14.3: …" → "iwlwifi". */+static void msg_driver(const char *msg, const char *end, char *out, size_t size) {+ out[0] = 0;+ const char *sp = memchr(msg, ' ', (size_t)(end - msg));+ if (!sp || sp == msg || (size_t)(sp - msg) >= size) return;+ const char *sp2 = memchr(sp + 1, ' ', (size_t)(end - sp - 1)); /* "<driver> <device>: " */+ if (!sp2 || sp2 - sp < 3 || sp2[-1] != ':') return;+ for (const char *p = msg; p < sp; p++) if (!isalnum((unsigned char)*p) && *p != '_' && *p != '-') return;+ memcpy(out, msg, (size_t)(sp - msg));+ out[sp - msg] = 0;+}++int hwscan_fw_parse(const char *text, size_t len, HwFwMiss *out, int max) {+ static const struct { const char *pre, *post; } pat[] = {+ { "Direct firmware load for ", " failed with error " },+ { "firmware: failed to load ", " (" },+ };+ int count = 0;+ const char *end = text + len;+ for (const char *l = text; l < end && count < max;) {+ const char *nl = memchr(l, '\n', (size_t)(end - l));+ const char *le = nl ? nl : end;+ const char *msg = l;+ /* kmsg: "6,1234,5678,-;message"; continuation lines start with a space */+ if (*l == ' ') { l = nl ? nl + 1 : end; continue; }+ const char *semi = memchr(l, ';', (size_t)(le - l));+ if (semi && isdigit((unsigned char)*l)) msg = semi + 1;+ else if (*l == '[') { /* dmesg: "[ 5.1] message" */+ const char *rb = memchr(l, ']', (size_t)(le - l));+ if (rb) msg = rb + 1 + (rb + 1 < le && rb[1] == ' ');+ }+ for (size_t k = 0; k < sizeof pat / sizeof pat[0]; k++) {+ size_t pl = strlen(pat[k].pre);+ const char *a = NULL;+ for (const char *s = msg; s + pl <= le; s++) if (!memcmp(s, pat[k].pre, pl)) { a = s + pl; break; }+ if (!a) continue;+ const char *z = NULL, *post = pat[k].post;+ size_t ql = strlen(post);+ for (const char *s = a; s + ql <= le; s++) if (!memcmp(s, post, ql)) { z = s; break; }+ if (!z || z == a || (size_t)(z - a) >= sizeof out->file) break;+ HwFwMiss m;+ memcpy(m.file, a, (size_t)(z - a));+ m.file[z - a] = 0;+ if (!hwscan_fw_name_valid(m.file)) break;+ msg_driver(msg, le, m.driver, sizeof m.driver);+ int dup = 0;+ for (int i = 0; i < count && !dup; i++) dup = !strcmp(out[i].file, m.file);+ if (!dup) out[count++] = m;+ break;+ }+ l = nl ? nl + 1 : end;+ }+ return count;+}++char *hwscan_read_kmsg(const char *root, size_t *len, int *denied) {+ *len = 0;+ *denied = 0;+ char p[1024];+ int fixture = root && root[0];+ if (fixture) rpath(p, sizeof p, root, "/kmsg");+ else snprintf(p, sizeof p, "/dev/kmsg");+ int fd = open(p, O_RDONLY | O_CLOEXEC | O_NONBLOCK | (fixture ? O_NOFOLLOW : 0));+ if (fd < 0) { *denied = errno == EPERM || errno == EACCES; return NULL; }+ size_t cap = 65536, n = 0;+ char *buf = malloc(cap);+ if (!buf) { close(fd); return NULL; }+ for (;;) {+ if (cap - n < 8193) {+ if (cap >= KMSG_MAX) break;+ char *nb = realloc(buf, cap * 2);+ if (!nb) break;+ buf = nb;+ cap *= 2;+ }+ ssize_t r = read(fd, buf + n, cap - n - 1);+ if (r < 0 && errno == EINTR) continue;+ if (r < 0 && errno == EPIPE) continue; /* a record was overwritten: go on */+ if (r < 0 && (errno == EPERM || errno == EACCES) && !n) { *denied = 1; free(buf); close(fd); return NULL; }+ if (r <= 0) break; /* EAGAIN: end of the ring */+ n += (size_t)r;+ }+ close(fd);+ buf[n] = 0;+ *len = n;+ return buf;+}++int hwscan_fw_missing(const char *root, const char *text, size_t len, HwFwMiss *out, int max) {+ HwFwMiss all[HWSCAN_FW_MAX];+ int n = hwscan_fw_parse(text, len, all, max < HWSCAN_FW_MAX ? max : HWSCAN_FW_MAX), k = 0;+ for (int i = 0; i < n; i++) if (!hwscan_fw_present(root, all[i].file)) out[k++] = all[i];+ return k;+}++static void put_firmware(HBuf *b, const char *root) {+ size_t len;+ int denied;+ char *log = hwscan_read_kmsg(root, &len, &denied);+ hb_printf(b, ",\"firmware\":{\"readable\":%s,\"missing\":[", log ? "true" : "false");+ if (log) {+ HwFwMiss m[HWSCAN_FW_MAX];+ int n = hwscan_fw_missing(root, log, len, m, HWSCAN_FW_MAX);+ for (int i = 0; i < n; i++) {+ hb_printf(b, "%s{\"file\":", i ? "," : "");+ hb_str(b, m[i].file);+ hb_printf(b, ",\"driver\":");+ hb_str(b, m[i].driver);+ hb_printf(b, "}");+ }+ free(log);+ }+ hb_printf(b, "]}");+}++char *hwscan_json(const char *root) {+ HBuf b = { 0 };+ struct utsname u;+ if (uname(&u)) snprintf(u.machine, sizeof u.machine, "unknown");+ char arch[72];+ if (root && root[0]) { /* a fixture may name its architecture */+ char p[1024];+ rpath(p, sizeof p, root, "/arch");+ read_attr(p, arch, sizeof arch);+ if (!arch[0]) snprintf(arch, sizeof arch, "%s", u.machine);+ } else snprintf(arch, sizeof arch, "%s", u.machine);+ hb_printf(&b, "{\"fixture\":%s,\"arch\":", root && root[0] ? "true" : "false");+ hb_str(&b, arch);+ hb_printf(&b, ",");+ put_dmi(&b, root);+ put_devicetree(&b, root);+ put_pci(&b, root);+ put_usb(&b, root);+ put_virtio(&b, root);+ put_firmware(&b, root);+ hb_printf(&b, "}");+ return hb_take(&b);+}diff --git a/server/src/hw/hwscan.h b/server/src/hw/hwscan.hnew file mode 100644index 0000000..8a398cd--- /dev/null+++ b/server/src/hw/hwscan.h@@ -0,0 +1,58 @@+/* hwscan.h — read-only hardware facts for the Store's "Suggested for your computer"+ * (apps/store, sdk/suggestengine.js, assets/store/suggestions.json; see docs/PACKAGES.md).+ *+ * Everything here reads world-readable kernel files without root: DMI strings+ * (/sys/class/dmi/id), the device tree model (/proc/device-tree), PCI and USB IDs and their drivers+ * (/sys/bus/pci, /sys/bus/usb), the virtio serial port names (/sys/class/virtio-ports), the+ * "libsane_matched" flag udev keeps for scanners (/run/udev/data) and, when the kernel allows it+ * (kernel.dmesg_restrict=0), the firmware files a driver asked for and didn't find (/dev/kmsg).+ * Nothing is written, nothing is executed and nothing goes over the network.+ *+ * With dmesg_restrict=1 (Debian's default) the session can't read the kernel log; then the root+ * helper's fixed action `hw-firmware-missing` (no arguments) reads it and returns only the+ * validated names of missing firmware files.+ *+ * `root` prefixes every path ("" for the real system); tests and the fixture mode+ * (LORD_HWSCAN_ROOT, development only) point it at a fake tree, where the kernel log is the+ * plain file <root>/kmsg. */+#ifndef LORD_HW_HWSCAN_H+#define LORD_HW_HWSCAN_H++#include <stddef.h>++#define HWSCAN_FW_MAX 64 /* missing firmware files reported */++typedef struct {+ char file[200]; /* relative to /lib/firmware */+ char driver[33]; /* the driver or subsystem that asked ("iwlwifi", "bluetooth"), or "" */+} HwFwMiss;++/* The facts as JSON (malloc'd), or NULL on out-of-memory:+ * { fixture, arch, dmi: { sysVendor, productName, boardVendor, boardName, chassisType },+ * model, compatible: [], pci: [{ vendor, device, class, driver }],+ * usb: [{ vendor, product, class, ifaces: ["070104", …], driver, sane }], virtio: [names],+ * firmware: { readable, missing: [{ file, driver }] } }+ * IDs are lowercase hex without "0x". firmware.readable is false when the kernel log can't be+ * read without root (the Store then asks hw-firmware-missing). */+char *hwscan_json(const char *root);++/* Parses kernel log text (kmsg records "pri,seq,ts,flags;message" or dmesg lines) for the+ * firmware loader's "Direct firmware load for X failed" and "firmware: failed to load X" lines.+ * Fills up to max unique, valid names; returns how many. */+int hwscan_fw_parse(const char *text, size_t len, HwFwMiss *out, int max);++/* 1 if name is a safe relative firmware path: [A-Za-z0-9._+,-/], no "..", no leading '/', ≤ 199. */+int hwscan_fw_name_valid(const char *name);++/* 1 if <root>/lib/firmware[/updates]/<name>[.xz|.zst] exists (installed since the miss). */+int hwscan_fw_present(const char *root, const char *name);++/* Reads the kernel log ring: <root>/kmsg when root is non-empty, /dev/kmsg otherwise+ * (non-blocking, every record still in the ring, at most 4 MB). NULL with *denied = 1 when the+ * kernel refuses (dmesg_restrict). */+char *hwscan_read_kmsg(const char *root, size_t *len, int *denied);++/* Missing firmware files: parse the log and drop the ones present now. */+int hwscan_fw_missing(const char *root, const char *text, size_t len, HwFwMiss *out, int max);++#endifdiff --git a/server/src/ui/js_hw.c b/server/src/ui/js_hw.cindex b891cde..f745272 100644--- a/server/src/ui/js_hw.c+++ b/server/src/ui/js_hw.c@@ -18,6 +18,9 @@* lord.mime.get(mime) / set(mime, id) / guess(path) / terminal() / setTerminal(id)* lord.timedate.refresh() answer as __lordHw('timedate', …)* lord.notifyd.closed(id, reason) / action(id, key) back to the Linux app that notified+ * lord.hwinfo.scan() read-only hardware facts for the Store's suggestions+ * (hw/hwscan.c: DMI, device tree, PCI/USB IDs, virtio+ * ports, missing firmware when the kernel log is readable)* lord.fan.status() / setProfile(p) / setCurve(pts) / force(v) / caseConfig() (js_fan.c, lord-fand)*/#include "js_hw.h"@@ -26,6 +29,7 @@#include "../hw/defaults.h"#include "../hw/display.h"#include "../hw/hw.h"+#include "../hw/hwscan.h"#include "../hw/mimeapps.h"#include "../hw/notifyd.h"#include "../hw/ppd.h"@@ -336,6 +340,24 @@ static JSValue f_nd_action(JSContext *c, JSValueConst t, int argc, JSValueConststatic const JSCFunctionListEntry nd_funcs[] = { JS_CFUNC_DEF("closed", 2, f_nd_closed), JS_CFUNC_DEF("action", 2, f_nd_action) };+/* ---- lord.hwinfo (the Store's "Suggested for your computer", docs/PACKAGES.md) ---- */++/* LORD_HWSCAN_ROOT (development and screenshots only): read a fake tree instead of the real+ * system; the facts then say fixture: true and the Store marks them as test data. Only an absolute+ * path without ".." is taken. */+static const char *hwscan_root(void) {+ const char *r = getenv("LORD_HWSCAN_ROOT");+ if (!r || r[0] != '/' || strstr(r, "..") || strlen(r) > 200) return "";+ return r;+}++static JSValue f_hwinfo_scan(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {+ (void)t; (void)argc; (void)argv;+ return json_or_null(c, hwscan_json(hwscan_root()));+}++static const JSCFunctionListEntry hwinfo_funcs[] = { JS_CFUNC_DEF("scan", 0, f_hwinfo_scan) };+static void add(JSContext *c, JSValue lord, const char *name, const JSCFunctionListEntry *f, int n) {JSValue o = JS_NewObject(c);JS_SetPropertyFunctionList(c, o, f, n);@@ -349,5 +371,6 @@ void js_hw_register(JSContext *c, JSValue lord) {add(c, lord, "mime", mime_funcs, sizeof mime_funcs / sizeof mime_funcs[0]);add(c, lord, "timedate", td_funcs, sizeof td_funcs / sizeof td_funcs[0]);add(c, lord, "notifyd", nd_funcs, sizeof nd_funcs / sizeof nd_funcs[0]);+ add(c, lord, "hwinfo", hwinfo_funcs, sizeof hwinfo_funcs / sizeof hwinfo_funcs[0]);js_fan_register(c, lord); /* lord.fan: Settings → Cooling and Monitor (js_fan.c) */}diff --git a/server/tests/hwscan_test.c b/server/tests/hwscan_test.cnew file mode 100644index 0000000..8c90b3c--- /dev/null+++ b/server/tests/hwscan_test.c@@ -0,0 +1,299 @@+/* hwscan_test.c — the Store suggestions' hardware facts (src/hw/hwscan.c) over fake trees: DMI,+ * device tree, PCI, USB (interfaces, drivers, udev's libsane flag), virtio ports and the firmware+ * misses of a kernel log (kmsg and dmesg formats, names already present, unsafe names).+ *+ * build/hwscan-test the tests (make test)+ * build/hwscan-test dump [root] the facts JSON of a tree, or of this machine+ * build/hwscan-test fixture <dir> <kind> writes a fake tree (vmware, virtualbox, nvidia,+ * printer, scanner, rpi5, qemu, firmware, demo) for+ * LORD_HWSCAN_ROOT (screenshots and manual tests) */+#include "hw/hwscan.h"+#include "sec/json.h"++#include <errno.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/stat.h>+#include <unistd.h>++static int n_ok, n_bad;+#define CHECK(cond, ...) do { if (cond) n_ok++; else { n_bad++; printf("✗ " __VA_ARGS__); printf("\n"); } } while (0)++static void mkdirs(const char *path) {+ char p[1024];+ snprintf(p, sizeof p, "%s", path);+ for (char *s = p + 1; *s; s++) if (*s == '/') { *s = 0; mkdir(p, 0755); *s = '/'; }+ mkdir(p, 0755);+}++/* <root>/<rel> with text (parent folders created). len < 0: strlen. */+static void put(const char *root, const char *rel, const char *text, int len) {+ char p[1024], d[1024];+ snprintf(p, sizeof p, "%s/%s", root, rel);+ snprintf(d, sizeof d, "%s", p);+ char *sl = strrchr(d, '/');+ if (sl) { *sl = 0; mkdirs(d); }+ FILE *f = fopen(p, "wb");+ if (!f) { printf("cannot write %s: %s\n", p, strerror(errno)); exit(2); }+ fwrite(text, 1, len < 0 ? strlen(text) : (size_t)len, f);+ fclose(f);+}++static void link_driver(const char *root, const char *dir, const char *driver) {+ char p[1024], target[256];+ snprintf(p, sizeof p, "%s/%s", root, dir);+ mkdirs(p);+ snprintf(p, sizeof p, "%s/%s/driver", root, dir);+ snprintf(target, sizeof target, "../../../bus/drivers/%s", driver);+ unlink(p);+ if (symlink(target, p)) printf("symlink %s: %s\n", p, strerror(errno));+}++static void pci(const char *root, const char *slot, const char *vendor, const char *device, const char *cls, const char *driver) {+ char d[256], f[300];+ snprintf(d, sizeof d, "sys/bus/pci/devices/%s", slot);+ snprintf(f, sizeof f, "%s/vendor", d); put(root, f, vendor, -1);+ snprintf(f, sizeof f, "%s/device", d); put(root, f, device, -1);+ snprintf(f, sizeof f, "%s/class", d); put(root, f, cls, -1);+ if (driver) link_driver(root, d, driver);+}++static void usb_dev(const char *root, const char *name, const char *vendor, const char *product, const char *dev) {+ char d[256], f[300];+ snprintf(d, sizeof d, "sys/bus/usb/devices/%s", name);+ snprintf(f, sizeof f, "%s/idVendor", d); put(root, f, vendor, -1);+ snprintf(f, sizeof f, "%s/idProduct", d); put(root, f, product, -1);+ snprintf(f, sizeof f, "%s/bDeviceClass", d); put(root, f, "00\n", -1);+ if (dev) { snprintf(f, sizeof f, "%s/dev", d); put(root, f, dev, -1); }+}++static void usb_iface(const char *root, const char *name, const char *cls, const char *sub, const char *proto, const char *driver) {+ char d[256], f[300];+ snprintf(d, sizeof d, "sys/bus/usb/devices/%s", name);+ snprintf(f, sizeof f, "%s/bInterfaceClass", d); put(root, f, cls, -1);+ snprintf(f, sizeof f, "%s/bInterfaceSubClass", d); put(root, f, sub, -1);+ snprintf(f, sizeof f, "%s/bInterfaceProtocol", d); put(root, f, proto, -1);+ if (driver) link_driver(root, d, driver);+}++static void dmi(const char *root, const char *vendor, const char *product) {+ put(root, "sys/class/dmi/id/sys_vendor", vendor, -1);+ put(root, "sys/class/dmi/id/product_name", product, -1);+ put(root, "sys/class/dmi/id/chassis_type", "1\n", -1);+}++/* the kinds of fake tree */+static void tree(const char *root, const char *kind) {+ int demo = !strcmp(kind, "demo");+ put(root, "arch", "x86_64\n", -1);+ /* every PC has a host bridge and a USB root hub, which never suggest anything */+ pci(root, "0000:00:00.0", "0x8086\n", "0x29c0\n", "0x060000\n", NULL);+ usb_dev(root, "usb1", "1d6b", "0002", "189:0\n");+ if (!strcmp(kind, "vmware")) {+ dmi(root, "VMware, Inc.\n", "VMware Virtual Platform\n");+ pci(root, "0000:00:0f.0", "0x15ad\n", "0x0405\n", "0x030000\n", "vmwgfx");+ } else if (!strcmp(kind, "virtualbox")) {+ dmi(root, "innotek GmbH\n", "VirtualBox\n");+ pci(root, "0000:00:04.0", "0x80ee\n", "0xcafe\n", "0x088000\n", "vboxguest");+ } else if (!strcmp(kind, "qemu")) {+ dmi(root, "QEMU\n", "Standard PC (Q35 + ICH9, 2009)\n");+ put(root, "sys/class/virtio-ports/vport2p1/name", "org.qemu.guest_agent.0\n", -1);+ } else if (!strcmp(kind, "rpi5")) {+ put(root, "arch", "aarch64\n", -1);+ put(root, "proc/device-tree/model", "Raspberry Pi 5 Model B Rev 1.1", 31);+ put(root, "proc/device-tree/compatible", "raspberrypi,5-model-b\0brcm,bcm2712\0", 35);+ } else {+ dmi(root, "Example Computer Co.\n", "Desktop 3000\n");+ }+ if (demo) put(root, "sys/class/virtio-ports/vport2p1/name", "org.qemu.guest_agent.0\n", -1);+ if (!strcmp(kind, "nvidia") || demo)+ pci(root, "0000:01:00.0", "0x10de\n", "0x2484\n", "0x030000\n", "nouveau");+ if (!strcmp(kind, "printer") || demo) {+ usb_dev(root, "1-2", "03f0", "2b17", "189:2\n");+ usb_iface(root, "1-2:1.0", "07\n", "01\n", "02\n", "usblp");+ usb_iface(root, "1-2:1.1", "07\n", "01\n", "04\n", NULL);+ }+ if (!strcmp(kind, "scanner")) {+ usb_dev(root, "1-3", "04b8", "0142", "189:3\n");+ usb_iface(root, "1-3:1.0", "ff\n", "ff\n", "ff\n", NULL);+ put(root, "run/udev/data/c189:3", "I:123\nE:ID_VENDOR=EPSON\nE:libsane_matched=yes\nG:scanner\n", -1);+ }+ if (!strcmp(kind, "firmware") || demo) {+ pci(root, "0000:02:00.0", "0x14e4\n", "0x43a0\n", "0x028000\n", NULL);+ put(root, "kmsg",+ "6,512,4100000,-;brcmfmac 0000:02:00.0: Direct firmware load for brcm/brcmfmac4360-pcie.bin failed with error -2\n"+ " SUBSYSTEM=pci\n DEVICE=+pci:0000:02:00.0\n"+ "3,513,4100100,-;brcmfmac 0000:02:00.0: brcmf_pcie_setup: Dongle setup failed\n"+ "6,514,4200000,-;bluetooth hci0: Direct firmware load for rtl_bt/rtl8761bu_fw.bin failed with error -2\n", -1);+ if (!demo) put(root, "lib/firmware/rtl_nic/rtl8168h-2.fw", "x", 1);+ }+}++static char *facts_of(const char *root) { return hwscan_json(root); }++static void test_tree(const char *kind, void (*check)(const JVal *)) {+ char root[] = "/tmp/hwscan-test-XXXXXX";+ if (!mkdtemp(root)) { perror("mkdtemp"); exit(2); }+ tree(root, kind);+ char *j = facts_of(root);+ JDoc d;+ char err[128];+ int bad = !j || json_parse(j, strlen(j), &d, err, sizeof err);+ CHECK(!bad, "%s: facts are valid JSON (%s)", kind, j ? err : "NULL");+ if (!bad) {+ CHECK(json_bool(d.root, "fixture", 0) == 1, "%s: fixture flag", kind);+ check(d.root);+ json_free(&d);+ }+ free(j);+ char cmd[300];+ snprintf(cmd, sizeof cmd, "rm -rf '%s'", root);+ if (system(cmd)) printf("cleanup failed\n");+}++static const JVal *nth(const JVal *arr, size_t i) {+ if (!arr || arr->type != J_ARR) return NULL;+ const JVal *v = arr->kid;+ while (v && i--) v = v->next;+ return v;+}+static const char *dmi_s(const JVal *r, const char *k) { return json_str(json_get(r, "dmi"), k); }+static size_t len_of(const JVal *r, const char *k) { const JVal *v = json_get(r, k); return v && v->type == J_ARR ? v->len : 999; }+static const JVal *pci_by(const JVal *r, const char *vendor) {+ for (const JVal *v = json_get(r, "pci") ? json_get(r, "pci")->kid : NULL; v; v = v->next)+ if (json_str(v, "vendor") && !strcmp(json_str(v, "vendor"), vendor)) return v;+ return NULL;+}+#define STREQ(a, b) ((a) && !strcmp((a), (b)))++static void c_vmware(const JVal *r) {+ CHECK(STREQ(dmi_s(r, "sysVendor"), "VMware, Inc."), "vmware: sysVendor");+ const JVal *g = pci_by(r, "15ad");+ CHECK(g && STREQ(json_str(g, "device"), "0405") && STREQ(json_str(g, "class"), "030000") && STREQ(json_str(g, "driver"), "vmwgfx"), "vmware: SVGA device");+ CHECK(len_of(r, "usb") == 0, "vmware: the root hub is not listed");+ const JVal *fw = json_get(r, "firmware");+ CHECK(fw && json_bool(fw, "readable", 1) == 0, "vmware: no kmsg file → not readable");+}+static void c_vbox(const JVal *r) {+ CHECK(STREQ(dmi_s(r, "productName"), "VirtualBox"), "virtualbox: productName");+ CHECK(pci_by(r, "80ee") != NULL, "virtualbox: guest device");+}+static void c_qemu(const JVal *r) {+ const JVal *v = nth(json_get(r, "virtio"), 0);+ CHECK(v && v->type == J_STR && STREQ(v->str, "org.qemu.guest_agent.0"), "qemu: guest agent port");+}+static void c_rpi(const JVal *r) {+ CHECK(STREQ(json_str(r, "model"), "Raspberry Pi 5 Model B Rev 1.1"), "rpi5: model");+ const JVal *c0 = nth(json_get(r, "compatible"), 0), *c1 = nth(json_get(r, "compatible"), 1);+ CHECK(c0 && STREQ(c0->str, "raspberrypi,5-model-b") && c1 && STREQ(c1->str, "brcm,bcm2712"), "rpi5: compatible");+ CHECK(STREQ(json_str(r, "arch"), "aarch64"), "rpi5: arch");+ CHECK(STREQ(dmi_s(r, "sysVendor"), ""), "rpi5: no DMI");+}+static void c_nvidia(const JVal *r) {+ const JVal *g = pci_by(r, "10de");+ CHECK(g && STREQ(json_str(g, "class"), "030000") && STREQ(json_str(g, "driver"), "nouveau"), "nvidia: VGA device on nouveau");+}+static void c_printer(const JVal *r) {+ const JVal *u = nth(json_get(r, "usb"), 0);+ CHECK(u && STREQ(json_str(u, "vendor"), "03f0") && STREQ(json_str(u, "product"), "2b17"), "printer: ids");+ const JVal *i0 = u ? nth(json_get(u, "ifaces"), 0) : NULL, *i1 = u ? nth(json_get(u, "ifaces"), 1) : NULL;+ CHECK(i0 && STREQ(i0->str, "070102") && i1 && STREQ(i1->str, "070104"), "printer: interfaces 07/01/02 and 07/01/04 (IPP over USB)");+ CHECK(u && STREQ(json_str(u, "driver"), "usblp"), "printer: driver");+ CHECK(u && json_bool(u, "sane", 1) == 0, "printer: not a scanner");+}+static void c_scanner(const JVal *r) {+ const JVal *u = nth(json_get(r, "usb"), 0);+ CHECK(u && STREQ(json_str(u, "vendor"), "04b8") && json_bool(u, "sane", 0) == 1, "scanner: udev libsane flag");+}+static void c_firmware(const JVal *r) {+ const JVal *fw = json_get(r, "firmware");+ CHECK(fw && json_bool(fw, "readable", 0) == 1, "firmware: log readable");+ const JVal *m = json_get(fw, "missing");+ const JVal *a = nth(m, 0), *b = nth(m, 1);+ CHECK(m && m->len == 2, "firmware: two misses (%zu)", m ? m->len : 0);+ CHECK(a && STREQ(json_str(a, "file"), "brcm/brcmfmac4360-pcie.bin") && STREQ(json_str(a, "driver"), "brcmfmac"), "firmware: brcm miss");+ CHECK(b && STREQ(json_str(b, "file"), "rtl_bt/rtl8761bu_fw.bin") && STREQ(json_str(b, "driver"), "bluetooth"), "firmware: bluetooth miss");+}++static void parse_tests(void) {+ HwFwMiss m[8];+ const char *log =+ "[ 3.1] iwlwifi 0000:00:14.3: Direct firmware load for iwlwifi-so-a0-gf-a0-89.ucode failed with error -2\n"+ "[ 3.2] iwlwifi 0000:00:14.3: Direct firmware load for iwlwifi-so-a0-gf-a0-89.ucode failed with error -2\n"+ "[ 3.3] r8169 0000:03:00.0: firmware: failed to load rtl_nic/rtl8168h-2.fw (-2)\n"+ "[ 3.4] evil 0000:00:01.0: Direct firmware load for ../../etc/shadow failed with error -2\n"+ "[ 3.5] evil 0000:00:01.0: Direct firmware load for /etc/shadow failed with error -2\n"+ "[ 3.6] evil 0000:00:01.0: Direct firmware load for a b failed with error -2\n"+ "[ 3.7] amdgpu: Direct firmware load for amdgpu/navi10_pfp.bin failed with error -2\n"+ "[ 3.8] some unrelated line about firmware\n";+ int n = hwscan_fw_parse(log, strlen(log), m, 8);+ CHECK(n == 3, "parse: 3 unique valid misses (%d)", n);+ CHECK(n > 0 && !strcmp(m[0].file, "iwlwifi-so-a0-gf-a0-89.ucode") && !strcmp(m[0].driver, "iwlwifi"), "parse: iwlwifi");+ CHECK(n > 1 && !strcmp(m[1].file, "rtl_nic/rtl8168h-2.fw") && !strcmp(m[1].driver, "r8169"), "parse: Debian's 'failed to load' line");+ CHECK(n > 2 && !strcmp(m[2].file, "amdgpu/navi10_pfp.bin") && !m[2].driver[0], "parse: no device → no driver name");+ CHECK(hwscan_fw_parse(log, strlen(log), m, 1) == 1, "parse: max respected");+ static const char *const bads[] = { "", "/x", "../x", "a/../b", ".hidden", "a//b", "a b", "a;b", "a\\b", "a\n" };+ for (size_t i = 0; i < sizeof bads / sizeof bads[0]; i++) CHECK(!hwscan_fw_name_valid(bads[i]), "name rejected: %s", bads[i]);+ static const char *const goods[] = { "iwlwifi-cc-a0-77.ucode", "rtl_bt/rtl8761bu_fw.bin", "brcm/brcmfmac43455-sdio.raspberrypi,5-model-b.bin", "intel/ibt-0040-0041.sfi", "mediatek/WIFI_RAM_CODE_MT7922_1.bin" };+ for (size_t i = 0; i < sizeof goods / sizeof goods[0]; i++) CHECK(hwscan_fw_name_valid(goods[i]), "name accepted: %s", goods[i]);+ /* a long line without the end of the pattern, and an empty log */+ char big[600];+ memset(big, 'x', sizeof big);+ memcpy(big, "Direct firmware load for ", 25);+ CHECK(hwscan_fw_parse(big, sizeof big, m, 8) == 0, "parse: truncated line");+ CHECK(hwscan_fw_parse("", 0, m, 8) == 0, "parse: empty");+}++static void present_tests(void) {+ char root[] = "/tmp/hwscan-fw-XXXXXX";+ if (!mkdtemp(root)) { perror("mkdtemp"); exit(2); }+ put(root, "lib/firmware/rtl_nic/rtl8168h-2.fw.zst", "x", 1);+ put(root, "lib/firmware/updates/iwlwifi-cc-a0-77.ucode", "x", 1);+ CHECK(hwscan_fw_present(root, "rtl_nic/rtl8168h-2.fw"), "present: .zst");+ CHECK(hwscan_fw_present(root, "iwlwifi-cc-a0-77.ucode"), "present: updates/");+ CHECK(!hwscan_fw_present(root, "rtl_bt/rtl8761bu_fw.bin"), "present: missing");+ CHECK(!hwscan_fw_present(root, "../firmware/rtl_nic/rtl8168h-2.fw.zst"), "present: unsafe name");+ const char *log = "4,1,1,-;r8169 0000:03:00.0: Direct firmware load for rtl_nic/rtl8168h-2.fw failed with error -2\n"+ "4,2,2,-;bluetooth hci0: Direct firmware load for rtl_bt/rtl8761bu_fw.bin failed with error -2\n";+ HwFwMiss m[4];+ int n = hwscan_fw_missing(root, log, strlen(log), m, 4);+ CHECK(n == 1 && !strcmp(m[0].file, "rtl_bt/rtl8761bu_fw.bin"), "missing: installed since → dropped (%d)", n);+ char cmd[300];+ snprintf(cmd, sizeof cmd, "rm -rf '%s'", root);+ if (system(cmd)) printf("cleanup failed\n");+}++int main(int argc, char **argv) {+ if (argc >= 2 && !strcmp(argv[1], "dump")) {+ char *j = hwscan_json(argc > 2 ? argv[2] : "");+ puts(j ? j : "null");+ free(j);+ return 0;+ }+ if (argc == 4 && !strcmp(argv[1], "fixture")) {+ mkdirs(argv[2]);+ tree(argv[2], argv[3]);+ printf("fixture %s in %s (run lord-server with LORD_HWSCAN_ROOT=%s)\n", argv[3], argv[2], argv[2]);+ return 0;+ }+ parse_tests();+ present_tests();+ test_tree("vmware", c_vmware);+ test_tree("virtualbox", c_vbox);+ test_tree("qemu", c_qemu);+ test_tree("rpi5", c_rpi);+ test_tree("nvidia", c_nvidia);+ test_tree("printer", c_printer);+ test_tree("scanner", c_scanner);+ test_tree("firmware", c_firmware);+ /* the real machine: valid JSON, not a fixture */+ char *j = hwscan_json("");+ JDoc d;+ int ok = j && !json_parse(j, strlen(j), &d, NULL, 0);+ CHECK(ok, "this machine: valid JSON");+ if (ok) { CHECK(json_bool(d.root, "fixture", 1) == 0, "this machine: not a fixture"); json_free(&d); }+ free(j);+ printf("hwscan-test: %d ok, %d failed\n", n_ok, n_bad);+ return n_bad ? 1 : 0;+}diff --git a/server/tests/run_suites.sh b/server/tests/run_suites.shindex b47e29e..874729e 100644--- a/server/tests/run_suites.sh+++ b/server/tests/run_suites.sh@@ -153,6 +153,9 @@ EOF# the Dock's pinned-list model (sdk/dockmodel.js)if have node; then run "dock-model-test (sdk/dockmodel.js)" node tests/dock_model_test.mjselse skip "dock-model-test" "node"; fi+ # the Store's "Suggested for your computer" rules (assets/store/suggestions.json)+ if have node; then run "suggest-engine-test (sdk/suggestengine.js)" node tests/suggest_engine_test.mjs+ else skip "suggest-engine-test" "node"; fi}full() {diff --git a/server/tests/suggest_engine_test.mjs b/server/tests/suggest_engine_test.mjsnew file mode 100644index 0000000..d7f68b5--- /dev/null+++ b/server/tests/suggest_engine_test.mjs@@ -0,0 +1,174 @@+// suggest_engine_test.mjs — the Store's "Suggested for your computer" rules+// (assets/store/suggestions.json + sdk/suggestengine.js) against fake hardware facts (the shape+// lord.hwinfo.scan() returns, hw/hwscan.c) and a fake package index, one fixture per rule; and the+// texts every rule needs in en/es/pt.+//+// node tests/suggest_engine_test.mjs (from server/; run_suites.sh runs it when node exists)+import fs from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const here = path.dirname(fileURLToPath(import.meta.url));+const repo = path.join(here, '../..');+const { evaluate, matches, firmwareFromLog, fresh } = await import(path.join(repo, 'sdk/suggestengine.js'));+const DATA = JSON.parse(fs.readFileSync(path.join(repo, 'assets/store/suggestions.json'), 'utf8'));++let n = 0, bad = 0;+const eq = (name, got, want) => {+ n++;+ const g = JSON.stringify(got), w = JSON.stringify(want);+ if (g !== w) { bad++; console.log(`✗ ${name}: want ${w}, got ${g}`); }+};++// ---- fake facts ----+const base = () => ({ fixture: true, arch: 'x86_64', dmi: { sysVendor: 'Example Computer Co.', productName: 'Desktop 3000', boardVendor: '', boardName: '', chassisType: '3' },+ model: '', compatible: [], pci: [{ vendor: '8086', device: '29c0', class: '060000', driver: '' }], usb: [], virtio: [], firmware: { readable: true, missing: [] } });+const facts = (patch) => ({ ...base(), ...patch });++// ---- fake index: name → { installed } ; absent = not in the configured sources ----+const MAIN = ['open-vm-tools', 'qemu-guest-agent', 'linux-headers-amd64', 'hplip', 'libsane-hpaio', 'printer-driver-escpr', 'printer-driver-brlaser',+ 'printer-driver-splix', 'printer-driver-gutenprint', 'ipp-usb', 'gpiod'];+const NONFREE = ['nvidia-driver', 'firmware-misc-nonfree', 'firmware-realtek', 'firmware-iwlwifi', 'firmware-atheros', 'firmware-brcm80211',+ 'firmware-mediatek', 'firmware-amd-graphics', 'firmware-intel-graphics', 'bluez-firmware', 'firmware-libertas', 'firmware-nvidia-graphics'];+const RPI = ['rpi-eeprom', 'raspi-utils'];+const index = ({ nonfree = true, rpi = false, installed = [] } = {}) => {+ const names = new Set([...MAIN, ...(nonfree ? NONFREE : []), ...(rpi ? RPI : [])]);+ return (name) => (names.has(name) ? { name, installed: installed.includes(name) ? '1.0' : null } : null);+};+const run = (f, opts = {}, ev = {}) => evaluate(DATA, f, { info: index(opts), ...ev });+const ids = (list) => list.map((s) => `${s.id}=${s.state}`);+const one = (list, id) => list.find((s) => s.id === id);++// ---- nothing special: no suggestion ----+eq('plain PC', ids(run(facts({}))), []);+eq('no facts', evaluate(DATA, null, {}), []);++// ---- VMware: open-vm-tools (preinstalled → installed) ----+const vmware = facts({ dmi: { ...base().dmi, sysVendor: 'VMware, Inc.', productName: 'VMware Virtual Platform' }, pci: [{ vendor: '15ad', device: '0405', class: '030000', driver: 'vmwgfx' }] });+eq('vmware installed', ids(run(vmware, { installed: ['open-vm-tools'] })), ['vmwareTools=installed']);+eq('vmware not installed', ids(run(vmware)), ['vmwareTools=install']);+eq('vmware install list', one(run(vmware), 'vmwareTools').install, ['open-vm-tools']);+eq('vmware by PCI only', ids(run(facts({ pci: [{ vendor: '15ad', device: '0740', class: '088000', driver: 'vmw_vmci' }] }))), ['vmwareTools=install']);+eq('vmware: never the X11 desktop package', one(run(vmware), 'vmwareTools').packages.includes('open-vm-tools-desktop'), false);++// ---- QEMU with a guest agent channel ----+const qemu = facts({ dmi: { ...base().dmi, sysVendor: 'QEMU', productName: 'Standard PC (Q35 + ICH9, 2009)' }, virtio: ['org.qemu.guest_agent.0', 'com.redhat.spice.0'] });+eq('qemu agent installed', ids(run(qemu, { installed: ['qemu-guest-agent'] })), ['qemuAgent=installed']);+eq('qemu agent missing', ids(run(qemu)), ['qemuAgent=install']);+eq('qemu without the channel', ids(run(facts({ dmi: qemu.dmi }))), []);++// ---- VirtualBox: the guest utilities are not in Debian 13 → explained ----+const vbox = facts({ dmi: { ...base().dmi, sysVendor: 'innotek GmbH', productName: 'VirtualBox' } });+eq('virtualbox unavailable', ids(run(vbox)), ['virtualboxGuest=unavailable']);+eq('virtualbox missing names it', one(run(vbox), 'virtualboxGuest').missing, ['virtualbox-guest-utils']);+eq('virtualbox by PCI 80ee:cafe', ids(run(facts({ pci: [{ vendor: '80ee', device: 'cafe', class: '088000', driver: 'vboxguest' }] }))), ['virtualboxGuest=unavailable']);+eq('another 80ee device is not the guest device', ids(run(facts({ pci: [{ vendor: '80ee', device: 'beef', class: '030000', driver: '' }] }))), []);++// ---- NVIDIA: non-free driver, never free, explained without non-free ----+const nv = facts({ pci: [...base().pci, { vendor: '10de', device: '2484', class: '030000', driver: 'nouveau' }] });+const s = one(run(nv), 'nvidiaDriver');+eq('nvidia install', s.state, 'install');+eq('nvidia packages', s.install, ['linux-headers-amd64', 'nvidia-driver', 'firmware-misc-nonfree']);+eq('nvidia not free', [s.free, s.component], [false, 'non-free']);+eq('nvidia notes', s.notes, ['nonfree', 'nouveau', 'secureBoot', 'older']);+eq('nvidia without non-free sources', ids(run(nv, { nonfree: false })), ['nvidiaDriver=unavailable']);+eq('nvidia already on the vendor driver', ids(run(nv, { installed: ['nvidia-driver'] })), ['nvidiaDriver=installed']);+eq('nvidia audio function only (class 0403)', ids(run(facts({ pci: [{ vendor: '10de', device: '10fa', class: '040300', driver: 'snd_hda_intel' }] }))), []);+eq('nvidia 3D controller (0302)', ids(run(facts({ pci: [{ vendor: '10de', device: '1eb8', class: '030200', driver: '' }] }))), ['nvidiaDriver=install']);+eq('nvidia on arm64: nothing', ids(run({ ...nv, arch: 'aarch64' })), []);+eq('nvidia: plan impossible (contrib missing) → explained', ids(run(nv, {}, { check: (names) => !names.includes('nvidia-driver') })), ['nvidiaDriver=unavailable']);+eq('nvidia: plan impossible names what it would install', one(run(nv, {}, { check: () => false }), 'nvidiaDriver').missing, ['linux-headers-amd64', 'nvidia-driver', 'firmware-misc-nonfree']);+eq('check passes → installable', ids(run(nv, {}, { check: () => true })), ['nvidiaDriver=install']);+eq('check is not asked for installed cards', ids(run(vmware, { installed: ['open-vm-tools'] }, { check: () => false })), ['vmwareTools=installed']);+eq('nvidia dismissed', ids(run(nv, {}, { dismissed: ['nvidiaDriver'] })), []);++// ---- Raspberry Pi 5 ----+const pi = facts({ arch: 'aarch64', dmi: { sysVendor: '', productName: '', boardVendor: '', boardName: '', chassisType: '' }, model: 'Raspberry Pi 5 Model B Rev 1.1',+ compatible: ['raspberrypi,5-model-b', 'brcm,bcm2712'], pci: [{ vendor: '1de4', device: '0001', class: '020000', driver: 'rp1' }] });+eq('pi5 with the Raspberry Pi archive, all installed', ids(run(pi, { rpi: true, installed: ['rpi-eeprom', 'raspi-utils', 'gpiod'] })), ['rpi5Tools=installed']);+eq('pi5 with the archive, nothing installed', one(run(pi, { rpi: true }), 'rpi5Tools').install, ['rpi-eeprom', 'raspi-utils', 'gpiod']);+eq('pi5 without the archive: only what Debian has', one(run(pi), 'rpi5Tools').install, ['gpiod']);+eq('pi4 is not a pi5', ids(run({ ...pi, compatible: ['raspberrypi,4-model-b', 'brcm,bcm2711'] })), []);++// ---- USB printers and scanners ----+const hp = facts({ usb: [{ vendor: '03f0', product: '2b17', class: '00', ifaces: ['070102', '070104'], driver: 'usblp', sane: false }] });+eq('hp printer + ipp-usb', ids(run(hp)), ['printer:03f0=install', 'ippUsb=install']);+eq('hp printer vendor param', one(run(hp), 'printer:03f0').params, { vendor: 'HP' });+eq('hp printer installed', ids(run(hp, { installed: ['hplip', 'ipp-usb'] })), ['printer:03f0=installed', 'ippUsb=installed']);+const epsonScan = facts({ usb: [{ vendor: '04b8', product: '0142', class: '00', ifaces: ['ffffff'], driver: '', sane: true }] });+eq('epson scanner: no Debian scanner driver to add', ids(run(epsonScan)), []);+const hpScan = facts({ usb: [{ vendor: '03f0', product: '5817', class: '00', ifaces: ['ffffff'], driver: '', sane: true }] });+eq('hp scanner', ids(run(hpScan)), ['scanner:03f0=install']);+eq('epson printer', one(run(facts({ usb: [{ vendor: '04b8', product: '1129', class: '00', ifaces: ['070102'], driver: 'usblp', sane: false }] })), 'printer:04b8').install, ['printer-driver-escpr']);+eq('unknown vendor printer: only ipp-usb', ids(run(facts({ usb: [{ vendor: '1234', product: '0001', class: '00', ifaces: ['070104'], driver: '', sane: false }] }))), ['ippUsb=install']);+eq('two HP printers: one suggestion', ids(run(facts({ usb: [hp.usb[0], { ...hp.usb[0], product: '1234' }] }))), ['printer:03f0=install', 'ippUsb=install']);+eq('a keyboard (class 03): nothing', ids(run(facts({ usb: [{ vendor: '046d', product: 'c31c', class: '00', ifaces: ['030101'], driver: 'usbhid', sane: false }] }))), []);+eq('bad vendor id ignored', ids(run(facts({ usb: [{ vendor: '03F0x', product: '1', class: '00', ifaces: ['070102'], driver: '', sane: false }] }))), []);++// ---- missing firmware ----+const fw = (missing) => facts({ firmware: { readable: true, missing } });+const wifi = run(fw([{ file: 'iwlwifi-so-a0-gf-a0-89.ucode', driver: 'iwlwifi' }, { file: 'iwlwifi-so-a0-gf-a0-88.ucode', driver: 'iwlwifi' }]));+eq('iwlwifi: one suggestion for the package', ids(wifi), ['firmware:firmware-iwlwifi=install']);+eq('iwlwifi params', one(wifi, 'firmware:firmware-iwlwifi').params, { package: 'firmware-iwlwifi', driver: 'iwlwifi', files: 'iwlwifi-so-a0-gf-a0-89.ucode, iwlwifi-so-a0-gf-a0-88.ucode', count: 2 });+eq('iwlwifi text', one(wifi, 'firmware:firmware-iwlwifi').text, 'firmware.wifi');+eq('firmware is not free', one(wifi, 'firmware:firmware-iwlwifi').free, false);+const mixed = run(fw([{ file: 'rtl_bt/rtl8761bu_fw.bin', driver: 'bluetooth' }, { file: 'brcm/brcmfmac4360-pcie.bin', driver: 'brcmfmac' },+ { file: 'mediatek/WIFI_RAM_CODE_MT7922_1.bin', driver: 'mt7921e' }, { file: 'amdgpu/navi10_pfp.bin', driver: '' }, { file: 'unknown/thing.bin', driver: 'x' },+ { file: 'intel/ibt-0040-0041.sfi', driver: 'bluetooth' }, { file: 'brcm/BCM4345C0.hcd', driver: 'bluetooth' }, { file: 'htc_9271.fw', driver: 'ath9k_htc' }]));+eq('firmware mapping', ids(mixed), ['firmware:firmware-realtek=install', 'firmware:firmware-brcm80211=install', 'firmware:firmware-mediatek=install',+ 'firmware:firmware-amd-graphics=install', 'firmware:firmware-iwlwifi=install', 'firmware:bluez-firmware=install', 'firmware:firmware-atheros=install']);+eq('firmware kinds', mixed.map((x) => x.text), ['firmware.bluetooth', 'firmware.wifi', 'firmware.wifi', 'firmware.graphics', 'firmware.bluetooth', 'firmware.bluetooth', 'firmware.wifi']);+eq('firmware package installed but file missing: nothing to offer', ids(run(fw([{ file: 'rtw88/rtw8822c_fw.bin', driver: 'rtw88_8822ce' }]), { installed: ['firmware-realtek'] })), []);+eq('firmware without non-free-firmware sources', ids(run(fw([{ file: 'rtw88/rtw8822c_fw.bin', driver: '' }]), { nonfree: false })), ['firmware:firmware-realtek=unavailable']);+eq('firmware component', one(run(fw([{ file: 'rtw88/rtw8822c_fw.bin', driver: '' }]), { nonfree: false }), 'firmware:firmware-realtek').component, 'non-free-firmware');+eq('unreadable log: nothing', ids(run(facts({ firmware: { readable: false, missing: [] } }))), []);++eq('firmware plan impossible → explained', ids(run(fw([{ file: 'rtw88/rtw8822c_fw.bin', driver: '' }]), {}, { check: () => false })), ['firmware:firmware-realtek=unavailable']);+eq('printer plan impossible → hidden (not explained)', ids(run(hp, {}, { check: () => false })), []);++// ---- ordering: installable first, then explained, then installed ----+const all = facts({ dmi: vmware.dmi, pci: [...nv.pci, ...vmware.pci], usb: hp.usb, firmware: { readable: true, missing: [{ file: 'rtw89/rtw8852b_fw.bin', driver: 'rtw89_8852be' }] } });+eq('order', ids(run(all, { nonfree: false, installed: ['open-vm-tools'] })),+ ['printer:03f0=install', 'ippUsb=install', 'nvidiaDriver=unavailable', 'firmware:firmware-realtek=unavailable', 'vmwareTools=installed']);++// ---- conditions ----+eq('unknown condition never matches', matches({ cpu: ['x'] }, base()), false);+eq('empty all never matches', matches({ all: [] }, base()), false);+eq('two keys = all', matches({ arch: ['x86_64'], dmi: { sysVendor: ['Example Computer Co.'] } }, base()), true);+eq('two keys, one false', matches({ arch: ['aarch64'], dmi: { sysVendor: ['Example Computer Co.'] } }, base()), false);++// ---- the root helper's lines ----+eq('firmwareFromLog', firmwareFromLog(['fw iwlwifi-cc-a0-77.ucode iwlwifi', 'fw rtl_bt/rtl8761bu_fw.bin -', 'progress x', 'fw ../etc/shadow x', 'fw /etc/shadow x', 'fw a b c', 42]),+ [{ file: 'iwlwifi-cc-a0-77.ucode', driver: 'iwlwifi' }, { file: 'rtl_bt/rtl8761bu_fw.bin', driver: '' }]);++// ---- notify once ----+const list = run(all, { installed: ['open-vm-tools'] });+eq('fresh: installable only', fresh(list, []).map((x) => x.id), ['nvidiaDriver', 'printer:03f0', 'ippUsb', 'firmware:firmware-realtek']);+eq('fresh: minus notified', fresh(list, ['printer:03f0', 'nvidiaDriver']).map((x) => x.id), ['ippUsb', 'firmware:firmware-realtek']);++// ---- data hygiene ----+const PKG = /^[a-z0-9][a-z0-9+.-]+$/;+const named = [...DATA.rules.flatMap((r) => r.packages), ...Object.values(DATA.usb.vendors).flatMap((v) => [...(v.printer || []), ...(v.scanner || [])]),+ ...DATA.usb.ippUsb, ...DATA.firmware.map.map((m) => m.package)];+eq('every package name is valid', named.filter((p) => !PKG.test(p)), []);+eq('rule ids unique', DATA.rules.length, new Set(DATA.rules.map((r) => r.id)).size);+eq('vendor ids are 4 hex digits', Object.keys(DATA.usb.vendors).filter((v) => !/^[0-9a-f]{4}$/.test(v)), []);+eq('no X11 guest package', named.includes('open-vm-tools-desktop'), false);++// every text a card can show, in every language+const texts = ['title', 'why', 'detail', 'unavailable'];+const need = [+ ...DATA.rules.flatMap((r) => [...texts.map((x) => `${r.id}.${x}`), ...(r.notes || []).filter((x) => x !== 'nonfree').map((x) => `${r.id}.note.${x}`)]),+ ...['printer', 'scanner', 'ippUsb'].flatMap((k) => texts.map((x) => `${k}.${x}`)),+ ...['wifi', 'bluetooth', 'network', 'graphics', 'other'].flatMap((k) => texts.map((x) => `firmware.${k}.${x}`)),+ 'title', 'subtitle', 'fixture', 'nonfreeBadge', 'installNonfree', 'confirmNonfree', 'dismiss', 'whatChanges', 'job', 'note.nonfree', 'note.firmware',+ 'notify.title', 'notify.body', 'notify.open',+];+for (const lang of ['en', 'es', 'pt']) {+ const cat = JSON.parse(fs.readFileSync(path.join(repo, `assets/locales/${lang}/store.json`), 'utf8'));+ eq(`${lang}: every suggestion text`, need.filter((k) => !(`suggest.${k}` in cat)), []);+}+eq('firmware kinds in the data are known', DATA.firmware.map.filter((m) => !['wifi', 'bluetooth', 'network', 'graphics', 'other'].includes(m.kind)).length, 0);++console.log(`suggest-engine-test: ${n - bad}/${n} ok`);+process.exit(bad ? 1 : 0);