From 5a7bf3ed0af5c9b97225fef7694ffc5e4c0b4bc9 Mon Sep 17 00:00:00 2001 From: yogeshprasad098 Date: Thu, 26 Nov 2026 17:32:08 -0800 Subject: [PATCH] test: add a script that measures the app's CPU with sample data The CPU problems in #90 were found only after release, on the installed app. scripts/measure-cpu.sh catches them before one: it builds the Debug app, runs it with --demo --live-readings, and prints the CPU of the app and the window server for each dashboard page in front, the window in the background and the window closed. It never takes the keyboard or moves the mouse. Two debug-only launch arguments make that possible: --background shows windows without activating the app, on the Mac's own screen when another display is connected, and --appear-active draws the dashboard as if it were in front. CONTRIBUTING and AGENTS.md say to run it after dashboard changes and before a release. Refs #90 Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 1 + App/AppDelegate.swift | 21 +++++++ App/ChargectlApp.swift | 21 +++++++ App/Dashboard/DashboardView.swift | 3 + CONTRIBUTING.md | 17 +++-- scripts/measure-cpu.sh | 101 ++++++++++++++++++++++++++++++ 6 files changed, 159 insertions(+), 5 deletions(-) create mode 100755 scripts/measure-cpu.sh diff --git a/AGENTS.md b/AGENTS.md index f025d23..fa768a1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -50,6 +50,7 @@ newly matching skills before continuing. Human contributors do not need them. | Check the cask as the tap's CI does | `./scripts/check.sh cask` | | Retake the README screenshots | `./scripts/screenshots.sh` (after `./scripts/build.sh Debug`; see CONTRIBUTING.md) | | Render the dashboard pages, menu bar panel and widgets to PNG files, light and dark, with sample data | `"${TMPDIR:-/tmp}/Chargectl-DerivedData/Build/Products/Debug/Chargectl.app/Contents/MacOS/Chargectl" --render-design --only ` after `./scripts/build.sh Debug`. It never talks to the helper; shot names are in `App/Debug/DesignRender.swift` | +| Measure the app's CPU with sample data, page by page, without taking the keyboard or mouse | `./scripts/measure-cpu.sh` (or `./scripts/measure-cpu.sh ` for another Debug build). Run it after dashboard or menu bar changes and before a release | | Try a changed release workflow without publishing (only when the user asks) | `gh workflow run release.yml --ref ` | The build and test scripts regenerate the Xcode project from `project.yml` diff --git a/App/AppDelegate.swift b/App/AppDelegate.swift index 61e6597..1781245 100644 --- a/App/AppDelegate.swift +++ b/App/AppDelegate.swift @@ -81,6 +81,13 @@ enum Dashboard { /// Shows the Dock icon and brings the window forward. static func show(_ window: NSWindow? = nil) { + if Setup.staysInBackground { + if let window = window ?? Self.window { + placeOnBuiltInScreen(window) + window.orderFrontRegardless() + } + return + } NSApp.setActivationPolicy(.regular) NSApp.activate() let window = window ?? Self.window @@ -90,6 +97,20 @@ enum Dashboard { window?.makeKeyAndOrderFront(nil) } + /// Measuring in the background: with another display connected, the window goes in the middle + /// of the Mac's own screen, away from whatever the user is doing on the main one. + private static func placeOnBuiltInScreen(_ window: NSWindow) { + guard NSScreen.screens.count > 1, + let screen = NSScreen.screens.first(where: { + let id = $0.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? CGDirectDisplayID + return id.map { CGDisplayIsBuiltin($0) != 0 } ?? false + }) + else { return } + let area = screen.visibleFrame + let size = window.frame.size + window.setFrameOrigin(NSPoint(x: area.midX - size.width / 2, y: area.midY - size.height / 2)) + } + /// Back to a menu bar–only app once no window of ours is open. static func didClose() { DispatchQueue.main.async { diff --git a/App/ChargectlApp.swift b/App/ChargectlApp.swift index a442c4c..d95349c 100644 --- a/App/ChargectlApp.swift +++ b/App/ChargectlApp.swift @@ -76,6 +76,27 @@ enum Setup { #endif } + /// Debug builds started with --background (scripts/measure-cpu.sh) show their windows + /// without making Chargectl the active app, and on the Mac's own screen when another display + /// is connected, so a measurement stays out of the way of whoever is using the Mac. + static var staysInBackground: Bool { + #if DEBUG + CommandLine.arguments.contains("--background") + #else + false + #endif + } + + /// Debug builds started with --appear-active draw the dashboard as if Chargectl were the app in + /// front, also while it stays in the background. + static var appearsActive: Bool { + #if DEBUG + CommandLine.arguments.contains("--appear-active") + #else + false + #endif + } + static var isNeeded: Bool { if isDemo { return false } return !UserDefaults.standard.bool(forKey: PreferenceKey.setupComplete) diff --git a/App/Dashboard/DashboardView.swift b/App/Dashboard/DashboardView.swift index 20e96b8..74a03ff 100644 --- a/App/Dashboard/DashboardView.swift +++ b/App/Dashboard/DashboardView.swift @@ -44,6 +44,7 @@ struct DashboardView: View { } .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) } + .transformEnvironment(\.appearsActive) { if Setup.appearsActive { $0 = true } } } .frame(maxWidth: .infinity, maxHeight: .infinity) .background { @@ -64,6 +65,8 @@ struct DashboardView: View { .onOpenURL { url in // chargectl://dashboard/ if let target = DashboardPage(rawValue: url.lastPathComponent) { page = target } + // Measuring in the background: keep the window above whatever the user brought forward. + if Setup.staysInBackground { Dashboard.show() } } } diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 48f392b..2cbf300 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -105,10 +105,14 @@ Changes to how charging is controlled must also be tried on a real MacBook. Say in the pull request which Mac and macOS version you used and what you saw. Changes to the dashboard or the menu bar panel should not raise the app's CPU -use. Run the Debug build with `--demo --live-readings`, which changes the -watts and the temperature every second as a real Mac does, and watch -Chargectl in Activity Monitor with the window open, in front and behind -another app. It should stay at a few percent. +use. `./scripts/measure-cpu.sh` builds the Debug app and measures it with +sample data whose watts and temperature change every second, as a real Mac's +do: each dashboard page in front, the window in the background, and the window +closed. It takes about two minutes and never takes the keyboard or moves the +mouse. The window comes forward without focus, on the Mac's own screen when +another display is connected; keep it uncovered while it runs. Compare the +Chargectl column with a run on `main`. The WindowServer column also counts +every other app on screen, so read it only as a rough guide. ### Screenshots @@ -194,7 +198,10 @@ review says. Open an issue describing the change instead. 1. Set `MARKETING_VERSION` in [`project.yml`](project.yml) and move the `Unreleased` entries in [`CHANGELOG.md`](CHANGELOG.md) under the new version. Add a one-sentence summary in bold, unless the release has one entry. -2. Merge that to `main`, then tag it: +2. Run `./scripts/measure-cpu.sh` and compare it with the last release. With + the window in front, a page that uses clearly more CPU than before needs a + reason before you ship. +3. Merge that to `main`, then tag it: ```sh git tag -a v0.2.0 -m "Chargectl 0.2.0" && git push origin v0.2.0 diff --git a/scripts/measure-cpu.sh b/scripts/measure-cpu.sh new file mode 100755 index 0000000..7e97276 --- /dev/null +++ b/scripts/measure-cpu.sh @@ -0,0 +1,101 @@ +#!/usr/bin/env bash +# Measures how much CPU Chargectl and the window server use with the dashboard open on each page, +# in the background and closed. It runs a Debug build with --demo --live-readings: sample data +# whose watts and temperature change every second, as a real Mac's do, and no helper, so it never +# changes how the Mac charges. Run it before a release and after changing the dashboard or the +# menu bar panel. +# +# scripts/measure-cpu.sh builds the Debug app, then measures it +# scripts/measure-cpu.sh measures another Debug build, to compare +# +# It never takes the keyboard or moves the mouse: the app stays in the background (--background) +# and its window comes forward without focus. "In front" is measured with --appear-active, which +# draws the dashboard as if Chargectl were the app in front. Keep the window uncovered while it +# runs, about two minutes. CHARGECTL_MEASURE_SECONDS sets how long each state is measured +# (default 15). +set -euo pipefail +source "$(dirname "${BASH_SOURCE[0]}")/env.sh" + +seconds="${CHARGECTL_MEASURE_SECONDS:-15}" +if [[ $# -gt 0 ]]; then + app="$1" +else + "$CHARGECTL_ROOT/scripts/build.sh" Debug + app="$CHARGECTL_DERIVED_DATA/Build/Products/Debug/Chargectl.app" +fi +# The full path without doubled slashes, as the process list shows it. +app="$(cd "$app" 2>/dev/null && pwd -P || true)" +executable="$app/Contents/MacOS/Chargectl" +if [[ ! -x "$executable" ]]; then + echo "measure-cpu: no Chargectl app at ${1:-the Debug build}" >&2 + exit 2 +fi + +now() { perl -MTime::HiRes=time -e 'printf "%.3f\n", time'; } +# CPU time a process has used so far, in seconds. +cpu_time() { ps -p "$1" -o time= | awk -F: '{ t = 0; for (i = 1; i <= NF; i++) t = t * 60 + $i; print t }'; } +# Average CPU of the app and the window server over the measuring time, as "app% server%". +measure() { + local app_before server_before start app_after server_after end + app_before=$(cpu_time "$pid") server_before=$(cpu_time "$server") start=$(now) + sleep "$seconds" + app_after=$(cpu_time "$pid") server_after=$(cpu_time "$server") end=$(now) + awk -v a="$app_before" -v b="$app_after" -v s="$server_before" -v t="$server_after" -v d="$start" -v e="$end" \ + 'BEGIN { printf "%.1f%% %.1f%%\n", (b - a) / (e - d) * 100, (t - s) / (e - d) * 100 }' +} +row() { printf '%-26s %10s %14s\n' "$1" "$2" "$3"; } +# Shows a dashboard page. Opening the link with this app, by path, keeps it away from an installed +# Chargectl, which handles chargectl:// links too; -g leaves the app in the background. +show() { open -g -a "$app" "chargectl://dashboard/$1"; } + +pid="" +stop() { if [[ -n "$pid" ]]; then kill "$pid" 2>/dev/null || true; fi; } +trap stop EXIT +# start [argument]: runs the app in the background with sample data and sets pid. +start() { + local arguments=(--demo --live-readings --background "$@") + open -g -n -a "$app" --args "${arguments[@]}" + pid="" + for _ in $(seq 1 20); do + pid=$(pgrep -f -x "$executable ${arguments[*]}" | head -1 || true) + [[ -n "$pid" ]] && break + sleep 0.5 + done + if [[ -z "$pid" ]]; then + echo "measure-cpu: Chargectl did not start" >&2 + exit 1 + fi + sleep 5 +} + +server=$(pgrep -x WindowServer | head -1) +# The window server's own load, before Chargectl starts. The app's column is this script's shell. +pid=$$ +read -r _ idle_server < <(measure) +pid="" + +echo "Chargectl $(defaults read "$app/Contents/Info.plist" CFBundleShortVersionString), $seconds s per state" +row "" "Chargectl" "WindowServer" +row "not running" "" "$idle_server" + +start --appear-active +for page in overview control history logs settings; do + show "$page" + sleep 4 + read -r app_cpu server_cpu < <(measure) + row "$page, in front" "$app_cpu" "$server_cpu" +done +stop + +start +show overview +sleep 4 +read -r app_cpu server_cpu < <(measure) +row "overview, in background" "$app_cpu" "$server_cpu" +# Quitting from outside only closes the dashboard; the app stays in the menu bar. AppleScript +# reports that as a cancelled quit. +osascript -e "tell application \"$app\" to quit" >/dev/null 2>&1 || true +sleep 4 +read -r app_cpu server_cpu < <(measure) +row "window closed" "$app_cpu" "$server_cpu" +row "memory" "$(($(ps -p "$pid" -o rss=) / 1024)) MB" ""