6 Problems Building a PC Monitor in C, Flask and CrewAI
PC Pulse is a system monitor I built as a browser dashboard. Three parts do the work. A C program judges how healthy the computer is. A Flask server collects the numbers with psutil. A CrewAI crew writes a short health report.
The project is on GitHub, and How to Make AI Projects in C shows how it works. This post covers the other half. You'll see the problems that came up, what each one looked like, and the tests that stop it from coming back.
The screenshots are from my own PC. I ran the checks on Python 3.14 with GCC 16.1 on Windows (the clean-environment check in problem 1 used Python 3.12).
Problem 1: Failed to Load Page (ERR_CONNECTION_REFUSED)
The browser could not reach 127.0.0.1:5000. Of the six, this one is the simplest. I opened http://127.0.0.1:5000/ and the browser said Failed to Load Page with ERR_CONNECTION_REFUSED.
Don't read that as a broken dashboard. It just means nothing is listening on port 5000. The Flask server isn't running. The real reason sits in the terminal where you started it. A missing package is the usual cause.
I reproduced it in a clean Python environment with only Flask installed (the output is shortened):
> python sever.py
Traceback (most recent call last):
File "sever.py", line 18, in <module>
from dotenv import load_dotenv
ModuleNotFoundError: No module named 'dotenv' (exit code 1)
> curl http://127.0.0.1:5000/
(connection refused, status code 000)
Two things are worth knowing.
First, the module that fails first is dotenv, not psutil. Install one package and you hit the next error. Installing python-dotenv alone just moves the failure to No module named 'psutil'. So install everything at once, like the README says:
pip install flask psutil python-dotenv requests
Second, the page can't tell you any of this. With the server down, the terminal is the only place to read the cause.
Problem 2: Disk Usage Was Only the C: Drive
The simplest disk card calls psutil.disk_usage('C:\\') and stops there. On my PC that gives the wrong answer, because I have two drives, C: and D:. So the server adds up every drive.
The numbers differ:
- Measured on my PC
- Used / Total / Percent
- C: drive only - 553 GB / 960 GB / 57.6%
- All drives (what the dashboard shows) - 564 GB / 1,020 GB / 55.3%
Adding up drives has traps, and the code guards against each one. A CD drive has to be skipped. The same device can show up twice. A card reader with no card, or a locked drive, raises PermissionError when you ask for its size. If no drive can be read at all, the code falls back to the drive that holds the project. That way the percentage never divides by zero.
The test below feeds the function exactly those cases:
def test_disk_adds_every_readable_drive_and_skips_the_rest(server, monkeypatch):
parts = [Part("C:\\", "C:\\", "rw,fixed"), Part("D:\\", "D:\\", "rw,fixed"), Part("E:\\", "E:\\", "ro,cdrom"), Part("C:\\", "C:\\", "rw,fixed"), Part("F:\\", "F:\\", "rw,removable")]
sizes = {"C:\\": Usage(500 * GB, 300 * GB, 200 * GB), "D:\\": Usage(250 * GB, 50 * GB, 200 * GB)}
def usage(mountpoint):
if mountpoint == "F:\\":
raise PermissionError("empty card reader")
return sizes[mountpoint]
monkeypatch.setattr(server.psutil, "disk_partitions", lambda all=False: parts)
monkeypatch.setattr(server.psutil, "disk_usage", usage)
used, total = server.total_disk()
assert (used, total) == (350 * GB, 750 * GB)# C: and D: once each; the CD drive, the duplicate and F: are ignored
Problem 3: The CPU Always Reads 0%
Next, the CPU card surprised me. In a fresh process, the first call to psutil.cpu_percent() always returns 0.0. The library measures the change since the previous call, and there isn't one yet.
I checked it directly, with half a second between two readings:
- first reading: 0.0
- second reading, 0.5 s later: 33.8
The dashboard gets around it by asking for the CPU with interval=0.5. That makes /api/stats wait half a second before it answers (I measured 0.55 seconds per request). The "Fix" code does the same thing by hand. It reads every process once to prime the counters, sleeps 0.5 seconds, then reads again.
A test records the reason, so nobody deletes the pause later:
def test_the_first_cpu_reading_is_zero_so_the_counter_must_be_primed():
code = "import psutil, time; a = psutil.cpu_percent(None); time.sleep(0.5); b = psutil.cpu_percent(None); print(a, b)"
first, second = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True).stdout.split()
assert float(first) == 0.0 # a fresh process always reads 0.0 the first time
assert float(second) > 0.0 # the value only means something after a pause
Problem 4: The RAM Is Almost Full, and a Button Has to Help
Memory at 92 percent and the CRITICAL badge, on my PC (13.7 GB of RAM). This problem exists because of my own PC. In the screenshots, the memory card reads 96 percent, then a minute later 92 percent of 13.7 GB. The badge says CRITICAL both times.
So the dashboard got a Fix button. It does two things, and neither kills anything. It asks Windows to page out unused memory from each process (the EmptyWorkingSet call, through ctypes). And it lowers the priority of the busiest programs.
The risk is touching processes you shouldn't. So the code skips the Idle and System processes (PIDs 0 and 4). It also skips any process that Windows won't let it open.
I measured what the call does on a child process holding about 300 MB:
- child working set: 327 MB -> 0 MB after EmptyWorkingSet
- process still running and unharmed: True
- OpenProcess on PID 4 (System) returned a handle: False
The memory is paged out, not lost. The process keeps running. Windows brings the pages in as the program uses them. That's also why the README warns that the button can report 0 MB freed if the memory was just trimmed.
The test makes its own child process, so it never touches any of your programs:
@pytest.mark.skipif(os.name != "nt", reason="EmptyWorkingSet exists only on Windows")
def test_trimming_the_working_set_frees_memory(server, monkeypatch):
import psutil
child = subprocess.Popen([sys.executable, "-c", "import time\nb = bytearray(300 * 1024 * 1024)\n" "for i in range(0, len(b), 4096): b[i] = 1\n" "print('ready', flush=True)\ntime.sleep(60)"], stdout=subprocess.PIPE, text=True)
try:
assert child.stdout.readline().strip() == "ready"
proc = psutil.Process(child.pid)
before = proc.memory_info().rss
only_the_child = type("P", (), {"info": {"pid": child.pid}})() # so no other process of yours is touched
monkeypatch.setattr(server.psutil, "process_iter", lambda attrs=None: iter([only_the_child]))
assert server._trim_working_sets() == 1
time.sleep(0.5)
assert proc.memory_info().rss < before * 0.5 # most of the 300 MB was paged out
finally:
child.kill()
Know the limit. The memory step relies on a Windows-only function. On Linux and macOS it does nothing. Lowering priority works on every system.
Problem 5: Every AI Report Is a Billed Run
My CrewAI usage page: 51 executions all time, 3 this month. A CrewAI crew writes the report in the dashboard, and every crew run costs money. The usage page above shows how fast that adds up: 51 executions in total, 3 this month. If the page asked for a fresh report on every load, you'd get a bill.
So the code has four protections:
- A 10 minute cache.
CACHE_SECONDS = 600. A comment in the code says it's half of the old 5 minute cadence. The page also refreshes the report only every 10 minutes, or when you press Refresh report. - Only real crew reports are cached. If the crew call fails, the built-in analyst steps in. Its answer never goes into the cache. The next request tries the crew again.
- One pass per report. The prompt the server sends says the crew gets ONE run per report. It has no extra tools, no delegation, no follow-up questions and no retries.
- A deadline. Every 3 seconds the server asks the crew how it's doing. After 45 seconds it stops waiting.
Two tests guard the money. The first checks that a second request within ten minutes doesn't start a new run, and that a run starts again once the cache has expired. The second checks that a fallback report is never cached:
def test_a_crew_report_is_reused_for_ten_minutes(crew, monkeypatch):
calls = []
monkeypatch.setattr(crew, "_generate_report", lambda stats: calls.append(1) or ("# report", "crewai"))
crew.generate_report({})
crew.generate_report({})
assert len(calls) == 1 # the second request was served from the cache: no billed run
now = time.time()
monkeypatch.setattr(crew.time, "time", lambda: now + crew.CACHE_SECONDS + 1)
crew.generate_report({})
assert len(calls) == 2 # after ten minutes the cache has expired
Problem 6: The AI Report Quoted Numbers That Were Not Mine
The cards show 13.2 / 13.7 GB of RAM and 523.7 / 950.3 GB of disk. The report's snapshot says something else. I haven't solved this one yet.
Look at the bottom of the screenshot. The report's Snapshot lists 500 MB of 8 GB for memory and 120 GB of 250 GB for storage. The cards above it show 13.7 GB of RAM and 950.3 GB of disk. Those totals can't come from my PC. (The 500 MB of free memory is real, since 13.7 minus 13.2 is about half a gigabyte. The 8 GB isn't.)
The report looked professional and was wrong. That's the dangerous kind of wrong.
I have a guess about the cause, but I haven't tested it. The crew's first task, Read the vitals, gets every number as a placeholder ({cpu}, {mem_total}, {disk_total} and so on). The last task, Write the report, asks for a Snapshot (the raw numbers), but its prompt has no placeholders. It only sees the findings from the earlier tasks. Findings don't always repeat the raw numbers, so the writer may fill the gap with a plausible guess.
The guide explains the full crew and all its prompts. The first change I'd try is giving the last task the same placeholders and telling it to copy those numbers exactly. Then I'd compare the new snapshot with the cards.
The page has a smaller trap as well. A crew report carries the label source: CrewAI agents (in-process). That's wrong. The crew never runs inside the server. The server calls the CrewAI service and polls until the answer comes back. The label misleads, and fixing it is easy.
The Tests, and Proof That They Can Fail
The nine tests live in my Sample-code- repository. They find the project through the PULSE_DIR variable. They build the C engine in a temporary copy, and they never copy your .env.
The last run looked like this:
9 passed in 3.60s
All nine passed on the first run. That made me suspicious, because a test that has never failed hasn't proved anything. So I broke the project six different ways on purpose, one at a time. Each break was caught by the test meant to catch it:
- What I broke / Result
- Counted CD drives and duplicate drives as disk space / caught
- Crashed on an unreadable drive / caught
- Set the crew cache to 0 seconds (every page load is a billed run) / caught
- Changed a health threshold in the C engine / caught
- Made the Fix button trim nothing / caught
- Changed the fallback when the C engine is missing / caught
Flask locates its folders through sys.modules. Because of that, each test registers its loaded copy of sever.py before running it. It is a trap I met in my chess game tests.
What to Remember
- Connection refused? The server isn't running. Check the terminal, and install all the packages in one go.
- Sum all the drives. Each one can fail on its own (CD drives, card readers, locked drives), so guard them one by one.
- Read a counter once before you trust it. Leave a note about why the pause exists.
- If a button changes the system, make it skip what it shouldn't touch. Then test it on a process you started yourself.
- Anything billed needs a cache and a deadline. Test the cache too.
- Check an AI report against the real numbers before you believe it.
Other posts with problems that were solved and tested: Flask and a C Engine: Why Your Chess Game Returns 500 and 404, A Failed API Call Saved as NULL and FileNotFoundError.
Comments
No comments yet. Start the discussion.