Swift rewrite of the dictation client (hark serve / hark agent) - #12
Conversation
Spec for DRYCodeWorks#2. Decisions: an LSUIElement bundle with a menu bar status item, capture absorbed in-process so rec stops being a child binary, config at ~/.config/hark/client.json with the key read from the server's own key file on a single-machine install, and Carbon RegisterEventHotKey rather than an event tap. The hotkey choice is the load-bearing one. RegisterEventHotKey needs no Accessibility grant, so the agent asks for permission to type rather than permission to watch you type. An event-tap agent would need exactly the all-or-nothing grant that made the Hammerspoon arrangement uncomfortable. It also makes two currently-silent failures visible: a missing Accessibility grant and a hotkey chord already owned by another app. Measured while writing this and folded into the design: identical Swift sources produce a different CDHash on every build. install-client.sh recompiles unconditionally today, which is harmless only because TCC attributes to Hammerspoon. Once the agent is the TCC principal, an unguarded rebuild invalidates its own Accessibility grant, so the installer has to hash its build inputs and skip the build when they match. Nothing on the user's machine gets deleted on migration. client/init.lua becomes a stub that binds no hotkey, so an existing symlink keeps resolving and the two clients never fight over the hotkey. Claude-Session: https://claude.ai/code/session_01VhMX8fBDkrNDpCmPYGycYX
All six reviewers returned REVISE on revision 1, and two of them independently killed its central argument. Revision 1 chose Carbon RegisterEventHotKey on the grounds that it asks for permission to type rather than permission to watch you type. That is wrong: synthesising Cmd+V needs Accessibility, and Accessibility is one atomic grant that also permits creating an event tap. It also claimed the API errors when another app owns the chord; the SDK header says the opposite and exclusivity needs kEventHotKeyExclusive. The mechanism is now undecided behind a Phase 0 spike, whose real question is whether a keyboard tap additionally needs Input Monitoring — README:245-247 suggests from this project's own experience that it might, which would revive the permission argument by a different route. Assuming a Developer ID deletes rather than fixes a whole section. CI builds, signs and notarises; the installer downloads instead of compiling, so it can no longer mint a new CDHash on every re-run and the input-hash guard goes away. It also drops the Xcode command line tools from the client machine, which is the point of the surrounding dependency work. Security findings that were missing entirely: the client never sanitised the server's response, so a spoofed server on the plaintext two-machine path could return a newline and have it typed into a terminal. There was no transport policy and no ATS declaration, so the client would have captured audio and then failed every POST. 400 was mapped to "microphone permission" inherited from the Lua client, but capture failures no longer reach the server and the server returns 400 for every InvalidAudioError, including a malformed header this client now builds by hand. Migration was insufficient rather than merely incomplete. A stub does not unload Lua already running in Hammerspoon, and leaving its grants in place preserves exactly the privilege escape this work exists to close. Also corrected: revision 1 claimed tests/test_audio.py pins the wire format. It validates sample width only, so a stereo 44.1 kHz WAV passes today. Claude-Session: https://claude.ai/code/session_01VhMX8fBDkrNDpCmPYGycYX
Round 2 of the panel returned 5 REVISE / 1 APPROVED. Almost every remaining objection was the same shape: the design named a mechanism without saying what it actually does. A length cap with no number is not a security contract, and a generation stamp that bash cannot verify is not a freshness check. Concrete now: 1 MiB response body enforced before JSON decoding, 8 KiB sanitised text, reject rather than truncate; a 5 s starting deadline separate from a 120 s capture cap, because rec.swift:167 arms its ceiling only after the first buffer; and a status file bound to the agent by PID plus process start time with a 30 s heartbeat, which is something --doctor can check from bash. The transport section contradicted itself, prohibiting non-loopback HTTP while promising a Tailscale opt-in that had nowhere to live. It now has one: an explicit per-host allowlist in client.json. Tailnets already encrypt at the network layer, so HTTP there is defensible, but it should be a stated choice rather than a silent default. Two things the panel found in shipped code rather than in the design. app.py:103-107 returns microphone advice for every InvalidAudioError and test_app.py:107 asserts that wording, so a malformed header from this client would send users to the wrong settings pane. And migration cannot claim to confirm Hammerspoon released the hotkey, because macOS exposes no way to ask WindowServer who owns a chord; confirmed process exit is the most that can be said. Claude-Session: https://claude.ai/code/session_01VhMX8fBDkrNDpCmPYGycYX
Round 3 found two contradictions I introduced. Per-host NSExceptionDomains cannot follow client.json, because that key lives in the signed Info.plist and writing to it after download invalidates the signature. Restricting insecure HTTP to IP literals lets a static NSAllowsLocalNetworking cover it without the plist naming any host. The migration also deadlocked: it required the agent verified healthy before quitting Hammerspoon, while the agent cannot register the hotkey until Hammerspoon releases it. Registration is now split out of the health check and happens after handover, with rollback that restores the symlink and relaunches Hammerspoon. Claude-Session: https://claude.ai/code/session_01VhMX8fBDkrNDpCmPYGycYX
Round 3 brought the panel down to two contradictions and a format bug, all of which I had introduced. Per-host NSExceptionDomains cannot follow client.json: that key lives in the signed Info.plist, so writing to it after download invalidates the signature and macOS kills the app at launch. Restricting insecure HTTP to IP literals lets a static NSAllowsLocalNetworking cover the case without the plist ever naming a host. A MagicDNS name is consequently not usable over HTTP; use the tailnet IP. The migration deadlocked. It required the agent verified healthy before quitting Hammerspoon, while the agent cannot register the hotkey until Hammerspoon releases it. Registration is now split out of the health check and happens after handover, with rollback that restores the symlink and relaunches Hammerspoon. The status file proposed matching an ISO timestamp against ps -o lstart, which prints a localised non-ISO string. It now stores what ps prints, verbatim, plus an epoch integer, so --doctor compares strings and integers rather than parsing dates. It also carries hotkey and login-item state, since a heartbeat that omits them passes while the product does not work. Also settled rather than deferred: response bounds now cover the error detail string, not just the transcript; the paste-target guarantee is stated at application granularity because that is all it enforces; and the clipboard self-clears after 90 seconds when changeCount is unchanged, which keeps the paste-recovery window the original decision wanted while bounding an exposure any local process could harvest. Rebased onto 8d12f7b. That matters more than usual here: the branch was cut from 4e35977 and main has since moved by eleven commits, so every line number in the document was stale. All of them are re-verified against 8d12f7b. Two sections changed meaning as a result. The zero-frames concern is no longer speculative, because DRYCodeWorks#9 was confirmed and fixed in 559aafe, and that commit is now cited as the reference implementation for the agent's permission handling rather than something this design has to invent. And two thirds of the superseded-spec work in the blast radius is already done by ef47aeb and c852392, so the document now points at what remains instead of repeating it. Claude-Session: https://claude.ai/code/session_01VhMX8fBDkrNDpCmPYGycYX
The verification pass returned 4 APPROVED / 2 REVISE, and both holdouts found real contradictions. Rollback restored the symlink, but this same change turns client/init.lua into a no-op stub, so the restored symlink pointed at a client that does nothing. The installer now preserves the working Lua client to ~/.config/hark/legacy-client.lua before cutover and repoints there on failure. It also writes an ownership record, because content-matching the symlink target cannot survive the repo moving: an absolute symlink to a moved checkout is dangling, and there is no content left to match. Rollback also left the agent installed while SMAppService.register() ran unconditionally at first launch, so a rolled-back install would start the agent at the next login and fight the Hammerspoon it had just restored. Registration is now the last step of a successful cutover rather than part of launch, and rollback unregisters. And xcrun stapler was required on the client two hundred lines after this document claimed the client no longer needs the Xcode command line tools. stapler ships with Xcode; the staple check moves to CI, where the toolchain already exists, and the client verifies with stock spctl and codesign. A downloaded artifact is quarantined, so spctl exercises the notarisation path anyway. Claude-Session: https://claude.ai/code/session_01VhMX8fBDkrNDpCmPYGycYX
Single hark binary with two roles (hark serve, hark agent) plus packaging under swift/Packaging. Full SwiftPM suite is green (48 tests): Config, Sanitize, WAV, Server, Integration, E2E, DictateClient, KeyFile. - DictateClient: construct URLSession with delegate:self so delegate callbacks fire. A bare URLSession(configuration:) never delivers them, which hung the synchronous dictate() path on its semaphore forever. - IntegrationTests: retain the HarkServer strongly (released in tearDown) so it isn't deallocated mid-test — its connection handler holds weak self.
|
Heads up: I duplicated a chunk of this in #13/#14 before spotting this PR — I checked open issues and not open PRs, so I read #2's "Open questions" as still live when #10/#11 had already settled them. My fault, and #13/#14 will be closed as superseded by this one. That does mean the agent side got run on real hardware — two Macs, both now dictating on it, Hammerspoon uninstalled and its grants revoked. Everything below is from that bring-up rather than from review, and two of them are live in this PR. Sharing so you don't have to pay for them twice. The paste is a zero-duration keystroke
down?.flags = .maskCommand
down?.post(tap: .cghidEventTap)
up?.flags = .maskCommand
up?.post(tap: .cghidEventTap)Some apps silently drop that. The implementation being replaced held the key for 200 ms — from Hammerspoon's local keyDelay = 200000
module.event.newKeyEvent(modifiers, character, true):post(targetApp)
timer.usleep(keyDelay)Same tap, same flags; the gap is the only difference. I used Worth saying that this was not what broke my first bring-up — an untrusted process was — but it is a real divergence from the known-good implementation.
|
|
Ran this on hardware — Studio, real dictation, against the existing Python server. It works now, and the integration commits are on Four defects, none visible to the 48 tests. Sharing the evidence rather than just the diffs. The hotkey misses almost every release — the Phase 0 spike, answered
Measured with a bare session tap over 45 s of ordinary use: One release out of dozens. In the agent that leaves a capture that never ends, and since Loosening the key-up test would mean tracking "a capture is open, end it on any space key-up", which re-implements something the OS already does. Switched to Carbon
|
Summary
Implements the native Swift client that replaces Hammerspoon (supersedes #10 design and #11 implementation plan). A single
harkbinary with two roles:hark serve— HTTP server on 127.0.0.1:8911 (/health,/dictate) with key auth, wildcard-bind guard, WAV validation, and whisper forwarding.hark agent— hold-to-talk recorder + hotkey + DictateClient for the native app.Packaging under
swift/Packaging/(build-app.shproduces a signedHark.app).Test Plan
Full SwiftPM suite is green — 48/48 tests (Config, Sanitize, WAV, Server, Integration, E2E, DictateClient, KeyFile). Two fixes landed during bring-up:
URLSessionwithdelegate: self. A bareURLSession(configuration:)never delivers delegate callbacks, which hung the synchronousdictate()path on its semaphore forever.HarkServerstrongly (released intearDown) so it isn't deallocated mid-test — its connection handler holdsweak self.Also verified end-to-end: release build, ad-hoc codesign, and
GET /health→{"status":"ok"}HTTP 200.