From 557e76890e98f84cec46e18d5ab3d487c7b2ee59 Mon Sep 17 00:00:00 2001 From: Marcelo Alcantara Date: Mon, 12 Oct 2026 19:25:06 +1000 Subject: [PATCH 1/7] Subscribe to audio events before every microphone mapping pass The watcher ran its first pass and only then started pactl subscribe, and after a lost subscription it repaired before resubscribing. A DSP microphone that appeared in between, as asahi-audio's does a moment after login, raised an event nobody heard, and the mapping waited for the ten-minute backstop. The supervisor now subscribes before its first pass, and every resubscription is followed by a full pass at once. --- omarchy-mac/README.md | 2 +- omarchy-mac/bin/omarchy-audio-asahi-mic-map | 8 +++++-- omarchy-mac/test/mic-test.sh | 23 +++++++++++++++++++-- 3 files changed, 28 insertions(+), 5 deletions(-) diff --git a/omarchy-mac/README.md b/omarchy-mac/README.md index e3bba1eb..79089dcb 100644 --- a/omarchy-mac/README.md +++ b/omarchy-mac/README.md @@ -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) on its next start, keeping its gain, mute and selection. 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..105f4887 100755 --- a/omarchy-mac/bin/omarchy-audio-asahi-mic-map +++ b/omarchy-mac/bin/omarchy-audio-asahi-mic-map @@ -747,8 +747,11 @@ class Subscription: 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) + # A full pass follows every subscription, so a device that appeared + # while nothing listened (the DSP at login) is still mapped. + 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) @@ -787,6 +790,7 @@ class Subscription: def supervise(operation, wait=None): subscription = Subscription() if wait is None else None if subscription is not None: + subscription.start() wait = lambda: subscription.wait(outage_due()) previous_error = None save_only = False diff --git a/omarchy-mac/test/mic-test.sh b/omarchy-mac/test/mic-test.sh index cb7b9566..e722786f 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,23 @@ 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 # 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 +776,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 DSP that appears late is mapped') PY From a52f846980d710c4defe9c02a3d74634da8a3e0c Mon Sep 17 00:00:00 2001 From: Marcelo Alcantara Date: Mon, 12 Oct 2026 19:25:17 +1000 Subject: [PATCH 2/7] Run the upgraded microphone mapper in place pacman restarts no user service, so after an upgrade the running watcher kept the old code until the next login: 0.1.2's virtual source stayed the default input after 0.1.3 was installed. The watcher now looks at its own file every two seconds; once a different file has stayed unchanged for a look and no pacman transaction holds the database (the interpreter may be upgraded in the same transaction; a lock older than a minute is ignored), it stops its subscriber and execs the new file under the same PID, whose first pass reconciles the live session, including a 0.1.2 source. A file that is missing, not executable or fails to exec leaves the old code running. --- omarchy-mac/README.md | 2 +- omarchy-mac/bin/omarchy-audio-asahi-mic-map | 79 ++++++++++++++++++--- omarchy-mac/test/mic-reload-test.sh | 45 ++++++++++++ omarchy-mac/test/mic-test.sh | 67 ++++++++++++++++- 4 files changed, 183 insertions(+), 10 deletions(-) create mode 100755 omarchy-mac/test/mic-reload-test.sh diff --git a/omarchy-mac/README.md b/omarchy-mac/README.md index 79089dcb..6609f135 100644 --- a/omarchy-mac/README.md +++ b/omarchy-mac/README.md @@ -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. 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. +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 105f4887..6b7127b7 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,46 @@ def run_once(audio, runtime, state, save_only=False, checked=None): reconcile(audio, state, save_only, checked) +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, or a minute has passed. + def __init__(self, path, lock=PACMAN_LOCK, patience=60.0): + self.path = Path(path) + self.lock = Path(lock) + self.patience = patience + self.started = self.seen = self.signature() + self.since = time.monotonic() + + 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: + return False + if current != previous: + self.since = time.monotonic() + return False + if self.lock.exists() and time.monotonic() - self.since < self.patience: + return False + return os.access(self.path, os.X_OK) + + def run(self): + # Returns only when the new file cannot be run; the old code goes on. + 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.started = self.signature() + + 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 +747,11 @@ 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 whether to stop for RELOAD. + self.stale, self.poll = stale, poll self.process = None self.buffer = b'' # Save-only wakes never reset the backstop, or a busy microphone @@ -746,7 +792,8 @@ class Subscription: return False def wait(self, limit=None): - # True: only the mapping's gain or mute may have changed. + # 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.process is None: @@ -758,10 +805,18 @@ class Subscription: due = None latest = None repair = False + poll = None if self.stale is None else started + self.poll while True: now = time.monotonic() + if poll is not None and now >= poll: + if self.stale(): + return RELOAD + poll = now + self.poll 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 poll is None else min(deadline, 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 @@ -787,9 +842,10 @@ 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 @@ -807,7 +863,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() @@ -829,7 +892,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..20e884d2 --- /dev/null +++ b/omarchy-mac/test/mic-reload-test.sh @@ -0,0 +1,45 @@ +#!/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 +WORK=$work PATH="$work/bin:$PATH" XDG_RUNTIME_DIR="$work/run" XDG_STATE_HOME="$work/state" \ + "$mapper" --watch 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 100); 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 e722786f..e426a041 100644 --- a/omarchy-mac/test/mic-test.sh +++ b/omarchy-mac/test/mic-test.sh @@ -654,6 +654,71 @@ with tempfile.TemporaryDirectory() as temporary: 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.0, (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() + # 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 (or +# its lock is a minute old). A missing or unrunnable file is never run. +with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary); path = directory / 'omarchy-audio-asahi-mic-map'; lock = directory / 'db.lck' + def put(text, mode=0o755): + new = directory / 'new'; new.write_text(text); new.chmod(mode); os.replace(new, path) + put('old') + program = m.Program(path, lock=lock) + 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 = m.Program(path, lock=lock) + put('newer'); lock.touch() + assert not program.replaced() and not program.replaced(), 'not while pacman holds its lock' + lock.unlink() + assert program.replaced(), 'once the transaction ends' + program = m.Program(path, lock=lock, patience=0.0) + put('stale lock'); lock.touch() + assert not program.replaced() and program.replaced(), 'a lock pacman left behind delays the reload only so long' + lock.unlink() + program = m.Program(path, lock=lock) + 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' + with mock.patch.object(m.os, 'execv', side_effect=OSError('Exec format error')): + program = m.Program(path, lock=lock); put('broken') + program.replaced(); assert program.replaced() + program.run() + assert not program.replaced(), 'a program that would not run is not retried until it changes again' # 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. @@ -776,5 +841,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 DSP that appears late is mapped') +print('ok - the watcher subscribes before each pass, so a late DSP is mapped, and runs its program once an upgrade replaced it') PY From f6494a3ae5ad6f8768acda5bc2b1b25edf970b16 Mon Sep 17 00:00:00 2001 From: Marcelo Alcantara Date: Mon, 12 Oct 2026 19:25:40 +1000 Subject: [PATCH 3/7] Restart microphone mappers that cannot reload themselves after an upgrade A mapper from 0.1.3 or earlier has no self-reload, so the upgrade that brings it would still leave it running old code until the next login; a 0.1.2 mapper kept its virtual source. A PostTransaction hook on the mapper's file now restarts, through each logged-in user's manager (systemctl --user --machine=user@ try-restart, without blocking pacman), every running mapper whose PID is not the one recorded in the user's runtime directory, which only self-reloading watchers write. Once every session runs a self-reloading watcher the hook restarts nothing. It does nothing off Apple Silicon, in a chroot or an unbooted root, and never fails the transaction. --- omarchy-mac/README.md | 2 +- omarchy-mac/bin/omarchy-audio-asahi-mic-map | 11 +++- omarchy-mac/lib/asahi-mic-restart | 35 +++++++++++ .../hooks/90-omarchy-mac-asahi-mic.hook | 9 +++ omarchy-mac/test/mic-reload-test.sh | 62 ++++++++++++++++++- 5 files changed, 115 insertions(+), 4 deletions(-) create mode 100755 omarchy-mac/lib/asahi-mic-restart create mode 100644 omarchy-mac/share/libalpm/hooks/90-omarchy-mac-asahi-mic.hook diff --git a/omarchy-mac/README.md b/omarchy-mac/README.md index 6609f135..fdc7d31e 100644 --- a/omarchy-mac/README.md +++ b/omarchy-mac/README.md @@ -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), 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. +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. Mappers from 0.1.3 and earlier cannot, so a pacman hook restarts, through each user's manager, every running mapper that has not recorded its PID in `omarchy-asahi-mic.reloads` under the user's runtime directory. 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 6b7127b7..c0b92c7b 100755 --- a/omarchy-mac/bin/omarchy-audio-asahi-mic-map +++ b/omarchy-mac/bin/omarchy-audio-asahi-mic-map @@ -53,9 +53,11 @@ 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. +# restarts no user service: the watcher runs the new file itself, under the +# same PID, which it records so the upgrade hook leaves it alone. PACMAN_LOCK = Path('/var/lib/pacman/db.lck') RELOAD = 'reload' +RELOAD_MARKER = 'omarchy-asahi-mic.reloads' class Deferred(Exception): @@ -892,7 +894,12 @@ 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, program=Program(os.path.abspath(sys.argv[0]))) + program = Program(os.path.abspath(sys.argv[0])) + try: + (runtime / RELOAD_MARKER).write_text(str(os.getpid())) + except OSError as error: + print('Could not record the microphone mapper: ' + str(error), file=sys.stderr, flush=True) + supervise(operation, program=program) else: try: operation() diff --git a/omarchy-mac/lib/asahi-mic-restart b/omarchy-mac/lib/asahi-mic-restart new file mode 100755 index 00000000..9647e524 --- /dev/null +++ b/omarchy-mac/lib/asahi-mic-restart @@ -0,0 +1,35 @@ +#!/bin/bash +# After an upgrade replaces the microphone mapper, restart each user's running +# mapper that predates self-reload (0.1.3 and earlier); newer ones record their +# PID and run the new file themselves. Never fails the transaction. + +# Unprivileged tests stage the package under a fixture root; root never does. +if (( EUID == 0 )); then + root="" +else + root=${OMARCHY_MAC_ROOT:-} +fi +unit=omarchy-asahi-mic.service + +restart_old_mappers() { + local runtime uid user pid marker + for runtime in "$root"/run/user/*; do + uid=${runtime##*/} + [[ $uid =~ ^[0-9]+$ && -S $runtime/systemd/private ]] || continue + user=$(id -nu "$uid" 2>/dev/null) || continue + pid=$(timeout 10 systemctl --user --machine="$user@" show --property=MainPID --value "$unit" 2>/dev/null) || continue + [[ $pid =~ ^[0-9]+$ ]] && (( pid > 0 )) || continue + marker=$runtime/omarchy-asahi-mic.reloads + if [[ -f $marker && ! -L $marker && $(<"$marker") == "$pid" ]]; then + continue + fi + echo "Restarting the microphone mapper of $user" + timeout 10 systemctl --user --machine="$user@" --no-block try-restart "$unit" || true + done +} + +# A chroot or an unbooted root has no user sessions. +if omarchy-hw-apple-silicon 2>/dev/null && [[ -d $root/run/systemd/system ]] && ! systemd-detect-virt --chroot --quiet; then + restart_old_mappers +fi +exit 0 diff --git a/omarchy-mac/share/libalpm/hooks/90-omarchy-mac-asahi-mic.hook b/omarchy-mac/share/libalpm/hooks/90-omarchy-mac-asahi-mic.hook new file mode 100644 index 00000000..f192873c --- /dev/null +++ b/omarchy-mac/share/libalpm/hooks/90-omarchy-mac-asahi-mic.hook @@ -0,0 +1,9 @@ +[Trigger] +Type = Path +Operation = Upgrade +Target = usr/bin/omarchy-audio-asahi-mic-map + +[Action] +Description = Restarting microphone mappers that cannot reload themselves... +When = PostTransaction +Exec = /usr/lib/omarchy-mac/asahi-mic-restart diff --git a/omarchy-mac/test/mic-reload-test.sh b/omarchy-mac/test/mic-reload-test.sh index 20e884d2..5c802177 100755 --- a/omarchy-mac/test/mic-reload-test.sh +++ b/omarchy-mac/test/mic-reload-test.sh @@ -28,9 +28,10 @@ WORK=$work PATH="$work/bin:$PATH" XDG_RUNTIME_DIR="$work/run" XDG_STATE_HOME="$w "$mapper" --watch 2>"$work/log" & watcher=$! for _ in $(seq 100); do - [[ -s $work/subscriber ]] && break + [[ -s $work/subscriber && -f $work/run/omarchy-asahi-mic.reloads ]] && break sleep 0.1 done +[[ $(<"$work/run/omarchy-asahi-mic.reloads") == "$watcher" ]] || fail 'the watcher records its PID for the upgrade hook' subscriber=$(<"$work/subscriber") printf '#!/bin/bash\necho "$$ $*" >"$WORK/reloaded"\nexec sleep 60\n' >"$work/new" chmod +x "$work/new" @@ -43,3 +44,62 @@ done ! 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' + +# The upgrade hook restarts only mappers that cannot reload themselves: those +# without a matching PID record. Nothing happens in a chroot, an unbooted root, +# off Apple Silicon, or when a user manager does not answer, and the +# transaction never fails. +hook=$work/root/usr/share/libalpm/hooks/90-omarchy-mac-asahi-mic.hook +grep -qx 'Target = usr/bin/omarchy-audio-asahi-mic-map' "$hook" && grep -qx 'Operation = Upgrade' "$hook" && + grep -qx 'Exec = /usr/lib/omarchy-mac/asahi-mic-restart' "$hook" || fail 'the hook runs on mapper upgrades' +restart=$work/root/usr/lib/omarchy-mac/asahi-mic-restart +fixture=$work/fixture +mkdir -p "$fixture/run/systemd/system" +socket() { python3 -c 'import socket, sys; socket.socket(socket.AF_UNIX).bind(sys.argv[1])' "$1"; } +for uid in 1000 1001 1002 1003; do + mkdir -p "$fixture/run/user/$uid/systemd" + socket "$fixture/run/user/$uid/systemd/private" +done +mkdir -p "$fixture/run/user/1004" +echo 200 >"$fixture/run/user/1001/omarchy-asahi-mic.reloads" +echo 999 >"$fixture/run/user/1002/omarchy-asahi-mic.reloads" +ln -s "$fixture/run/user/1001/omarchy-asahi-mic.reloads" "$fixture/run/user/1003/omarchy-asahi-mic.reloads" +cat >"$work/bin/id" <<'STUB' +#!/bin/bash +[[ $1 == "-nu" ]] && echo "user$2" +STUB +# MainPIDs: 1000 runs an old mapper, 1001 a self-reloading one, 1002 one that +# replaced a self-reloading one, 1003 an old one beside a linked record, 1004 +# has no manager. +cat >"$work/bin/systemctl" <<'STUB' +#!/bin/bash +echo "$*" >>"$WORK/systemctl" +case $2 in + --machine=user1000@) pid=100 ;; + --machine=user1001@) pid=200 ;; + --machine=user1002@) pid=300 ;; + --machine=user1003@) pid=200 ;; + *) pid=0 ;; +esac +[[ $3 == "show" ]] && echo "$pid" +[[ -z ${SYSTEMCTL_FAILS:-} ]] +STUB +printf '#!/bin/bash\nexit "${CHROOT:-1}"\n' >"$work/bin/systemd-detect-virt" +chmod +x "$work/bin/"* +hook_run() { WORK=$work PATH="$work/bin:$PATH" OMARCHY_MAC_ROOT=$fixture "$@" "$restart" >/dev/null; } +hook_run env +restarted=$(grep try-restart "$work/systemctl" | sed 's/.*--machine=\([^ ]*\)@.*/\1/' | sort | tr '\n' ' ') +[[ $restarted == "user1000 user1002 user1003 " ]] || fail 'only mappers without a matching PID record restart' "$restarted" +grep -q -- '--user --machine=user1000@ --no-block try-restart omarchy-asahi-mic.service' "$work/systemctl" || + fail 'the restart goes through the user manager without blocking pacman' +rm "$work/systemctl" +hook_run env CHROOT=0 +[[ ! -e $work/systemctl ]] || fail 'a chroot is left alone' +hook_run env PLATFORM=aarch64 +[[ ! -e $work/systemctl ]] || fail 'other machines are left alone' +rm -r "$fixture/run/systemd/system" +hook_run env +[[ ! -e $work/systemctl ]] || fail 'an unbooted root is left alone' +mkdir -p "$fixture/run/systemd/system" +hook_run env SYSTEMCTL_FAILS=1 || fail 'a user manager that fails never fails the transaction' +pass 'the upgrade hook restarts only mappers that predate self-reload' From 2d0c5b2f050e11a6baab44d08d1cf2a1cedb6061 Mon Sep 17 00:00:00 2001 From: Marcelo Alcantara Date: Mon, 12 Oct 2026 19:25:40 +1000 Subject: [PATCH 4/7] Release omarchy-mac 0.1.4 --- omarchy-mac/README.md | 2 +- omarchy-mac/version | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/omarchy-mac/README.md b/omarchy-mac/README.md index fdc7d31e..5acb877d 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 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 From 59c7bc9b335fcee82c1c504062f111aa10a913c4 Mon Sep 17 00:00:00 2001 From: Marcelo Alcantara Date: Mon, 12 Oct 2026 20:02:01 +1000 Subject: [PATCH 5/7] Keep the mapper's reload poll across waits and retry a failed exec Review found three holes. The two-second look at the mapper's own file restarted with every wait, so watched events more often than that, or a subscriber that kept dying, postponed the reload indefinitely; the next look is now kept on the subscription and consulted on every return path. A failed exec (the interpreter mid-replacement) disarmed the reload for good, while the upgrade hook skips a mapper that recorded its PID; it now retries with a growing back-off. And the lock was bypassed after a minute even with pacman still running its hooks; a lock is now ignored only when no pacman process exists. Popen returning does not mean pulse has registered the subscription, so a pass now also follows a second after subscribing. The end-to-end reload test points the pacman lock at its fixture and drops PULSE_SERVER and PIPEWIRE_REMOTE, so it passes the same on any host. --- omarchy-mac/bin/omarchy-audio-asahi-mic-map | 65 +++++++++++++++------ omarchy-mac/test/mic-reload-test.sh | 17 +++++- omarchy-mac/test/mic-test.sh | 63 +++++++++++++++----- 3 files changed, 109 insertions(+), 36 deletions(-) diff --git a/omarchy-mac/bin/omarchy-audio-asahi-mic-map b/omarchy-mac/bin/omarchy-audio-asahi-mic-map index c0b92c7b..b89dc97c 100755 --- a/omarchy-mac/bin/omarchy-audio-asahi-mic-map +++ b/omarchy-mac/bin/omarchy-audio-asahi-mic-map @@ -694,16 +694,25 @@ 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, or a minute has passed. - def __init__(self, path, lock=PACMAN_LOCK, patience=60.0): + # 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(lock) - self.patience = patience + self.lock = Path(PACMAN_LOCK if lock is None else lock) + self.running = running self.started = self.seen = self.signature() - self.since = time.monotonic() + self.retry_at = None + self.backoff = 2.0 def signature(self): try: @@ -715,23 +724,24 @@ class Program: def replaced(self): current = self.signature() previous, self.seen = self.seen, current - if current is None or current == self.started: + if current is None or current == self.started or current != previous: return False - if current != previous: - self.since = time.monotonic() + if self.retry_at is not None and time.monotonic() < self.retry_at: return False - if self.lock.exists() and time.monotonic() - self.since < self.patience: + 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 old code goes on. + # 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.started = self.signature() + self.retry_at = time.monotonic() + self.backoff + self.backoff = min(self.backoff * 2, 300.0) class Subscription: @@ -752,8 +762,12 @@ class Subscription: 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 whether to stop for RELOAD. + # 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 @@ -766,6 +780,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): @@ -791,31 +807,44 @@ 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. 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 - poll = None if self.stale is None else started + self.poll while True: + if self.reload_due(): + return RELOAD now = time.monotonic() - if poll is not None and now >= poll: - if self.stale(): - return RELOAD - poll = now + self.poll deadline = hard if due is None else min(due, latest) if repair else min(due, latest, hard) - wake = deadline if poll is None else min(deadline, poll) + 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 diff --git a/omarchy-mac/test/mic-reload-test.sh b/omarchy-mac/test/mic-reload-test.sh index 5c802177..90b7fdad 100755 --- a/omarchy-mac/test/mic-reload-test.sh +++ b/omarchy-mac/test/mic-reload-test.sh @@ -24,8 +24,19 @@ chmod +x "$work/bin/"* # 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 -WORK=$work PATH="$work/bin:$PATH" XDG_RUNTIME_DIR="$work/run" XDG_STATE_HOME="$work/state" \ - "$mapper" --watch 2>"$work/log" & +# 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 && -f $work/run/omarchy-asahi-mic.reloads ]] && break @@ -36,7 +47,7 @@ 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 100); do +for _ in $(seq 200); do [[ -s $work/reloaded ]] && break sleep 0.1 done diff --git a/omarchy-mac/test/mic-test.sh b/omarchy-mac/test/mic-test.sh index e426a041..c0e37e10 100644 --- a/omarchy-mac/test/mic-test.sh +++ b/omarchy-mac/test/mic-test.sh @@ -665,10 +665,35 @@ with tempfile.TemporaryDirectory() as temporary: 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.0, (results, looks) + 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 = [] @@ -688,37 +713,45 @@ with tempfile.TemporaryDirectory() as temporary: 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 (or -# its lock is a minute old). A missing or unrunnable file is never run. +# 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 = m.Program(path, lock=lock) + 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 = m.Program(path, lock=lock) + program = watched() put('newer'); lock.touch() - assert not program.replaced() and not program.replaced(), 'not while pacman holds its lock' - lock.unlink() - assert program.replaced(), 'once the transaction ends' - program = m.Program(path, lock=lock, patience=0.0) - put('stale lock'); lock.touch() - assert not program.replaced() and program.replaced(), 'a lock pacman left behind delays the reload only so long' + 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 = m.Program(path, lock=lock) + 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' - with mock.patch.object(m.os, 'execv', side_effect=OSError('Exec format error')): - program = m.Program(path, lock=lock); put('broken') + 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 is not retried until it changes again' + 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. From 8db7207708443db76bd6dd316ff5e4af9432fc3a Mon Sep 17 00:00:00 2001 From: Marcelo Alcantara Date: Mon, 12 Oct 2026 20:02:01 +1000 Subject: [PATCH 6/7] Bound the upgrade hook's read of the user's PID record The record lives in the user's runtime directory, so root reads at most a few bytes of it under a timeout, and the user lookup is bounded too. --- omarchy-mac/lib/asahi-mic-restart | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/omarchy-mac/lib/asahi-mic-restart b/omarchy-mac/lib/asahi-mic-restart index 9647e524..989579d2 100755 --- a/omarchy-mac/lib/asahi-mic-restart +++ b/omarchy-mac/lib/asahi-mic-restart @@ -16,11 +16,12 @@ restart_old_mappers() { for runtime in "$root"/run/user/*; do uid=${runtime##*/} [[ $uid =~ ^[0-9]+$ && -S $runtime/systemd/private ]] || continue - user=$(id -nu "$uid" 2>/dev/null) || continue + user=$(timeout 5 id -nu "$uid" 2>/dev/null) || continue pid=$(timeout 10 systemctl --user --machine="$user@" show --property=MainPID --value "$unit" 2>/dev/null) || continue [[ $pid =~ ^[0-9]+$ ]] && (( pid > 0 )) || continue marker=$runtime/omarchy-asahi-mic.reloads - if [[ -f $marker && ! -L $marker && $(<"$marker") == "$pid" ]]; then + # The record is the user's file: read a few bytes, and never wait on it. + if [[ -f $marker && ! -L $marker && $(timeout 2 head -c 16 -- "$marker" 2>/dev/null) == "$pid" ]]; then continue fi echo "Restarting the microphone mapper of $user" From e01ca1036af3cfc63163225d27f94a863c1c4a91 Mon Sep 17 00:00:00 2001 From: Marcelo Alcantara Date: Mon, 12 Oct 2026 22:13:26 +1000 Subject: [PATCH 7/7] Drop the upgrade hook for mappers that cannot reload themselves Only lab Macs run 0.1.3, and their mapper switches to the self-reloading one at the next login. Keeping a root hook that restarts users' services for one transition isn't worth the precedent. --- omarchy-mac/README.md | 2 +- omarchy-mac/bin/omarchy-audio-asahi-mic-map | 11 +--- omarchy-mac/lib/asahi-mic-restart | 36 ----------- .../hooks/90-omarchy-mac-asahi-mic.hook | 9 --- omarchy-mac/test/mic-reload-test.sh | 62 +------------------ 5 files changed, 4 insertions(+), 116 deletions(-) delete mode 100755 omarchy-mac/lib/asahi-mic-restart delete mode 100644 omarchy-mac/share/libalpm/hooks/90-omarchy-mac-asahi-mic.hook diff --git a/omarchy-mac/README.md b/omarchy-mac/README.md index 5acb877d..8d2b4093 100644 --- a/omarchy-mac/README.md +++ b/omarchy-mac/README.md @@ -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), 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. Mappers from 0.1.3 and earlier cannot, so a pacman hook restarts, through each user's manager, every running mapper that has not recorded its PID in `omarchy-asahi-mic.reloads` under the user's runtime directory. 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. +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 b89dc97c..20f58f6d 100755 --- a/omarchy-mac/bin/omarchy-audio-asahi-mic-map +++ b/omarchy-mac/bin/omarchy-audio-asahi-mic-map @@ -53,11 +53,9 @@ 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, under the -# same PID, which it records so the upgrade hook leaves it alone. +# restarts no user service: the watcher runs the new file itself. PACMAN_LOCK = Path('/var/lib/pacman/db.lck') RELOAD = 'reload' -RELOAD_MARKER = 'omarchy-asahi-mic.reloads' class Deferred(Exception): @@ -923,12 +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)) - program = Program(os.path.abspath(sys.argv[0])) - try: - (runtime / RELOAD_MARKER).write_text(str(os.getpid())) - except OSError as error: - print('Could not record the microphone mapper: ' + str(error), file=sys.stderr, flush=True) - supervise(operation, program=program) + supervise(operation, program=Program(os.path.abspath(sys.argv[0]))) else: try: operation() diff --git a/omarchy-mac/lib/asahi-mic-restart b/omarchy-mac/lib/asahi-mic-restart deleted file mode 100755 index 989579d2..00000000 --- a/omarchy-mac/lib/asahi-mic-restart +++ /dev/null @@ -1,36 +0,0 @@ -#!/bin/bash -# After an upgrade replaces the microphone mapper, restart each user's running -# mapper that predates self-reload (0.1.3 and earlier); newer ones record their -# PID and run the new file themselves. Never fails the transaction. - -# Unprivileged tests stage the package under a fixture root; root never does. -if (( EUID == 0 )); then - root="" -else - root=${OMARCHY_MAC_ROOT:-} -fi -unit=omarchy-asahi-mic.service - -restart_old_mappers() { - local runtime uid user pid marker - for runtime in "$root"/run/user/*; do - uid=${runtime##*/} - [[ $uid =~ ^[0-9]+$ && -S $runtime/systemd/private ]] || continue - user=$(timeout 5 id -nu "$uid" 2>/dev/null) || continue - pid=$(timeout 10 systemctl --user --machine="$user@" show --property=MainPID --value "$unit" 2>/dev/null) || continue - [[ $pid =~ ^[0-9]+$ ]] && (( pid > 0 )) || continue - marker=$runtime/omarchy-asahi-mic.reloads - # The record is the user's file: read a few bytes, and never wait on it. - if [[ -f $marker && ! -L $marker && $(timeout 2 head -c 16 -- "$marker" 2>/dev/null) == "$pid" ]]; then - continue - fi - echo "Restarting the microphone mapper of $user" - timeout 10 systemctl --user --machine="$user@" --no-block try-restart "$unit" || true - done -} - -# A chroot or an unbooted root has no user sessions. -if omarchy-hw-apple-silicon 2>/dev/null && [[ -d $root/run/systemd/system ]] && ! systemd-detect-virt --chroot --quiet; then - restart_old_mappers -fi -exit 0 diff --git a/omarchy-mac/share/libalpm/hooks/90-omarchy-mac-asahi-mic.hook b/omarchy-mac/share/libalpm/hooks/90-omarchy-mac-asahi-mic.hook deleted file mode 100644 index f192873c..00000000 --- a/omarchy-mac/share/libalpm/hooks/90-omarchy-mac-asahi-mic.hook +++ /dev/null @@ -1,9 +0,0 @@ -[Trigger] -Type = Path -Operation = Upgrade -Target = usr/bin/omarchy-audio-asahi-mic-map - -[Action] -Description = Restarting microphone mappers that cannot reload themselves... -When = PostTransaction -Exec = /usr/lib/omarchy-mac/asahi-mic-restart diff --git a/omarchy-mac/test/mic-reload-test.sh b/omarchy-mac/test/mic-reload-test.sh index 90b7fdad..08302a1d 100755 --- a/omarchy-mac/test/mic-reload-test.sh +++ b/omarchy-mac/test/mic-reload-test.sh @@ -39,10 +39,9 @@ env -u PULSE_SERVER -u PIPEWIRE_REMOTE WORK="$work" PATH="$work/bin:$PATH" XDG_R python3 "$work/watch.py" "$mapper" "$work/db.lck" 2>"$work/log" & watcher=$! for _ in $(seq 100); do - [[ -s $work/subscriber && -f $work/run/omarchy-asahi-mic.reloads ]] && break + [[ -s $work/subscriber ]] && break sleep 0.1 done -[[ $(<"$work/run/omarchy-asahi-mic.reloads") == "$watcher" ]] || fail 'the watcher records its PID for the upgrade hook' subscriber=$(<"$work/subscriber") printf '#!/bin/bash\necho "$$ $*" >"$WORK/reloaded"\nexec sleep 60\n' >"$work/new" chmod +x "$work/new" @@ -55,62 +54,3 @@ done ! 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' - -# The upgrade hook restarts only mappers that cannot reload themselves: those -# without a matching PID record. Nothing happens in a chroot, an unbooted root, -# off Apple Silicon, or when a user manager does not answer, and the -# transaction never fails. -hook=$work/root/usr/share/libalpm/hooks/90-omarchy-mac-asahi-mic.hook -grep -qx 'Target = usr/bin/omarchy-audio-asahi-mic-map' "$hook" && grep -qx 'Operation = Upgrade' "$hook" && - grep -qx 'Exec = /usr/lib/omarchy-mac/asahi-mic-restart' "$hook" || fail 'the hook runs on mapper upgrades' -restart=$work/root/usr/lib/omarchy-mac/asahi-mic-restart -fixture=$work/fixture -mkdir -p "$fixture/run/systemd/system" -socket() { python3 -c 'import socket, sys; socket.socket(socket.AF_UNIX).bind(sys.argv[1])' "$1"; } -for uid in 1000 1001 1002 1003; do - mkdir -p "$fixture/run/user/$uid/systemd" - socket "$fixture/run/user/$uid/systemd/private" -done -mkdir -p "$fixture/run/user/1004" -echo 200 >"$fixture/run/user/1001/omarchy-asahi-mic.reloads" -echo 999 >"$fixture/run/user/1002/omarchy-asahi-mic.reloads" -ln -s "$fixture/run/user/1001/omarchy-asahi-mic.reloads" "$fixture/run/user/1003/omarchy-asahi-mic.reloads" -cat >"$work/bin/id" <<'STUB' -#!/bin/bash -[[ $1 == "-nu" ]] && echo "user$2" -STUB -# MainPIDs: 1000 runs an old mapper, 1001 a self-reloading one, 1002 one that -# replaced a self-reloading one, 1003 an old one beside a linked record, 1004 -# has no manager. -cat >"$work/bin/systemctl" <<'STUB' -#!/bin/bash -echo "$*" >>"$WORK/systemctl" -case $2 in - --machine=user1000@) pid=100 ;; - --machine=user1001@) pid=200 ;; - --machine=user1002@) pid=300 ;; - --machine=user1003@) pid=200 ;; - *) pid=0 ;; -esac -[[ $3 == "show" ]] && echo "$pid" -[[ -z ${SYSTEMCTL_FAILS:-} ]] -STUB -printf '#!/bin/bash\nexit "${CHROOT:-1}"\n' >"$work/bin/systemd-detect-virt" -chmod +x "$work/bin/"* -hook_run() { WORK=$work PATH="$work/bin:$PATH" OMARCHY_MAC_ROOT=$fixture "$@" "$restart" >/dev/null; } -hook_run env -restarted=$(grep try-restart "$work/systemctl" | sed 's/.*--machine=\([^ ]*\)@.*/\1/' | sort | tr '\n' ' ') -[[ $restarted == "user1000 user1002 user1003 " ]] || fail 'only mappers without a matching PID record restart' "$restarted" -grep -q -- '--user --machine=user1000@ --no-block try-restart omarchy-asahi-mic.service' "$work/systemctl" || - fail 'the restart goes through the user manager without blocking pacman' -rm "$work/systemctl" -hook_run env CHROOT=0 -[[ ! -e $work/systemctl ]] || fail 'a chroot is left alone' -hook_run env PLATFORM=aarch64 -[[ ! -e $work/systemctl ]] || fail 'other machines are left alone' -rm -r "$fixture/run/systemd/system" -hook_run env -[[ ! -e $work/systemctl ]] || fail 'an unbooted root is left alone' -mkdir -p "$fixture/run/systemd/system" -hook_run env SYSTEMCTL_FAILS=1 || fail 'a user manager that fails never fails the transaction' -pass 'the upgrade hook restarts only mappers that predate self-reload'