diff --git a/omarchy-mac/README.md b/omarchy-mac/README.md index e3bba1eb..8d2b4093 100644 --- a/omarchy-mac/README.md +++ b/omarchy-mac/README.md @@ -1,6 +1,6 @@ # omarchy-mac -Apple Silicon defaults and support services for Omarchy. Version: `0.1.3` (candidate). This add-on complements `omarchy` and `omarchy-settings`; it selects no kernel and contains no installer or repository trust configuration. It covers what stays on an installed Mac; installing one is the job of the [Omarchy Installer](https://github.com/omacom/omarchy-mac-installer), and boot support is the separate `omarchy-mac-boot` package beside this one. +Apple Silicon defaults and support services for Omarchy. Version: `0.1.4` (candidate). This add-on complements `omarchy` and `omarchy-settings`; it selects no kernel and contains no installer or repository trust configuration. It covers what stays on an installed Mac; installing one is the job of the [Omarchy Installer](https://github.com/omacom/omarchy-mac-installer), and boot support is the separate `omarchy-mac-boot` package beside this one. ## Build and stage @@ -14,7 +14,7 @@ Upgrade the matching runtime, settings and add-on candidates in one pacman trans Run `omarchy-mac-setup-system` as root on the target hardware (inside its target chroot for offline provisioning). An optional absolute root argument supports staging against the same target hardware without a bus. It exits without changes unless the runtime's Apple predicate `omarchy-hw-apple-silicon` holds (`omarchy-hw-platform` reports `aarch64-apple`, or `apple-silicon` on a runtime from before the platform rename), and fails if the detector does. It removes the Intel Mac Broadcom quirk (`options brcmfmac feature_disable=0x82000`, which breaks Apple Silicon Wi-Fi) from `/etc/modprobe.d/brcmfmac.conf` wherever an unguarded runtime migration appended it: only that exact line, with the comment block and blank line written right above it, goes; the file goes when nothing but blank lines is left, a link is left alone with the manual fix, and the initramfs rebuild it owes is recorded under `/var/lib/omarchy/migrations/1789172112-initramfs-pending`, which the runtime's migration finishes. It enables resume recovery only for BCM4378, BCM4387 and BCM4388 on Apple Silicon; Intel/T2 Macs are excluded. It is the only enabler of `speakersafetyd`, without which the kernel keeps the speakers muted: it applies the package's `80-omarchy-mac-audio.preset` once speakersafetyd is installed, so `/etc` presets that sort before it or replace it by name, masks and later explicit disables win, and image builders that apply presets get the same result. A live run also restarts a speakersafetyd left dead by a start-limit. No NetworkManager restart or driver reload occurs during setup. The backend applies when NetworkManager next starts; notch changes apply when appledrm next loads. A live run gives iwd a profile for each Wi-Fi network NetworkManager saved with its key before the switch, as NetworkManager itself does for a new connection, so saved networks keep connecting instead of reading as a wrong password. The greeter drop-in needs no setup: from the next `sddm` start it holds the greeter, for at most 10 s, until Apple's display controller has replaced the boot framebuffer. -Run `omarchy-mac-setup-user` as each target user with their HOME/XDG directories. It enables the vendor unit without a session bus. It writes nothing into the user's Hyprland files; a block an earlier version appended to `input.lua` or `looknfeel.lua` stays, as the user's. With a live bus, reached only through XDG_RUNTIME_DIR (which `sudo -i` clears), it reloads the user manager, reports the effective unit and starts the mapper. The mapper makes the microphone a typed stereo source, `omarchy_asahi_mic` ("MacBook Microphone"): pipewire-pulse's `module-remap-source` records asahi-audio's mono DSP source, which WirePlumber links to the left side and the mapper to the right, and offers an `Audio/Source` with front-left and front-right, the shape of a stock microphone, so the desktop's audio panel drives its volume, mute and level meter as it does any other. It makes that source the default input only if a brief sample finds signal, and hands a silent one back to the DSP source. A muted mapping is the user's microphone mute and is left alone. On upgrade from 0.1.2 the mapper replaces 0.1.2's virtual source of the same name (an `Audio/Source/Virtual`, which the panel gives no level meter) on its next start, keeping its gain, mute and selection. Provisioning and first run call setup; subsequent session starts only start the enabled unit, without reloading the user manager or repeating setup. The first desktop session does not depend on a bus existing during installation. Custom fragments, masks, activation links and headset or speaker policies are preserved; setup markers preserve explicit disables after initial setup. User gain state remains in `omarchy/asahi-mic-gain.json` under XDG_STATE_HOME. The desktop saves that state before restarting audio. +Run `omarchy-mac-setup-user` as each target user with their HOME/XDG directories. It enables the vendor unit without a session bus. It writes nothing into the user's Hyprland files; a block an earlier version appended to `input.lua` or `looknfeel.lua` stays, as the user's. With a live bus, reached only through XDG_RUNTIME_DIR (which `sudo -i` clears), it reloads the user manager, reports the effective unit and starts the mapper. The mapper makes the microphone a typed stereo source, `omarchy_asahi_mic` ("MacBook Microphone"): pipewire-pulse's `module-remap-source` records asahi-audio's mono DSP source, which WirePlumber links to the left side and the mapper to the right, and offers an `Audio/Source` with front-left and front-right, the shape of a stock microphone, so the desktop's audio panel drives its volume, mute and level meter as it does any other. It makes that source the default input only if a brief sample finds signal, and hands a silent one back to the DSP source. A muted mapping is the user's microphone mute and is left alone. On upgrade from 0.1.2 the mapper replaces 0.1.2's virtual source of the same name (an `Audio/Source/Virtual`, which the panel gives no level meter), keeping its gain, mute and selection. pacman restarts no user service, so a running mapper watches its own file: once an upgrade has replaced it and the transaction has ended, it runs the new file in place, within a few seconds, and that reconciles the live session. At session start the mapper subscribes to audio events before its first pass, so a DSP microphone that appears after it starts is mapped and made the default input at once. Provisioning and first run call setup; subsequent session starts only start the enabled unit, without reloading the user manager or repeating setup. The first desktop session does not depend on a bus existing during installation. Custom fragments, masks, activation links and headset or speaker policies are preserved; setup markers preserve explicit disables after initial setup. User gain state remains in `omarchy/asahi-mic-gain.json` under XDG_STATE_HOME. The desktop saves that state before restarting audio. A runtime whose `omarchy-lifecycle-dispatch` has the `setup-system` and `setup-user` operations (the platform setup seam, which registers `/usr/lib/omarchy/mac` for Apple Silicon) reaches both through the entrypoints this package stages there; an older runtime calls the two commands itself: `setup-system [image-first-boot]` (root, from the last hardware leaf and on an image's first boot, where it downloads nothing; it rebuilds no boot file) and `setup-user` (as the user being set up, at finalization and again in first run). Each re-checks the platform. diff --git a/omarchy-mac/bin/omarchy-audio-asahi-mic-map b/omarchy-mac/bin/omarchy-audio-asahi-mic-map index 4a68e246..20f58f6d 100755 --- a/omarchy-mac/bin/omarchy-audio-asahi-mic-map +++ b/omarchy-mac/bin/omarchy-audio-asahi-mic-map @@ -52,6 +52,10 @@ outage = dict(since=None, notified=False, repaired=False) recheck = dict(at=None) # The mapping's Pulse index, so a change of its own gain or mute is saved. mapping_index = dict(value=None) +# A package upgrade replaces this file under a running watcher, and pacman +# restarts no user service: the watcher runs the new file itself. +PACMAN_LOCK = Path('/var/lib/pacman/db.lck') +RELOAD = 'reload' class Deferred(Exception): @@ -688,6 +692,56 @@ def run_once(audio, runtime, state, save_only=False, checked=None): reconcile(audio, state, save_only, checked) +def pacman_running(): + for comm in Path('/proc').glob('[0-9]*/comm'): + with contextlib.suppress(OSError): + if comm.read_text().strip() == 'pacman': + return True + return False + + +class Program: + # The watcher's own file is replaced once it differs from the one started, + # is unchanged since the previous look and no pacman transaction (which may + # upgrade the interpreter too) holds the database; a lock no pacman holds is stale. + def __init__(self, path, lock=None, running=pacman_running): + self.path = Path(path) + self.lock = Path(PACMAN_LOCK if lock is None else lock) + self.running = running + self.started = self.seen = self.signature() + self.retry_at = None + self.backoff = 2.0 + + def signature(self): + try: + status = os.stat(self.path) + except OSError: + return None + return status.st_dev, status.st_ino, status.st_size, status.st_mtime_ns + + def replaced(self): + current = self.signature() + previous, self.seen = self.seen, current + if current is None or current == self.started or current != previous: + return False + if self.retry_at is not None and time.monotonic() < self.retry_at: + return False + if self.lock.exists() and self.running(): + return False + return os.access(self.path, os.X_OK) + + def run(self): + # Returns only when the new file cannot be run (the interpreter may be + # mid-replacement): the old code goes on and tries again, backing off. + print('Running the updated microphone mapper', file=sys.stderr, flush=True) + try: + os.execv(self.path, [str(self.path), *sys.argv[1:]]) + except OSError as error: + print('Could not run the updated microphone mapper: ' + str(error), file=sys.stderr, flush=True) + self.retry_at = time.monotonic() + self.backoff + self.backoff = min(self.backoff * 2, 300.0) + + class Subscription: # Wakes the supervisor when the mapping may need repair: a sink, source, # card or module appeared or vanished, a card or module changed, or the @@ -703,9 +757,15 @@ class Subscription: EVENT = re.compile(rb"^Event '(new|remove)' on (sink|source|card|module) #|^Event 'change' on (card|module|server) #") SOURCE_CHANGE = re.compile(rb"^Event 'change' on source #([0-9]+)$") - def __init__(self, command=('pactl', 'subscribe'), quiet=0.5, settle=5.0, backstop=600.0, retry=2.0): + def __init__(self, command=('pactl', 'subscribe'), quiet=0.5, settle=5.0, backstop=600.0, retry=2.0, stale=None, poll=2.0): self.command = list(command) self.quiet, self.settle, self.backstop, self.retry = quiet, settle, backstop, retry + # stale() is asked every poll seconds, across waits, whether to stop + # for RELOAD. A pass a moment after subscribing covers a device that + # appeared before pactl had registered the subscription. + self.stale, self.poll = stale, poll + self.next_poll = None + self.confirm = None self.process = None self.buffer = b'' # Save-only wakes never reset the backstop, or a busy microphone @@ -718,6 +778,8 @@ class Subscription: except OSError: self.process = None self.buffer = b'' + if self.process is not None: + self.confirm = time.monotonic() + 1.0 return self.process is not None def stop(self): @@ -743,22 +805,47 @@ class Subscription: def full(self): self.last_full = time.monotonic() + self.confirm = None return False + def reload_due(self): + if self.stale is None: + return False + now = time.monotonic() + if self.next_poll is None: + self.next_poll = now + self.poll + if now < self.next_poll: + return False + self.next_poll = now + self.poll + return self.stale() + def wait(self, limit=None): - # True: only the mapping's gain or mute may have changed. - if self.process is None and not self.start(): - time.sleep(self.retry) + # True: only the mapping's gain or mute may have changed. RELOAD: the + # watcher's program was replaced. + # A full pass follows every subscription, so a device that appeared + # while nothing listened (the DSP at login) is still mapped. + if self.reload_due(): + return RELOAD + if self.process is None: + if not self.start(): + time.sleep(self.retry) return self.full() started = time.monotonic() hard = self.last_full + self.backstop if limit is None else min(self.last_full + self.backstop, started + limit) + if self.confirm is not None: + hard = min(hard, self.confirm) due = None latest = None repair = False while True: + if self.reload_due(): + return RELOAD now = time.monotonic() deadline = hard if due is None else min(due, latest) if repair else min(due, latest, hard) - if deadline <= now or not select.select([self.process.stdout], [], [], deadline - now)[0]: + wake = deadline if self.next_poll is None else min(deadline, self.next_poll) + if wake <= now or not select.select([self.process.stdout], [], [], wake - now)[0]: + if time.monotonic() < deadline: + continue if due is None or repair or time.monotonic() >= hard: return self.full() return True @@ -784,9 +871,11 @@ class Subscription: latest = now + self.settle -def supervise(operation, wait=None): - subscription = Subscription() if wait is None else None - if subscription is not None: +def supervise(operation, wait=None, program=None): + subscription = None + if wait is None: + subscription = Subscription(stale=None if program is None else program.replaced) + subscription.start() wait = lambda: subscription.wait(outage_due()) previous_error = None save_only = False @@ -803,7 +892,14 @@ def supervise(operation, wait=None): if message != previous_error: print(message, file=sys.stderr, flush=True) previous_error = message - save_only = bool(wait()) + result = wait() + if result == RELOAD: + if subscription is not None: + subscription.stop() + program.run() + save_only = False + else: + save_only = bool(result) finally: if subscription is not None: subscription.stop() @@ -825,7 +921,7 @@ def main(): if args.watch: # Let a service stop unwind through supervise so the subscriber exits too. signal.signal(signal.SIGTERM, lambda *_: sys.exit(0)) - supervise(operation) + supervise(operation, program=Program(os.path.abspath(sys.argv[0]))) else: try: operation() diff --git a/omarchy-mac/test/mic-reload-test.sh b/omarchy-mac/test/mic-reload-test.sh new file mode 100755 index 00000000..08302a1d --- /dev/null +++ b/omarchy-mac/test/mic-reload-test.sh @@ -0,0 +1,56 @@ +#!/bin/bash +set -euo pipefail +source "$(dirname "$0")/base-test.sh" +work=$(mktemp -d) +watcher= +cleanup() { + [[ -z $watcher ]] || kill "$watcher" 2>/dev/null || true + rm -rf "$work" +} +trap cleanup EXIT +mkdir -p "$work/bin" "$work/run" "$work/state" +printf '#!/bin/bash\necho "${PLATFORM:-aarch64-apple}"\n' >"$work/bin/omarchy-hw-platform" +stub_apple_predicate "$work/bin" +# The subscriber records its PID and waits; nothing else answers. +cat >"$work/bin/pactl" <<'STUB' +#!/bin/bash +[[ $1 == "subscribe" ]] || exit 1 +echo $$ >"$WORK/subscriber" +exec sleep 60 +STUB +chmod +x "$work/bin/"* + +# A package upgrade replaces the running watcher's file: the watcher runs the +# new file under its own PID with its arguments, and stops its subscriber. +"$ROOT"/install "$work/root" +mapper=$work/root/usr/bin/omarchy-audio-asahi-mic-map +# The host's pacman lock and audio session stay out of it. +cat >"$work/watch.py" <<'WATCH' +import importlib.machinery, importlib.util, sys +from pathlib import Path +loader = importlib.machinery.SourceFileLoader('mapper', sys.argv[1]) +spec = importlib.util.spec_from_loader(loader.name, loader) +mapper = importlib.util.module_from_spec(spec); loader.exec_module(mapper) +mapper.PACMAN_LOCK = Path(sys.argv[2]) +sys.argv = [sys.argv[1], '--watch'] +sys.exit(mapper.main()) +WATCH +env -u PULSE_SERVER -u PIPEWIRE_REMOTE WORK="$work" PATH="$work/bin:$PATH" XDG_RUNTIME_DIR="$work/run" XDG_STATE_HOME="$work/state" \ + python3 "$work/watch.py" "$mapper" "$work/db.lck" 2>"$work/log" & +watcher=$! +for _ in $(seq 100); do + [[ -s $work/subscriber ]] && break + sleep 0.1 +done +subscriber=$(<"$work/subscriber") +printf '#!/bin/bash\necho "$$ $*" >"$WORK/reloaded"\nexec sleep 60\n' >"$work/new" +chmod +x "$work/new" +mv "$work/new" "$mapper" +for _ in $(seq 200); do + [[ -s $work/reloaded ]] && break + sleep 0.1 +done +[[ $(<"$work/reloaded") == "$watcher --watch" ]] || fail 'the watcher runs its replaced file in place' "$(cat "$work/log")" +! kill -0 "$subscriber" 2>/dev/null || fail 'the old subscriber stops with the old code' +grep -q 'Running the updated microphone mapper' "$work/log" || fail 'the reload is logged' +pass 'a running watcher runs its upgraded program in place within seconds' diff --git a/omarchy-mac/test/mic-test.sh b/omarchy-mac/test/mic-test.sh index cb7b9566..c0e37e10 100644 --- a/omarchy-mac/test/mic-test.sh +++ b/omarchy-mac/test/mic-test.sh @@ -591,8 +591,9 @@ with tempfile.TemporaryDirectory() as temporary: # The watcher sleeps on pactl events instead of polling: device events wake # it once they settle, application and stream events never do, a steady # stream cannot starve repair, and a lost subscription still yields one. - def feed(script): - return m.Subscription(command=['bash', '-c', script], quiet=0.1, settle=1.0, backstop=0.6, retry=0.05) + def feed(script, **options): + sub = m.Subscription(command=['bash', '-c', script], **dict(dict(quiet=0.1, settle=1.0, backstop=0.6, retry=0.05), **options)) + sub.start(); sub.last_full = time.monotonic(); return sub def timed(sub): start = time.monotonic(); sub.wait(); elapsed = time.monotonic() - start; sub.stop(); return elapsed elapsed = timed(feed("echo \"Event 'new' on source #7\"; sleep 3")) @@ -636,6 +637,121 @@ with tempfile.TemporaryDirectory() as temporary: sub = feed('exit 0'); elapsed = timed(sub) assert elapsed < 0.5 and sub.process is None, 'a lost subscription must yield a repair and resubscribe later' assert timed(m.Subscription(command=['/nonexistent/pactl'], retry=0.05)) < 0.5, 'a missing subscriber must degrade to a paced retry' + # A device that appears while nothing listens (the DSP at login, or after + # pipewire-pulse restarts) is mapped: the supervisor subscribes before its + # first pass, and every resubscription is followed by a pass at once. + sub = m.Subscription(command=['bash', '-c', "sleep 3; echo \"Event 'new' on source #7\""], backstop=60.0, retry=0.05) + start = time.monotonic(); result = sub.wait(); elapsed = time.monotonic() - start + assert result is False and elapsed < 0.5 and sub.process is not None, ('a new subscription is followed by a pass', result, elapsed) + sub.stop() + order = [] + class Recorded: + def __init__(self, **options): order.append(('subscription', options.get('stale'))) + def start(self): order.append('subscribe'); return True + def wait(self, limit=None): raise KeyboardInterrupt() + def stop(self): order.append('stop') + with mock.patch.object(m, 'Subscription', Recorded): + try: m.supervise(lambda save=False: order.append('pass')) + except KeyboardInterrupt: pass + assert order == [('subscription', None), 'subscribe', 'pass', 'stop'], order + # A replaced program is noticed while events keep arriving, and only then. + looks = [] + def stale(): + looks.append(time.monotonic()); return len(looks) >= 2 + sub = feed("while true; do echo \"Event 'change' on source #5\"; sleep 0.05; done", backstop=60.0, stale=stale, poll=0.2) + m.mapping_index['value'] = '5' + results = []; start = time.monotonic() + while time.monotonic() - start < 2: + results.append(sub.wait()) + if results[-1] == m.RELOAD: break + sub.stop(); m.mapping_index['value'] = None + assert results[-1] == m.RELOAD and len(looks) == 2 and time.monotonic() - start < 1.5, (results, looks) + sub = feed('sleep 3', backstop=0.5, stale=lambda: False, poll=0.1) + assert sub.wait() is False, 'an unchanged program never stops the wait' + sub.stop() + # The poll runs across waits: events that end each wait sooner than the + # poll interval never postpone it, nor does a subscriber that keeps dying. + looks = [] + sub = feed("while true; do echo \"Event 'new' on sink #1\"; sleep 0.3; done", quiet=0.05, settle=0.1, backstop=60.0, stale=stale, poll=0.5) + results = []; start = time.monotonic() + while time.monotonic() - start < 3: + results.append(sub.wait()) + if results[-1] == m.RELOAD: break + sub.stop() + assert results[-1] == m.RELOAD and False in results and time.monotonic() - start < 2.0, (results, looks) + looks = [] + sub = m.Subscription(command=['bash', '-c', 'exit 0'], retry=0.05, stale=stale, poll=0.3) + results = []; start = time.monotonic() + while time.monotonic() - start < 3: + results.append(sub.wait()) + if results[-1] == m.RELOAD: break + sub.stop() + assert results[-1] == m.RELOAD and time.monotonic() - start < 2.0, (results, looks) + # A moment after subscribing the watcher looks once more, for a device + # that appeared before pactl had registered its subscription. + sub = feed('sleep 5', backstop=60.0) + start = time.monotonic(); result = sub.wait(); elapsed = time.monotonic() - start + assert result is False and 0.8 <= elapsed < 1.5, ('a pass follows a moment after subscribing', elapsed) + start = time.monotonic(); sub.wait(0.3); assert time.monotonic() - start >= 0.3, 'only once' + sub.stop() + # On RELOAD the supervisor stops its subscriber and runs the new program; + # if that cannot run, the old code carries on with a full pass. + events = [] + class Replaced: + def replaced(self): return False + def run(self): events.append('run') + class Watched: + def __init__(self, **options): pass + def start(self): return True + def wait(self, limit=None): + if len(events) > 3: raise KeyboardInterrupt() + return m.RELOAD + def stop(self): events.append('stop') + passes = [] + with mock.patch.object(m, 'Subscription', Watched): + try: m.supervise(lambda save=False: passes.append(save), program=Replaced()) + except KeyboardInterrupt: pass + assert events[:4] == ['stop', 'run', 'stop', 'run'] and passes[:3] == [False, False, False], (events, passes) +# The watcher's program counts as replaced once a different file is in place, +# unchanged since the previous look, and no pacman transaction is running (a +# lock no pacman holds is stale). A missing or unrunnable file is never run, +# and one that fails to run is tried again later, backing off. +with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary); path = directory / 'omarchy-audio-asahi-mic-map'; lock = directory / 'db.lck' + pacman = [True] + def put(text, mode=0o755): + new = directory / 'new'; new.write_text(text); new.chmod(mode); os.replace(new, path) + def watched(): return m.Program(path, lock=lock, running=lambda: pacman[0]) + put('old') + program = watched() + assert not program.replaced() and not program.replaced(), 'the started program is current' + put('new') + assert not program.replaced(), 'a file just written may still be changing' + assert program.replaced(), 'a replaced file unchanged since the previous look is run' + program = watched() + put('newer'); lock.touch() + assert not program.replaced() and not program.replaced() and not program.replaced(), 'not while pacman holds its lock' + pacman[0] = False + assert program.replaced(), 'a lock no pacman holds is stale' + lock.unlink() + program = watched() + path.unlink() + assert not program.replaced() and not program.replaced(), 'a removed program is not run' + put('not executable', 0o644) + assert not program.replaced() and not program.replaced(), 'an unrunnable program is not run' + clock = [1000.0] + with mock.patch.object(m.os, 'execv', side_effect=OSError('Text file busy')), mock.patch.object(m.time, 'monotonic', lambda: clock[0]): + program = watched(); put('busy') + program.replaced(); assert program.replaced() + program.run() + assert not program.replaced(), 'a program that would not run waits out a back-off' + clock[0] += 2.0 + assert program.replaced(), 'and is then tried again' + program.run(); clock[0] += 2.0 + assert not program.replaced(), 'the back-off grows' + clock[0] += 2.0 + assert program.replaced() +assert m.Program(Path('/nonexistent')).lock == m.PACMAN_LOCK # The live probe reads float samples from the mapping through parec: any # non-zero sample, however quiet, is signal; zeros (either sign) are digital # silence; a recorder that yields nothing is unknown. @@ -758,4 +874,5 @@ assert '--watch' in unit and 'PartOf=graphical-session.target' in unit assert 'PartOf=pipewire.service' not in unit and 'After=graphical-session.target' not in unit print('ok - transactional Asahi mapping preserves choices/gain, rolls back failures and recovers lifecycle loss') print('ok - the mapping is a typed stereo remap source that replaces the 0.1.2 virtual source on upgrade') +print('ok - the watcher subscribes before each pass, so a late DSP is mapped, and runs its program once an upgrade replaced it') PY diff --git a/omarchy-mac/version b/omarchy-mac/version index b1e80bb2..845639ee 100644 --- a/omarchy-mac/version +++ b/omarchy-mac/version @@ -1 +1 @@ -0.1.3 +0.1.4