Project 6: system-monitor-tui

Build a terminal UI system monitor that feels like a real product.

Quick Reference

Attribute Value
Difficulty Level 4 (Advanced)
Time Estimate 2 weeks
Language Go (Alternatives: Rust, Python)
Prerequisites Projects 1–4 or solid CLI + terminal I/O
Key Topics TUI layout, rendering loops, OS metrics

1. Learning Objectives

By completing this project, you will:

  1. Design a terminal UI with panes, headers, and live updates.
  2. Build a model-view-update architecture for terminal rendering.
  3. Collect and normalize CPU, memory, disk, and process metrics.
  4. Handle resize events and partial redraws without flicker.
  5. Provide both interactive and non-interactive output modes.

2. Theoretical Foundation

2.1 Core Concepts

  • Terminal Rendering: TUIs repaint screens by writing ANSI escape codes. Efficient redraws avoid full-screen flicker.
  • Event Loops: A TUI must handle input events, timers, and OS signals concurrently.
  • Model-View-Update (MVU): State changes trigger view updates. This separates rendering from data collection.
  • OS Metrics: CPU usage, memory, and process tables differ across OSes; you need a portable abstraction.
  • Backpressure: Rendering too often can starve input handling; rate limiting is essential.

2.2 Why This Matters

Modern tools like htop, btop, and glances are indispensable. Building one teaches you how to structure a responsive interface on top of raw terminal primitives.

2.3 Historical Context / Background

top was introduced in the 1980s as a real-time process viewer. htop added color and interaction. Your project recreates those capabilities with modern libraries.

2.4 Common Misconceptions

  • “Just redraw everything”: Full redraws cause flicker and high CPU usage.
  • “Metrics are consistent across OSes”: They vary; abstractions are required.

3. Project Specification

3.1 What You Will Build

A TUI system monitor that shows:

  • CPU usage per core
  • Memory and swap usage
  • Disk usage
  • Top processes by CPU or memory

It supports interactive controls (sort, filter, quit) and a --json mode for scripting.

3.2 Functional Requirements

  1. Dashboard Layout: Split screen with header, charts, and process table.
  2. Live Updates: Refresh at a fixed interval (e.g., 500ms).
  3. Input Controls: Keys to sort and filter processes.
  4. Resize Handling: Reflow layout on terminal resize.
  5. Output Modes: TUI for interactive, JSON for non-interactive.

3.3 Non-Functional Requirements

  • Performance: Should not exceed 5% CPU on idle systems.
  • Reliability: Must not crash on missing permissions.
  • Usability: Clear hotkeys and on-screen hints.

3.4 Example Usage / Output

$ system-monitor-tui

3.5 Real World Outcome

When launched, you see a full-screen dashboard:

  • Top bar shows hostname, uptime, and load averages.
  • Left panel shows CPU usage bars per core updating live.
  • Right panel shows memory and disk usage gauges.
  • Bottom panel lists top processes with PID, CPU%, MEM%, and command.

Pressing m switches sort to memory. Pressing / opens a filter prompt. Pressing q exits cleanly and restores your terminal.


4. Solution Architecture

4.1 High-Level Design

+--------------+      +----------------+      +-----------------+
| Metrics Poll | ---> | Model Store    | ---> | Renderer        |
+--------------+      +----------------+      +-----------------+
        |                     |                        |
        +--------- Input/Event Loop +------------------+

4.2 Key Components

Component Responsibility Key Decisions
Poller Collect metrics Poll interval
Model Store state Immutable vs mutable
Renderer Draw UI Full vs partial redraw
Input Keyboard handling Keybindings

4.3 Data Structures

type Metrics struct {
    CPU []float64
    MemoryUsed uint64
    MemoryTotal uint64
    DiskUsed uint64
    DiskTotal uint64
    Processes []Process
}

type Process struct {
    PID int
    CPU float64
    MEM float64
    Command string
}

4.4 Algorithm Overview

Key Algorithm: MVU loop

  1. Poll metrics periodically.
  2. Update state model.
  3. Render view using diff-aware updates.
  4. Process input events to update model.

Complexity Analysis:

  • Time: O(P) per refresh for P processes.
  • Space: O(P) for process list.

5. Implementation Guide

5.1 Development Environment Setup

# Go example
brew install go
mkdir system-monitor-tui && cd system-monitor-tui
go mod init system-monitor-tui

5.2 Project Structure

system-monitor-tui/
├── cmd/
│   └── root.go
├── internal/
│   ├── metrics/
│   ├── model/
│   ├── view/
│   └── input/
└── README.md

5.3 The Core Question You Are Answering

“How do I build a responsive terminal UI that looks good, performs well, and handles real-time data?”

5.4 Concepts You Must Understand First

  1. ANSI escape codes
  2. Event loops
  3. OS metrics collection
  4. Terminal resize handling

5.5 Questions to Guide Your Design

  1. How often should you redraw to balance smoothness and CPU usage?
  2. What is your process selection and sorting strategy?
  3. How will you handle permission errors for process info?

5.6 Thinking Exercise

Sketch your UI layout on paper. Decide which panels are fixed height and which flex.

5.7 The Interview Questions They Will Ask

  1. How do you avoid flicker in TUIs?
  2. Why should rendering be decoupled from polling?
  3. How do you handle terminal resize events?

5.8 Hints in Layers

Hint 1: Start with static mock data and render once.

Hint 2: Add polling and refresh with a fixed timer.

Hint 3: Add keyboard input and sorting.

5.9 Books That Will Help

Topic Book Chapter
Terminal I/O “Advanced Programming in the UNIX Environment” Ch. 18
Systems overview “The Linux Programming Interface” Ch. 2-4

5.10 Implementation Phases

Phase 1: Foundation (3-4 days)

Goals:

  • Basic renderer with mock data

Checkpoint: TUI renders without flicker.

Phase 2: Metrics Integration (4-5 days)

Goals:

  • Real metrics collection

Checkpoint: Data updates live.

Phase 3: Interaction (2-3 days)

Goals:

  • Sorting and filtering

Checkpoint: Hotkeys affect process list.


6. Testing Strategy

6.1 Test Categories

Category Purpose Examples
Unit Tests Metrics parsing CPU % math
Integration Tests Renderer output expected layout
Edge Cases No permissions fallback behavior

6.2 Critical Test Cases

  1. Resize terminal and ensure UI reflows.
  2. Run under limited permissions and show warnings.
  3. Verify JSON output mode matches model state.

7. Common Pitfalls and Debugging

Pitfall Symptom Solution
Full redraw flicker Screen flashes Use partial redraws
Polling too fast High CPU usage Throttle interval
Missing permissions Crashes Graceful fallbacks

8. Extensions and Challenges

8.1 Beginner Extensions

  • Add a help screen (?)
  • Add color themes

8.2 Intermediate Extensions

  • Add process kill action
  • Add configurable refresh rate

8.3 Advanced Extensions

  • Add network usage panel
  • Add plugin panel system

9. Real-World Connections

  • htop, btop UI design
  • Monitoring dashboards in DevOps

10. Resources

  • termui / tview / bubbletea docs
  • gopsutil for metrics

11. Self-Assessment Checklist

  • I can explain MVU architecture for TUIs
  • I can handle resize events gracefully

12. Submission / Completion Criteria

Minimum Viable Completion:

  • TUI renders with mock metrics

Full Completion:

  • Live metrics + input controls

Excellence (Going Above and Beyond):

  • Plugins, network panel, or export mode