computer-vitals 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,211 @@
1
+ // Turns a raw list of running processes into "apps" a person would recognize, and explains the
2
+ // well-known background ones in plain words: what it is, whether it is normal, whether it stops
3
+ // by itself, and what to do. Pure: no system calls here.
4
+ import path from "node:path";
5
+
6
+ import { cleanText } from "./text.js";
7
+
8
+ // kind: scan, update, index, sync and backup are work that ends by itself.
9
+ const TEMPORARY = new Set(["scan", "update", "index", "sync", "backup"]);
10
+ export const isTemporary = (kind) => TEMPORARY.has(kind);
11
+
12
+ const BROWSER_NOTE = "Every open tab and every extension uses memory and some processor time. Close the tabs you are not using, and remove extensions you do not need.";
13
+ const VM_NOTE = "A virtual machine or container tool is running. These set aside a lot of memory for themselves. Shut them down when you are not using them.";
14
+ const AV_NOTE = "Your antivirus checking files. This is normal and a scan finishes by itself. Do not turn it off.";
15
+ const SYNC_NOTE = "Copying files to or from the cloud. It stops when everything is in sync. You can pause it from its own menu if you need the speed now.";
16
+
17
+ const K = (title, kind, note = null) => ({ title, kind, note });
18
+
19
+ const WINDOWS = [
20
+ [["msmpeng", "mpdefendercoreservice", "nissrv", "defenderaiplatformhost"], K("Windows Security (virus scan)", "scan", "The built-in antivirus checking files. This is normal and it finishes by itself, usually within the hour. Leave it running; do not turn it off.")],
21
+ [["tiworker", "trustedinstaller", "mousocoreworker", "usoclient", "wuauclt", "musnotification", "musnotificationux", "monotificationux"], K("Windows Update", "update", "Windows is downloading or installing updates. This is normal. Let it finish, then restart the computer when it asks.")],
22
+ [["searchindexer", "searchprotocolhost", "searchfilterhost"], K("Windows Search (indexing files)", "index", "Windows is making a list of your files so that searching is fast. Normal after an update or after adding many files. It finishes by itself.")],
23
+ [["compattelrunner"], K("Windows compatibility check", "index", "A Microsoft background task that checks this computer before updates. It finishes by itself.")],
24
+ [["wsappx", "appxsvc"], K("Microsoft Store (app updates)", "update", "Apps from the Microsoft Store are being installed or updated. It finishes by itself.")],
25
+ [["officeclicktorun"], K("Microsoft Office updater", "update", "Office is checking for or installing an update. It finishes by itself.")],
26
+ [["msiexec"], K("A program installer (Windows Installer)", "update", "A program is being installed, updated or repaired. It finishes by itself.")],
27
+ [["dfrgui", "defrag"], K("Drive optimization", "scan", "Windows tidying up the drive. It finishes by itself.")],
28
+ [["onedrive", "onedrive.sync.service", "filecoauth"], K("OneDrive", "sync", SYNC_NOTE)],
29
+ [["dropbox"], K("Dropbox", "sync", SYNC_NOTE)],
30
+ [["googledrivefs"], K("Google Drive", "sync", SYNC_NOTE)],
31
+ [["iclouddrive", "icloudservices", "icloud", "icloudphotos"], K("iCloud", "sync", SYNC_NOTE)],
32
+ [["system"], K("Windows itself (System)", "system", "The core of Windows and its hardware drivers. If it stays busy for a long time, a restart usually calms it down. If it does not, a hardware driver needs updating.")],
33
+ [["memory compression"], K("Windows memory compression", "system", "Windows squeezing memory to make room. A large number here means memory is tight.")],
34
+ [["dwm"], K("Desktop Window Manager (draws the screen)", "system", "Part of Windows that draws every window. If it is busy all the time, update the graphics driver.")],
35
+ [["explorer"], K("Windows Explorer (desktop, taskbar, file windows)", "system", "Part of Windows. If it misbehaves, signing out and back in restarts it.")],
36
+ [["wmiprvse", "wmiapsrv"], K("Windows system information service", "self", "Answers questions about the computer. This check itself keeps it busy for a few seconds.")],
37
+ // Not a program at all: Windows' name for processor time that nobody is using.
38
+ [["idle", "system idle process"], K("Idle time", "self")],
39
+ [["chrome"], K("Google Chrome", "browser", BROWSER_NOTE)],
40
+ [["msedge"], K("Microsoft Edge", "browser", BROWSER_NOTE)],
41
+ [["firefox"], K("Firefox", "browser", BROWSER_NOTE)],
42
+ [["brave"], K("Brave", "browser", BROWSER_NOTE)],
43
+ [["opera", "vivaldi"], K("Web browser", "browser", BROWSER_NOTE)],
44
+ [["msedgewebview2"], K("Edge WebView (web pages inside other apps)", "app", "Used by apps such as Teams, Outlook and Widgets to show web content. It closes when those apps close.")],
45
+ [["ms-teams", "teams", "msteams"], K("Microsoft Teams", "app")],
46
+ [["zoom"], K("Zoom", "app")],
47
+ [["slack"], K("Slack", "app")],
48
+ [["discord"], K("Discord", "app")],
49
+ [["spotify"], K("Spotify", "app")],
50
+ [["steam", "steamwebhelper", "steamservice"], K("Steam", "app")],
51
+ [["epicgameslauncher", "epicwebhelper"], K("Epic Games Launcher", "app")],
52
+ [["eadesktop", "eacefsubprocess", "eabackgroundservice", "ealocalhostsvc"], K("EA app", "app")],
53
+ [["battle.net", "agent"], K("Battle.net", "app")],
54
+ [["outlook", "olk"], K("Outlook", "app")],
55
+ [["winword"], K("Word", "app")],
56
+ [["excel"], K("Excel", "app")],
57
+ [["powerpnt"], K("PowerPoint", "app")],
58
+ [["code"], K("Visual Studio Code", "app")],
59
+ [["claude"], K("Claude", "app")],
60
+ [["vmmem", "vmmemwsl", "vmwp", "vmware-vmx", "virtualboxvm", "vboxheadless", "com.docker.backend", "docker desktop", "wslservice", "vmcompute"], K("Virtual machines (WSL, Docker or similar)", "vm", VM_NOTE)],
61
+ [["mcshield", "mfemms", "mfevtps", "mcuicnt", "mcapexe", "mccspservicehost", "modulecoreservice"], K("McAfee antivirus", "scan", AV_NOTE)],
62
+ [["avp", "avpui"], K("Kaspersky antivirus", "scan", AV_NOTE)],
63
+ [["avastsvc", "avastui", "aswengsrv", "aswidsagent"], K("Avast antivirus", "scan", AV_NOTE)],
64
+ [["avgsvc", "avgui"], K("AVG antivirus", "scan", AV_NOTE)],
65
+ [["nortonsecurity", "nortonsvc", "ns"], K("Norton antivirus", "scan", AV_NOTE)],
66
+ [["bdservicehost", "bdagent", "vsserv"], K("Bitdefender antivirus", "scan", AV_NOTE)],
67
+ [["mbam", "mbamservice"], K("Malwarebytes", "scan", AV_NOTE)],
68
+ [["ekrn", "egui"], K("ESET antivirus", "scan", AV_NOTE)],
69
+ ];
70
+
71
+ // Windows pieces nobody needs to see one by one. They are added up under one line.
72
+ const WINDOWS_BACKGROUND = new Set(
73
+ (
74
+ "svchost services lsass csrss wininit winlogon smss registry fontdrvhost sihost taskhostw runtimebroker ctfmon conhost dllhost " +
75
+ "spoolsv audiodg lsaiso ngciso searchhost startmenuexperiencehost shellexperiencehost shellhost textinputhost widgets widgetservice " +
76
+ "widgetboard wudfhost unsecapp securityhealthservice securityhealthsystray sgrmbroker servicehost uihost lockapp logonui " +
77
+ "backgroundtaskhost applicationframehost systemsettings systemsettingsbroker useroobebroker aggregatorhost dashost wlanext " +
78
+ "crossdeviceservice crossdeviceresume phoneexperiencehost gamingservices gamingservicesnet locator sppsvc mousocoreworker " +
79
+ "smartscreen taskmgr sdxhelper backgroundtransferhost"
80
+ ).split(" "),
81
+ );
82
+ for (const spaced of ["secure system", "system interrupts", "interrupts"]) WINDOWS_BACKGROUND.add(spaced);
83
+ const WINDOWS_BACKGROUND_INFO = K("Windows background services", "system", "Many small parts of Windows added together. This is normal; do not end them.");
84
+
85
+ const MAC = [
86
+ [["kernel_task"], K("macOS itself (kernel_task)", "heat", "The core of macOS. When it shows heavy processor use, the Mac is usually hot and is holding the processor back on purpose to cool down. Keep the vents clear and the Mac on a hard, flat surface. It is not something you can quit.")],
87
+ [["windowserver"], K("WindowServer (draws the screen)", "system", "Part of macOS that draws everything on screen. It works harder with many windows, several displays or moving wallpaper.")],
88
+ [["mds", "mds_stores", "mdworker", "mdworker_shared", "mdsync", "mdbulkimport", "corespotlightd", "spotlightknowledged", "spotlight"], K("Spotlight (indexing files)", "index", "macOS is making a list of your files so that searching is fast. Normal after an update or after copying many files. It finishes by itself, usually within an hour or two.")],
89
+ [["photoanalysisd", "photolibraryd", "mediaanalysisd", "mediaanalysisd-access"], K("Photos (sorting your photo library)", "index", "Photos is looking through pictures for faces and scenes. It runs while the Mac is plugged in and finishes by itself; a big library can take a few days.")],
90
+ [["backupd", "backupd-helper"], K("Time Machine backup", "backup", "A backup is running. It finishes by itself. Let it.")],
91
+ [["bird", "cloudd", "fileproviderd", "nsurlsessiond"], K("iCloud (syncing files)", "sync", SYNC_NOTE)],
92
+ [["softwareupdated", "installd", "system_installd", "mobileassetd", "softwareupdatenotificationmanager"], K("macOS software update", "update", "macOS is downloading or installing an update. This is normal. Let it finish and restart when it asks.")],
93
+ [["xprotect", "xprotectservice", "xprotectpluginservice", "xprotectremediator"], K("macOS malware scan (XProtect)", "scan", "The built-in malware scan. It finishes by itself.")],
94
+ [["trustd", "syspolicyd"], K("macOS security checks", "scan", "macOS checking that apps are safe to open. Short bursts are normal.")],
95
+ [["wallpaperaerialsextension", "wallpapervideoextension", "screensaverengine", "legacyscreensaver"], K("Moving wallpaper or screen saver", "app", "The animated wallpaper or screen saver. Choosing a still picture in System Settings > Wallpaper saves processor time and battery.")],
96
+ [["vtdecoderxpcservice", "vtencoderxpcservice"], K("Video playback", "app", "Shows that a video is playing or being recorded somewhere.")],
97
+ [["safari", "com.apple.webkit.webcontent", "com.apple.webkit.gpu", "com.apple.webkit.networking"], K("Safari", "browser", BROWSER_NOTE)],
98
+ [["google chrome"], K("Google Chrome", "browser", BROWSER_NOTE)],
99
+ [["microsoft edge"], K("Microsoft Edge", "browser", BROWSER_NOTE)],
100
+ [["firefox"], K("Firefox", "browser", BROWSER_NOTE)],
101
+ [["brave browser", "arc", "opera", "vivaldi"], K("Web browser", "browser", BROWSER_NOTE)],
102
+ [["ios simulator", "simulator"], K("iOS Simulator", "vm", "A pretend iPhone used for making apps. It uses a lot of memory. Quit Simulator when you are not using it.")],
103
+ [["docker", "com.docker.virtualization", "com.docker.backend", "com.apple.virtualization.virtualmachine", "virtual machine service", "qemu-system-aarch64", "qemu-system-x86_64", "vmware fusion", "parallels desktop", "prl_vm_app", "utm"], K("Virtual machines (Docker or similar)", "vm", VM_NOTE)],
104
+ [["dropbox"], K("Dropbox", "sync", SYNC_NOTE)],
105
+ [["onedrive"], K("OneDrive", "sync", SYNC_NOTE)],
106
+ [["google drive"], K("Google Drive", "sync", SYNC_NOTE)],
107
+ [["avast", "avast security", "com.avast.daemon"], K("Avast antivirus", "scan", AV_NOTE)],
108
+ [["finder"], K("Finder", "system", "Part of macOS: the desktop and file windows.")],
109
+ [["claude"], K("Claude", "app")],
110
+ ];
111
+ const MAC_BACKGROUND_INFO = K("macOS background services", "system", "Many small parts of macOS added together. This is normal; they are not something to quit.");
112
+ const MAC_SYSTEM_PATH = /^(\/System\/|\/usr\/libexec\/|\/usr\/sbin\/|\/usr\/bin\/|\/sbin\/|\/bin\/|\/Library\/Apple\/)/;
113
+
114
+ const LINUX = [
115
+ [["gnome-shell", "plasmashell", "kwin_x11", "kwin_wayland", "cinnamon", "xfwm4", "mutter"], K("Desktop (draws the screen and windows)", "system", "Part of the desktop. Logging out and back in restarts it.")],
116
+ [["xorg", "xwayland"], K("Display server (draws the screen)", "system", "Part of the desktop.")],
117
+ [["tracker-miner-f", "tracker-extract", "baloo_file", "baloo_file_extr", "updatedb", "updatedb.mlocat", "updatedb.plocat"], K("File indexing", "index", "The system is making a list of your files so that searching is fast. It finishes by itself.")],
118
+ [["packagekitd", "apt", "apt-get", "aptd", "dpkg", "unattended-upgr", "snapd", "dnf", "yum", "update-manager", "gnome-software", "flatpak"], K("Software updates", "update", "The system is checking for or installing updates. This is normal and finishes by itself.")],
119
+ [["kswapd0", "kswapd1", "kcompactd0"], K("Memory juggling (kswapd)", "system", "The system is short on memory and is busy moving things out to the disk.")],
120
+ [["firefox", "firefox-bin", "firefox-esr", "web content", "isolated web co", "privileged cont", "webextensions", "socket process", "rdd process", "isolated servic"], K("Firefox", "browser", BROWSER_NOTE)],
121
+ [["chrome", "google-chrome", "chrome_crashpad"], K("Google Chrome", "browser", BROWSER_NOTE)],
122
+ [["chromium", "chromium-browse"], K("Chromium", "browser", BROWSER_NOTE)],
123
+ [["qemu-system-x86", "qemu-system-aar", "vboxheadless", "virtualboxvm", "dockerd", "containerd", "containerd-shim", "vmware-vmx"], K("Virtual machines or containers", "vm", VM_NOTE)],
124
+ [["dropbox"], K("Dropbox", "sync", SYNC_NOTE)],
125
+ [["clamd", "freshclam", "clamscan"], K("ClamAV antivirus", "scan", AV_NOTE)],
126
+ [["claude"], K("Claude", "app")],
127
+ ];
128
+ const LINUX_BACKGROUND = /^(systemd(-.*)?|\(sd-pam\)|dbus-daemon|dbus-broker(-lau.*)?|networkmanager|polkitd|udisksd|upowerd|rtkit-daemon|accounts-daemon|wpa_supplicant|avahi-daemon|cron|rsyslogd|pipewire(-pulse)?|wireplumber|pulseaudio|gvfsd.*|gsd-.*|at-spi.*|ibus-.*|xdg-.*|gdm.*|sshd|agetty|login|irqbalance|thermald|colord|cupsd|cups-browsed|modemmanager|snapfuse|multipathd|power-profiles-|switcheroo-cont|bluetoothd|fwupd|evolution-.*|goa-.*|gnome-keyring-d|dconf-service)$/;
129
+ const LINUX_BACKGROUND_INFO = K("System background services", "system", "Many small parts of the system added together. This is normal.");
130
+ const LINUX_KERNEL_INFO = K("The Linux kernel", "system", "The core of the system. Not something to stop.");
131
+
132
+ function table(rows) {
133
+ const m = new Map();
134
+ for (const [names, info] of rows) for (const n of names) m.set(n, info);
135
+ return m;
136
+ }
137
+ const TABLES = { win32: table(WINDOWS), darwin: table(MAC), linux: table(LINUX) };
138
+
139
+ /** macOS: the app a process belongs to, from its program path. "Google Chrome Helper (Renderer)" counts as Google Chrome. */
140
+ export function macAppName(comm) {
141
+ const c = String(comm || "").trim();
142
+ if (/\/CoreSimulator\//.test(c)) return "iOS Simulator";
143
+ const app = /\/([^/]+)\.app\//.exec(c);
144
+ if (app) return app[1];
145
+ if (c.startsWith("/")) return path.posix.basename(c);
146
+ // Not a path but a title a program gave itself, such as "sshd: someone [priv]". Keep only the program part.
147
+ return c.split(/[\s:]/)[0] || c;
148
+ }
149
+
150
+ /**
151
+ * Who is this process, in words a person would recognize?
152
+ * raw: { name, kernel? }. On macOS name is the full program path as ps prints it.
153
+ * Returns { name, kind, note }.
154
+ */
155
+ export function identify(platform, raw) {
156
+ const t = TABLES[platform] || new Map();
157
+ if (platform === "win32") {
158
+ const base = String(raw.name || "").replace(/#\d+$/, "").replace(/\.exe$/i, "");
159
+ const key = base.toLowerCase();
160
+ const hit = t.get(key);
161
+ if (hit) return { name: hit.title, kind: hit.kind, note: hit.note };
162
+ if (WINDOWS_BACKGROUND.has(key)) return { name: WINDOWS_BACKGROUND_INFO.title, kind: "system", note: WINDOWS_BACKGROUND_INFO.note };
163
+ return { name: cleanText(base, 48) || "unknown", kind: "app", note: null };
164
+ }
165
+ if (platform === "darwin") {
166
+ const comm = String(raw.name || "");
167
+ const name = macAppName(comm);
168
+ const hit = t.get(name.toLowerCase());
169
+ if (hit) return { name: hit.title, kind: hit.kind, note: hit.note };
170
+ const isApp = /\/([^/]+)\.app\//.test(comm);
171
+ const underSystemLibrary = comm.startsWith("/System/Library/");
172
+ if ((!isApp && MAC_SYSTEM_PATH.test(comm)) || (isApp && underSystemLibrary)) return { name: MAC_BACKGROUND_INFO.title, kind: "system", note: MAC_BACKGROUND_INFO.note };
173
+ return { name: cleanText(name, 48) || "unknown", kind: "app", note: null };
174
+ }
175
+ const name = String(raw.name || "").trim().replace(/\.exe$/i, "");
176
+ const key = name.toLowerCase();
177
+ const hit = t.get(key);
178
+ if (hit) return { name: hit.title, kind: hit.kind, note: hit.note };
179
+ if (raw.kernel) return { name: LINUX_KERNEL_INFO.title, kind: "system", note: LINUX_KERNEL_INFO.note };
180
+ if (LINUX_BACKGROUND.test(key)) return { name: LINUX_BACKGROUND_INFO.title, kind: "system", note: LINUX_BACKGROUND_INFO.note };
181
+ return { name: cleanText(name, 48) || "unknown", kind: "app", note: null };
182
+ }
183
+
184
+ /**
185
+ * procs: [{ name, cpu, mem, kernel? }] with cpu as a percentage of ONE processor core and mem in bytes.
186
+ * Returns apps: [{ name, kind, note, count, corePct, cpuPct, memBytes }], where cpuPct is the share
187
+ * of the whole computer (all cores together).
188
+ */
189
+ export function groupApps(platform, procs, cores) {
190
+ const n = Math.max(1, cores || 1);
191
+ const apps = new Map();
192
+ for (const p of procs || []) {
193
+ const id = identify(platform, p);
194
+ let a = apps.get(id.name);
195
+ if (!a) {
196
+ a = { name: id.name, kind: id.kind, note: id.note, count: 0, corePct: 0, memBytes: 0 };
197
+ apps.set(id.name, a);
198
+ }
199
+ a.count += 1;
200
+ a.corePct += Number.isFinite(p.cpu) ? Math.max(0, p.cpu) : 0;
201
+ a.memBytes += Number.isFinite(p.mem) ? Math.max(0, p.mem) : 0;
202
+ }
203
+ const list = [...apps.values()];
204
+ for (const a of list) {
205
+ a.corePct = Math.round(a.corePct * 10) / 10;
206
+ a.cpuPct = Math.round((a.corePct / n) * 10) / 10;
207
+ }
208
+ return list;
209
+ }
210
+
211
+ export const topBy = (apps, key, count = 5) => [...(apps || [])].sort((a, b) => b[key] - a[key]).slice(0, count);
@@ -0,0 +1,287 @@
1
+ // Turns the gathered facts into a verdict a non-technical person can act on. Pure: facts in,
2
+ // { verdict, findings, steps } out, so every rule can be tested with made-up facts.
3
+ import { isTemporary, topBy } from "./apps.js";
4
+ import { memSize, diskSize } from "./units.js";
5
+
6
+ const GB = 1024 ** 3;
7
+
8
+ export const LIMITS = {
9
+ disk: { problemFreeGb: 5, problemPct: 5, problemPctBelowGb: 20, warnFreeGb: 15, warnPct: 10, warnPctBelowGb: 50 },
10
+ memory: { outAvailPct: 5, tightAvailPct: 15, commitOutPct: 95, commitTightPct: 85, waitOutPct: 10, macSwapShareOut: 0.5 },
11
+ cpu: { busyPct: 85, appSharePct: 50, oneCorePct: 90, mentionPct: 15 },
12
+ diskBusyPct: 90,
13
+ uptimeDays: { win32: 14, darwin: 30, linux: 60 },
14
+ startupMany: { win32: 10, darwin: 15, linux: 10 },
15
+ batteryWornPct: 80,
16
+ };
17
+
18
+ const QUIT = {
19
+ win32: "To close a program that is stuck: press Ctrl+Shift+Esc, pick it in the list and choose End task.",
20
+ darwin: "To close an app that is stuck: press Option+Command+Esc, pick it and choose Force Quit.",
21
+ linux: "To close a program that is stuck: open System Monitor, pick it and choose End Process.",
22
+ };
23
+ const RESTART = {
24
+ win32: "Restart the computer: Start > Power > Restart. Use Restart, not Shut down: on Windows only Restart gives a completely fresh start.",
25
+ darwin: "Restart the Mac: Apple menu > Restart.",
26
+ linux: "Restart the computer.",
27
+ };
28
+ const LOW_POWER_OFF = {
29
+ win32: "When you need full speed, turn Energy saver off: Settings > System > Power & battery.",
30
+ darwin: "When you need full speed, turn Low Power Mode off: System Settings > Battery.",
31
+ linux: "When you need full speed, switch the power mode to Balanced or Performance in Settings > Power.",
32
+ };
33
+
34
+ const STEP = {
35
+ backupNow: "Copy your important files to another drive or to cloud storage today, before doing anything else.",
36
+ replaceDrive: "Have the drive replaced. A repair shop can do this and move your files and programs across.",
37
+ freeSpace: "Free up space on the system drive. Ask me what is using your disk space and I will show where it went.",
38
+ emptyTrash: "Empty the Trash or Recycle Bin, and clear out your Downloads folder.",
39
+ closeApps: "Close programs you are not using.",
40
+ tabs: "Close web browser tabs you are not using. Each one uses memory.",
41
+ moreMemory: "If this happens often with only a few things open, this computer needs more memory for the way you use it. A repair shop can say whether more can be added; on many thin laptops and recent Macs it cannot.",
42
+ wait: "Give it time. This kind of work finishes by itself; the computer speeds up again afterwards.",
43
+ again: "If the computer is only slow some of the time, run this check again while it is slow.",
44
+ cool: "Let it cool: put it on a hard, flat surface (not a bed or sofa), make sure the air vents are not blocked, and close heavy programs.",
45
+ dust: "If it overheats often, the vents and fan are probably full of dust. A repair shop can clean them.",
46
+ ssd: "Replace the hard drive with a solid-state drive (SSD). It is the biggest single speed-up for a computer like this, and a repair shop can copy everything across.",
47
+ startup: "Ask me to check what starts with the computer, and turn off the ones you do not need.",
48
+ net: "If it is web pages, video or downloads that are slow, the cause may be the internet connection and not this computer. Home Net Doctor, a companion tool, checks that.",
49
+ battery: "A worn battery mostly means less time away from the charger. If that bothers you, the battery can be replaced.",
50
+ diskBusy: "If the disk is busy like this all the time, check for a backup, sync or antivirus program that never finishes.",
51
+ };
52
+
53
+ export function memoryState(m, platform) {
54
+ if (!m || !m.total) return null;
55
+ const availPct = m.available === null || m.available === undefined ? null : (100 * m.available) / m.total;
56
+ const L = LIMITS.memory;
57
+ if (platform === "darwin" && m.pressure) {
58
+ // macOS judges this itself. "short" is its warning zone with a lot already pushed out to the disk.
59
+ const swapShare = m.swapUsed ? m.swapUsed / m.total : 0;
60
+ if (m.pressure === "critical") return "out";
61
+ if (m.pressure === "warn") return swapShare >= L.macSwapShareOut ? "short" : "tight";
62
+ return "ok";
63
+ }
64
+ if (m.waitPct !== null && m.waitPct !== undefined && m.waitPct >= L.waitOutPct) return "out";
65
+ if (m.commitPct !== null && m.commitPct !== undefined && m.commitPct >= L.commitOutPct) return "out";
66
+ if (availPct !== null && availPct < L.outAvailPct) return "out";
67
+ if ((m.commitPct !== null && m.commitPct !== undefined && m.commitPct >= L.commitTightPct) || (availPct !== null && availPct < L.tightAvailPct)) return "tight";
68
+ return availPct === null ? null : "ok";
69
+ }
70
+
71
+ export function diskState(d) {
72
+ if (!d || !Number.isFinite(d.total) || !Number.isFinite(d.free) || d.total <= 0) return null;
73
+ const freeGb = d.free / GB;
74
+ const pct = (100 * d.free) / d.total;
75
+ const L = LIMITS.disk;
76
+ if (freeGb < L.problemFreeGb || (pct < L.problemPct && freeGb < L.problemPctBelowGb)) return "full";
77
+ if (freeGb < L.warnFreeGb || (pct < L.warnPct && freeGb < L.warnPctBelowGb)) return "low";
78
+ return "ok";
79
+ }
80
+
81
+ const days = (sec) => Math.floor(sec / 86400);
82
+ const procs = (a) => (a.count > 1 ? `, in ${a.count} processes` : "");
83
+ export const pct = (x) => (x === null || x === undefined ? "?" : x > 0 && x < 1 ? "under 1%" : `${Math.round(x)}%`);
84
+
85
+ export function diagnose(f) {
86
+ const findings = [];
87
+ const add = (level, area, text) => findings.push({ level, area, text });
88
+ const steps = [];
89
+ const step = (...texts) => texts.forEach((t) => t && !steps.includes(t) && steps.push(t));
90
+ const p = f.platform;
91
+
92
+ const apps = (f.apps || []).filter((a) => a.kind !== "self");
93
+ const byCpu = topBy(apps, "cpuPct", 5);
94
+ const top = byCpu[0] || null;
95
+ const use = f.cpu?.usePct ?? null;
96
+ const cores = f.cores || 1;
97
+
98
+ // ---- processor ----
99
+ const hog = top && top.cpuPct >= LIMITS.cpu.appSharePct ? top : null;
100
+ const oneCore = !hog && top && cores >= 4 && top.corePct >= LIMITS.cpu.oneCorePct ? top : null;
101
+ const flatOut = use !== null && use >= LIMITS.cpu.busyPct;
102
+ if (flatOut) add("problem", "cpu", `The processor is flat out: ${pct(use)} busy during the check.`);
103
+ else if (use !== null && use >= 50) add("note", "cpu", `The processor is fairly busy: ${pct(use)} during the check.`);
104
+ else if (use !== null) add("ok", "cpu", `The processor has plenty to spare: ${pct(use)} busy during the check.`);
105
+ for (const a of byCpu) {
106
+ if (a === oneCore) {
107
+ // A core's worth of work is normal for a video call, a game or an export, so this is only a note.
108
+ add("note", "cpu", `${a.name} is using about one whole processor core${procs(a)}.${a.note ? ` ${a.note}` : " That is normal while it is doing real work, such as a video call, a game or an export. If it does this while you are not using it, quit it and open it again."}`);
109
+ continue;
110
+ }
111
+ if (a.cpuPct < LIMITS.cpu.mentionPct) continue;
112
+ add(a === hog ? "problem" : "note", "cpu", `${a.name} is using ${pct(a.cpuPct)} of the processor${procs(a)}.${a.note ? ` ${a.note}` : ""}`);
113
+ }
114
+
115
+ // ---- heat ----
116
+ const limit = f.thermal?.speedLimit;
117
+ const kernelTask = apps.find((a) => a.kind === "heat" && a.corePct >= 80);
118
+ const hot = (limit !== null && limit !== undefined && limit < 100) || f.thermal?.throttledNow === true || Boolean(kernelTask);
119
+ if (hot) {
120
+ add("problem", "heat", `The computer is hot and is holding its processor back to cool down${limit !== null && limit !== undefined && limit < 100 ? ` (speed limited to ${limit}%)` : ""}.`);
121
+ }
122
+
123
+ // ---- memory ----
124
+ const m = f.memory;
125
+ const mem = memoryState(m, p);
126
+ // Only things a person can close are named as memory users to act on; system parts never are.
127
+ const closable = (a) => ["app", "browser", "vm", "sync"].includes(a.kind);
128
+ const memTop = topBy(apps.filter(closable), "memBytes", 3).filter((a) => a.memBytes >= 0.3 * GB);
129
+ const memTopText = memTop.length ? ` The biggest users you could close: ${memTop.map((a) => `${a.name} ${memSize(a.memBytes)}`).join("; ")}.` : "";
130
+ const short = mem === "out" || mem === "short";
131
+ if (m?.total && p === "darwin" && m.pressure) {
132
+ const swapText = m.swapUsed >= 1 * GB ? ` and has moved ${memSize(m.swapUsed)} of work out to the disk to cope` : "";
133
+ if (mem === "out") add("problem", "memory", `Memory is full: macOS reports its memory pressure as critical (red in Activity Monitor)${swapText}. Fetching that work back from the disk is what makes everything slow.${memTopText}`);
134
+ else if (mem === "short") add("problem", "memory", `Memory is short: macOS reports memory pressure in its warning zone (yellow in Activity Monitor)${swapText}. Fetching that work back from the disk is what makes switching between apps slow.${memTopText}`);
135
+ else if (mem === "tight") add("warning", "memory", `Memory is getting tight: macOS reports memory pressure in its warning zone (yellow in Activity Monitor). Opening more will start to slow things down.${memTopText}`);
136
+ else add("ok", "memory", `Memory is fine: macOS reports normal memory pressure (${memSize(m.total)} installed).`);
137
+ } else if (m?.total) {
138
+ const freeText = m.available === null || m.available === undefined ? "" : `${memSize(m.available)} of ${memSize(m.total)} is available`;
139
+ const swapText = p === "linux" && m.swapUsed >= 1 * GB ? ` ${memSize(m.swapUsed)} of work has been moved out to the disk (swap).` : "";
140
+ if (mem === "out") add("problem", "memory", `Memory is full${freeText ? `: only ${freeText}` : ""}.${swapText} When memory runs out, the computer uses the disk as overflow, which is far slower.${memTopText}`);
141
+ else if (mem === "tight") add("warning", "memory", `Memory is nearly full${freeText ? `: ${freeText}` : ""}.${swapText} Opening more will start to slow things down.${memTopText}`);
142
+ else if (mem === "ok") add("ok", "memory", `Memory is fine${freeText ? `: ${freeText}` : ""}.`);
143
+ } else add("note", "memory", "I could not read how much memory is in use.");
144
+
145
+ // ---- system drive ----
146
+ const d = f.drive || {};
147
+ const disk = diskState(d);
148
+ if (d.health === "failing") add("problem", "drive", "The system drive reports that it is failing. It can stop working without further warning, and files on it can be lost.");
149
+ else if (d.health === "warn") add("warning", "drive", "The system drive reports a health warning. It may be starting to fail.");
150
+ if (disk) {
151
+ const pctFull = Math.round(100 * (1 - d.free / d.total));
152
+ const text = `${diskSize(d.free, p)} free of ${diskSize(d.total, p)} on the system drive (${pctFull}% full)`;
153
+ if (disk === "full") add("problem", "disk", `The system drive is almost full: ${text}. The system needs free space to work; without it everything slows down and updates fail.`);
154
+ else if (disk === "low") add("warning", "disk", `The system drive is getting full: ${text}.`);
155
+ else add("ok", "disk", `There is enough free space: ${text}.`);
156
+ } else add("note", "disk", "I could not read the free space on the system drive.");
157
+ const isHdd = d.kind === "hdd" && !d.virtual;
158
+ if (isHdd) add("warning", "drive", "This computer runs from a spinning hard drive. Those are far slower than the solid-state drives (SSDs) in computers today, and are the most common reason an older computer feels slow at everything.");
159
+ // In a virtual machine the "drive" is a file the host provides, so its type and health say nothing.
160
+ else if (!d.virtual && d.kind === "ssd" && d.health !== "failing" && d.health !== "warn") add("ok", "drive", `The system drive is a solid-state drive (SSD)${d.health === "ok" ? " and reports good health" : ""}.`);
161
+ else if (!d.virtual && d.health === "ok") add("ok", "drive", "The system drive reports good health.");
162
+ if (d.virtual) add("note", "drive", "This is a virtual machine, so the drive type, drive health and temperature cannot be read from inside it.");
163
+ const diskBusy = d.busyPct !== null && d.busyPct !== undefined && d.busyPct >= LIMITS.diskBusyPct;
164
+ if (diskBusy) add("problem", "diskbusy", `The disk was working flat out during the check (${Math.round(d.busyPct)}% busy). While that goes on, everything that needs the disk has to wait.`);
165
+
166
+ // ---- power ----
167
+ const saver = f.power?.saver === true;
168
+ if (saver) add("warning", "power", `${p === "darwin" ? "Low Power Mode" : p === "win32" ? "Energy saver (battery saver)" : "The low-power profile"} is on. It slows the computer on purpose to make the battery last longer.`);
169
+ else if (f.power?.efficiencyMode) {
170
+ add("note", "power", "The Windows power mode is set to \"Best power efficiency\", which trades some speed for battery life.");
171
+ }
172
+
173
+ // ---- restart ----
174
+ const up = Number.isFinite(f.uptimeSec) ? days(f.uptimeSec) : null;
175
+ const overdue = up !== null && up >= (LIMITS.uptimeDays[p] ?? 30);
176
+ const pending = f.restart?.pending === true;
177
+ if (pending) add("warning", "restart", "A restart is waiting to finish installing updates. Until it happens, the computer can be slow and is missing those fixes.");
178
+ if (overdue) {
179
+ add(
180
+ p === "win32" ? "warning" : "note",
181
+ "restart",
182
+ `This computer has been running for ${up} days without a restart.${p === "win32" && f.restart?.fastStartup ? " Shutting down does not count on this PC: Windows only half-closes when you choose Shut down (a feature called Fast Startup), so problems carry over. Only Restart clears them." : " Small problems build up over time, and a restart clears them."}`,
183
+ );
184
+ } else if (up !== null && !pending) add("ok", "restart", up < 1 ? "It was restarted in the last day." : `It was last restarted ${up} day${up === 1 ? "" : "s"} ago.`);
185
+
186
+ // ---- startup programs ----
187
+ const sc = f.startup?.count;
188
+ const many = sc !== null && sc !== undefined && sc >= (LIMITS.startupMany[p] ?? 10);
189
+ const thing = p === "darwin" ? "background helper" : "program";
190
+ if (many) add("warning", "startup", `${sc} ${thing}s that you could turn off start by themselves when you sign in. Each one makes start-up slower and keeps using memory all day.`);
191
+ else if (sc !== null && sc !== undefined) add("ok", "startup", `${sc === 0 ? `No optional ${thing}s start` : sc === 1 ? `1 optional ${thing} starts` : `${sc} optional ${thing}s start`} by ${sc === 1 ? "itself" : "themselves"} at sign-in. That is a normal amount.`);
192
+
193
+ // ---- battery ----
194
+ const b = f.battery || {};
195
+ const worn = b.present && ((b.healthPct !== null && b.healthPct !== undefined && b.healthPct < LIMITS.batteryWornPct) || /service|replace|poor/i.test(b.condition || ""));
196
+ if (worn) add("warning", "battery", `The battery is worn${b.healthPct !== null && b.healthPct !== undefined ? `: it holds about ${b.healthPct}% of what it did when new` : ""}${b.cycles ? ` (${b.cycles} charge cycles)` : ""}.`);
197
+ else if (b.present && b.healthPct !== null && b.healthPct !== undefined) add("ok", "battery", `The battery is in good shape: about ${b.healthPct}% of its original capacity${b.cycles ? `, ${b.cycles} charge cycles` : ""}.`);
198
+
199
+ if (f.wmiRefused) add("note", "check", "Windows did not answer some of my questions (its management service, WMI, refused or is not working), so this check is less complete than usual. Restarting the computer usually fixes this.");
200
+ else if (f.incomplete) add("note", "check", "Some readings were not available on this computer, so this check is less complete than usual.");
201
+
202
+ // ---- the verdict: the first of these that applies ----
203
+ let verdict;
204
+ const name = (a) => a.name;
205
+ if (d.health === "failing") {
206
+ verdict = { code: "drive_failing", title: "The system drive says it is failing. Back up your files now." };
207
+ step(STEP.backupNow, STEP.replaceDrive);
208
+ } else if (disk === "full") {
209
+ verdict = { code: "disk_full", title: `The system drive is almost full (${diskSize(d.free, p)} left). That alone makes a computer slow.` };
210
+ step(STEP.emptyTrash, STEP.freeSpace);
211
+ } else if (short) {
212
+ verdict =
213
+ mem === "out"
214
+ ? { code: "memory_out", title: "The computer has run out of memory: more is open than it has room for." }
215
+ : { code: "memory_short", title: "The computer is short on memory: more is open than fits, so it keeps moving work out to the disk and back." };
216
+ if (memTop[0]) step(`Close what you are not using, starting with the biggest: ${memTop.map((a) => `${a.name}, ${memSize(a.memBytes)}`).join("; ")}.`);
217
+ else step(STEP.closeApps);
218
+ if (memTop.some((a) => a.kind === "browser")) step(STEP.tabs);
219
+ step(RESTART[p], STEP.moreMemory);
220
+ } else if (hog && hog.kind !== "heat" && isTemporary(hog.kind)) {
221
+ verdict = { code: "background", title: `The computer is busy with background work right now: ${name(hog)}. This is temporary.` };
222
+ step(STEP.wait, "Leaving the computer on and plugged in lets it finish sooner.", STEP.again);
223
+ } else if (hog && hog.kind !== "heat") {
224
+ verdict = { code: "runaway", title: `One program is using most of the processor: ${name(hog)} (${pct(hog.cpuPct)}).` };
225
+ if (hog.kind === "system") step("This is part of the system, so do not try to end it.", RESTART[p]);
226
+ else step(`If you are not using ${name(hog)} right now, quit it (save your work first).`, QUIT[p], `If ${name(hog)} does this every time, update it or reinstall it.`);
227
+ } else if (hot) {
228
+ verdict = { code: "heat", title: "The computer is overheating and has slowed itself down to cool off." };
229
+ step(STEP.cool, STEP.dust);
230
+ } else if (flatOut) {
231
+ const names = byCpu.filter((a) => a.cpuPct >= 5).slice(0, 3).map(name);
232
+ verdict = { code: "cpu_busy", title: `The processor is flat out, shared between several programs${names.length ? ` (${names.join(", ")})` : ""}.` };
233
+ step(STEP.closeApps, STEP.again);
234
+ } else if (diskBusy) {
235
+ verdict = { code: "disk_busy", title: "The disk is working flat out, and everything else is waiting for it." };
236
+ step("This is often an update, a virus scan or file indexing, and it passes. Give it 15 minutes, then run this check again.", STEP.diskBusy);
237
+ if (isHdd) step(STEP.ssd);
238
+ } else if (saver) {
239
+ verdict = { code: "low_power", title: "A battery-saving mode is on, and it slows the computer on purpose." };
240
+ step(LOW_POWER_OFF[p], "Plugging in the charger also helps.");
241
+ } else if (isHdd) {
242
+ verdict = { code: "hdd", title: "This computer runs from an old-style spinning hard drive. That is the main reason it feels slow." };
243
+ step(STEP.ssd);
244
+ } else if (pending) {
245
+ verdict = { code: "restart_pending", title: "A restart is needed to finish installing updates." };
246
+ step(RESTART[p]);
247
+ } else if (overdue && p === "win32") {
248
+ verdict = { code: "restart_overdue", title: `The computer has not had a real restart for ${up} days. A restart is the first thing to try.` };
249
+ step(RESTART[p]);
250
+ } else if (many) {
251
+ verdict = { code: "startup_many", title: `${sc} ${thing}s start by themselves at sign-in. That slows start-up and uses memory all day.` };
252
+ step(STEP.startup);
253
+ } else if (d.health === "warn") {
254
+ verdict = { code: "warning_drive", title: "Nothing explains slowness right now, but the system drive reports a health warning." };
255
+ step(STEP.backupNow, "Have the drive checked by a repair shop.");
256
+ } else if (disk === "low") {
257
+ verdict = { code: "warning_disk", title: `Nothing is badly wrong, but the system drive is getting full (${diskSize(d.free, p)} left).` };
258
+ step(STEP.freeSpace);
259
+ } else if (mem === "tight") {
260
+ verdict = { code: "warning_memory", title: "Nothing is badly wrong, but memory is nearly full." };
261
+ if (memTop[0]) step(`If things feel slow, close what you are not using, starting with: ${memTop.map((a) => `${a.name}, ${memSize(a.memBytes)}`).join("; ")}.`);
262
+ if (memTop.some((a) => a.kind === "browser")) step(STEP.tabs);
263
+ } else if (overdue) {
264
+ verdict = { code: "restart_overdue", title: `Nothing is clearly wrong. The computer has not been restarted for ${up} days, so a restart is worth trying.` };
265
+ step(RESTART[p]);
266
+ } else if (worn) {
267
+ verdict = { code: "warning_battery", title: "Nothing on this computer explains slowness right now. The battery is worn, though." };
268
+ step(STEP.battery);
269
+ } else {
270
+ verdict = { code: "healthy", title: "Nothing on this computer explains slowness right now." };
271
+ }
272
+
273
+ // Extra advice for the lesser things found along the way.
274
+ if (verdict.code !== "disk_full" && disk === "low") step(STEP.freeSpace);
275
+ if (verdict.code !== "restart_pending" && pending) step(RESTART[p]);
276
+ if (!["restart_overdue", "restart_pending", "memory_out", "memory_short"].includes(verdict.code) && overdue && p === "win32") step(RESTART[p]);
277
+ if (verdict.code !== "low_power" && saver) step(LOW_POWER_OFF[p]);
278
+ if (f.power?.efficiencyMode && !saver) step("For more speed, change the power mode to Balanced: Settings > System > Power & battery > Power mode.");
279
+ if (verdict.code !== "hdd" && isHdd && !diskBusy) step(STEP.ssd);
280
+ if (verdict.code !== "startup_many" && many) step(STEP.startup);
281
+ if (verdict.code !== "warning_battery" && worn) step(STEP.battery);
282
+ if (d.health === "warn" && verdict.code !== "warning_drive") step(STEP.backupNow);
283
+ if (["healthy", "warning_battery", "restart_overdue", "warning_disk", "startup_many"].includes(verdict.code)) step(STEP.net);
284
+ if (!["background", "cpu_busy"].includes(verdict.code)) step(STEP.again);
285
+
286
+ return { verdict, findings, steps, memory: mem, disk };
287
+ }