diff --git a/AGENTS.md b/AGENTS.md index 9ebefa7b9c12..4bb146171a54 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -116,6 +116,7 @@ Exceptions are allowed for migration and package-helper scripts where the helper # Background Work - Long-running code (the shell, daemons, watchers) reacts to events instead of polling with a timer. Polling is the last resort, for state with no change signal; [`agents/skills/shell-dev.md`](agents/skills/shell-dev.md) lists the event sources and the push-refresh pattern. +- `test/shell.d/shell-idle-spawn-test.sh` fails when an idle shell starts any process, and other tests hold the router, menu guards and theme switch to budgets; see "Performance guards" in [`docs/testing.md`](docs/testing.md). # Menu diff --git a/docs/testing.md b/docs/testing.md index 8f8720c2199e..272e9d620ec4 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -84,6 +84,17 @@ Gate only what needs gating — put `require_compositor` in files whose runtime half needs a live session, and keep static analysis of the same area in code that runs unconditionally before or beside it. +## Performance guards + +A handful of tests fail when a fast path gets slow again. Each prefers a count that is the same on every machine over a wall-clock time. Where it has to time something it takes the fastest of several runs, and either compares two paths timed in the same run or scales its budget with `process_speed_percent` from `base-test.sh`: how long 100 fork/execs take here against the 25ms they take on the laptop the budgets were set on. A machine more than 8x slower skips the timing (`require_comparable_speed`) rather than guess. + +- `test/shell.d/shell-idle-spawn-test.sh` starts a second shell on the default config, waits for its startup work to go quiet, then fails if it starts any process over 30 idle seconds, naming each command line. A preloaded shim (`fixtures/idle-shell/exec-log.c`, built with `cc` at test time) logs every exec, fork and spawn the shell and its descendants make, so a probe that lives for a millisecond is caught, and nothing outside the shell's process tree can be. A command that legitimately runs while idle is allowed with `allow` in that file, only while its reason holds and at most as often as the reason implies. The test watches Hyprland, UPower and NetworkManager events meanwhile; a spawn that coincides with one is given a second window before it fails, and the events are printed with it. The test shell gets stubs for everything that would act on the session (signals, power profiles, `bash -l`). Compositor-gated, and skipped without a C compiler. +- `test/cli` times `omarchy screenshot` against help for it on a copy of the real command table, and fails unless the alias dispatch costs under a quarter of the full load (13ms against 190ms today). +- `test/shell.d/menu-guard-budget-test.sh` runs the shipped menu's guard batch on this machine's real hardware: the batch within 200ms (about 50ms today) and each guard alone within 100ms (the slowest is about 30ms), scaled to the machine, listing the slowest guards when either fails. Skipped without `$XDG_RUNTIME_DIR`, which holds the package snapshot the menu relies on. +- `test/shell.d/theme-set-budget-test.sh` runs the whole `omarchy-theme-set` in a scratch home where every app is a stub given its real cost (a running Hunk, VS Code's Electron boot, three tmux sessions). It fails when either theme's switch takes over 500ms scaled to the machine (about 80ms today), starts more than a handful of tmux clients, starts VS Code to list its extensions, or waits for Hunk's settle nudge. + +Override a budget through the environment variable named at the top of each file when measuring something slower on purpose. + ## Companion checkouts Some checks hold Omarchy's scripts against the packages in the separate omarchy-pkgs repository (or the installer in omarchy-iso). `find_omarchy_pkgs` sets `OMARCHY_PKGS_ROOT` to that checkout's `pkgbuilds/` directory. When `OMARCHY_PKGS_PATH` is set, only it (the checkout or its `pkgbuilds/`) is tried, and an override that doesn't resolve fails the test, so a typo never turns package checks into skips. Without the override, the usual places beside this checkout and `~/Work/omacom` are tried; finding none returns 1, and the test skips only the checks that need it, the same way a missing compositor is handled, so the suite stays green on a machine with just this repository. Point `OMARCHY_PKGS_PATH` at the checkout when running from a worktree or an unusual location. @@ -123,6 +134,7 @@ only a live session can prove. executables (`sudo`, `tmux`, `gsettings`, helper commands) that log their arguments to a file, prepend it to `PATH`, and then run the real script under test. Assertions grep the call log and the files the script wrote. +- **Login shells drop the stubs.** A `bash -l` rereads `/etc/profile`, which resets `OMARCHY_PATH` from `/etc/omarchy.conf` and puts that checkout's `bin/` ahead of the stub directory, so a command run through one reaches the real commands again. Commands that start `bash -lc` (`omarchy-theme-set` runs its app retints that way) need a `bash` stub that drops the `-l`. - **Fake `$HOME`, real `$OMARCHY_PATH`.** Anything touching user state runs with `HOME` pointed at a `mktemp -d` directory (cleaned up via `trap ... EXIT`) and `OMARCHY_PATH="$ROOT"`, so tests exercise the checkout diff --git a/test/cli b/test/cli index 1d5f86180d39..90e98b75ccaa 100755 --- a/test/cli +++ b/test/cli @@ -837,3 +837,40 @@ if (( EUID != 0 )); then rm -f "$TMPDIR/omarchy-zz-unreadable" pass "an alias dispatch reads only the commands that can own its route" fi + +# The same guarantee against the real command table, timed: an alias dispatch +# that loads every header costs what help on it costs (about 190ms either way +# before the candidates-only path, against 13ms after). Timing both in the same +# run keeps the check independent of how fast the machine is. +make_tmpdir ROUTER_BIN +cp -a "$ROOT/bin/." "$ROUTER_BIN/" +# The real header, so the alias resolves as shipped, over a body that takes no +# screenshot. +{ + awk 'NR == 1 || /^#/ || /^[[:space:]]*$/ { print; next } { exit }' "$ROOT/bin/omarchy-capture-screenshot" + printf 'echo screenshot-stub-ran\n' +} >"$ROUTER_BIN/omarchy-capture-screenshot" + +fastest_ms() { + local best="" start end elapsed + + for _ in 1 2 3 4 5; do + start=$EPOCHREALTIME + "$@" >/dev/null 2>&1 + end=$EPOCHREALTIME + elapsed=$(( (${end/[.,]/} - ${start/[.,]/}) / 1000 )) + if [[ -z $best ]] || (( elapsed < best )); then + best=$elapsed + fi + done + echo "$best" +} + +[[ $("$ROUTER_BIN/omarchy" screenshot) == "screenshot-stub-ran" ]] || fail "omarchy screenshot dispatches to the capture command" +alias_ms=$(fastest_ms "$ROUTER_BIN/omarchy" screenshot) +full_ms=$(fastest_ms "$ROUTER_BIN/omarchy" screenshot --help) +if (( alias_ms * 4 > full_ms )); then + printf 'omarchy screenshot took %dms; loading the whole table for its help took %dms.\n' "$alias_ms" "$full_ms" >&2 + fail "an alias dispatch costs a fraction of loading the whole command table" +fi +pass "an alias dispatch costs a fraction of loading the whole command table (${alias_ms}ms vs ${full_ms}ms)" diff --git a/test/shell.d/base-test.sh b/test/shell.d/base-test.sh index 6989e4a64a83..5a157623f438 100644 --- a/test/shell.d/base-test.sh +++ b/test/shell.d/base-test.sh @@ -181,6 +181,37 @@ platform_root_copy() { fail "$(basename -- "$script") reads the platform root from the fixture" } +# How long this machine takes to start processes, as a percentage of the +# laptop the timing budgets were measured on (100 there, never less): the +# fastest of three runs of 100 fork/execs of true, against the 25ms they take +# on that laptop. A test timing process-heavy work multiplies its budget by +# this, so a Raspberry Pi or an ARM VM gets the room its slower process starts +# need, and only what is still several times over fails. +process_speed_percent() { + local best="" start end elapsed + + for _ in 1 2 3; do + start=$EPOCHREALTIME + for _ in {1..100}; do /usr/bin/true; done + end=$EPOCHREALTIME + elapsed=$(( ${end/[.,]/} - ${start/[.,]/} )) + if [[ -z $best ]] || (( elapsed < best )); then + best=$elapsed + fi + done + echo $(( best > 25000 ? best * 100 / 25000 : 100 )) +} + +# Sets SPEED_PERCENT for a timing test, skipping the rest of the file when the +# machine is so much slower than the reference that a budget scaled to it +# could no longer tell a regression from the machine. +require_comparable_speed() { + SPEED_PERCENT=$(process_speed_percent) + (( SPEED_PERCENT <= 800 )) && return 0 + skip "processes start $(( SPEED_PERCENT / 100 ))x slower than on the reference laptop; skipping $1" + exit 0 +} + run_node_test() { require_command node diff --git a/test/shell.d/fixtures/idle-shell/exec-log.c b/test/shell.d/fixtures/idle-shell/exec-log.c new file mode 100644 index 000000000000..c829ff7b3b42 --- /dev/null +++ b/test/shell.d/fixtures/idle-shell/exec-log.c @@ -0,0 +1,249 @@ +// Preloaded into the shell under test and inherited by everything it starts, +// so every program any descendant runs is logged, however briefly it lives. +// Sampling the process tree instead misses the short-lived probes polling +// spawns. One line per exec: the pid that runs the program and its parent's, +// then argv joined by spaces. A fork logs the same line without a command, so +// a reader can follow ancestry through a subshell that never execs. +// +// Known gap: system() and popen() spawn their /bin/sh from inside libc, past +// these wrappers, so that sh is not logged itself. What it runs is, since the +// preload is inherited, under a parent the log has never seen. +// +// The exec family can run in a vfork child, which shares the parent's memory, +// so the logging path allocates nothing and takes no locks: raw syscalls from +// a stack buffer, with errno left as the caller had it. The real functions are +// resolved once, at load. +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include + +#define MAX_LIST_ARGS 256 + +typedef int (*execve_fn)(const char *, char *const[], char *const[]); +typedef int (*execv_fn)(const char *, char *const[]); +typedef int (*fexecve_fn)(int, char *const[], char *const[]); +typedef pid_t (*fork_fn)(void); +typedef int (*spawn_fn)(pid_t *, const char *, const posix_spawn_file_actions_t *, + const posix_spawnattr_t *, char *const[], char *const[]); +typedef int (*pidfd_spawn_fn)(int *, const char *, const posix_spawn_file_actions_t *, + const posix_spawnattr_t *, char *const[], char *const[]); +typedef pid_t (*pidfd_getpid_fn)(int); + +static execve_fn real_execve; +static execv_fn real_execv; +static execv_fn real_execvp; +static execve_fn real_execvpe; +static fexecve_fn real_fexecve; +static fork_fn real_fork; +static spawn_fn real_posix_spawn; +static spawn_fn real_posix_spawnp; +static pidfd_spawn_fn real_pidfd_spawn; +static pidfd_spawn_fn real_pidfd_spawnp; +static pidfd_getpid_fn real_pidfd_getpid; +static char log_path[4096]; + +__attribute__((constructor)) static void init(void) { + real_execve = (execve_fn)dlsym(RTLD_NEXT, "execve"); + real_execv = (execv_fn)dlsym(RTLD_NEXT, "execv"); + real_execvp = (execv_fn)dlsym(RTLD_NEXT, "execvp"); + real_execvpe = (execve_fn)dlsym(RTLD_NEXT, "execvpe"); + real_fexecve = (fexecve_fn)dlsym(RTLD_NEXT, "fexecve"); + real_fork = (fork_fn)dlsym(RTLD_NEXT, "fork"); + real_posix_spawn = (spawn_fn)dlsym(RTLD_NEXT, "posix_spawn"); + real_posix_spawnp = (spawn_fn)dlsym(RTLD_NEXT, "posix_spawnp"); + // glibc 2.39 and later; absent before, and then nothing calls them. + real_pidfd_spawn = (pidfd_spawn_fn)dlsym(RTLD_NEXT, "pidfd_spawn"); + real_pidfd_spawnp = (pidfd_spawn_fn)dlsym(RTLD_NEXT, "pidfd_spawnp"); + real_pidfd_getpid = (pidfd_getpid_fn)dlsym(RTLD_NEXT, "pidfd_getpid"); + + const char *path = getenv("OMARCHY_EXEC_LOG"); + if (path && strlen(path) < sizeof(log_path)) strcpy(log_path, path); +} + +static size_t put_number(char *buf, size_t at, size_t cap, long value) { + char digits[24]; + int count = 0; + + if (value < 0) value = 0; + do { + digits[count++] = (char)('0' + value % 10); + value /= 10; + } while (value > 0 && count < (int)sizeof(digits)); + while (count > 0 && at < cap) buf[at++] = digits[--count]; + return at; +} + +static void record_as(pid_t pid, pid_t parent, char *const argv[]) { + if (!log_path[0]) return; + + int saved_errno = errno; + char line[8192]; + size_t cap = sizeof(line) - 1, at = 0; + + at = put_number(line, at, cap, (long)pid); + if (at < cap) line[at++] = ' '; + at = put_number(line, at, cap, (long)parent); + for (int i = 0; argv && argv[i]; i++) { + if (at < cap) line[at++] = ' '; + for (const char *c = argv[i]; *c && at < cap; c++) line[at++] = *c == '\n' ? ' ' : *c; + } + line[at++] = '\n'; + + int fd = open(log_path, O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC, 0600); + if (fd >= 0) { + ssize_t written = write(fd, line, at); + (void)written; + close(fd); + } + errno = saved_errno; +} + +static void record(char *const argv[]) { + record_as(getpid(), getppid(), argv); +} + +int execve(const char *path, char *const argv[], char *const envp[]) { + record(argv); + return real_execve(path, argv, envp); +} + +int execv(const char *path, char *const argv[]) { + record(argv); + return real_execv(path, argv); +} + +int execvp(const char *file, char *const argv[]) { + record(argv); + return real_execvp(file, argv); +} + +int execvpe(const char *file, char *const argv[], char *const envp[]) { + record(argv); + return real_execvpe(file, argv, envp); +} + +int fexecve(int fd, char *const argv[], char *const envp[]) { + record(argv); + return real_fexecve(fd, argv, envp); +} + +// The list forms call the vector ones from inside libc, past the wrappers above, +// so collect their arguments here and go through the wrappers instead. +static int collect(const char *first, va_list *args, char *argv[]) { + int count = 0; + + argv[count++] = (char *)first; + while (argv[count - 1]) { + if (count == MAX_LIST_ARGS) { + errno = E2BIG; + return -1; + } + argv[count++] = va_arg(*args, char *); + } + return 0; +} + +int execl(const char *path, const char *arg, ...) { + char *argv[MAX_LIST_ARGS]; + va_list args; + + va_start(args, arg); + int status = collect(arg, &args, argv); + va_end(args); + return status < 0 ? -1 : execv(path, argv); +} + +int execlp(const char *file, const char *arg, ...) { + char *argv[MAX_LIST_ARGS]; + va_list args; + + va_start(args, arg); + int status = collect(arg, &args, argv); + va_end(args); + return status < 0 ? -1 : execvp(file, argv); +} + +int execle(const char *path, const char *arg, ...) { + char *argv[MAX_LIST_ARGS]; + va_list args; + + va_start(args, arg); + int status = collect(arg, &args, argv); + char *const *envp = va_arg(args, char *const *); + va_end(args); + return status < 0 ? -1 : execve(path, argv, envp); +} + +pid_t fork(void) { + pid_t pid = real_fork(); + if (pid == 0) record(NULL); + return pid; +} + +// A vfork cannot be wrapped: the child would return through this frame and +// tear down the stack its suspended parent still needs. POSIX lets vfork be a +// fork, so make it one, and log it the same way. +pid_t vfork(void) { + return fork(); +} + +// A spawned child runs its program from inside libc, past these wrappers, so +// it is logged from the parent, under the child's pid, once it exists. +int posix_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *actions, + const posix_spawnattr_t *attr, char *const argv[], char *const envp[]) { + pid_t child = 0; + int status = real_posix_spawn(&child, path, actions, attr, argv, envp); + if (status == 0) record_as(child, getpid(), argv); + if (pid) *pid = child; + return status; +} + +int posix_spawnp(pid_t *pid, const char *file, const posix_spawn_file_actions_t *actions, + const posix_spawnattr_t *attr, char *const argv[], char *const envp[]) { + pid_t child = 0; + int status = real_posix_spawnp(&child, file, actions, attr, argv, envp); + if (status == 0) record_as(child, getpid(), argv); + if (pid) *pid = child; + return status; +} + +// The caller may pass no pidfd slot, which glibc allows though its header +// says otherwise, so spawn through a local one (read through a volatile copy, +// past the nonnull the declaration promises) and hand it over or close it. +static void finish_pidfd(int pidfd, int *volatile out, char *const argv[]) { + pid_t child = real_pidfd_getpid ? real_pidfd_getpid(pidfd) : 0; + record_as(child > 0 ? child : 0, getpid(), argv); + if (out) { + *out = pidfd; + } else { + int saved_errno = errno; + close(pidfd); + errno = saved_errno; + } +} + +int pidfd_spawn(int *pidfd, const char *path, const posix_spawn_file_actions_t *actions, + const posix_spawnattr_t *attr, char *const argv[], char *const envp[]) { + if (!real_pidfd_spawn) return ENOSYS; + int *volatile out = pidfd; + int child = -1; + int status = real_pidfd_spawn(&child, path, actions, attr, argv, envp); + if (status == 0) finish_pidfd(child, out, argv); + return status; +} + +int pidfd_spawnp(int *pidfd, const char *file, const posix_spawn_file_actions_t *actions, + const posix_spawnattr_t *attr, char *const argv[], char *const envp[]) { + if (!real_pidfd_spawnp) return ENOSYS; + int *volatile out = pidfd; + int child = -1; + int status = real_pidfd_spawnp(&child, file, actions, attr, argv, envp); + if (status == 0) finish_pidfd(child, out, argv); + return status; +} diff --git a/test/shell.d/menu-guard-budget-test.sh b/test/shell.d/menu-guard-budget-test.sh new file mode 100755 index 000000000000..fbfb4946d799 --- /dev/null +++ b/test/shell.d/menu-guard-budget-test.sh @@ -0,0 +1,129 @@ +#!/bin/bash + +# The menu opens on its last guard answers, so however long the guard batch +# takes is how long a row can contradict the state it describes. This runs the +# batch for the shipped menu on this machine, against its real hardware and +# packages, and fails when it gets slow again: as a whole, or because one guard +# has turned expensive. A slow guard alone barely moves the batch, since the +# batch runs its guards side by side, but it holds up every menu evaluation. +# +# menu-guards-test.sh and menu-guards-parallel-test.sh pin down how the batch +# is built; this catches what they can't see, such as a guard calling a +# command that has become slow. + +set -euo pipefail + +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +require_command node + +# The batch keeps its package snapshot in $XDG_RUNTIME_DIR, as the menu does in +# a session. Without one every run lists the package database again, which no +# menu pays, so there is nothing representative to time. +if [[ -z ${XDG_RUNTIME_DIR:-} || ! -d $XDG_RUNTIME_DIR ]]; then + skip "no XDG_RUNTIME_DIR for the guard batch's package snapshot; skipping menu guard budgets" + exit 0 +fi + +require_comparable_speed "menu guard budgets" + +# On the reference laptop the batch takes about 50ms and its slowest guard, run +# alone, 30ms. Before the guards ran side by side and the hardware and network +# guards were made cheap, the batch took 380ms, and five guards alone took +# 130-150ms each. The budgets leave several times today's cost and still catch +# either, and grow with how much slower this machine starts processes. +BATCH_BUDGET_MS=$(( ${OMARCHY_MENU_GUARD_BUDGET_MS:-200} * SPEED_PERCENT / 100 )) +GUARD_BUDGET_MS=$(( ${OMARCHY_MENU_SINGLE_GUARD_BUDGET_MS:-100} * SPEED_PERCENT / 100 )) + +# Prints the batch for the whole shipped menu, then one batch per guarded row, +# each as a NUL-terminated id and script. +guard_scripts() { + node -e ' + const path = require("path") + const fs = require("fs") + const menu = require(path.join(process.env.ROOT, "shell/plugins/menu/MenuModel.js")) + const shipped = menu.parseMenuJsonc(fs.readFileSync(path.join(process.env.ROOT, "default/omarchy/omarchy-menu.jsonc"), "utf8")) + const all = {} + for (const item of shipped) all[item.id] = item + process.stdout.write(`menu\0${menu.guardScript(all)}\0`) + for (const item of shipped) { + const script = menu.guardScript({ [item.id]: item }) + if (script) process.stdout.write(`${item.id}\0${script}\0`) + } + ' +} + +# The menu runs the batch from its own checkout, so the guards call this +# checkout's commands. Prints the fastest of three runs, in milliseconds. A run +# that never returns is cut off at 10s and counts as taking all of it, so a +# stuck guard is named among the slowest instead of hanging the test. +fastest_ms() { + local best="" start end elapsed status + + for _ in 1 2 3; do + start=$EPOCHREALTIME + status=0 + OMARCHY_PATH="$ROOT" PATH="$ROOT/bin:$PATH" timeout --kill-after=1s 10s bash -c "$1" >"$output" 2>/dev/null || status=$? + end=$EPOCHREALTIME + elapsed=$(( (${end/[.,]/} - ${start/[.,]/}) / 1000 )) + if (( status == 124 || status == 137 )); then + elapsed=10000 + elif (( status != 0 )); then + # The menu throws away a batch that fails, so a fast failure is no answer. + echo "error $status" + return 0 + fi + if [[ -z $best ]] || (( elapsed < best )); then + best=$elapsed + fi + done + echo "$best" +} + +output=$(mktemp) +trap 'rm -f "$output"' EXIT + +declare -A scripts=() +ids=() +while IFS= read -r -d '' id && IFS= read -r -d '' script; do + scripts[$id]=$script + [[ $id == "menu" ]] || ids+=("$id") +done < <(guard_scripts) + +[[ -n ${scripts[menu]:-} ]] || fail "the shipped menu has guards to evaluate" +(( ${#ids[@]} > 0 )) || fail "the shipped menu has guarded rows" + +batch_ms=$(fastest_ms "${scripts[menu]}") +[[ $batch_ms != error* ]] || fail "the shipped menu's guard batch exits cleanly" "It exited with status ${batch_ms#error }." +(( $(wc -l <"$output") >= ${#ids[@]} )) || fail "the guard batch answers every guarded row" "$(cat "$output")" + +timings=() +slowest=0 +failed=() +for id in "${ids[@]}"; do + elapsed=$(fastest_ms "${scripts[$id]}") + if [[ $elapsed == error* ]]; then + failed+=("$id (status ${elapsed#error })") + continue + fi + timings+=("$(printf '%6dms %s' "$elapsed" "$id")") + (( elapsed > slowest )) && slowest=$elapsed +done + +(( ${#failed[@]} == 0 )) || fail "every shipped menu guard evaluates without failing its batch" "$(printf '%s\n' "${failed[@]}")" + +slowest_guards() { + printf 'Slowest guards, each run alone (fastest of three runs):\n' + printf '%s\n' "${timings[@]}" | sort -rn | head -8 +} + +(( batch_ms <= BATCH_BUDGET_MS )) || + fail "the shipped menu's guard batch runs within ${BATCH_BUDGET_MS}ms" "$( + printf 'Fastest of three batches took %dms.\n' "$batch_ms" + slowest_guards + )" +pass "the shipped menu's guard batch runs within ${BATCH_BUDGET_MS}ms (${batch_ms}ms)" + +(( slowest <= GUARD_BUDGET_MS )) || + fail "every shipped menu guard runs within ${GUARD_BUDGET_MS}ms alone" "$(slowest_guards)" +pass "every shipped menu guard runs within ${GUARD_BUDGET_MS}ms alone (slowest ${slowest}ms)" diff --git a/test/shell.d/shell-idle-spawn-test.sh b/test/shell.d/shell-idle-spawn-test.sh new file mode 100755 index 000000000000..a522d92f3a75 --- /dev/null +++ b/test/shell.d/shell-idle-spawn-test.sh @@ -0,0 +1,446 @@ +#!/bin/bash + +# An idle shell must not start processes. The shell runs all day, once per +# session, and a Timer that starts a Process costs that process every tick for +# as long as the machine is up (see "Keeping state current without polling" in +# agents/skills/shell-dev.md). This starts a second shell on the default config, +# lets its startup work finish, then watches it sit idle and fails naming every +# command it ran. +# +# Spawns are logged from inside the shell: a preloaded shim records every exec +# the shell or any of its descendants makes, so a probe that lives a few +# milliseconds is caught as surely as a long one, and nothing outside the +# shell's own process tree (this test included) can be mistaken for it. + +set -euo pipefail + +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +# Long enough to catch any poll at 30s or faster, the slowest interval a +# widget has been seen polling at; override to look for slower ones. +IDLE_WINDOW=${OMARCHY_IDLE_SPAWN_WINDOW:-30} + +TMPDIR="" +QS_PID="" +MONITOR_PIDS=() + +descendants() { + local child + + for child in $(cat /proc/"$1"/task/*/children 2>/dev/null); do + echo "$child" + descendants "$child" + done +} + +# Sends TERM, gives the processes a few seconds, then KILLs what is left. +stop_processes() { + local pid + + (( $# > 0 )) || return 0 + kill "$@" 2>/dev/null || true + for _ in {1..30}; do + for pid in "$@"; do + kill -0 "$pid" 2>/dev/null && break + pid="" + done + [[ -z $pid ]] && return 0 + sleep 0.1 + done + kill -KILL "$@" 2>/dev/null || true +} + +# The event monitors run as pipelines in subshells; stop each whole one. +stop_event_monitors() { + local pid pids=() + + for pid in "${MONITOR_PIDS[@]}"; do + pids+=("$pid") + mapfile -t -O "${#pids[@]}" pids < <(descendants "$pid") + done + stop_processes "${pids[@]}" + MONITOR_PIDS=() +} + +# Quickshell leaves some of its children running when it is stopped, among +# them the inotifywait watching the plugin directory, and one that outlives the +# test holds on to whatever it inherited. Stop everything the test shell +# started: what is still below it, and whatever still carries this run's log +# in its environment, which finds the ones that were reparented. +cleanup() { + local pid leftovers=() + + stop_event_monitors + if [[ -n $QS_PID ]] && kill -0 "$QS_PID" 2>/dev/null; then + mapfile -t leftovers < <(descendants "$QS_PID") + stop_processes "$QS_PID" + wait "$QS_PID" 2>/dev/null || true + fi + if [[ -f ${exec_log:-} ]]; then + for pid in $(cut -d' ' -f1 "$exec_log" | sort -u); do + { tr '\0' '\n' <"/proc/$pid/environ"; } 2>/dev/null | grep -qxF "OMARCHY_EXEC_LOG=$exec_log" && leftovers+=("$pid") + done + fi + stop_processes "${leftovers[@]}" + [[ -n ${test_root:-} ]] && rm -f "$(shell_ipc_socket "$test_root")" + [[ -n $TMPDIR && -d $TMPDIR ]] && rm -rf "$TMPDIR" + return 0 +} +trap cleanup EXIT + +require_compositor "idle shell spawn test" + +if ! command -v quickshell >/dev/null 2>&1; then + skip "quickshell not installed; skipping idle shell spawn test" + exit 0 +fi + +if ! command -v cc >/dev/null 2>&1; then + skip "no C compiler to build the exec logger; skipping idle shell spawn test" + exit 0 +fi + +require_command jq +require_command socat +require_command node + +TMPDIR=$(mktemp -d) +test_root="$TMPDIR/omarchy" +test_home="$TMPDIR/home" +stub_bin="$TMPDIR/bin" +log="$TMPDIR/quickshell.log" +exec_log="$TMPDIR/exec.log" +mkdir -p "$test_root" "$test_home" "$stub_bin" + +# Nobody touches the seat while the test watches, so a long enough window +# would reach the screensaver and the lock: actions on an event, not polling, +# and run against the session's desktop. Keep the test shell awake. +mkdir -p "$test_home/.local/state/omarchy/indicators" +touch "$test_home/.local/state/omarchy/indicators/stay-awake" + +cc -shared -fPIC -O2 -o "$TMPDIR/exec-log.so" "$SHELL_TEST_DIR/fixtures/idle-shell/exec-log.c" -ldl || + fail "the exec logger builds" + +# A copy, so the test shell gets its own IPC socket and never answers for, or +# replaces, the shell running the session. +cp -a "$ROOT/shell" "$test_root/shell" +ln -s "$ROOT/config" "$test_root/config" +ln -s "$ROOT/bin" "$test_root/bin" +ln -s "$ROOT/default" "$test_root/default" + +stub() { + printf '#!/bin/bash\n%s\n' "$2" >"$stub_bin/$1" + chmod +x "$stub_bin/$1" +} + +# Keep startup off the network. These only shape what startup does; a poll +# still shows up as an exec whether or not its command is stubbed. +stub omarchy-update-available 'exit 1' +# A weather fetch that fails is retried, so answer it the way wttr.in does. +stub curl 'case "${*: -1}" in + *"?format=j1") printf "{\"current_condition\":[{\"weatherCode\":\"113\",\"temp_F\":\"72\"}]}\n" ;; + *"?format=%l") printf "Test City, Test Region\n" ;; + *) exit 1 ;; +esac' +# The test shell must not act on the session. The clipboard plugin clears +# stale watchers at startup with a pkill that matches the session shell's too, +# and a charger plugged in or out switches the power profile. +stub pkill 'exit 1' +stub killall 'exit 1' +stub omarchy-powerprofiles-set 'exit 0' +stub powerprofilesctl 'exit 0' +# The shell runs some commands under `bash -lc`, and a login shell resets PATH +# and OMARCHY_PATH from /etc/omarchy.conf, which would put the session's +# checkout and its real commands back ahead of these stubs. +stub bash '[[ ${1:-} == "-lc" ]] && shift && set -- -c "$@" +exec /bin/bash "$@"' + +fail_with_log() { + sed -n '1,120p' "$log" >&2 + fail "$@" +} + +exec_count() { + if [[ -f $exec_log ]]; then + wc -l <"$exec_log" + else + echo 0 + fi +} + +OMARCHY_PATH="$test_root" \ +HOME="$test_home" \ +XDG_CONFIG_HOME="$test_home/.config" \ +XDG_CACHE_HOME="$test_home/.cache" \ +XDG_STATE_HOME="$test_home/.local/state" \ +PATH="$stub_bin:$ROOT/bin:$PATH" \ +OMARCHY_EXEC_LOG="$exec_log" \ +LD_PRELOAD="$TMPDIR/exec-log.so" \ +QS_DISABLE_FILE_WATCHER=1 \ +QS_NO_RELOAD_POPUP=1 \ + quickshell -p "$test_root/shell" --no-color >"$log" 2>&1 & +QS_PID=$! + +ready=0 +for _ in {1..150}; do + if OMARCHY_PATH="$test_root" "$ROOT/bin/omarchy-shell" shell listPlugins 2>/dev/null | jq -e 'length > 0' >/dev/null 2>&1; then + ready=1 + break + fi + kill -0 "$QS_PID" 2>/dev/null || fail_with_log "test shell exited before it became ready" + sleep 0.1 +done +(( ready )) || fail_with_log "test shell answers IPC within 15 seconds" + +# Startup runs its one-off probes (hardware, packages, config) for a few seconds +# after IPC answers, and ends by restoring the cursor once the startup cover has +# faded, which waits on the wallpaper. Idle starts once that has happened and +# everything has been quiet for a few seconds. A shell that never goes quiet +# fails below with the commands it kept running. +startup_done() { + grep -q 'omarchy_startup_cursor_restore' "$exec_log" 2>/dev/null +} + +settle_start=$SECONDS +quiet_since=$SECONDS +last=$(exec_count) +while (( SECONDS - settle_start < 40 )); do + sleep 0.5 + now=$(exec_count) + if (( now != last )); then + last=$now + quiet_since=$SECONDS + elif (( SECONDS - quiet_since >= 4 )) && { startup_done || (( SECONDS - settle_start >= 20 )); }; then + break + fi +done + +kill -0 "$QS_PID" 2>/dev/null || fail_with_log "test shell exited during startup" +(( $(exec_count) > 0 )) || fail_with_log "the exec logger records what the shell starts" + +# Commands an idle shell may legitimately run, as extended regexes matched +# against the logged command line. Each holds only while its reason does, and +# at most as often as that reason implies; a limit of "" leaves it unbounded. +# The reasons are looked at as each window opens and again as it closes, and +# one that held at either end holds for the window: a remote session can start +# or a Wi-Fi network connect while the test watches. +ALLOW_PATTERNS=() +ALLOW_LIMITS=() +ALLOW_REASONS=() +# An allowance seen at both ends of a window keeps the larger of its limits. +allow() { + local i + + for i in "${!ALLOW_PATTERNS[@]}"; do + if [[ ${ALLOW_PATTERNS[$i]} == "$1" ]]; then + if [[ -n ${ALLOW_LIMITS[$i]} && -n $2 ]] && (( $2 > ALLOW_LIMITS[$i] )); then + ALLOW_LIMITS[$i]=$2 + fi + return 0 + fi + done + ALLOW_PATTERNS+=("$1") + ALLOW_LIMITS+=("$2") + ALLOW_REASONS+=("$3") +} + +# Whether the keyboard layout widget keeps asking: while the seat has more +# than one keyboard someone can type on, or none of those reports a keymap. +# Which ones count is the widget's own call, so ask its model. +keyboard_widget_polls() { + hyprctl -j devices 2>/dev/null | ROOT="$ROOT" node -e ' + const model = require(require("path").join(process.env.ROOT, "shell/plugins/bar/widgets/KeyboardLayoutModel.js")) + let devices = {} + try { devices = JSON.parse(require("fs").readFileSync(0, "utf8")) } catch (e) {} + const typed = (devices.keyboards || []).filter(keyboard => model.isTypedKeyboard(keyboard.name)) + process.exit(typed.length > 1 || !typed.some(keyboard => keyboard.active_keymap) ? 0 : 1) + ' +} + +add_allowances() { + # Per-screen widgets are counted afresh each time, since a monitor can be + # plugged in while the test watches. + local screens + screens=$(hyprctl -j monitors 2>/dev/null | jq 'length' 2>/dev/null || true) + [[ $screens =~ ^[0-9]+$ ]] && (( screens > 0 )) || screens=1 + + # wl-paste runs the capture script for each clipboard change, which another + # program on the desktop can make at any moment. + allow '/shell/plugins/clipboard/capture\.sh ' "" "runs on each clipboard change" + + # The keyboard layout widget, one per screen, asks every 10s while the seat + # has more than one keyboard: Hyprland raises no event when a keyboard + # arrives or leaves, so which one the label describes can only be learned by + # asking. It also keeps asking while no keyboard reports a keymap, until a + # reading it can use lands. + if keyboard_widget_polls; then + allow '(^|/)hyprctl -j devices$' $(( screens * (IDLE_WINDOW / 10 + 1) )) \ + "the keyboard widget's 10s check of a seat with several keyboards, or none it can read" + fi + + # While a remote session is active its end has to be polled for, every 2s: + # Hyprland reports the screencast stopped whenever frames pause, and nothing + # at all when the server exits. + if pgrep -x -u "$(id -u)" gliff-server >/dev/null; then + allow '/shell/plugins/services/remote-session/probe\.sh$' $(( IDLE_WINDOW / 2 + 1 )) \ + "the remote session's 2s check while a session is active" + fi + + # The network widget, one per screen, reads a connected Wi-Fi network's + # strength from the access point list every 5s when NetworkManager reports + # none for it, which raises no change signal. Whether it reports one can only + # be seen from inside the shell, so this holds while Wi-Fi is connected at all. + if LC_ALL=C nmcli -t -f TYPE,STATE device 2>/dev/null | grep -qx 'wifi:connected'; then + allow '(^|/)nmcli -t -f IN-USE,SIGNAL device wifi list ifname ' $(( screens * (IDLE_WINDOW / 5 + 1) )) \ + "the network widget's 5s strength read while Wi-Fi is connected" + fi +} + +# Events that legitimately make the shell start something (a config reload, a +# theme switch, a charger plugged in, a screencast) come from the session +# around the test, which the test cannot hold still. Record them while +# watching, so a spawn that lines up with one can be told from a poll. +start_event_monitors() { + local events="$1" socket="${XDG_RUNTIME_DIR:-/run/user/$UID}/hypr/${HYPRLAND_INSTANCE_SIGNATURE:-}/.socket2.sock" + + MONITOR_PIDS=() + : >"$events" + # Each monitor runs in a subshell of its own, so stopping its descendants + # stops the whole pipeline. + if [[ -n ${HYPRLAND_INSTANCE_SIGNATURE:-} && -S $socket ]]; then + ( socat -u "UNIX-CONNECT:$socket" - 2>/dev/null | sed -u 's/^/hyprland /' >>"$events" ) & + MONITOR_PIDS+=("$!") + fi + if command -v upower >/dev/null; then + ( upower --monitor 2>/dev/null | + sed -u -n 's/^\[[^]]*\][[:space:]]*\([a-z ]*\):.*/upower \1/p' >>"$events" ) & + MONITOR_PIDS+=("$!") + fi + if command -v nmcli >/dev/null; then + # It opens by stating that NetworkManager is running, which is no event. + ( nmcli monitor 2>/dev/null | sed -u -e '/^NetworkManager is running$/d' -e 's/^/networkmanager /' >>"$events" ) & + MONITOR_PIDS+=("$!") + fi +} + +# Watches the shell for one window and leaves what it started outside the +# allowances in `unexpected`, and the events seen meanwhile in $1. +watch_window() { + local events="$1" window_log="$TMPDIR/window.log" start pid ppid command i count limit + local -A parent=() matched=() execed=() running=() forked_from=() seen=() allowed_count=() + + ALLOW_PATTERNS=() + ALLOW_LIMITS=() + ALLOW_REASONS=() + add_allowances + start=$(exec_count) + start_event_monitors "$events" + sleep "$IDLE_WINDOW" + # The shell keeps appending, so judge one copy taken as the window closes, + # before anything else takes time out of it: both passes below have to read + # the same lines, and the limits are for the window's length. + cp "$exec_log" "$window_log" + stop_event_monitors + add_allowances + kill -0 "$QS_PID" 2>/dev/null || fail_with_log "test shell exited while idle" + + # Whatever an allowed command goes on to run is allowed with it, through any + # subshells in between. Ancestry is read from the whole log before anything + # is judged, since a process started before the window can still exec during + # it, and a spawned child is only logged once the spawn returns, which can be + # after its own children. + while read -r pid ppid command; do + [[ -n ${parent[$pid]:-} ]] || parent[$pid]=$ppid + if [[ -z $command ]]; then + forked_from[$pid]=${running[$ppid]:-process $ppid} + continue + fi + execed[$pid]=1 + running[$pid]=$command + [[ -n ${matched[$pid]:-} ]] && continue + for i in "${!ALLOW_PATTERNS[@]}"; do + if [[ $command =~ ${ALLOW_PATTERNS[$i]} ]]; then + matched[$pid]=$i + break + fi + done + done <"$window_log" + + allowed_by() { + local pid="$1" depth=0 + + while [[ -n $pid ]] && (( depth++ < 64 )); do + if [[ -n ${matched[$pid]:-} ]]; then + echo "${matched[$pid]}" + return 0 + fi + pid=${parent[$pid]:-} + done + return 1 + } + + unexpected=() + local line_number=0 entry key + while read -r pid ppid command; do + line_number=$(( line_number + 1 )) + (( line_number > start )) || continue + + if entry=$(allowed_by "$pid"); then + # Count the allowed command itself, once per process, against its limit. + if [[ -n $command && ${matched[$pid]:-} == "$entry" && -z ${seen[$pid]:-} ]]; then + seen[$pid]=1 + allowed_count[$entry]=$(( ${allowed_count[$entry]:-0} + 1 )) + fi + continue + fi + + if [[ -n $command ]]; then + # A failed exec attempt is retried down PATH under the same pid, and a + # process that execs on (bash -c's last command, a stub) keeps it, so + # each process is named once, by the command it was started as. + key=$pid + elif [[ -z ${execed[$pid]:-} ]]; then + # A process forked to run only built-ins never execs, but it is a process. + key=$pid + command="(subshell of ${forked_from[$pid]})" + else + continue + fi + if [[ -z ${seen[$key]:-} ]]; then + seen[$key]=1 + unexpected+=("$command") + fi + done <"$window_log" + + for i in "${!ALLOW_PATTERNS[@]}"; do + count=${allowed_count[$i]:-0} + limit=${ALLOW_LIMITS[$i]} + if [[ -n $limit ]] && (( count > limit )); then + unexpected+=("$count runs matching ${ALLOW_PATTERNS[$i]}, more than the $limit allowed for ${ALLOW_REASONS[$i]}") + fi + done +} + +report() { + printf 'The shell started %d process(es) in %ds of idling:\n' "${#unexpected[@]}" "$IDLE_WINDOW" + printf '%s\n' "${unexpected[@]}" | sort | uniq -c | sort -rn | sed 's/^/ /' | head -40 + if [[ -s $1 ]]; then + printf 'Session events seen meanwhile:\n' + cut -d'>' -f1 "$1" | sort | uniq -c | sort -rn | sed 's/^/ /' | head -20 + fi + printf 'Poll on an event instead (agents/skills/shell-dev.md), or allow it in %s with the reason.\n' "${BASH_SOURCE[0]}" +} + +events="$TMPDIR/events.log" +watch_window "$events" + +# A spawn that lined up with a session event may have been the shell reacting +# to it. Watch once more: a poll comes back, a reaction needs its event again. +if (( ${#unexpected[@]} > 0 )) && [[ -s $events ]]; then + printf '# %s\n' "Spawns coincided with session events; watching once more:" >&2 + report "$events" | sed 's/^/# /' >&2 + watch_window "$events" +fi + +(( ${#unexpected[@]} == 0 )) || fail "an idle shell starts no processes" "$(report "$events")" +pass "an idle shell starts no processes over ${IDLE_WINDOW}s" diff --git a/test/shell.d/theme-set-budget-test.sh b/test/shell.d/theme-set-budget-test.sh new file mode 100755 index 000000000000..22ba4f39be2e --- /dev/null +++ b/test/shell.d/theme-set-budget-test.sh @@ -0,0 +1,206 @@ +#!/bin/bash + +# A theme switch returns once the desktop has its new colours; slow app +# retints run behind it or not at all. This runs the whole omarchy-theme-set +# against a scratch home in which every app is a stub, and gives the stubs the +# costs the real apps have: a running Hunk, VS Code with the theme's extension +# installed (answering --list-extensions after an Electron boot), a Framework 16 +# keyboard and three tmux sessions. A switch that waits on any of them again, +# or that starts a client per value, fails. + +set -euo pipefail + +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +require_command jq + +require_comparable_speed "theme switch budget" + +# The switch costs about 0.1s on the reference laptop. Waiting on Hunk's settle +# nudge or on one VS Code boot costs a second more. The budget grows with how +# much slower this machine starts processes, which a slow enough one can stretch +# past that second, so the waits are also checked directly below. +BUDGET_MS=$(( ${OMARCHY_THEME_SET_BUDGET_MS:-500} * SPEED_PERCENT / 100 )) +STUB_COST=1 + +sandbox=$(mktemp -d) +# A gated Hunk nudge still waiting gives up once the gate opens or the sandbox +# is gone; open it on the way out, then give the waiter a moment to see it. +cleanup() { + if [[ -d $sandbox ]]; then + touch "$sandbox/hunk-gate" + /usr/bin/sleep 0.3 + fi + rm -rf "$sandbox" +} +trap cleanup EXIT + +test_home="$sandbox/home" +stub_bin="$sandbox/bin" +calls="$sandbox/calls.log" +mkdir -p "$test_home" "$stub_bin" "$sandbox/run" "$sandbox/tmux" "$sandbox/policy" + +# Every stub logs its name and arguments, so the test can tell which apps the +# switch reached, and what it would have done to them. +stub() { + local name="$1" body="${2:-}" + + cat >"$stub_bin/$name" <>"$calls" +$body +exit 0 +SH + chmod +x "$stub_bin/$name" +} + +# The switch sees no program of the host's but plain tools, so an app the host +# happens to have installed (an ASUS keyboard's asusctl, VSCodium, a browser) +# is absent rather than retinted for real. Everything it may reach on the +# desktop is a stub: the compositor, the shell, signals to running apps and +# privileged writes. +tools_bin="$sandbox/tools" +mkdir -p "$tools_bin" +for tool in awk base64 basename cat chmod cksum cmp cp cut date dirname env find flock \ + gawk grep head id jq ln ls md5sum mkdir mktemp mv ps readlink realpath rm rmdir sed \ + seq setsid sha256sum sleep sort stat tail tee timeout touch tr tty uname uniq wc xargs; do + path=$(command -v "$tool") || fail "required command is available: $tool" + ln -s "$path" "$tools_bin/$tool" +done + +for name in hyprctl omarchy-shell pkill killall omarchy-theme-set-browser-policy \ + omarchy-theme-set-herdr-machines omarchy-theme-bg-cache omarchy-hook; do + stub "$name" +done +# Never escalate: the browser policy hook would rewrite the system's policy. +stub sudo 'exit 1' +stub pkexec 'exit 1' +stub pgrep '[[ " $* " == *" hunk "* ]] || exit 1' +stub tmux '[[ $1 == "list-sessions" ]] && printf "%s\n" one two three' +stub code "[[ \$* == *--list-extensions* ]] && { sleep $STUB_COST; echo enkia.tokyo-night; }" +stub qmk_hid +# Hunk's settle nudge sleeps from inside omarchy-theme-set-hunk; with a gate set +# it waits for the gate instead. Every other sleep is a real one. +cat >"$stub_bin/sleep" <<'SH' +#!/bin/bash +if [[ -n ${HUNK_GATE:-} ]] && tr '\0' ' ' <"/proc/$PPID/cmdline" 2>/dev/null | grep -q omarchy-theme-set-hunk; then + for _ in {1..100}; do + [[ -e $HUNK_GATE || ! -d ${HUNK_GATE%/*} ]] && exit 0 + /usr/bin/sleep 0.1 + done + exit 0 +fi +exec /usr/bin/sleep "$@" +SH +chmod +x "$stub_bin/sleep" + +# The app retints run under `bash -lc`, and a login shell resets PATH and +# OMARCHY_PATH from /etc/omarchy.conf, which would put the real commands back +# ahead of these stubs. Keep the login shell from rereading the profile. +cat >"$stub_bin/bash" <<'SH' +#!/bin/bash +[[ $1 == "-lc" ]] && shift && set -- -c "$@" +exec /bin/bash "$@" +SH +chmod +x "$stub_bin/bash" + +# VS Code's own registry already lists the theme's extension. +mkdir -p "$test_home/.vscode/extensions/enkia.tokyo-night" "$test_home/.config/Code/User" +jq -n '[{identifier: {id: "enkia.tokyo-night"}, relativeLocation: "enkia.tokyo-night"}]' \ + >"$test_home/.vscode/extensions/extensions.json" +echo '{}' >"$test_home/.config/Code/User/settings.json" + +# Cursor is the one editor the VS Code hook names by absolute path. +mkdir -p "$test_home/.local/state/omarchy/toggles" +touch "$test_home/.local/state/omarchy/toggles/skip-cursor-theme-changes" + +run_theme_set() { + env -i \ + HOME="$test_home" \ + USER="${USER:-omarchy}" \ + LANG=C.UTF-8 \ + OMARCHY_PATH="$ROOT" \ + PATH="$stub_bin:$ROOT/bin:$tools_bin" \ + XDG_RUNTIME_DIR="$sandbox/run" \ + TMUX_TMPDIR="$sandbox/tmux" \ + OMARCHY_THEME_SKIP_BACKGROUND=1 \ + OMARCHY_BROWSER_POLICY_DIRS="$sandbox/policy" \ + HUNK_GATE="${HUNK_GATE:-}" \ + "$ROOT/bin/omarchy-theme-set" "$1" >"$sandbox/theme-set.log" 2>&1 +} + +# A first switch sets up the scratch home, so the timed ones change between two +# themes the way a user would. +run_theme_set "Catppuccin" || fail "theme set runs in a scratch home" "$(cat "$sandbox/theme-set.log")" + +# Each theme is held to the budget on its own: the two take different paths +# through the hooks (Tokyo Night's VS Code extension is installed, Catppuccin's +# is not), and a fast one must not cover for a slow one. +declare -A best=() +slowest_theme="" +for theme in "Tokyo Night" "Catppuccin" "Tokyo Night" "Catppuccin"; do + : >"$calls" + start=$EPOCHREALTIME + run_theme_set "$theme" || fail "theme set switches to $theme in a scratch home" "$(cat "$sandbox/theme-set.log")" + end=$EPOCHREALTIME + elapsed=$(( (${end/[.,]/} - ${start/[.,]/}) / 1000 )) + if [[ -z ${best[$theme]:-} ]] || (( elapsed < best[$theme] )); then + best[$theme]=$elapsed + cp "$calls" "$sandbox/calls-$theme.log" + fi +done +for theme in "${!best[@]}"; do + if [[ -z $slowest_theme ]] || (( best[$theme] > best[$slowest_theme] )); then + slowest_theme=$theme + fi +done + +# The stubs only prove anything if the switches reached them. +cat "$sandbox"/calls-*.log >"$sandbox/calls-all.log" +for reached in "pgrep -x hunk" "qmk_hid via" "tmux list-sessions" "hyprctl reload" "omarchy-theme-set-browser-policy"; do + grep -qF -- "$reached" "$sandbox/calls-all.log" || + fail "theme set reaches the stubbed apps ($reached)" "$(cut -c1-160 "$sandbox/calls-all.log" | sort -u)" +done +pass "theme set reaches every stubbed app" + +(( best[$slowest_theme] <= BUDGET_MS )) || fail "theme set returns within ${BUDGET_MS}ms with slow apps running" "$( + printf 'The faster of two switches to %s took %dms. Stubbed app calls in it:\n' "$slowest_theme" "${best[$slowest_theme]}" + cut -c1-160 "$sandbox/calls-$slowest_theme.log" | sort | uniq -c | sort -rn | sed 's/^/ /' | head -30 +)" +pass "theme set returns within ${BUDGET_MS}ms with slow apps running (${best[$slowest_theme]}ms for $slowest_theme)" + +# Every tmux client is a process start, so the count is the cost, and unlike +# the time it is the same on every machine. Before the theme went over as one +# source-file, every value took a client of its own: about 600 for these three sessions. +tmux_clients=$(grep -c '^tmux ' "$calls" || true) +(( tmux_clients <= 8 )) || fail "theme set syncs tmux with a handful of clients" "$( + printf 'The last switch started %d tmux clients:\n' "$tmux_clients" + grep '^tmux ' "$calls" | cut -c1-120 | sort | uniq -c | sort -rn | head -10 +)" +pass "theme set syncs tmux with a handful of clients ($tmux_clients)" + +# The waits themselves, which a slow machine's budget can hide. VS Code's own +# registry already lists the theme's extension, so no editor is started to ask, +# and Hunk's settle nudge comes after the switch has returned. +list_calls=$(cat "$sandbox"/calls-*.log | grep -c '^code .*--list-extensions' || true) +(( list_calls == 0 )) || fail "theme set reads VS Code's extension registry instead of starting the editor" \ + "$(grep '^code ' "$sandbox"/calls-*.log)" +pass "theme set reads VS Code's extension registry instead of starting the editor" + +# Hunk's settle nudge waits on a gate here, not on the clock, so a slow +# machine's long switch cannot pass it by. A switch that waits for the nudge +# stays held until the gate opens (10s at most), and returns having sent both. +sleep 1.5 +: >"$calls" +HUNK_GATE="$sandbox/hunk-gate" run_theme_set "Catppuccin" || + fail "theme set switches to Catppuccin in a scratch home" "$(cat "$sandbox/theme-set.log")" +nudges=$(grep -c '^pkill -WINCH -x hunk' "$calls" || true) +touch "$sandbox/hunk-gate" +(( nudges == 1 )) || fail "theme set returns before Hunk's settle nudge" "Hunk was nudged $nudges times before the switch returned." +# The gate open, the settle nudge follows. +for _ in {1..30}; do + (( $(grep -c '^pkill -WINCH -x hunk' "$calls" || true) == 2 )) && break + /usr/bin/sleep 0.1 +done +(( $(grep -c '^pkill -WINCH -x hunk' "$calls" || true) == 2 )) || fail "Hunk gets its settle nudge once the gate opens" +pass "theme set returns before Hunk's settle nudge"