Skip to content

GNOME Wayland HUD: tested Dot scope prototype with live microphone levels #464

Open

Description

@subhoghoshX

A tested GNOME Wayland HUD prototype using Hex's actual Dot scope renderer

Related to #455, but this concerns the recording HUD on current Rune-based Hex,
not the old libgtk-layer-shell loader error. This is an implementation report,
not a PR or a request to publish a release.

I tested a local companion on Fedora 44, GNOME Shell 50, Wayland, against
dev-249's source commit a07f994e928219037651cc01c059d1dab174c550. The installed
Hex already dictates here, but GNOME does not offer layer-shell, so its native
HUD is unavailable. The companion displays the real Hex GPU animation through
a GNOME extension. A small opt-in patch supplies live levels from Hex's existing
capture loop. It does not record the microphone a second time.

Confirmed on the real desktop: after approving GNOME's shortcut dialog,
the patched Hex service enabled with the existing Ctrl+Space shortcut, the
helper connected to the live feed, and the user confirmed the bottom HUD changes
as they speak during normal dictation. This is the physical microphone driving
Hex's real Dot scope animation, not the synthetic Demo command.

How the GNOME host works

  1. The extension starts the renderer with Meta.WaylandClient.new_subprocess.
    It checks client.owns_window(window) before touching any window. An app ID
    alone is not an ownership check.
  2. In window-created, before initial mapping/focus, it calls
    window.hide_from_window_list() and
    window.set_type(Meta.WindowType.NOTIFICATION).
  3. Once that window maps, a plain non-reactive Clutter.Clone displays its
    window actor through Main.layoutManager.addChrome. The original actor is
    hidden, but the Wayland surface stays mapped and frames continue through the
    clone. Do not minimize the source window.
  4. The renderer uses a transparent, undecorated, inactive winit Wayland window
    with an empty pointer input region. The clone is non-reactive too. The host
    follows the Top/Bottom preference and hides the clone in overview/lock mode.
  5. Disabling the extension disconnects its signals, destroys its clone, closes
    its pipes, and kills only its own renderer. Hex keeps running.

GNOME 50 detail: the window-list/type methods are on Meta.Window, not the old
Meta.WaylandClient API used in some extension examples. Setting these after
the initial map can briefly steal focus, so the early window-created handler
matters. A custom clone picking override was unnecessary; the plain
non-reactive clone passed click-through checks.

The helper vendors Hex's unchanged dictation_indicator, dot_scope,
spring, HUD placement, WGSL shader, and GPU painter at that source commit.
It replaces the Rune overlay host, not the animation. It uses wgpu 30/Vulkan
and presents at the compositor's frame rate. There is no screenshot polling,
CPU pixel copying, JavaScript recreation of the waveform, GTK layer-shell
dependency, XWayland fallback, or input injection.

Why status polling was not enough

Stock dev-249 exposes no live microphone levels to external clients. Its status
socket can provide a recording/processing state and indicator position, but
cannot make a waveform react to speech. Demo animation is not live audio.

There is also a concrete lifecycle trap with release-microphone-while-idle:

HotkeyEvent::Start -> Dictating
RecoveringAudioInputEvent::Reopened -> Listening
first audio chunk starts the capture without another Dictating report

Polling status alone can therefore miss the beginning of an entire recording.
The initial fallback followed only new lifecycle metadata in live.ndjson,
starting at EOF rather than replaying history. It ignores transcript/text
fields and never logs them. Started/stop/cancel metadata corrects this interval.
An older job's pasted/printed event must not end a newer recording.

The feed removes both problems. While it is healthy, the helper does not poll
status or read lifecycle logs. On disconnect or a three-second heartbeat
timeout, it reconnects at bounded intervals and resumes the legacy bridge.

Minimal Hex-side addition

The source patch below adds an opt-in HEX_HUD_FEED=1, off by default. It starts
after the normal single-instance service socket is claimed. Failure logs a
warning and does not prevent dictation.

LinuxIndicator is the useful observation point. It already sees capture
state, accepted/pending work, completion, and meter(samples). The feed uses the
same RMS and absolute peak calculation as the native HUD, even when no native
overlay is available. It does not change capture boundaries, transcription,
the model, paste behavior, or the existing native overlay.

The wire format is NDJSON, one complete snapshot per line, on hud.sock next to
service.sock:

{"version":1,"pid":1234,"sequence":42,"capture":3,"recording":true,"pending":0,"terminal":"none","average":0.04,"peak":0.2,"position":"top"}
  • capture increases on each start. A reader that misses an entire stop/start
    still recognizes a new capture without restarting on every meter update.
  • Recording wins over pending jobs. An old job completing cannot finish the
    current capture. Pending stays nonzero until the accepted work finishes.
  • The helper maps the nonempty pending queue to one surrogate model job. It
    does not fabricate individual job IDs from a coalesced count.
  • The terminal field records completed/failed/cancelled, not transcript output.
    Top/Bottom/Hidden comes from the saved indicator preference.
  • These are latest-state snapshots, not a lossless event log. Very short
    intermediate phases can be coalesced. This is a prototype protocol, not a
    proposed stable API to adopt unchanged.

Privacy and backpressure

  • The directory is private and user-owned; the socket is 0600. The server
    checks SO_PEERCRED UID; the client checks directory/socket ownership,
    permissions, peer UID, and snapshot PID against peer credentials.
  • The feed contains numeric levels and HUD state only. No audio samples,
    transcript text, application context, URLs, or credentials are sent. Level
    metadata still reveals recording activity, so it is explicitly opt-in.
  • The capture loop publishes fixed-size atomics. Socket work, JSON allocation,
    and client management happen on another thread. It never queues audio or
    waits for a HUD consumer.
  • The worker polls at 20 ms, retains at most four clients, bounds accepts per
    turn, coalesces to the newest snapshot, sends one-second heartbeats, and drops
    an unfinished write after 200 ms. Shutdown removes only the same socket inode
    it created. Input is rejected; the socket cannot control Hex.
  • The helper connects/reads nonblocking, caps a line at 2 KiB and reads at most
    16 KiB per turn. It uses a single-slot graphics-thread mailbox, not an
    unbounded event queue of meter updates. Invalid versions/levels, stale data,
    and disconnects cause fallback rather than affecting capture.

Executed checks

  • The helper's 48 tests pass: 38 unchanged upstream model/animation/placement
    tests, two lifecycle-bridge tests, and eight feed server/client tests. They
    cover partial/coalesced frames, invalid fields, oversized/public sockets,
    reconnect/timeout, meters without animation restart, older jobs during a new
    recording, initial replay, private socket mode, and publisher load.
  • The actual Hex checkout builds successfully, with its original dependency
    pins. scripts/check linux_hud_feed passes formatting and both server tests
    in the full Hex test binary. No Rune or transcription dependency bump was
    needed for this isolated patch.
  • An isolated headless GNOME Shell runs on a private D-Bus session with private
    settings/data. The test-only Shell evaluation bootstrap is never installed
    on the user's desktop. It verifies the actual Vulkan renderer continues at
    about 60 FPS with the original actor hidden, zero focus changes to the HUD,
    absence from the task switcher, pointer click-through to a GTK target,
    fullscreen visibility, positions, completion, and process cleanup.
  • Feed-driven compositor checks change RMS/peak while legacy status deliberately
    contradicts the feed, check rendered dot-power changes, preserve a new
    recording through old-job completion, and test fallback/reconnect. The
    rendered dot-power sum changed from about 2.3 million to 9.1 million. The
    lifecycle fallback appeared in 54 ms in the microphone-reopen regression.
  • A separate virtual-microphone test launches patched Hex against private
    settings and a temporary PipeWire source. It does not change the default
    microphone or stop the user's Hex. Generated silence, quiet tones, and
    speech go through Hex's actual capture loop. The optimized build produced
    520 recording snapshots, a 27 ms first report, RMS 0 to 0.264, and peak 0.781.
    The feed showed submission/completion, and stop --print retained the full
    synthetic transcript ending without pasting. Three additional clients never
    read; all three were disconnected without disrupting capture or transcription.
  • Separate optimized runs kept the full transcript with no feed opt-in and with
    an unmanaged file occupying hud.sock. The latter logged the optional-feed
    failure without overwriting the file or preventing dictation.
  • Finally, the optimized local executable was activated in the actual user
    service with the existing settings and shortcut. Status showed Enabled,
    Listening, the expected granted portal shortcuts, and a live HUD snapshot
    positioned at Bottom. The user then confirmed speech-reactive animation in
    normal desktop use. This establishes the live voice response, not long-term
    reliability or every application/desktop interaction.

The virtual microphone test keeps HEX_STREAMING=0. HUD metering is independent
of transcription streaming. This preserves the full-clip workaround for the
separate dev-249 pause-truncation issue #458, fixed upstream by #459.

One test detail worth keeping: the virtual pointer's first synthetic click can
be lost when the device is created. Establish a successful positive-control
click before asserting that a click passes through the visible HUD.

Packaging without the extensions website

Hex can bundle the extension and helper. System packages can install under
/usr/share/gnome-shell/extensions/<uuid>/; per-user installers can use
~/.local/share/gnome-shell/extensions/<uuid>/. Put the renderer alongside the
extension or in a package-owned libexec directory. Keep the upstream MIT
license and pinned-source attribution with vendored renderer code.

Marketplace publication is optional. Enabling remains the user's choice, and
a newly copied extension can need logout/login before an existing Wayland
session discovers it. Updating an already-discovered extension can use
disable/copy/enable. No Shell restart, root access, or display-session logout
should be triggered automatically.

For local testing, the patched executable is separate from /usr/bin/hex and
is built with HEX_LOCAL_BUILD=1, so it cannot update itself. A managed user
service drop-in can select it and set HEX_HUD_FEED=1. Removing only that drop-in
restores the packaged executable. Existing transcription overrides stay intact.

The live-startup trap was an unanswered GNOME permission dialog

The first activation appeared stuck at Enabling… / Unregistered, with the
feed at sequence 0. We rolled it back rather than leaving dictation unavailable.
This initially looked like a local-build or portal integration failure.

A private GNOME test with the real portal services identified the missing step:
CreateSession succeeded, then BindShortcuts waited while GNOME displayed
Add Keyboard Shortcuts. Without clicking Add, Hex's request times out
after about 60 seconds with GlobalShortcuts portal did not answer BindShortcuts.
The listener has not reached LinuxIndicator::new at that point, so an idle
socket is not evidence that the meter feed has broken capture.

The virtual-microphone tests had deliberately used a nonexistent session bus
to avoid desktop dialogs. They did not cover this approval step. A synthetic
keyboard attempt in the private compositor also failed to activate Add, so it
was not counted as a successful portal-startup test.

On the next live attempt we warned the user before restarting. They approved
the GNOME dialog, the listener became ready, and the live waveform worked.
No portal daemon restart, shortcut bypass, raw input access, or wider dictation
change was needed. The tested local build is now running, while /usr/bin/hex
remains untouched and available for rollback. An installer/test procedure
should explicitly announce the dialog and allow the user time to respond.

The included linux_portal.rs diff adds debug-only-level tracing of these
startup stages. It is diagnostic logging, not a change to portal behavior.

Limits and next steps

This is tested on GNOME 50, not GNOME 51 or GNOME OS. It does not establish
GlobalShortcuts/RemoteDesktop portal compatibility there or fix GNOME's missing
clipboard-restoration protocol. Mixed-DPI/multi-monitor placement, long-running
desktop use, and every lock/fullscreen edge case remain unverified. Overview
and lock hiding are implemented, but the compositor test is not a real
lock-screen security validation. Physical-microphone responsiveness is now
user-confirmed on this machine; virtual-input and compositor results are kept
separate above. The local source fork and GNOME-version-specific extension
still need maintenance when upstream Hex or GNOME changes.

The useful upstream split seems to be a small, bounded read-only HUD feed in
Hex, the existing shared renderer/model, and optional GNOME-specific hosting
outside the capture process. A missing or disabled extension must leave
dictation alone.

The full Hex-side patch is included below so this is more than an architectural
suggestion. It is based on dev-249 for reproducibility and has not been pushed
or submitted as a PR.

The extension host and bounded client/model adapter are included too. The
renderer integration consumes the latest snapshot on its own event loop:

for event in reconcile.apply(&snapshot) {
    model.handle(event, now, false);
}

Only state/position/visibility changes go back to Shell over stdout. Meter
updates stay in the renderer process. The host expects a bundled executable
named hex-hud-renderer, and the included client uses Hex's unchanged
DictationIndicatorEvent. These are implementation pieces, not an installable
binary attached to this issue.

Tested local Hex patch against a07f994
diff --git a/docs/features/dictation.md b/docs/features/dictation.md
index 9a26e1c..595d40a 100644
--- a/docs/features/dictation.md
+++ b/docs/features/dictation.md
@@ -1114,6 +1114,23 @@ fullscreen app on a notched Mac is not yet observed.
 
 ### Dot scope
 
+Local prototype: `HEX_HUD_FEED=1` starts an owner-only, peer-UID-checked
+`hud.sock` next to the Linux service socket. `linux_hud_feed` serves versioned
+NDJSON snapshots of recording state, pending count, completion/cancellation,
+indicator position, and the existing HUD's RMS/peak levels. The listener
+publishes fixed-size atomics; networking and serialization stay on a separate
+thread, with at most four clients and a bounded slow-reader deadline. No audio,
+transcript, application context, or command input is exposed. A GNOME companion
+can therefore render the same Dot scope without layer-shell or another mic
+capture. The feed is off by default, and failure never stops dictation.
+
+Checks: `linux_hud_feed::tests` covers state, privacy fields, socket permissions,
+initial replay, a publisher load with an unread client, and shutdown cleanup.
+Contributor observation, October 30, 2026: after approving GNOME 50's
+Add Keyboard Shortcuts dialog, the local build enabled on Fedora 44 Wayland.
+The user confirmed the companion's bottom HUD reacts to physical-microphone
+speech during normal dictation. Long-term and mixed-DPI behavior is unverified.
+
 The HUD is Dot scope on every OS ([dot_scope.rs](../../src/dot_scope.rs),
 `dot_scope_fragment` in [rune_hud.wgsl](../../src/rune_hud.wgsl), drawn by
 a Rune overlay). It was the `dot-scope` experiment (#264) until 2026-10-29,
diff --git a/src/linux_app.rs b/src/linux_app.rs
index 698c080..a15b6a6 100644
--- a/src/linux_app.rs
+++ b/src/linux_app.rs
@@ -295,6 +295,11 @@ pub(crate) fn run(
     activation: Option<Activation>,
 ) -> Result<()> {
     let mut server = linux_service::Server::bind()?;
+    // The external HUD is optional: failing it must never fail dictation.
+    let _hud_feed = crate::linux_hud_feed::Feed::start().unwrap_or_else(|error| {
+        tracing::warn!(%error, "external HUD feed unavailable; dictation is unaffected");
+        None
+    });
     crate::experiments::log_launch();
     let (settings, error) = match AppSettings::load() {
         Ok(settings) => (settings, None),
diff --git a/src/linux_portal.rs b/src/linux_portal.rs
index 0e977dc..58e38ec 100644
--- a/src/linux_portal.rs
+++ b/src/linux_portal.rs
@@ -147,6 +147,7 @@ pub(crate) struct PortalBus {
 impl PortalBus {
     /// `None` when the session has no portal offering `interface`.
     pub(crate) fn open(interface: &'static str, stop: &AtomicBool) -> Result<Option<Self>> {
+        tracing::debug!(interface, "starting portal runtime");
         let runtime = tokio::runtime::Builder::new_multi_thread()
             .worker_threads(1)
             .thread_name("hex-portal")
@@ -155,11 +156,13 @@ impl PortalBus {
             .wrap_err("could not start the portal runtime")?;
         let (signals, received) = channel();
         let connected = runtime.block_on(async {
+            tracing::debug!(interface, "connecting portal session bus");
             let connection = tokio::time::timeout(CALL_TIMEOUT, Connection::session())
                 .await
                 .ok()?
                 .ok()?;
             // Subscribed before any request so a fast answer cannot be missed.
+            tracing::debug!(interface, "portal session bus connected");
             let rule = MatchRule::builder()
                 .msg_type(message::Type::Signal)
                 .path_namespace(DESKTOP_PATH)
@@ -168,6 +171,7 @@ impl PortalBus {
             let mut stream = MessageStream::for_match_rule(rule, &connection, None)
                 .await
                 .ok()?;
+            tracing::debug!(interface, "portal signal subscription installed");
             tokio::spawn(async move {
                 while let Some(Ok(message)) = stream.next().await {
                     if let Some(signal) = parse(&message)
@@ -210,6 +214,7 @@ impl PortalBus {
                 return Ok(None);
             }
         }
+        tracing::debug!(interface, version = bus.version, "portal version read");
         let written = ensure_desktop_entry()?;
         // Host apps have no sandbox identity; older portals without the
         // registry derive one from the systemd unit instead.
@@ -236,6 +241,7 @@ impl PortalBus {
         if stop.load(Ordering::Acquire) {
             return Err(eyre!("portal registration canceled"));
         }
+        tracing::debug!(interface, "portal identity registered");
         Ok(Some(bus))
     }
 
@@ -287,6 +293,7 @@ impl PortalBus {
         B: serde::Serialize + zbus::Type,
     {
         let token = self.token();
+        tracing::debug!(interface = self.interface, method, "sending portal request");
         let path = format!("{DESKTOP_PATH}/request/{}/{token}", self.sender);
         let interface = self.interface;
         self.call::<_, OwnedObjectPath>(DESKTOP_PATH, interface, method, &body(&token))
@@ -295,6 +302,7 @@ impl PortalBus {
         loop {
             match self.signals.recv_timeout(STOP_POLL) {
                 Ok(Signal::Response(answered, code, results)) if answered == path => {
+                    tracing::debug!(interface, method, code, "portal request answered");
                     return match code {
                         0 => Ok(results),
                         1 => Err(eyre!("the {interface} request {method} was dismissed")),
diff --git a/src/linux_rune_hud.rs b/src/linux_rune_hud.rs
index 6707f32..934b621 100644
--- a/src/linux_rune_hud.rs
+++ b/src/linux_rune_hud.rs
@@ -34,11 +34,12 @@ pub(crate) struct LinuxIndicator {
 
 impl LinuxIndicator {
     pub(crate) fn new(position: IndicatorPosition) -> Self {
+        crate::linux_hud_feed::configure(position);
         *POSITION.lock().unwrap_or_else(|error| error.into_inner()) = position;
         if let Some(sender) = HUD.get() {
             sender.set_position(position);
         }
-        let generation = (position != IndicatorPosition::Hidden).then(|| {
+        let generation = Some({
             let mut current = GENERATION.lock().unwrap_or_else(|error| error.into_inner());
             *current += 1;
             *current
@@ -56,10 +57,21 @@ impl LinuxIndicator {
     fn sender(&self) -> Option<&'static HudSender> {
         let generation = self.generation?;
         let current = *GENERATION.lock().unwrap_or_else(|error| error.into_inner());
-        (generation == current).then(|| HUD.get()).flatten()
+        (generation == current
+            && *POSITION.lock().unwrap_or_else(|error| error.into_inner())
+                != IndicatorPosition::Hidden)
+            .then(|| HUD.get())
+            .flatten()
     }
 
     fn send(&self, event: HudEvent) {
+        let Some(generation) = self.generation else {
+            return;
+        };
+        if *GENERATION.lock().unwrap_or_else(|error| error.into_inner()) != generation {
+            return;
+        }
+        crate::linux_hud_feed::publish(event);
         if let Some(sender) = self.sender() {
             sender.send(event);
         }
@@ -104,7 +116,11 @@ impl LinuxIndicator {
 
     /// Captured audio while recording, for the level the HUD shows.
     pub(crate) fn meter(&self, samples: &[f32]) {
-        if let Some(sender) = self.sender() {
+        if crate::linux_hud_feed::enabled() {
+            if let Some(event) = HudEvent::meter(samples) {
+                self.send(event);
+            }
+        } else if let Some(sender) = self.sender() {
             sender.meter(samples);
         }
     }
diff --git a/src/main.rs b/src/main.rs
index babb090..ec8c69c 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -85,6 +85,8 @@ mod linux_context;
 #[cfg(target_os = "linux")]
 mod linux_dictation;
 #[cfg(target_os = "linux")]
+mod linux_hud_feed;
+#[cfg(target_os = "linux")]
 mod linux_input;
 #[cfg(target_os = "linux")]
 mod linux_paste;
diff --git a/src/linux_hud_feed.rs b/src/linux_hud_feed.rs
new file mode 100644
index 0000000..06ef2d1
--- /dev/null
+++ b/src/linux_hud_feed.rs
@@ -0,0 +1,457 @@
+//! Opt-in, read-only HUD snapshots for an external compositor host.
+//!
+//! The listener publishes fixed-size atomics only. A separate thread serves
+//! complete snapshots, coalesces meters, and disconnects slow clients. No audio,
+//! transcript, application context, or command input crosses this socket.
+
+use std::fs;
+use std::io::{self, ErrorKind, Write};
+use std::os::fd::AsRawFd;
+use std::os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt};
+use std::os::unix::net::{UnixListener, UnixStream};
+use std::path::PathBuf;
+use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering};
+use std::sync::{Arc, OnceLock};
+use std::thread::{self, JoinHandle};
+use std::time::{Duration, Instant};
+
+use serde::Serialize;
+
+use crate::app_settings::IndicatorPosition;
+use crate::dictation_indicator::DictationIndicatorEvent as Event;
+
+const MAX_CLIENTS: usize = 4;
+const POLL: Duration = Duration::from_millis(20);
+const HEARTBEAT: Duration = Duration::from_secs(1);
+const WRITE_DEADLINE: Duration = Duration::from_millis(200);
+static FEED: OnceLock<Arc<State>> = OnceLock::new();
+
+#[derive(Clone, Debug, Serialize)]
+struct Snapshot {
+    version: u32,
+    pid: u32,
+    sequence: u64,
+    capture: u64,
+    recording: bool,
+    pending: u32,
+    terminal: &'static str,
+    average: f32,
+    peak: f32,
+    position: &'static str,
+}
+
+/// One writer: the current Linux listener. Readers never hold a lock the
+/// capture loop can wait on. Odd sequence numbers mark an in-progress update.
+#[derive(Default)]
+struct State {
+    sequence: AtomicU64,
+    capture: AtomicU64,
+    recording: AtomicBool,
+    pending: AtomicU32,
+    terminal: AtomicU8,
+    average: AtomicU32,
+    peak: AtomicU32,
+    position: AtomicU8,
+}
+
+impl State {
+    fn publish(&self, event: Event) {
+        self.sequence.fetch_add(1, Ordering::AcqRel);
+        std::sync::atomic::fence(Ordering::Release);
+        match event {
+            Event::Reset => {
+                self.recording.store(false, Ordering::Relaxed);
+                self.pending.store(0, Ordering::Relaxed);
+                self.terminal.store(0, Ordering::Relaxed);
+                self.average.store(0, Ordering::Relaxed);
+                self.peak.store(0, Ordering::Relaxed);
+            }
+            Event::Started => {
+                self.capture.fetch_add(1, Ordering::Relaxed);
+                self.recording.store(true, Ordering::Relaxed);
+                self.terminal.store(0, Ordering::Relaxed);
+                self.average.store(0, Ordering::Relaxed);
+                self.peak.store(0, Ordering::Relaxed);
+            }
+            Event::Submitted { .. } => {
+                self.recording.store(false, Ordering::Relaxed);
+                self.pending.fetch_add(1, Ordering::Relaxed);
+                self.terminal.store(0, Ordering::Relaxed);
+            }
+            Event::Meter { average, peak } => {
+                let clean = |value: f32| {
+                    if value.is_finite() {
+                        value.clamp(0.0, 1.0)
+                    } else {
+                        0.0
+                    }
+                };
+                self.average
+                    .store(clean(average).to_bits(), Ordering::Relaxed);
+                self.peak.store(clean(peak).to_bits(), Ordering::Relaxed);
+            }
+            Event::Cancelled | Event::Discarded => {
+                self.recording.store(false, Ordering::Relaxed);
+                self.terminal.store(3, Ordering::Relaxed);
+            }
+            Event::JobCompleted { .. } | Event::JobFailed { .. } | Event::JobCancelled { .. } => {
+                let pending = self.pending.load(Ordering::Relaxed);
+                self.pending
+                    .store(pending.saturating_sub(1), Ordering::Relaxed);
+                self.terminal.store(
+                    match event {
+                        Event::JobCompleted { .. } => 1,
+                        Event::JobFailed { .. } => 2,
+                        _ => 3,
+                    },
+                    Ordering::Relaxed,
+                );
+            }
+            Event::Failed => {
+                self.recording.store(false, Ordering::Relaxed);
+                self.terminal.store(2, Ordering::Relaxed);
+            }
+            Event::Transcribing { .. }
+            | Event::Processing { .. }
+            | Event::ConfigureDotScope(_)
+            | Event::DemoVoice => {}
+        }
+        self.sequence.fetch_add(1, Ordering::Release);
+    }
+
+    fn configure(&self, position: IndicatorPosition) {
+        self.sequence.fetch_add(1, Ordering::AcqRel);
+        std::sync::atomic::fence(Ordering::Release);
+        self.position.store(
+            match position {
+                IndicatorPosition::Top => 0,
+                IndicatorPosition::Bottom => 1,
+                IndicatorPosition::Hidden => 2,
+            },
+            Ordering::Relaxed,
+        );
+        self.recording.store(false, Ordering::Relaxed);
+        self.pending.store(0, Ordering::Relaxed);
+        self.terminal.store(0, Ordering::Relaxed);
+        self.average.store(0, Ordering::Relaxed);
+        self.peak.store(0, Ordering::Relaxed);
+        self.sequence.fetch_add(1, Ordering::Release);
+    }
+
+    fn snapshot(&self) -> Option<Snapshot> {
+        let sequence = self.sequence.load(Ordering::Acquire);
+        if sequence & 1 != 0 {
+            return None;
+        }
+        let snapshot = Snapshot {
+            version: 1,
+            pid: std::process::id(),
+            sequence,
+            capture: self.capture.load(Ordering::Relaxed),
+            recording: self.recording.load(Ordering::Relaxed),
+            pending: self.pending.load(Ordering::Relaxed),
+            terminal: match self.terminal.load(Ordering::Relaxed) {
+                1 => "completed",
+                2 => "failed",
+                3 => "cancelled",
+                _ => "none",
+            },
+            average: f32::from_bits(self.average.load(Ordering::Relaxed)),
+            peak: f32::from_bits(self.peak.load(Ordering::Relaxed)),
+            position: match self.position.load(Ordering::Relaxed) {
+                1 => "bottom",
+                2 => "hidden",
+                _ => "top",
+            },
+        };
+        // Pair with the writer's release fence if any relaxed payload read
+        // observed its next publication; then the sequence check must fail.
+        std::sync::atomic::fence(Ordering::Acquire);
+        (self.sequence.load(Ordering::Acquire) == sequence).then_some(snapshot)
+    }
+}
+
+pub(crate) fn enabled() -> bool {
+    FEED.get().is_some()
+}
+
+pub(crate) fn publish(event: Event) {
+    if let Some(state) = FEED.get() {
+        state.publish(event);
+    }
+}
+
+pub(crate) fn configure(position: IndicatorPosition) {
+    if let Some(state) = FEED.get() {
+        state.configure(position);
+    }
+}
+
+pub(crate) struct Feed {
+    stop: Arc<AtomicBool>,
+    worker: Option<JoinHandle<()>>,
+}
+
+impl Feed {
+    pub(crate) fn start() -> io::Result<Option<Self>> {
+        if std::env::var("HEX_HUD_FEED").as_deref() != Ok("1") {
+            return Ok(None);
+        }
+        let root = crate::app_paths::support_dir().map_err(io::Error::other)?;
+        let state = Arc::new(State::default());
+        let feed = Self::bind(root.join("hud.sock"), state.clone())?;
+        FEED.set(state)
+            .map_err(|_| io::Error::other("HUD feed already initialized"))?;
+        Ok(Some(feed))
+    }
+
+    fn bind(path: PathBuf, state: Arc<State>) -> io::Result<Self> {
+        // Server::bind already validates the support directory. Check it again
+        // here so this transport cannot accidentally be reused on a public path.
+        let parent = path
+            .parent()
+            .ok_or_else(|| io::Error::other("missing HUD socket directory"))?;
+        let metadata = fs::symlink_metadata(parent)?;
+        // SAFETY: geteuid has no pointer arguments or side effects.
+        let uid = unsafe { libc::geteuid() };
+        if !metadata.is_dir() || metadata.uid() != uid || metadata.mode() & 0o077 != 0 {
+            return Err(io::Error::other(
+                "HUD feed requires a private, user-owned directory",
+            ));
+        }
+        if let Ok(metadata) = fs::symlink_metadata(&path) {
+            if !metadata.file_type().is_socket() || metadata.uid() != uid {
+                return Err(io::Error::other(
+                    "refusing to replace an unmanaged HUD socket",
+                ));
+            }
+            match UnixStream::connect(&path) {
+                Ok(_) => {
+                    return Err(io::Error::new(
+                        ErrorKind::AddrInUse,
+                        "HUD socket is already live",
+                    ));
+                }
+                Err(error) if error.kind() == ErrorKind::ConnectionRefused => {
+                    fs::remove_file(&path)?
+                }
+                Err(error) => return Err(error),
+            }
+        }
+        let listener = UnixListener::bind(&path)?;
+        fs::set_permissions(&path, fs::Permissions::from_mode(0o600))?;
+        listener.set_nonblocking(true)?;
+        let metadata = fs::symlink_metadata(&path)?;
+        let identity = (metadata.dev(), metadata.ino());
+        let stop = Arc::new(AtomicBool::new(false));
+        let stopping = stop.clone();
+        let worker = thread::Builder::new()
+            .name("hud-feed".into())
+            .spawn(move || {
+                serve(listener, &state, &stopping);
+                if fs::symlink_metadata(&path).is_ok_and(|m| (m.dev(), m.ino()) == identity) {
+                    let _ = fs::remove_file(&path);
+                }
+            })?;
+        Ok(Self {
+            stop,
+            worker: Some(worker),
+        })
+    }
+}
+
+impl Drop for Feed {
+    fn drop(&mut self) {
+        self.stop.store(true, Ordering::Release);
+        if let Some(worker) = self.worker.take() {
+            let _ = worker.join();
+        }
+    }
+}
+
+fn same_user(stream: &UnixStream) -> bool {
+    // SAFETY: getsockopt receives a valid fd and correctly sized, initialized
+    // ucred storage. No client-controlled pointer is used.
+    unsafe {
+        let mut credentials: libc::ucred = std::mem::zeroed();
+        let mut length = std::mem::size_of::<libc::ucred>() as libc::socklen_t;
+        libc::getsockopt(
+            stream.as_raw_fd(),
+            libc::SOL_SOCKET,
+            libc::SO_PEERCRED,
+            (&mut credentials as *mut libc::ucred).cast(),
+            &mut length,
+        ) == 0
+            && length as usize == std::mem::size_of::<libc::ucred>()
+            && credentials.uid == libc::geteuid()
+    }
+}
+
+struct Client {
+    stream: UnixStream,
+    sequence: u64,
+    outgoing: Vec<u8>,
+    sent: usize,
+    queued_at: Instant,
+    last_message: Instant,
+}
+
+impl Client {
+    fn new(stream: UnixStream) -> Option<Self> {
+        if !same_user(&stream) || stream.set_nonblocking(true).is_err() {
+            return None;
+        }
+        let now = Instant::now();
+        Some(Self {
+            stream,
+            sequence: u64::MAX,
+            outgoing: Vec::new(),
+            sent: 0,
+            queued_at: now,
+            last_message: now,
+        })
+    }
+
+    fn refresh(&mut self, snapshot: &Snapshot) -> bool {
+        // Detect disconnected readers and reject input: this socket has no
+        // command/control plane and cannot change Hex's behavior.
+        let mut byte = 0u8;
+        // SAFETY: byte points to writable one-byte storage for this nonblocking
+        // peek. The fd remains owned by self.stream throughout the call.
+        let peek = unsafe {
+            libc::recv(
+                self.stream.as_raw_fd(),
+                (&mut byte as *mut u8).cast(),
+                1,
+                libc::MSG_PEEK | libc::MSG_DONTWAIT,
+            )
+        };
+        if peek >= 0 {
+            return false;
+        }
+        if io::Error::last_os_error().kind() != ErrorKind::WouldBlock {
+            return false;
+        }
+        if self.outgoing.is_empty()
+            && (self.sequence != snapshot.sequence || self.last_message.elapsed() >= HEARTBEAT)
+        {
+            self.outgoing = match serde_json::to_vec(snapshot) {
+                Ok(bytes) => bytes,
+                Err(_) => return false,
+            };
+            self.outgoing.push(b'\n');
+            self.sent = 0;
+            self.queued_at = Instant::now();
+            self.sequence = snapshot.sequence;
+        }
+        if self.outgoing.is_empty() {
+            return true;
+        }
+        if self.queued_at.elapsed() > WRITE_DEADLINE {
+            return false;
+        }
+        match self.stream.write(&self.outgoing[self.sent..]) {
+            Ok(0) => false,
+            Ok(count) => {
+                self.sent += count;
+                if self.sent == self.outgoing.len() {
+                    self.outgoing.clear();
+                    self.last_message = Instant::now();
+                }
+                true
+            }
+            Err(error) => matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::Interrupted),
+        }
+    }
+}
+
+fn serve(listener: UnixListener, state: &State, stop: &AtomicBool) {
+    let mut clients = Vec::<Client>::new();
+    while !stop.load(Ordering::Acquire) {
+        // Bound accepts as well as retained clients, so a connection flood
+        // cannot prevent existing readers from receiving state updates.
+        for _ in 0..8 {
+            match listener.accept() {
+                Ok((stream, _)) if clients.len() < MAX_CLIENTS => {
+                    if let Some(client) = Client::new(stream) {
+                        clients.push(client);
+                    }
+                }
+                Ok(_) => {}
+                Err(_) => break,
+            }
+        }
+        if let Some(snapshot) = state.snapshot() {
+            clients.retain_mut(|client| client.refresh(&snapshot));
+        }
+        thread::sleep(POLL);
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use std::io::{BufRead, BufReader};
+
+    #[test]
+    fn snapshots_keep_current_capture_and_only_level_metadata() {
+        let state = State::default();
+        state.publish(Event::Submitted { job_id: 1 });
+        state.publish(Event::Started);
+        state.publish(Event::Meter {
+            average: 0.04,
+            peak: 0.2,
+        });
+        state.publish(Event::JobCompleted { job_id: 1 });
+        let snapshot = state.snapshot().unwrap();
+        assert!(
+            snapshot.recording,
+            "older completion must not end a newer capture"
+        );
+        assert_eq!(snapshot.pending, 0);
+        assert_eq!(snapshot.average, 0.04);
+        let text = serde_json::to_string(&snapshot).unwrap();
+        for forbidden in ["audio", "transcript", "text", "application", "url"] {
+            assert!(!text.contains(forbidden));
+        }
+        state.publish(Event::Meter {
+            average: f32::NAN,
+            peak: f32::INFINITY,
+        });
+        assert_eq!(state.snapshot().unwrap().average, 0.0);
+    }
+
+    #[test]
+    fn private_feed_replays_latest_state_without_blocking_publisher() {
+        let directory =
+            std::env::temp_dir().join(format!("hex-hud-feed-test-{}", std::process::id()));
+        fs::create_dir_all(&directory).unwrap();
+        fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)).unwrap();
+        let path = directory.join("hud.sock");
+        let state = Arc::new(State::default());
+        state.publish(Event::Started);
+        let feed = Feed::bind(path.clone(), state.clone()).unwrap();
+        assert_eq!(fs::metadata(&path).unwrap().mode() & 0o777, 0o600);
+        let stream = UnixStream::connect(&path).unwrap();
+        stream
+            .set_read_timeout(Some(Duration::from_secs(2)))
+            .unwrap();
+        let mut reader = BufReader::new(stream);
+        let mut line = String::new();
+        reader.read_line(&mut line).unwrap();
+        let value: serde_json::Value = serde_json::from_str(&line).unwrap();
+        assert_eq!(value["recording"], true);
+        let started = Instant::now();
+        for _ in 0..100_000 {
+            state.publish(Event::Meter {
+                average: 0.1,
+                peak: 0.3,
+            });
+        }
+        assert!(started.elapsed() < Duration::from_secs(2));
+        drop(reader);
+        drop(feed);
+        assert!(!path.exists());
+        fs::remove_dir(directory).unwrap();
+    }
+}
GNOME 50 extension host
import Clutter from 'gi://Clutter';
import Gio from 'gi://Gio';
import GLib from 'gi://GLib';
import Meta from 'gi://Meta';
import * as Main from 'resource:///org/gnome/shell/ui/main.js';
import {Extension} from 'resource:///org/gnome/shell/extensions/extension.js';

const IFACE = `<node><interface name="local.HexHud.Prototype">
  <method name="Show"><arg type="s" direction="in" name="phase"/></method>
  <method name="Hide"/>
  <method name="Demo"/>
  <method name="Inspect"><arg type="s" direction="out" name="state"/></method>
</interface></node>`;

export default class HexHudPrototype extends Extension {
    enable() {
        this._signals = [];
        this._clone = null;
        this._window = null;
        this._phase = 'idle';
        this._rendererVisible = false;
        this._position = 'top';
        this._disabled = false;
        this._client = null;
        this._child = null;
        this._childExited = false;
        this._cancellable = new Gio.Cancellable();
        this._output = null;
        this._focusBefore = global.display.focus_window;
        this._signals.push([global.display,
            global.display.connect('window-created', (_display, window) => {
                if (this._owns(window)) {
                    // GNOME 50 moved these operations from WaylandClient to
                    // Meta.Window. Apply before initial focus/placement.
                    window.hide_from_window_list();
                    window.set_type(Meta.WindowType.NOTIFICATION);
                }
            })]);
        this._signals.push([global.window_manager,
            global.window_manager.connect('map', (_manager, actor) => this._mapped(actor))]);
        this._signals.push([Main.layoutManager,
            Main.layoutManager.connect('monitors-changed', () => this._place())]);
        this._signals.push([Main.sessionMode,
            Main.sessionMode.connect('updated', () => this._visibility())]);
        this._signals.push([Main.overview,
            Main.overview.connect('showing', () => this._visibility())]);
        this._signals.push([Main.overview,
            Main.overview.connect('hidden', () => this._visibility())]);
        this._dbus = Gio.DBusExportedObject.wrapJSObject(IFACE, this);
        this._dbus.export(Gio.DBus.session, '/local/HexHud/Prototype');
        try {
            const launcher = new Gio.SubprocessLauncher({
                flags: Gio.SubprocessFlags.STDIN_PIPE | Gio.SubprocessFlags.STDOUT_PIPE,
            });
            launcher.setenv('GDK_BACKEND', 'wayland', true);
            launcher.unsetenv('XDG_ACTIVATION_TOKEN');
            launcher.unsetenv('DESKTOP_STARTUP_ID');
            const binary = `${this.path}/hex-hud-renderer`;
            if (!GLib.file_test(binary, GLib.FileTest.IS_EXECUTABLE))
                throw new Error('HUD renderer is missing; run tools/install.py after building it');
            this._native = true;
            this._client = Meta.WaylandClient.new_subprocess(global.context,
                launcher, [binary]);
            launcher.close();
            this._child = this._client.get_subprocess();
            this._output = new Gio.DataOutputStream({
                base_stream: this._child.get_stdin_pipe(),
            });
            this._input = new Gio.DataInputStream({base_stream: this._child.get_stdout_pipe()});
            this._readRenderer();
            this._child.wait_async(null, (_child, result) => {
                try {
                    _child.wait_finish(result);
                } catch (error) {
                    console.warn(`Hex HUD renderer wait: ${error.message}`);
                }
                this._childExited = true;
                if (!this._disabled)
                    this._dropSurface();
            });
            console.log('Hex HUD prototype renderer launched');
        } catch (error) {
            console.error(`Hex HUD prototype: ${error.stack ?? error}`);
        }
    }

    _readRenderer() {
        if (this._disabled || !this._input)
            return;
        this._input.read_line_async(GLib.PRIORITY_DEFAULT, this._cancellable, (input, result) => {
            if (this._disabled)
                return;
            try {
                const [line] = input.read_line_finish_utf8(result);
                if (line === null)
                    return;
                if (line.length <= 4096) {
                    const state = JSON.parse(line);
                    this._phase = state.phase ?? 'idle';
                    this._rendererVisible = !!state.visible;
                    if (state.position === 'top' || state.position === 'bottom')
                        this._position = state.position;
                    this._place();
                    this._visibility();
                }
            } catch (error) {
                console.warn(`Hex HUD renderer state: ${error.message}`);
            }
            this._readRenderer();
        });
    }

    _owns(window) {
        return this._client && window.get_client_type() === Meta.WindowClientType.WAYLAND
            && this._client.owns_window(window);
    }

    _mapped(actor) {
        const window = actor.meta_window;
        if (this._window || !this._owns(window))
            return;
        this._clone = new Clutter.Clone({source: actor, reactive: false,
            width: this._native ? 304 : 420, height: this._native ? 80 : 90});
        this._clone.connect('destroy', () => { this._clone = null; });
        this._window = window;
        this._actor = actor;
        Main.layoutManager.addChrome(this._clone, {
            affectsStruts: false, trackFullscreen: false,
        });
        this._signals.push([actor, actor.connect('destroy', () => {
            this._signals = this._signals.filter(([object]) => object !== actor);
            this._dropSurface();
        })]);
        this._signals.push([actor, actor.connect('notify::visible', () => {
            if (this._clone && actor.visible)
                actor.hide();
        })]);
        this._place();
        this._visibility();
        window.hide_from_window_list();
        // The source remains a mapped Wayland surface, but its original
        // compositor actor is hidden. Clutter paints it through the clone.
        actor.hide();
        console.log('Hex HUD prototype attached a native Wayland actor');
    }

    _place() {
        if (!this._clone)
            return;
        const monitor = Main.layoutManager.primaryMonitor;
        if (!monitor)
            return;
        const area = global.workspace_manager.get_active_workspace()
            .get_work_area_for_monitor(monitor.index);
        const y = this._position === 'bottom'
            ? area.y + area.height - this._clone.height - 24 : area.y + 12;
        this._clone.set_position(Math.round(monitor.x + (monitor.width - this._clone.width) / 2), y);
    }

    _visibility() {
        if (this._clone)
            this._clone.visible = this._rendererVisible && !Main.sessionMode.isLocked
                && !Main.overview.visible;
    }

    Show(phase) {
        if (!['recording', 'transcribing', 'done', 'error'].includes(phase))
            throw new Error('Unknown HUD phase');
        this._phase = phase;
        this._rendererVisible = true;
        if (this._output) {
            try {
                this._output.put_string(`${JSON.stringify({phase})}\n`, null);
            } catch (error) {
                console.warn(`Hex HUD renderer write: ${error.message}`);
            }
        }
        this._visibility();
    }

    Hide() {
        this._phase = 'idle';
        this._rendererVisible = false;
        if (this._output) {
            try {
                this._output.put_string('{"phase":"idle"}\n', null);
            } catch (_) {
            }
        }
        this._visibility();
    }

    Demo() {
        this._phase = 'recording';
        this._rendererVisible = true;
        this._output?.put_string('{"phase":"recording","demo":true}\n', null);
        this._visibility();
    }

    Inspect() {
        return JSON.stringify({attached: !!this._window, phase: this._phase,
            cloneVisible: this._clone?.visible ?? false,
            minimized: this._window?.minimized ?? null,
            sourceMapped: this._actor?.mapped ?? false,
            sourceVisible: this._actor?.visible ?? false,
            skipTaskbar: this._window?.is_skip_taskbar() ?? false,
            nativeRenderer: !!this._native,
            position: this._position,
            bounds: this._clone ? {x: this._clone.x, y: this._clone.y,
                width: this._clone.width, height: this._clone.height} : null,
            focusIsHud: !!this._window && global.display.focus_window === this._window,
            focusTitle: global.display.focus_window?.title ?? null,
            clientPid: this._client?.get_pid() ?? null});
    }

    _dropSurface() {
        if (this._clone) {
            const clone = this._clone;
            this._clone = null;
            Main.layoutManager.removeChrome(clone);
            clone.destroy();
        }
        this._window = null;
        this._actor = null;
        this._rendererVisible = false;
    }

    disable() {
        this._disabled = true;
        this._cancellable?.cancel();
        this._dbus?.unexport();
        this._dbus = null;
        for (const [object, id] of this._signals ?? []) {
            try {
                object.disconnect(id);
            } catch (_) {
                // A source actor may already have been destroyed.
            }
        }
        this._signals = [];
        this._dropSurface();
        try {
            this._output?.close(null);
        } catch (_) {
        }
        this._output = null;
        this._input = null;
        if (this._child && !this._childExited)
            this._child.force_exit();
        this._child = null;
        this._client = null;
    }
}
Bounded feed client and model reconciliation
//! Bounded, read-only client for the opt-in Hex HUD snapshot socket.
use std::{
    fs, io::{self, Read},
    os::{fd::{AsRawFd, FromRawFd}, unix::{ffi::OsStrExt, fs::{FileTypeExt, MetadataExt}, net::UnixStream}},
    path::PathBuf,
    time::{Duration, Instant},
};
use serde::Deserialize;
use crate::dictation_indicator::DictationIndicatorEvent as Event;

const MAX_LINE: usize = 2048;
const STALE: Duration = Duration::from_secs(3);

#[derive(Clone, Debug, Deserialize)]
pub struct Snapshot {
    pub version: u32,
    pub pid: u32,
    pub sequence: u64,
    pub capture: u64,
    pub recording: bool,
    pub pending: u32,
    pub terminal: Terminal,
    pub average: f32,
    pub peak: f32,
    pub position: Position,
}

#[derive(Clone, Copy, Debug, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum Terminal { None, Completed, Failed, Cancelled }

#[derive(Clone, Copy, Debug, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum Position { Top, Bottom, Hidden }

impl Position {
    pub fn name(self) -> &'static str {
        match self { Self::Top => "top", Self::Bottom => "bottom", Self::Hidden => "hidden" }
    }
}

impl Snapshot {
    fn valid(&self, pid: u32) -> bool {
        self.version == 1 && self.pid == pid && self.sequence & 1 == 0
            && self.pending <= 1024
            && self.average.is_finite() && (0.0..=1.0).contains(&self.average)
            && self.peak.is_finite() && (0.0..=1.0).contains(&self.peak)
    }

    pub fn phase(&self) -> &'static str {
        if self.position == Position::Hidden { "idle" }
        else if self.recording { "recording" }
        else if self.pending > 0 { "transcribing" }
        else { "idle" }
    }
}

pub struct Reader {
    path: PathBuf,
    socket: Option<UnixStream>,
    pid: u32,
    pending: Vec<u8>,
    latest: Option<Snapshot>,
    last_message: Instant,
    next_connect: Instant,
}

impl Reader {
    pub fn new(path: PathBuf) -> Self {
        let now = Instant::now();
        Self { path, socket: None, pid: 0, pending: Vec::new(), latest: None,
            last_message: now, next_connect: now }
    }

    pub fn healthy(&self) -> bool { self.socket.is_some() && self.latest.is_some() }

    fn disconnect(&mut self) {
        self.socket = None;
        self.latest = None;
        self.pending.clear();
        self.next_connect = Instant::now() + Duration::from_secs(1);
    }

    fn connect(&mut self) -> io::Result<()> {
        let parent = fs::symlink_metadata(self.path.parent().ok_or_else(|| io::Error::other("no parent"))?)?;
        let meta = fs::symlink_metadata(&self.path)?;
        // SAFETY: geteuid takes no arguments.
        let uid = unsafe { libc::geteuid() };
        if !parent.is_dir() || parent.uid() != uid || parent.mode() & 0o077 != 0
            || !meta.file_type().is_socket() || meta.uid() != uid || meta.mode() & 0o077 != 0 {
            return Err(io::Error::other("HUD socket is not private and user-owned"));
        }
        let bytes = self.path.as_os_str().as_bytes();
        // SAFETY: sockaddr_un is plain storage; every field is initialized.
        let mut address: libc::sockaddr_un = unsafe { std::mem::zeroed() };
        if bytes.len() >= address.sun_path.len() { return Err(io::Error::other("HUD path too long")); }
        address.sun_family = libc::AF_UNIX as libc::sa_family_t;
        for (dest, source) in address.sun_path.iter_mut().zip(bytes) { *dest = *source as libc::c_char; }
        // Nonblocking from creation: even a full listen backlog cannot hang
        // fallback status polling. A pending connect is simply retried later.
        // SAFETY: socket has no pointer arguments, and a successful fd is owned below.
        let fd = unsafe { libc::socket(libc::AF_UNIX, libc::SOCK_STREAM | libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC, 0) };
        if fd < 0 { return Err(io::Error::last_os_error()); }
        // SAFETY: fd is a newly created, exclusively owned stream socket.
        let socket = unsafe { UnixStream::from_raw_fd(fd) };
        // SAFETY: initialized sockaddr_un with a NUL-terminated pathname.
        if unsafe { libc::connect(fd, (&address as *const libc::sockaddr_un).cast(),
            std::mem::size_of_val(&address) as libc::socklen_t) } != 0 {
            return Err(io::Error::last_os_error());
        }
        // SAFETY: getsockopt writes to sized ucred storage on our live fd.
        let mut peer: libc::ucred = unsafe { std::mem::zeroed() };
        let mut len = std::mem::size_of_val(&peer) as libc::socklen_t;
        if unsafe { libc::getsockopt(socket.as_raw_fd(), libc::SOL_SOCKET, libc::SO_PEERCRED,
            (&mut peer as *mut libc::ucred).cast(), &mut len) } != 0
            || len as usize != std::mem::size_of_val(&peer) || peer.uid != uid || peer.pid <= 0 {
            return Err(io::Error::other("HUD peer is not this user"));
        }
        self.pid = peer.pid as u32;
        self.socket = Some(socket);
        self.last_message = Instant::now();
        Ok(())
    }

    /// At most 16 KiB per turn, with a 2 KiB line cap. Return only the newest
    /// complete snapshot, so a fast publisher cannot build an event-loop queue.
    pub fn poll(&mut self) -> Option<Snapshot> {
        if self.socket.is_none() {
            if Instant::now() < self.next_connect { return None; }
            if self.connect().is_err() { self.disconnect(); return None; }
        }
        let mut newest = None;
        let mut bytes = [0u8; 2048];
        for _ in 0..8 {
            match self.socket.as_mut().unwrap().read(&mut bytes) {
                Ok(0) => { self.disconnect(); return None; }
                Ok(count) => {
                    for byte in &bytes[..count] {
                        if *byte == b'\n' {
                            let parsed = serde_json::from_slice::<Snapshot>(&self.pending);
                            self.pending.clear();
                            let Ok(snapshot) = parsed else { self.disconnect(); return None; };
                            if !snapshot.valid(self.pid)
                                || self.latest.as_ref().is_some_and(|old| snapshot.sequence < old.sequence) {
                                self.disconnect(); return None;
                            }
                            self.last_message = Instant::now();
                            self.latest = Some(snapshot.clone());
                            newest = Some(snapshot);
                        } else {
                            if self.pending.len() >= MAX_LINE { self.disconnect(); return None; }
                            self.pending.push(*byte);
                        }
                    }
                }
                Err(e) if e.kind() == io::ErrorKind::WouldBlock => break,
                Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
                Err(_) => { self.disconnect(); return None; }
            }
        }
        if self.last_message.elapsed() > STALE { self.disconnect(); return None; }
        newest
    }
}

/// The model needs only one surrogate job for the nonempty pending queue.
/// This preserves recording priority without inventing a list of job IDs from
/// a coalesced count. Meters never send Started or restart the simulation.
#[derive(Default)]
pub struct Reconcile { previous: Option<Snapshot> }

impl Reconcile {
    pub fn reset(&mut self) { self.previous = None; }

    pub fn apply(&mut self, snapshot: &Snapshot) -> Vec<Event> {
        let mut events = Vec::new();
        let old = self.previous.as_ref().filter(|p| p.pid == snapshot.pid);
        let fresh = old.is_none();
        if fresh { events.push(Event::Reset); }
        let old_recording = old.is_some_and(|p| p.recording);
        let old_pending = old.is_some_and(|p| p.pending > 0);
        let new_pending = snapshot.pending > 0;
        let new_capture = snapshot.recording
            && (!old_recording || old.is_none_or(|p| p.capture != snapshot.capture));
        let was_hidden = old.is_some_and(|p| p.position == Position::Hidden);
        if snapshot.position == Position::Hidden {
            if fresh || !was_hidden { events.push(Event::Reset); }
        } else {
            // Rebuild when emerging from Hidden, whose model was reset.
            let old_pending = old_pending && !was_hidden;
            let old_recording = old_recording && !was_hidden;
            if new_pending && !old_pending { events.push(Event::Submitted { job_id: 1 }); }
            if !new_pending && old_pending {
                events.push(match snapshot.terminal {
                    Terminal::Completed => Event::JobCompleted { job_id: 1 },
                    Terminal::Failed => Event::JobFailed { job_id: 1 },
                    _ => Event::JobCancelled { job_id: 1 },
                });
            }
            if snapshot.recording && (new_capture || was_hidden || (!old_pending && new_pending)) {
                events.push(Event::Started);
            } else if !snapshot.recording && old_recording {
                events.push(if snapshot.terminal == Terminal::Failed { Event::Failed } else { Event::Cancelled });
            }
            if snapshot.recording {
                events.push(Event::Meter { average: snapshot.average, peak: snapshot.peak });
            }
        }
        self.previous = Some(snapshot.clone());
        events
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    fn snapshot() -> Snapshot {
        Snapshot { version: 1, pid: 123, sequence: 2, capture: 1, recording: true,
            pending: 0, terminal: Terminal::None, average: 0.04, peak: 0.2, position: Position::Top }
    }

    #[test]
    fn meters_do_not_restart_the_capture() {
        let mut reconcile = Reconcile::default();
        let mut s = snapshot();
        assert!(reconcile.apply(&s).iter().any(|e| matches!(e, Event::Started)));
        for n in 0..100 {
            s.sequence += 2;
            s.average = n as f32 / 100.;
            assert!(matches!(reconcile.apply(&s).as_slice(), [Event::Meter { .. }]));
        }
        s.capture += 1;
        assert!(reconcile.apply(&s).iter().any(|e| matches!(e, Event::Started)));
    }

    #[test]
    fn old_jobs_cannot_end_a_new_recording() {
        let mut reconcile = Reconcile::default();
        let mut s = snapshot();
        s.pending = 2;
        reconcile.apply(&s);
        s.pending = 1;
        assert!(matches!(reconcile.apply(&s).as_slice(), [Event::Meter { .. }]));
        s.pending = 0;
        s.terminal = Terminal::Completed;
        let events = reconcile.apply(&s);
        assert!(matches!(events.as_slice(), [Event::JobCompleted { .. }, Event::Meter { .. }]));
    }

    #[test]
    fn hidden_then_visible_restores_state_and_reconnect_resets() {
        let mut reconcile = Reconcile::default();
        let mut s = snapshot();
        reconcile.apply(&s);
        s.position = Position::Hidden;
        assert!(matches!(reconcile.apply(&s).as_slice(), [Event::Reset]));
        s.position = Position::Bottom;
        assert!(matches!(reconcile.apply(&s).as_slice(), [Event::Started, Event::Meter { .. }]));
        reconcile.reset();
        assert!(matches!(reconcile.apply(&s).as_slice(), [Event::Reset, Event::Started, Event::Meter { .. }]));
    }

    #[test]
    fn invalid_version_pid_and_meters_are_rejected() {
        let mut s = snapshot();
        assert!(s.valid(123));
        assert!(!s.valid(124));
        s.version = 2; assert!(!s.valid(123));
        s.version = 1; s.average = f32::NAN; assert!(!s.valid(123));
        s.average = 0.; s.sequence = 3; assert!(!s.valid(123));
    }

    struct Fixture { path: PathBuf, listener: std::os::unix::net::UnixListener }
    impl Fixture {
        fn new() -> Self {
            use std::os::unix::fs::PermissionsExt;
            static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
            let dir = std::env::temp_dir().join(format!("hud-client-{}-{}", std::process::id(),
                NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));
            fs::create_dir(&dir).unwrap();
            fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).unwrap();
            let path = dir.join("hud.sock");
            let listener = std::os::unix::net::UnixListener::bind(&path).unwrap();
            fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap();
            Self { path, listener }
        }
        fn frame(&self, sequence: u64, average: f32) -> String {
            format!("{}\n", serde_json::json!({"version":1,"pid":std::process::id(),
                "sequence":sequence,"capture":1,"recording":true,"pending":0,
                "terminal":"none","position":"top","average":average,"peak":0.5}))
        }
    }
    impl Drop for Fixture {
        fn drop(&mut self) {
            let _ = fs::remove_file(&self.path);
            let _ = fs::remove_dir(self.path.parent().unwrap());
        }
    }

    #[test]
    fn reader_handles_partial_coalesced_frames_and_reconnects() {
        use std::io::Write;
        let fixture = Fixture::new();
        let mut reader = Reader::new(fixture.path.clone());
        assert!(reader.poll().is_none());
        let (mut server, _) = fixture.listener.accept().unwrap();
        let frame = fixture.frame(2, 0.1);
        server.write_all(&frame.as_bytes()[..20]).unwrap();
        assert!(reader.poll().is_none());
        server.write_all(&frame.as_bytes()[20..]).unwrap();
        assert_eq!(reader.poll().unwrap().average, 0.1);
        server.write_all(format!("{}{}", fixture.frame(4, 0.2), fixture.frame(6, 0.3)).as_bytes()).unwrap();
        assert_eq!(reader.poll().unwrap().average, 0.3);
        assert!(reader.healthy());
        drop(server);
        assert!(reader.poll().is_none());
        assert!(!reader.healthy());
        reader.next_connect = Instant::now();
        assert!(reader.poll().is_none());
        let (mut server, _) = fixture.listener.accept().unwrap();
        server.write_all(fixture.frame(2, 0.4).as_bytes()).unwrap();
        assert_eq!(reader.poll().unwrap().average, 0.4);
        reader.last_message = Instant::now() - Duration::from_secs(4);
        assert!(reader.poll().is_none());
        assert!(!reader.healthy());
    }

    #[test]
    fn reader_rejects_public_sockets_and_oversized_frames() {
        use std::{io::Write, os::unix::fs::PermissionsExt};
        let fixture = Fixture::new();
        let mut reader = Reader::new(fixture.path.clone());
        fs::set_permissions(&fixture.path, fs::Permissions::from_mode(0o666)).unwrap();
        assert!(reader.connect().is_err());
        fs::set_permissions(&fixture.path, fs::Permissions::from_mode(0o600)).unwrap();
        reader.connect().unwrap();
        let (mut server, _) = fixture.listener.accept().unwrap();
        server.write_all(&vec![b'x'; MAX_LINE + 1]).unwrap();
        assert!(reader.poll().is_none());
        assert!(!reader.healthy());
        assert!(reader.pending.is_empty());
    }
}

Activity

  1. thdxr commented on Oct 30, 2026

    @thdxr
    Member

    Thanks for the suggestion!

    The prototype is a useful proof that the Dot scope can work on GNOME Wayland, and Hex already has the pieces it would hook into. The listener's indicator already sends recording state and microphone samples to the in-process HUD, and Hex already says when layer-shell is missing. Today the socket carries only Activate, the shortcut commands, Status and Quit, so external clients can't see live levels.

    Things we need to work out

    • Hex's Wayland support avoids code for one particular desktop, and a GNOME extension plus a helper renderer would be the first exception.
    • A new streaming feed would widen the deliberately small, bounded Linux socket protocol and would have to stay stable across updates.
    • Building, versioning and packaging a GNOME Shell extension and a second renderer adds release and support work on every GNOME Shell version.

    Questions for you

    • Could the extension draw from the existing state plus a simple level number, or does it need the raw RMS and peak stream to match the Dot scope?
    • Would you keep the extension and renderer outside Hex and have Hex ship only the opt-in feed?
    • Did the feed make any difference to dictation timing or CPU use while recording on your Fedora 44 setup?

    We'll take a closer look.

    — from 𝕺𝖕𝖊𝖓𝕮𝖔𝖉𝖊

  2. added
    needs-design
    on Oct 30, 2026
  3. subhoghoshX commented on Oct 30, 2026

    @subhoghoshX
    Author

    Thanks for reviewing this. Here are the clarifications, including a local performance comparison:

    1. One level value is sufficient

    The current Dot scope uses only the RMS average value from Meter; it ignores peak. The prototype forwards both for parity, but peak could be dropped. No microphone samples or waveform data need to leave Hex.

    Authoritative recording/pending state plus one RMS value is enough. The state matters because dev-249's status can incorrectly return to Listening while capture is starting. The helper was chosen to reuse Hex's exact Rust animation and WGSL shader; drawing directly in Shell would require adapting that rendering code, which I haven't tested.

    2. The GNOME companion can stay outside Hex

    Keeping only an opt-in, desktop-independent feed in Hex seems a reasonable split. The extension and renderer could be distributed separately, keeping GNOME-version support outside Hex's release process.

    The prototype already uses a separate hud.sock, leaving service.sock unchanged. It still introduces a compatibility contract, so I agree it should stay small and versioned.

    3. Performance comparison

    I compared the same optimized patched Hex with the feed off, on without clients, on with one lightweight reader, and on with the actual installed renderer. Six randomized blocks used identical roughly 10.6-second synthetic recordings, warmed models, and HEX_STREAMING=0.

    Case Hex CPU while recording Mean stop-to-text Median stop-to-text
    Feed off 0.965% 378.4 ms 378.9 ms
    Feed on, no client 1.212% 398.4 ms 378.6 ms
    Feed on, one reader 0.979% 376.8 ms 375.5 ms
    Feed on, actual renderer 1.030% 378.9 ms 378.5 ms

    CPU is relative to one logical CPU, with 100% meaning one fully busy CPU. The Hex column excludes the renderer/compositor.

    With the full companion, the paired mean stop-to-text difference was +0.55 ms, with an exploratory bootstrap 95% interval of -4.4 to +5.2 ms. All 24 captures retained the full expected words. This run did not detect a consistent latency increase, but six blocks cannot establish zero overhead or rule out rare stalls.

    The no-client average includes a 505.8 ms outlier, retained rather than discarded; its median was 378.6 ms. Chrome/Slack was briefly opened/closed during the run, and the exact overlap is unknown. I cannot attribute that outlier to either the browser or the feed.

    Rendering costs more than the feed. During real captures, the installed helper averaged 11.5% of one CPU, and the private GNOME compositor averaged 4.65%, versus 0.025% during feed-off captures. Renderer RSS was about 58 MiB. DRM graphics-engine busy time was about 1.0% for the renderer and 0.9% for the compositor. Those are engine-time fractions, not GPU power or whole-GPU utilization.

    A separate four-block rendering-only comparison measured about 0.10% CPU for the idle helper, versus 11.05% while animating, plus 4.31% compositor CPU. This is the installed unoptimized debug helper; an optimized renderer has not been measured.

    Environment: Fedora 44, GNOME Shell 50.6, Ryzen AI 7 PRO 350 / Radeon 860M, balanced power profile. Tests used private Hex instances, a temporary virtual microphone, and a private 1280x720 GNOME compositor. The live service and default microphone stayed unchanged. Stop-to-text uses stop --print, not paste; portal/hotkey latency and real-desktop compositor cost are not covered. The feed comparison measures the runtime opt-in in the same compiled patch, not stock Hex versus the patch.

    My conclusion is small feed overhead on this machine, with animation being the larger cost, not "zero overhead".

    Please treat this as a reference implementation, not a finished integration or an API proposal to adopt unchanged. It demonstrates the working path on a real GNOME Wayland setup. The renderer, protocol, and packaging can all be improved. In particular, building and measuring an optimized release helper is a clear next step; the current rendering cost is not an optimized baseline.

  4. thdxr commented on Oct 30, 2026

    @thdxr
    Member

    Thanks for the follow-up!

    Your answers narrow this to one RMS level plus recording and pending state, which the Linux listener already sends to the built-in HUD through LinuxIndicator, so a feed would copy existing reports rather than add capture code. Keeping the extension and renderer outside Hex also fits Hex's rule against desktop-specific code, and your benchmark settles our timing concern. What's left is the shape of a new public socket, and Hex's experiment flag could let it ship as opt-in and unsupported while that settles.

    Things we need to work out

    • A second versioned socket is a compatibility promise that must survive self-updates, unlike the deliberately small current protocol.
    • A level stream needs a fixed update rate and a drop policy so a slow or stuck reader never touches the listener.
    • The brief Listening status during capture start is a separate Status bug and should be tracked on its own.

    Questions for you

    • Would shipping the feed first behind an experiment, opt-in and explicitly unsupported, work for your extension?
    • What update rate and message format does the renderer need, for example newline-delimited JSON at about 30 Hz with dropped frames for slow readers?
    • Could you open a separate issue with reproduction steps for Status briefly reporting Listening while capture starts?

    We'll take a closer look.

    — from 𝕺𝖕𝖊𝖓𝕮𝖔𝖉𝖊

  5. subhoghoshX commented on Oct 30, 2026

    @subhoghoshX
    Author

    Yes, an opt-in, explicitly unsupported experiment would work for the companion. The GNOME extension and renderer can remain outside Hex, and I'm happy to adapt the companion as the experimental protocol changes.

    30 Hz NDJSON is sufficient for the tested renderer path. I tested a candidate helper with peak omitted, accepting only RMS for the meter. The feed delivered 29.88 snapshots/s, while the renderer advanced at 60.01 FPS. RMS changes drove the dots without restarting the animation.

    Focus, click-through, position, completion, old-job/new-recording priority, reconnect, and cleanup checks passed. All 49 renderer/client tests passed too. This was an isolated GNOME compositor test; I haven't replaced the working live helper or compared 30 versus 50 Hz on the physical display.

    My suggested contract is:

    • Complete snapshots with authoritative recording state, pending count, and one normalized linear RMS value.
    • Version, sequence, and capture ID so reconnects and coalesced stop/start transitions are unambiguous.
    • An active update cap around 30 Hz, with intermediate snapshots coalesced, plus a one-second idle heartbeat.
    • Bounded clients and buffering. Drop intermediate whole snapshots; disconnect a reader whose partially written line exceeds a short deadline rather than accumulating a queue or corrupting NDJSON framing.
    • Serialization and socket I/O off the listener, with owner-only access and peer-UID checks.

    Those are preferences, not a request to adopt the reference protocol unchanged. The existing slow-reader tests cover the 50 Hz reference server; the new test validates consumption at 30 Hz.

    I also reproduced the Status bug in packaged dev-249 without the HUD feed. It can remain Listening throughout a recording, not just briefly during startup. The separate reproduction report is #469: #469.

  6. thdxr commented on Oct 30, 2026

    @thdxr
    Member

    Thanks for the follow-up!

    Your reply settles the release path: the feed can ship as an off-by-default, unsupported entry in Hex's experiments list, and your complete-snapshot contract with a ~30 Hz cap, heartbeat, bounded clients and dropped slow readers fits Hex's rules. The Linux listener already sends recording state, pending count and audio samples to LinuxIndicator, so the feed can copy those reports without capturing the microphone again. What's left is the size and security review of a new socket server, which is more than our automated pipeline should build alone.

    Things we need to work out

    • LinuxIndicator sends nothing when the HUD position is Hidden, so the feed can't simply reuse its reports.
    • A second socket with its own threads, client limits, peer-UID checks and restart cleanup is a real server, not a small patch.
    • The Linux service socket must keep carrying only Activate, shortcut commands, Status and Quit, so the feed needs its own socket and path.

    Questions for you

    • Would you open a pull request with your candidate helper, so we can review it as the starting point for the experiment?
    • Should the feed run when the native HUD is set to Hidden, which is likely on GNOME, or only while the HUD is enabled?
    • Where should the feed socket live, next to Hex's service socket in its data folder or in the user's runtime directory?

    We'll take a closer look.

    — from 𝕺𝖕𝖊𝖓𝕮𝖔𝖉𝖊

  7. subhoghoshX commented on Oct 30, 2026

    @subhoghoshX
    Author

    I'd love to open a PR, but GitHub currently restricts pull requests in this repository to collaborators, so I can't submit one myself. A collaborator would need to take the implementation forward using the code, test results, and findings I've shared here.

    Feed behavior when the native HUD is Hidden

    I'd keep the explicitly enabled experimental feed running independently of native HUD visibility. The companion should still honor position: hidden by default. That separates opting into the feed from choosing whether an indicator is visible.

    You're right that stock LinuxIndicator suppresses reports when Hidden. The local patch already addresses this by keeping feed publication active while suppressing delivery to the native HUD. The experiment would need that distinction too, rather than simply tapping the currently gated reports.

    Socket location

    For the initial experiment, I'd keep hud.sock beside service.sock in Hex's private data folder. That keeps discovery straightforward and preserves separation between different Hex data roots. It would remain a separate socket with owner-only permissions, peer-UID checks, bounded clients and writes, and careful stale-socket cleanup. The existing service protocol would stay unchanged.

    These are suggestions based on the reference implementation, not requirements to adopt it unchanged. I'm happy to provide any additional information, run more tests, or help adapt the external companion to whichever experimental feed you settle on.

  8. thdxr commented on Oct 30, 2026

    @thdxr
    Member

    Thanks @subhoghoshX for testing the GNOME Wayland HUD prototype; it helped shape the fix. #479 (fixing #465) shows the real Dot scope HUD on GNOME through XWayland: only the HUD opens there, as an override-redirect, click-through, never-focused window on the primary monitor's edge, while Hex itself stays native Wayland so portal shortcuts keep working. Live microphone levels drive it as on other desktops. It also stops a stale XAUTHORITY from breaking X11 after a reboot.

    It ships in the next dev build: https://github.com/anomalyco/hex#install-hex. We'd love to hear how it looks on your setup.

    — from 𝕺𝖕𝖊𝖓𝕮𝖔𝖉𝖊

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    needs-design

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions