hex/AGENTS.md

783 lines
50 KiB
Markdown

# HEX Agent Guide
## Private Kit Tool
Commit and push straight to `main`, no PRs. Merge any open PR without asking.
After pushing, update the installed copy. See `~/code/control/AGENTS.md`.
## Purpose
Build HEX as a local, observable macOS voice appliance with explicit Linux
X11, wlroots-compatible Wayland, and Windows (x64 and ARM64) beta contracts. Keep the engine native Rust
and keep consequential behavior explicit. Protected commands and typed captures
remain compiled Rust; ordinary literal commands live in the explicit TypeScript user config. User-facing
runtime settings persist in Application Support.
The distributed release starts in hotkey-dictation-only mode. Voice commands and
their catalog remain available as a persisted opt-in that defaults off.
Voice Action also requires its own persisted opt-in, defaulting off even for
existing settings without an explicit enabled flag. Meetings (beta) is a third
persisted opt-in (`meetings.enabled`, default off) that adds call detection, the
Meetings pane, menu-bar recording controls, and meeting paste in release builds.
`DEVELOPER_FEATURES_ENABLED` keeps meetings always available in debug builds and
keeps the meeting CLI, Activity, and HUD Lab debug-only.
## Feature Map
[`docs/features/README.md`](docs/features/README.md) indexes existing user-facing
capabilities, entry points, checks, and gaps. Before designing, changing,
debugging, or reviewing a user-facing feature, read the index and relevant
feature files, then check their referenced implementation. The map is not a
substitute for source inspection or a second roadmap.
- Update the affected map in the same change when behavior, entry points,
defaults, prerequisites, platform availability, recovery, or verification
coverage changes. Do not churn unrelated maps for internal-only refactors.
- Organize by user capability, not Rust module or UI pane. Dictation, Voice
Commands, and Voice Action are distinct features; link shared flows and
recovery rather than duplicating their descriptions. Keep the index current
when adding or splitting a feature file.
- Prefer small action/outcome diagrams in `ts` fences with Unicode tree
characters, not tables. Preserve stable behavior IDs and keep source/check
references and proof limits beside the behavior they explain.
- Distinguish implemented behavior, available checks, and observed verification.
A test's existence is not a passing run, and a preview is not native end-to-end
proof. Record missing coverage and known defects explicitly; never rewrite an
expected outcome merely to hide a regression. A map does not authorize live
device tests. Keep future work in `ROADMAP.md`.
## Architecture
- `audio`: `cpal` device enumeration and timestamped mono float PCM delivery,
live selection, and bounded stream recovery.
- `moonshine`: the only Moonshine C adapter and the streaming recognizer.
- `suppression`: the macOS event tap, shortcut suppression, and the
configurable dictation-hotkey state machine.
- `keyboard`: active-layout key resolution and balanced synthetic shortcuts.
- `dictation`: warm pre-roll, growable capture, and 16 kHz
local-transcription resampling.
- `pause_segmenter`: pure 16 kHz pause detection that cuts meeting audio into
rolling transcription chunks.
- `dictation_audio`: the authoritative microphone timeline, lazy stream
lifecycle, recording owner, exact shortcut boundaries, recovery handoff, and
disposable bounded command audio projection.
- `recording_environment`: serialized RAII ownership of idle-sleep prevention,
output muting, and supported media-player pause/resume behavior.
- `dictation_processor`: the one OpenCode client and ordered processing policy
for macOS and Windows: context-selected corrections, deadline-bounded
OpenCode rewrite profiles with corrected-transcript fallback, the ranked
model catalog, Voice Action generation, and the transformation stage. Both
apps discover the `opencode2` beta executable and link missing installs to
`https://v2.opencode.ai/`. On macOS, `opencode2 api get` discovers or starts
the managed service, and generation uses the matching owner-only service
registration and authenticated loopback HTTP through the system curl; request
bodies and credentials use stdin, never argv or new temporary files. Windows
sends the same requests through the `opencode2 api` CLI inside a job object.
- `parakeet`: the strict-Metal `transcribe.cpp` adapter plus the dictation
worker that hands clips to the transcription engine and runs bounded,
ordered processing, output, paste, last-result, and meeting-delta work.
- `apple_speech`: the Swift `SpeechAnalyzer` bridge with per-locale support
checks, asset reservation, and batch transcription.
- `transcription`: runtime selection and transactional warm-model activation.
- `gguf_session`: the `transcribe.cpp` session owner shared by `parakeet` and
`local_transcriber`; it recreates the native session around each run (and
each live stream) so inference scratch stays bounded.
- `local_transcriber`: the Linux and Windows GGUF loader, prewarm, whole-clip
transcription, and stream entry point.
- `transcription_engine`: the thread that owns the loaded model on every OS and
runs every inference in order: live streams fed during capture, their finish,
whole-clip runs, and (macOS) model loads and switches. The capture owns its
`LiveStream` and hands it to the finished clip; finishing returns a
`PendingTranscript` whose wait enforces the stream deadline and falls back to
the whole clip.
- `transcription_preparation`: application-owned model preparation shared by
Settings and the menu bar, with one worker, latest-choice pending admission,
cancellation fences, and an installed-only path that never downloads a model.
- `transcription_models`: the compiled model catalog, language recommendations,
pinned artifact verification, and lazy installation.
- `transcription_service`: bounded host-audio admission, hostile WAV validation,
normalization, cancellation, and warm inference ownership.
- `local_api`: authenticated loopback discovery or direct-child endpoint
handoff, bounded HTTP parsing, model preparation progress, and raw
transcription routes.
- `sdk/typescript`: Promise and Effect v4 host wrappers for direct-child
lifecycle, authenticated model preparation, and host-audio transcription.
- `developer_control`: the typed debug-only command/reply protocol the local
API uses to drive the running app from `hex dev`.
- `paste`: clipboard insertion, continuation joins, and generation-safe
clipboard restoration.
- `accessibility`: bounded focused-window and selected-text capture through
Accessibility without touching the clipboard.
- `recognition`: the semantic coordinator for Moonshine, command mode, hotkey
and voice-delimited controls, workers, and observations. It does not own the
authoritative microphone timeline.
- `command_grammar`: typed command patterns, captures, overlap detection, and
command catalog metadata.
- `keys`: the platform-neutral key and modifier vocabulary of command actions.
- `commands`: pure contextual resolution plus bounded asynchronous action
execution (`open` and CoreGraphics keystrokes on macOS; shell-opened URLs,
paths, and applications on Windows).
- `personal_commands`: the Bun-hosted `@hex/commands` TypeScript workspace:
managed SDK provisioning (built `dist` on macOS, the embedded TypeScript
`src` on Windows), the watch-reloaded user command and transformation host,
bounded invocation dispatch, and status snapshots. macOS and Windows share
it; Windows hosts transformations only.
- `text_replacements`: phrase-boundary-aware compilation of configured text
replacements applied longest-match-first to transcripts.
- `config`: compiled commands, preferred input devices, and dictation profiles.
- `context`: the foreground context snapshot and selectors shared by commands
and modes, plus native macOS capture. Browser host is the domain concept;
Brave AppleScript is the first macOS adapter and `windows_context` reads any
browser through UI Automation.
- `application_catalog`: cached installed-application discovery with icons for
the Modes picker, one module per OS: macOS bundles, Windows executables from
Start menu shortcuts, App Paths, and open windows, Linux `.desktop` entries.
- `app_settings`: the one persisted `settings.json` on every OS and its live
runtime projection for commands, hotkeys, microphone and transcription
selection, recording behavior, processing, sound volume, indicator position,
interface language, and Dock policy. It records one-time changes in
`migrations` and migrates the Windows and Linux beta files once.
- `login_item`: the native `SMAppService.mainAppService` adapter. macOS owns
registration state; it is deliberately not duplicated in `settings.json`.
- `app_paths`: the Application Support owner for runtime logs and shared state,
including the one-time macOS `voice-control` to `hex` folder rename, which runs
in `main` before logging, the instance lock, or any file in the folder opens.
- `onboarding`: required permission health, selected dictation-model
installation, the release startup gate, and opt-in command-model setup.
- `sparkle`: packaged-app-only Sparkle lifecycle and manual update checks.
- `linux`, `linux_app`, `linux_dictation`, `linux_input`, `linux_paste`,
`linux_migration`: the Linux beta CLI, the service host and Settings process,
the hotkey capture-transcribe-paste loop with Paste Last and Voice Action, the
X11 grabs and shortcut options, paste and primary-selection reads, and the
one-time `linux-settings.json` migration.
- `linux_context`: the frontmost X11 application for modes; Wayland has none.
- `linux_audio_control`: While-dictating mute through `wpctl`/`pactl` and
MPRIS pause over D-Bus, restoring only what it changed.
- `linux_session`: display-backend selection matching GPUI's nonempty
`WAYLAND_DISPLAY` rule, independent of persisted preferences.
- `linux_wayland_input`: read-only evdev input, explicit physical key mappings,
cancellable shortcut capture, exact chord state, and bounded device rediscovery.
- `linux_service`: owner-only, same-user Unix IPC, bounded service/client transport,
and per-user systemd lifecycle. Settings and CLI are clients of one runtime.
- `linux_desktop`: the service-owned GTK thread for the focus-free, click-through
recording/processing HUD: layer-shell on Wayland, an override-redirect popup on
X11, at the top or bottom. Settings never owns its lifecycle; Linux has no tray
icon.
- `self_update`: the signed-feed core the Linux and Windows updaters share:
ed25519 feed verification, per-target manifest validation, bounded HTTPS
downloads, and size and checksum verification.
- `linux_updater`: signed direct-install updates, atomic version activation,
and restart handoff for user-local Linux installs.
- `windows`, `windows_app`, `windows_dictation`, `windows_input`,
`windows_paste`, `windows_migration`, `windows_indicator`, `windows_updater`,
`windows_context`, `windows_audio_control`, `login_item`: the Windows beta
CLI, the tray, HUD, and listener host around the shared window, the WASAPI
dictation loop, low-level keyboard hook, clipboard paste, the one-time
`windows-settings.json` migration, HUD, signed self-update, UI Automation
context, audio ducking, and login item.
- `windows_ui`: Windows window chrome on the shared design system: the split
caption row (brand over the full-height sidebar, window buttons over the
content), Segoe Fluent Icons glyphs, and window, tray, and HUD-popup
integration.
- `dictation_modes`: the mode runtime the Windows and Linux listeners share:
mode selection by application and website, then global replacements, mode
corrections, OpenCode rewriting, and transformations, and the History entry.
- `desktop_i18n`: interface translations keyed by the English source string,
`tr`, `tr_fill`, and `tr_named`. A test fails if any string the shared window
translates lacks a language.
- `history`: the owner-only bounded retained-dictation store: retention
windows with hard entry and byte caps, atomic crash-safe persistence, and
search. Text and bounded metadata only, never audio.
- `events`: bounded asynchronous append-only NDJSON observations and bounded
incremental reading; `dashboard` and the GPUI Activity pane are read-only
projections.
- `desktop_activity`: the shared listener, device, session, and latest-failure
projection over `EventReader`. Transcript rows read retained events directly.
- `desktop_host`: the Linux Settings/service snapshot-and-action contract.
- `design_tokens`: the desktop design tokens (surface, text and role colours,
the five-step type scale, spacing, radii, and control geometry) plus the
`Typography` trait and the test that rejects raw styles in desktop sources.
- `desktop_ui`: the platform-neutral GPUI components shared by both desktop
roots: the pane scaffold, cards and rows, the one button system, tags, menus,
segmented controls, icons, and empty and error states.
- `text_input`: the shared GPUI single- and multi-line text input with editing,
selection, clipboard, and input-method support.
- `desktop_transcription_picker`: the single GPUI language/model picker used by
both desktop roots over portable model presentation and platform preparation
callbacks.
- `app_window`: the one window on macOS, Windows, and Linux: Settings, Modes
with mode-owned corrections and processing, Voice Action, History, opt-in
Commands, and developer-only Meetings, Activity, and HUD Lab panes. A
`Capabilities` struct decides which panes and rows exist; `app_window/macos.rs`,
`windows.rs`, and `linux.rs` supply each OS's chrome, settings hooks, and
backends. Keep shared UI in `app_window.rs` and only OS behavior in those
modules.
- `status_item`: the persistent macOS menu-bar owner for Settings, Paste Last
Dictation, meeting recording state and Stop & Transcribe, update checks, and
orderly application shutdown.
- `dictation_indicator`: the click-through Metal/GPUI capture and processing HUD.
- `meeting`: explicit capture through `meeting_capture`, owner-only WAV and transcript
artifacts, Screen Recording permission checks, final local-model publication,
the user-facing Markdown copy, and recovery.
- `meeting_capture`: independent self-healing microphone (cpal) and system
audio (Core Audio process tap, ScreenCaptureKit fallback) sources; one
failing never stops the other, and resumed audio is padded onto the timeline.
- `meeting_transcript`: streaming 16 kHz resampling, pause-aware overlapping
chunks, the utility-QoS rolling transcriber that yields to dictation, seam
deduplication, echo suppression, and Markdown rendering.
- `meeting_live`: bounded dual-stream Moonshine draft transcription,
byte-offset transcript tailing, and the echo-filtered live view.
- `meeting_echo`: 20 ms energy envelopes of both tracks and the signal-level
bleed/local classification of microphone segments.
- `meeting_notes`: a bounded provisional title while recording, then one
post-publication call over a bounded transcript excerpt for the final title
and a two-sentence summary, with deadline, manifest storage, and
marker-delimited in-place Markdown updates.
- `meeting_query`: read-only meeting queries for agents (`meeting::query`):
lock-aware listing, in-memory BM25 full-text search with stemming and fuzzy
matching, transcript paging, stored notes, and Markdown rendering. It never
writes to the meetings folder.
- `meeting_mcp`: the thin `rmcp` stdio adapter behind `hex mcp`, exposing
`meeting_query` as read-only tools and `hex-meeting://` resources.
- `apple_intelligence`: the weak-linked FoundationModels Swift bridge:
availability, context size, and guided-generation notes at utility priority.
- `microphone_activity`: permission-light CoreAudio process input observation.
- `meeting_detection`: pure provider classification, debounce, per-call snooze,
and call-ended presence.
- `meeting_watcher`: GPUI application lifecycle, recognition ownership, the
focus-free meeting capsules, menu-bar meeting state, and explicit handoff into
capture.
- `instance`: the exclusive Application Support lock that prevents concurrent
command listeners.
- `feedback`: bounded volume-controlled mode, capture, cancellation, and
failure tones.
Keep modules deep. Callers should not coordinate Moonshine stream handles,
CoreAudio formats, AppleScript details, or event serialization.
## Invariants
- Every build starts dictation-ready without loading Moonshine or a command
executor unless the persisted command opt-in is enabled. Enabling commands
loads Moonshine off the audio-consumption loop; disabling them unloads the
recognizer and executor.
- On a new Mac, release dictation starts only after Microphone, Input Monitoring,
Accessibility, and the selected dictation model are ready. Opt-in command
recognition additionally requires Moonshine, but its background preparation or
failure must never block hotkey dictation. Failed preparation exposes explicit
retry and disable actions without silently changing the command opt-in.
- Among recognized voice commands, sleeping mode accepts only standalone wake
phrases. Dictation and explicit paste shortcuts remain available.
- Unmatched completed speech is ignored and logged.
- The dictation shortcut defaults to Option but supports modifier-only,
modifier-plus-key, standalone Globe/Fn, and standalone function-key bindings.
Capturing a new binding suspends global matching.
- GUI startup must successfully call `keyboard::initialize_layout` on the OS
main thread before settings, keyboard-using workers, or GPUI start. That
snapshot is fixed until restart; cached misses must not re-enter TIS/TSM.
Uncached headless lookups retain live-layout resolution, with all native
lookup and snapshot construction serialized by the same lock.
- Stale shortcut recovery requires at least 100 ms of sampled keyboard neutrality,
no pending input, and no hold or pending gesture. A lock is repaired only when
it tracks a held key, and it stays locked so a fresh press can still finish it.
It emits no capture actions.
Native `SecondaryFn` navigation metadata may be ignored only with timestamped
modifier-change evidence that Fn is up; the full key scan and delayed-event
fences remain required. Never strip Fn globally from shortcut matching.
- Hold the shortcut to dictate and release to transcribe. Captures shorter than
300 ms discard. A 450 ms hotkey pre-roll and one-second voice-trigger pre-roll
protect speech onset. Capture has no automatic duration limit; release,
explicit stop, or Escape ends it.
- When enabled, a second shortcut tap within 300 ms locks dictation. Press the
shortcut again to finish or Escape to cancel.
- When commands are enabled, every dictation or paste hotkey action resets
Moonshine so shortcut audio cannot leak into a later command.
- Recording audio behavior and idle-sleep prevention begin only after the
intentional-hold threshold. Ordinary shortcut chords must not mute output,
pause media, or prevent sleep.
- The start tone confirms the shortcut press itself, not the hold threshold: it
is provisional, sounds after a 40 ms chord grace, and a chord, short tap,
cancel, or Voice Action takeover retracts it (silently inside the grace, else
a 20 ms fade). With the microphone released while idle, the tone waits for
the open microphone and the hold.
- `Release microphone while idle` and Commands are mutually exclusive through
explicit confirmed transitions and a shared runtime policy. When release is
enabled, pressing the shortcut opens the selected device asynchronously with
no pre-roll, preserves the physical press for the hold threshold, discards a
release before readiness, and closes only after the authoritative capture is
idle. Accepted jobs never keep the stream open. A stream failure before the
hold threshold returns the press to pending and reopens; later failures fail
the capture. Cold opens retry the selected device briefly before falling back.
- Dictation remains available while command recognition sleeps.
- Model inference, optional post-processing, paste, and application actions must
never block authoritative audio capture. Their queues remain bounded.
- CoreAudio capture timestamps and annotated-session CGEvent shortcut timestamps
share the macOS boot-time nanosecond clock. Do not apply the Mach timebase to
annotated-session timestamps. Physical HID-tap timestamps arrived as raw Mach
ticks on the tested Apple Silicon system, while some HID events already used
nanoseconds; changing tap location requires revalidating timestamp units.
Delayed press handling reconstructs the original onset from the timeline;
delayed release handling excludes audio captured after the physical release
plus `POST_RELEASE_TAIL` (200 ms).
- A shortcut release or locked press that finishes a transcribed capture keeps
audio through that exact event plus the 200 ms tail. The event timestamp is
never moved; the hold threshold uses it alone. The audio owner waits at most
the tail plus 100 ms for that audio, and a stream stall, failure, or gap in
the tail finishes with the audio already delivered instead of failing the
capture. Escape, short taps, voice controls, programmatic stops, and meetings
get no tail. A press during the tail is handled after the old clip finishes.
- Active dictation capture is lossless with respect to Moonshine, event, UI,
context, and worker stalls. Command recognition is explicitly best-effort:
its backlog is bounded by duration, and pressure invalidates the generation,
discards stale audio and updates, and resets Moonshine without touching the
active recording.
- The dictation shortcut has a persisted `shortcut_mode`: `hold` (default)
or `toggle`. Toggle reuses the lock state on every platform: each press acts
as the second tap of a double-tap, so release locks and the next shortcut
press finishes. Only Escape cancels, and a modifier pressed alone never ends a
key-chord capture. Double-tap settings apply to Hold only.
- Streaming dictation is speculative on every OS: a hotkey capture's stream
receives exactly the capture's 16 kHz audio, the finish always carries the
complete clip, and a failed, empty, overfed, late, or interrupted stream
falls back to the whole clip. Nothing pastes, and no partial text shows,
before the final text. One engine thread runs every inference because a live
stream holds the model's compute lease. Streams run only on GPU devices
(Metal, Vulkan); models that cannot stream transcribe the whole clip after
release. Dictation is never cut at pauses; meetings are.
- Starting a new capture never cancels accepted dictation work. Pending jobs
preserve submission-order output while capture remains immediately available.
- Completing or pasting an older job must not reconcile or finish a newer
capture. Shortcut boundaries come from delivered CGEvent timestamps; do not
fabricate a release timestamp from later physical state.
- Escape cancels the active capture first, then the newest unfinished dictation.
Cancelled jobs never paste, update the last result, or block later output.
- Model switches activate only after the pinned artifact is checksum-verified,
loaded on strict Metal, and prewarmed. A failed switch preserves the active
model and persisted selection.
- The menu-bar model picker lists only downloaded, available models and remembers
each model's last selected language and recognition hints. It works without a
Settings window. Settings and the menu bar share one preparation owner; a newer
choice supersedes uncommitted work, and preparation/save failures leave the old
selection intact. Menu-bar selections never silently download or repair a model.
- Cohere's advertised encoder input capacity is not its recommended inference
window. Both GGUF adapters cap Cohere chunks at the reference processor's
35 seconds (or a stricter advertised bound); capture duration remains unlimited.
- A selected microphone switches live only while capture is idle. Opening the
replacement must succeed before the old stream is dropped. If the persisted
device is unavailable at startup, log the failure and fall back through the
compiled preferred-device order to the macOS default. An explicit CLI
`--device` remains authoritative for that listener process. A runtime stream
failure cancels an incomplete capture, discards stale chunks, and retries the
same selection with bounded backoff; it must not require a settings change or
process restart. An initial open failure uses the same bounded recovery without
stopping the listener. Cancellation does not stop warm-microphone retries;
enabling release-while-idle stops them once capture is idle.
- Feedback volume is persisted from zero through one; zero disables tones.
Volume changes apply immediately and preview one recording-start tone.
- Launch at Login uses `SMAppService` for the signed main app. Treat both
`NotRegistered` and `NotFound` as disabled before registration, represent
`RequiresApproval` with a link to Login Items settings, and poll macOS as the
source of truth instead of persisting a parallel Boolean.
- Voice Action is an optional second capture target. Its saved shortcut defaults
to Option-Command, but no shortcut is active or reserved until the user enables
Voice Action. Disabling it cancels its active capture, not accepted jobs, and
preserves the saved shortcut and model. The toggle remains reachable when
OpenCode is unavailable. Promoting an active Option capture preserves all recorded
audio. Selected text is optional prompt context; inaccessible or empty
selections act as no selection. Use the dedicated OpenCode model and deadline,
return only paste-ready text, and paste at the current focus. Failed, empty,
cancelled, or timed-out actions paste nothing. Voice Action jobs share normal
queueing and cancellation but never update the last dictation.
- Mode processing is best-effort and ordered: corrections, optional OpenCode
rewriting, then selected transformations. A failed stage preserves its input;
the transformation chain is one stage, so failure discards its partial results.
It applies to Paste and Send, but not Voice Action or meetings.
- OpenCode availability checks stay off the UI thread. When the app finds the
`opencode2` executable, `opencode2 api` discovers or starts the managed service;
the catalog uses authenticated loopback HTTP to avoid large CLI pipe truncation.
HEX never invokes
`opencode2 serve --service` or owns that service's lifecycle directly. A
missing beta install is retried at a coarse interval so installing
`opencode2` while Settings is open refreshes the model catalog without
restarting HEX. Catalog failures require an explicit retry rather than
spawning clients in a tight loop.
- Ordinary resolver commands execute only from completed Moonshine lines.
Voice-delimited activation and stable control phrases are deliberate exceptions.
- Contextual commands enter the candidate set only when their predicate matches.
- Literal and typed command patterns compile into one registry. Reject overlaps
at configuration time and generate the catalog from that registry.
- Successful commands rely on their action for feedback. Wake/sleep use quiet
tones; execution failures use an error tone.
- Clipboard insertion is the fixed text-insertion path. Restore the previous
clipboard only if no newer paste or external clipboard change superseded it.
- Option-Shift-V pastes the last completed dictation. Option-Control-V pastes
completed meeting turns added since the previous successful invocation.
- Do not persist captured audio by default. Explicit foreground meeting
recording must remain visibly active. Diagnostic dictation retention is an
explicit, bounded, owner-only opt-in through `HEX_RETAIN_DICTATION_AUDIO`.
- Retained dictation history records only successful pasted output: raw and
final text plus bounded metadata, never audio, full browser URLs, or window
titles. History defaults to seven days, and every retention window remains
subject to hard entry and byte caps. No new entries are accepted while Off.
Turning retention Off preserves existing entries; clearing history is explicit.
Time-based retention expires during idle uptime through the shared history
owner; searches never return expired entries while waiting for disk cleanup.
- Meeting detection may inspect process audio metadata but must not capture
samples. Detection can offer recording; it must never start automatically, and
an offer that times out only closes. Release builds keep the meeting controller
idle, without inspecting microphone activity, until the user opts in. When the
detected call app leaves the microphone, offer `Keep Recording` or
`Stop & Transcribe`; never stop automatically. An active recording stays
visible and stoppable from the menu bar without the Settings window.
- Meeting transcription never blocks dictation: it runs on its own model session
at utility QoS, waits while an intentional dictation capture or dictation
inference is active, and keeps its queue (one-second audio blocks) and chunk
backlog bounded; a source that falls behind keeps what it transcribed and is
rebuilt from its WAV after Stop.
- Meeting system audio uses a Core Audio process tap (System Audio Recording
consent), never requiring a display; ScreenCaptureKit is only the fallback.
Losing either source never stops the other or the meeting: it retries until
Stop, and resumed audio is padded with silence so WAV positions stay on the
shared capture clock.
- Meeting recording prevents idle sleep but does not apply dictation mute or
pause-media behavior.
- Apple Intelligence meeting notes run only after final publication, on a
utility-QoS thread that yields to dictation, within a bounded chunk count and
total deadline. Failures record `notes_error` and leave the Markdown
untouched. Notes never rename the file and rewrite only the heading HEX wrote
and the `<!-- hex:notes -->` block.
- `hex mcp` is read-only and available in release builds regardless of the
Meetings opt-in. It dispatches before process logging, the instance lock,
GUI, or permission setup; never writes, recovers, or indexes on disk inside
the meetings folder; runs no model; and makes no network request. Stdout
carries only MCP messages.
- Meeting echo is judged on one timeline built from WAV sample positions, never
from packet arrival. A `You` line or rolling entry is judged only once the
system audio that could explain it has arrived (bounded when the system track
stalls). Measure echo changes with `meeting_echo_replay` on a recorded
speaker-mode call, counting genuine `You` lines lost as well as echo kept.
- Moonshine sessions run single-threaded (`MOONSHINE_ORT_SINGLE_THREAD`, set
first thing in `main`); ONNX Runtime's default spinning pools cost several
times the CPU of the decoding itself.
- Live meeting drafts remain available if final transcription fails. Final
publication is atomic; adjacent same-source entries within three seconds form
one displayed turn labeled `You` or `Them`. Speaker echo never shows as `You`:
the live view, rolling snapshot, live paste, and final transcript drop a
microphone utterance when delayed system audio explains its energy, or when
its words repeat overlapping remote speech unless the signal shows local
speech (double-talk). An undecided draft line waits while the remote side
speaks until it completes. Each finished
meeting is also written as Markdown to the configured folder (default
`~/Documents/Hex Meetings`) without overwriting existing files; an export
failure does not fail the meeting.
- Meeting paste cursors advance only after successful insertion and reset when
HEX restarts.
- Deleting a meeting moves its exported Markdown and then its recording folder
to the Trash (never `rm`), after a two-step confirmation, and is refused while
it records, transcribes, or writes notes. Renaming rewrites the manifest and
only a Markdown heading that still reads the previous title; files keep
their names.
- Visible state remains `Transcribing` until every accepted transcription or
paste output has completed, including ordered post-processing and insertion.
- The HUD is observational and click-through. It must not alter capture
boundaries, steal focus, or block controls in the foreground application.
- Desktop UI is governed by [`docs/design-system.md`](docs/design-system.md);
read it before changing any GPUI pane, capsule, or picker. Use only
`design_tokens` values and `desktop_ui` components: no raw colours, type
sizes, line heights, or radii (`desktop_sources_use_tokens_instead_of_raw_styles`
enforces this). Use sentence case and the product name "Hex" in all copy.
Reserve the accent (Primary) fill for at most one main action per screen;
states such as recording or an available update use a Secondary button with
a status dot. Extend a token or component instead of adding a parallel helper, and verify
visual changes with `scripts/capture-preview.sh`.
- Public app updates are Developer ID signed, notarized, stapled, EdDSA signed,
published artifact-first/feed-last, and installed through Sparkle.
- Linux direct-install updates accept only a strictly newer signed stable
x86_64 manifest, verify exact size and SHA-256 from a content-addressed
artifact, and atomically switch the user-local `current` version. Never
overwrite development, root, or package-manager-owned binaries.
- The Wayland beta requires compatible clipboard, virtual-keyboard, and
layer-shell protocols plus explicit read access to all `/dev/input/event*`
nodes. Do not silently fall back to XWayland or privileged input injection.
Raw input observes, but does not suppress, physical US-labeled keys. Explain
the broad keystroke access; never grant device permissions automatically.
- Linux Settings owns no microphone, model workers, saved settings, or tray. The
per-user `hex.service` owns these independently of GUI lifetime. Closing or
crashing Settings must not stop capture or accepted work. Socket access is
owner-only and peer-UID checked; framing, queues, and I/O remain bounded.
Client disconnect cancels only its uncommitted shortcut capture, with a bounded
lease fallback. Never replay uncertain mutation requests after reconnecting.
- X11 shortcut capture uses focused GPUI input, not evdev permissions. Editing
shortcut/double-tap settings stops and restores only a previously running
listener; cancellation restores the old binding unless its save already
committed. Settings and the CLI must expose service state, recovery, and errors.
Explicit service shutdown drains workers; closing Settings only disconnects its
client. HUD teardown only hides that listener's HUD.
- Linux paste keeps transcripts off helper argv, bounds helper I/O, and waits
for physical modifiers without discarding accepted output. Shutdown cancels
that wait. New installs use Ctrl-V; the terminal-paste preference selects
Ctrl-Shift-V and defaults on for persisted legacy X11 settings. The beta retains
the transcript clipboard; arbitrary MIME restoration and consumption
acknowledgments remain unimplemented.
## Development
### TypeScript SDK Releases
The public TypeScript SDK is `@kitlangton/hex` in `sdk/typescript`. The first
release, `0.1.0`, was bootstrapped manually; subsequent user-facing SDK changes
must include a Changeset under `sdk/.changeset/` unless preparing an initial
unpublished package. Run package commands from the `sdk` workspace root.
Before release, run:
```sh
cd sdk
bun install --frozen-lockfile
cd typescript
bun run check
bun run test
bun run build
npm pack --dry-run
```
When exports or packaging change, install the packed tarball in a clean consumer
and import both `@kitlangton/hex` and `@kitlangton/hex/effect`. The release
workflow is `.github/workflows/release-typescript.yml`; npm trusted publishing
authorizes `anomalyco/hex` and that exact workflow filename for `npm publish`.
The workflow uses npm trusted publishing without requesting a Sigstore
provenance bundle.
Use the configured Changesets release command (`cd sdk && bun run release`), not
direct `npm publish`, after the bootstrap release.
```sh
./scripts/setup.sh
./scripts/setup-parakeet.sh
bun run --cwd sdk/commands build
cargo run -- listen
cargo run -- status
cargo run -- meeting record --title "Design sync"
cargo run -- meeting probe
cargo run -- mcp --meetings-dir tests/fixtures/meetings
cargo run -- meeting watch --preview
cargo run -- app --preview-dictation
cargo run -- preview onboarding
cargo run -- preview transcription-picker --language zh --model-state installed
./scripts/capture-preview.sh /tmp/hex-preview.png settings
./scripts/capture-preview.sh /tmp/hex-update.png settings --update-available
./scripts/capture-preview.sh /tmp/hex-model-missing.png settings --model-missing
./scripts/capture-preview.sh /tmp/hex-command-model-missing.png settings --command-model-missing
./scripts/capture-preview.sh /tmp/hex-microphone-confirmation.png settings --confirm-release-microphone
./scripts/capture-preview.sh /tmp/hex-history-retention.png history --open-history-retention
./scripts/capture-preview.sh /tmp/hex-modes.png modes
./scripts/capture-preview.sh /tmp/hex-modes-collapsed.png modes --collapse-mode-processing
./scripts/capture-preview.sh /tmp/hex-modes-picker.png modes --collapse-mode-processing --open-transformation-picker
./scripts/capture-preview.sh /tmp/hex-modes-global.png modes --collapse-mode-processing --select-global-mode
./scripts/capture-preview.sh /tmp/hex-voice-action-off.png voice-action
./scripts/capture-preview.sh /tmp/hex-voice-action-unavailable.png voice-action --voice-action-enabled --opencode-unavailable
HEX_PREVIEW_SKIP_BUILD=1 ./scripts/capture-preview.sh /tmp/hex-modes.png modes
./scripts/install-app.sh
cargo fmt --check
cargo test
cargo clippy --all-targets --all-features -- -D warnings
git diff --check
./scripts/test-app-identity.sh # macOS only
./scripts/test-install-linux-release.sh # x86_64 Linux only
cd sdk/typescript && bun run check && bun run test && bun run build
```
Use `scripts/capture-preview.sh` as the default desktop-UI iteration loop. It
builds the release binary, launches one isolated deterministic preview, waits
for that process's `Hex` window, captures only that window, and terminates the
preview. Targets include `settings`, `modes`, `voice-action`, `commands`,
`meetings`, `activity`, `onboarding`, `transcription-picker`, `hud-lab`,
`dictation-hud`, and `meeting-offer` (with `--meeting-panel call-ended|ready`).
Pass `--meetings-enabled` and `--screen-recording-missing` to Settings for the
Meetings section. The `meetings` preview has sample meetings with notes and a
transcript; add `--meeting-recording` for the live state,
`--confirm-meeting-delete` for the delete confirmation, `--open-meeting-actions`
for the overflow menu, or `--meetings-empty`. The Modes preview includes representative activation,
correction, model-variant, and transformation data so it exercises the complete
editor. Pass `--collapse-mode-processing` to expose the lower transformation
and deletion states without scrolling. Use `--open-transformation-picker`,
`--select-global-mode`, and `--opencode-unavailable` to capture those states
directly instead of scripting pointer coordinates. After a successful build, set
`HEX_PREVIEW_SKIP_BUILD=1` for repeated
captures that do not require recompilation; `HEX_PREVIEW_BINARY` can override
the release binary path. Keep release previews authoritative for production
navigation because debug builds expose developer-only panes.
The supported Linux beta and release host use x86_64 Arch Linux. Install its
native build dependencies with:
```sh
sudo pacman -S --needed base-devel git rustup python alsa-lib curl jq openssl xxd \
util-linux gtk3 gtk-layer-shell libappindicator-gtk3 libxkbcommon \
libxkbcommon-x11 libx11 libxcb openblas vulkan-headers vulkan-icd-loader \
shaderc spirv-headers clang cmake pkgconf wl-clipboard wtype
rustup default stable
```
For a source install, run `scripts/install-linux.sh`, then `hex model install`.
The installer owns the user-local version layout, desktop entry, and autostart
entry; only that managed layout participates in automatic updates.
`nix develop` supplies the same native build environment as the Nix package;
`nix flake check` checks modules, shell configuration, session readiness, and
the display-free Rust suite. See `docs/nix.md`. Nix owns package updates and
optional Home Manager autostart. Native Linux PR checks do not replace real
X11/Wayland, keyboard hotplug, microphone, and target-application smoke tests.
Automatic microphone selection follows the compiled preference order in
`src/config.rs`, then falls back to the macOS default. A saved microphone takes
precedence while available; override everything with `--device`. The app bundle
build requires Xcode 26 for Icon Composer compilation and a Developer ID signing
identity. `scripts/release-app.sh` prepares a notarized and stapled DMG plus its
signed Sparkle appcast; run `scripts/release-app.sh publish` only after validating
the prepared artifact. Public app downloads and update feeds use
`https://downloads.hex.kitlangton.dev`, connected directly to the `hex-releases`
R2 bucket through Custom Domains. The same bucket is also
`https://downloads.hex.kitlangton.com`, which the website, docs, and script
installers use; apps, feeds, the appcast, and release scripts keep the `.dev`
host, which must keep working unchanged. Preserve the legacy public R2 endpoint for
installed clients. The publisher verifies both R2 artifacts and the identical
GitHub DMG mirror before publishing the appcast. GitHub app releases use
`app-v<VERSION>` tags with `--latest=false`, keeping them distinct from SDK
releases. Never overwrite a published artifact with different bytes.
`https://hex.kitlangton.com` (in-repo `site/`, Worker `hex-voice-site`) is the
only Hex website; its Worker 301s `hex.kitlangton.dev` and every other host to
the same path there. After publishing a version, bump `MAC_VERSION` or
`DESKTOP_VERSION` in `site/src/release.ts`, the explicit GitHub mirror/version
link in `README.md`, and (macOS) the Homebrew cask. `bun run --cwd site
check:downloads` fails until every download link serves a file; the Site
workflow runs it and deploys from `main` when the repository has a
`CLOUDFLARE_API_TOKEN` secret, otherwise deploy from `site` on the Pro with
`bun run build && bunx wrangler deploy`. Verify the live links afterwards.
The Rust app is named `Hex`, packaged as `Hex.app`,
with bundle identifier `com.kitlangton.hex2` and executable `hex`. Kit has approved
his personal Developer ID signing team `QC99C9JE59` for this app. Signing requires
an explicit `VOICE_CONTROL_TEAM_ID` and matching `HEX_NOTARY_PROFILE`; the build
and release scripts verify the selected team rather than assuming an Anomaly team.
`scripts/validate-app.sh` checks this identity before preparation and publication.
The manual DMG contains `Hex.app`; the signed Sparkle ZIP preserves `HEX.app`
as its archive root so existing Rust 2.0.x installations can discover the update
despite the new bundle ID. Both artifacts contain the same signed, stapled app.
Sparkle compares `CFBundleVersion`, not source changes or signing timestamps.
Public releases must advance beyond distributed beta builds as well as the feed;
the older local Rust 2.1.0 beta already used build 20100. Do not reuse a released
version/build for changed code. Validate updates from both the public 2.0.x app
and the older 2.1.0 beta when changing update identity or packaging.
There is no Swift migration: never import Swift preferences or data, adopt its
bundle identifier, publish Rust artifacts to its S3 feed, or automatically quit,
delete, or replace the Swift app. Prefer a website-only informational item in
the legacy Sparkle feed, with no enclosure, pointing to the new app for manual
installation and fresh setup. Publish it only after the new artifact is live. See
`docs/plans/swift-app-handoff.md`. The Rust data root remains unchanged, but the
new app identity requires fresh macOS permission grants. Validate signed
distribution with the selected signing team before publishing an app update.
`SMAppService` is meaningful only from a signed app installed in
`/Applications`. When replacing a local bundle outside Finder during a login-item
smoke test, register the new bundle with Launch Services before launch:
```sh
'/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister' \
-f /Applications/Hex.app
```
Pass the actual installed Rust host path to `lsregister` if it was renamed.
Verify both registration and unregistration with `sfltool dumpbtm`, and restore
the user's original login-item state after the test. Do not add release test
hooks or persist a second launch-at-login flag.
Linux and Windows releases are built and signed by
`.github/workflows/release-desktop.yml`, then published from the release Mac.
Run the workflow with `workflow_dispatch` and a `ref` (or push an
`app-v<VERSION>` tag, which must match the crate version). It builds Linux
x86_64 in an Arch container and Windows x64 and ARM64 on native runners with
each script's `build` mode. A job that compiles nothing then signs all three
feeds with `scripts/release-feed.sh` and validates signatures, sizes, SHA-256,
version order against the live feeds, and the absence of Visual C++ runtime
imports. The `release` environment, limited to `main` and `app-v*` tags, holds
only `HEX_RELEASE_SIGNING_KEY`. The run's `signed-release` artifact holds the
executables, the signed feeds, and `release.json` (commit and version).
Publish a successful run from `main` or a tag on the Pro, whose Wrangler login is
the personal account that owns `hex-releases`:
`scripts/publish-desktop-release.sh <run-id>`. It downloads the signed artifact,
re-verifies it, uploads content-addressed artifacts first (never replacing
different bytes), then the installers as committed at the release commit, then
the feeds after rechecking that the version is newer, and re-downloads each
object from `downloads.hex.kitlangton.dev`. It then runs
`scripts/publish-desktop-downloads.sh`, which uploads the immutable
`releases/HEX-Setup-<version>-x64.exe` and `-arm64.exe` and attaches them and
`HEX-<version>-x86_64-linux` to the `app-v<version>` GitHub release as
identical-byte mirrors. Rerunning either after an interruption is safe. `gh` on
the Pro is not logged in; pass `GH_TOKEN` for the session only.
`HEX-Setup-<version>-<x64|arm64>.exe` is a per-user Inno Setup installer
(`packaging/windows/hex.iss`, built by `scripts/build-windows-installer.ps1`)
that installs exactly the managed layout `install-windows.ps1` creates, so
self-updates keep working: `%APPDATA%\voice-control\versions\<version>\hex.exe`,
`current-version`, and a Start Menu shortcut carrying the managed mark. Its
uninstaller lives in `voice-control\uninstall` because updates prune old version
directories; it removes every version, the shortcut, and Launch at login, and
keeps settings. It refuses to roll back a newer self-updated version. Keep its
`AppId` forever: the updater rewrites that Apps & Features entry's version.
Release desktop and the Windows installer workflow install, reinstall, refuse a
downgrade with, and uninstall it silently on x64 and ARM64 runners
(`scripts/test-windows-installer.ps1`). The installer and `hex.exe` are not
Authenticode-signed, so SmartScreen warns on first run.
Both scripts still work locally: `prepare` builds and signs with the Ed25519
private PEM in `HEX_RELEASE_SIGNING_KEY` (or `HEX_LINUX_SIGNING_KEY`), and
`publish` uploads after validation. Run the Linux script on x86_64 Linux and the
Windows script from Git Bash once per architecture with `HEX_WINDOWS_ARCH=x86_64`
(the default; Vulkan SDK required) or `aarch64` (clang-cl and Ninja; best on an
ARM64 host). The feeds are `linux-update.json`, `windows-update.json` for x64,
and `windows-aarch64-update.json` for ARM64, all on the same key, bucket, and
`downloads.hex.kitlangton.dev` origin. Signing refuses a key that does not match
the public key compiled into HEX, and publishing refuses a non-monotonic stable
release. Builds use `-DGGML_NATIVE=OFF` so the CPU kernels stay portable, and the
static runtime in `.cargo/config.toml` keeps the Visual C++ Redistributable
unnecessary; the release workflow asserts neither Windows executable imports it.
Use `termctrl` to verify TUI changes at both wide and narrow dimensions. The
dashboard keys are `1` for commands, `2` for the activity log, `3` for meetings,
Tab to cycle, and `q`/Escape to quit.
## Diagnostics
- `~/Library/Application Support/hex/logs/live.ndjson`: state,
transcript, command decision, outcome, processing, and context.
- `~/Library/Application Support/hex/logs/process.log`: Rust,
CoreAudio, Moonshine, and context-adapter diagnostics.
- `~/Library/Application Support/hex/meetings/`: manifests, separate
tracks, recoverable live drafts, and atomically published final transcripts.
Older macOS builds used `voice-control`; the first launch of a newer build
renames it to `hex` and leaves a `voice-control -> hex` symlink. If the rename
fails, Hex keeps using `voice-control` and logs why. Windows and Linux keep
`voice-control`.
When diagnosing a missed command, inspect both logs and distinguish microphone
capture, transcription, command mode/dictation, context matching, command resolution,
and action execution before changing aliases or thresholds.
## Future Direction
See `ROADMAP.md`. Do not add hypothetical seams for roadmap items. Introduce a
seam once there are two real adapters or a current test requires substitution.
## Current Work
`ROADMAP.md` is the authoritative work list. Keep these constraints visible:
- Validate public onboarding from a clean macOS account and signed Linux updates
on the supported Arch/i3 host.
- Validate native Wayland on a real compatible compositor, including physical
device reconnect, focus/click-through, target paste, and tray-less shutdown.
- Add a second real browser adapter before generalizing browser context.
- Do not turn concrete macOS, Linux X11, or command modules into hypothetical
platform or plugin frameworks.