This document describes the high-level architecture of Herdr Perch. If you want to find your way around the code, start here. It names modules and types rather than linking to them; use symbol search to jump to them.
Perch is a macOS menu bar app that shows the state of every coding agent running in Herdr in the MacBook notch. It is a read-only companion: Herdr owns all agent state, and Perch's job is to mirror it with low latency and to surface what needs attention.
Herdr comes in two shapes, and Perch follows both at once: the Herdr TUI (one server per session, the "legacy" backend in the code), and herdr-core (hc), the terminal runtime behind the Herdr app.
~/.config/herdr/herdr.sock Herdr TUI: one server per session
~/.config/herdr/sessions/<name>/herdr.sock NDJSON, one request per connection
│
▼
PerchCore SessionRegistry ─▶ SessionRuntime × N ──┐
├─▶ PerchStore.rows: [AgentRow]
CoreRegistry ─▶ CoreRuntime × N ─────────┤
▲ │
│ JSON-RPC, a pushed event stream │ HerdrAppMirror ◀── ls (Done verdicts)
~/.local/state/herdr-core/<s>/<s>.sock │ ▲
│ ~/.config/herdr-app/herdr-app.sock
▼
PerchApp NotchModel ─▶ PresentationState ─▶ SwiftUI views in a NotchPanel
perchctl the same runtime, printing rows as JSON (debugging, end-to-end tests)
Data flows one way. Each Herdr TUI runtime keeps the latest session.snapshot of its server; each herdr-core runtime keeps a mirror of its session's terminals. PerchStore turns both into one sorted list of AgentRows, which is the only thing the UI ever sees. The only calls that change anything are focusing a pane (Herdr TUI) or showing an agent (Herdr app) after the user clicks a row.
The package has three targets and no third-party dependencies.
Everything that talks to Herdr and derives state. Shared by the app and perchctl, so end-to-end tests can exercise discovery, subscription and state without driving the UI.
Architecture invariant: PerchCore does not import AppKit or SwiftUI.
Herdr/— the Herdr TUI socket client.SocketConnectiondoes one request per connection (Herdr closes a connection after one response);HerdrClientwrapsping,session.snapshot,events.subscribeand the three focus calls.Modelsdecodes snapshots leniently: an agent or pane missing a required field is skipped, not fatal. Unknown status strings decode asunknown.Core/— the herdr-core client.CoreModelsdecodes terminal records and event notifications leniently;CoreMirroris the pure reducer that applies events to a snapshot inseqorder;CoreClientholds the long-lived subscription.HerdrApp/—HerdrAppClienttalks to the Herdr app's control socket (ls,agent.focus);HerdrAppMirrordecides when to read it.Discovery/—SessionScannerlists Herdr TUI sessions by looking for socket files:<root>/herdr.sockis the default session,<root>/sessions/<name>/herdr.sockare named ones.CoreScannerdoes the same for herdr-core:<state>/herdr-core/<name>/<name>.sock. Neither runs a CLI; both ignore symlinks.Sync/— when to refresh.SubscriptionPlandecides which events to subscribe to,PollingPolicythe fallback polling interval, andRefreshSchedulercoalesces refresh requests (50 ms window, at most one snapshot in flight, one more if requests arrive during a read).Runtime/—SessionRegistryscans every second, starts aSessionRuntime(an actor) per reachable session and removes it when its socket disappears;CoreRegistryandCoreRuntimedo the same for herdr-core.PerchStore(main actor,@Observable) publishes rows and both kinds of sessions, and ownsSeenTurns.Jumperruns the focus chain.StateTracewrites every published row list as NDJSON whenPERCH_TRACEis set.State/— pure derivation.RowBuilderturns Herdr TUI session states intoAgentRows and owns the display order;CoreRowBuilderdoes it for herdr-core;StatusClockremembers when each Herdr TUI agent was first seen in its current state (for durations and ordering);SeenTurnsdecides Done for herdr-core agents;TitleCleanerstrips prompt characters and icons from titles such asπ > ….
Architecture invariant: Herdr is the only source of truth for status. Displayed state is a direct mapping of what the latest snapshot (Herdr TUI) or the event-ordered mirror (herdr-core) reports. The only local memory is StatusClock (Herdr TUI timing) and SeenTurns (whether a herdr-core finish has been seen; see below).
The executable: an .accessory app with a status item and a borderless panel over the notch.
App/—AppDelegatewires the store, model and windows together.Preferencesloads and saves settings inUserDefaults;SettingsViewholds the one-page Settings window and the About window;MenuBarControllerowns the status item.Presentation/— pure logic, unit-tested without a window:PresentationState(the notch state machine, see Presentation),CompactSummary(what the collapsed notch shows per style),ListGroups,PeekLayout,PointerTracker(turns mouse positions into enter/exit/click events),HerdrStatus.Views/— SwiftUI.NotchModelconnects the store to the reducer and owns timers and sizing;NotchRootViewdraws the shape and its three always-mounted layers (collapsed band, peek cards, list);ListViewholds the grouped list and the peek cards;PixelRamandAgentIcondraw the mascot and the agent marks.Window/—NotchPanel(a non-activating panel at status bar level, on all spaces and over full-screen apps),NotchGeometry(every size, derived from the screen),NotchWindowController(placement and mouse handling).Platform/—TerminalActivatorbrings the user's terminal forward after a jump;HerdrAppWatchertells the store whether the Herdr app is running and frontmost, and brings it forward after a jump.
Architecture invariant: types in Presentation/ are pure. Time is passed in (handle(_:now:)), and the caller schedules a .tick at nextTick.
A small CLI over PerchCore: dump prints the current rows once, watch prints them on every change (same format as StateTrace), jump <session> <pane> runs the Herdr TUI focus chain. --root and --core-root point it at other state directories. Used for debugging and by the end-to-end tests.
scripts/—bundle.shbuildsdist/Herdr Perch.app(the version number lives here),make-dmg.shpackages it,smoke.shandperf.shexercise the packaged app,demo.pyrecords the README GIFs,make-icon.pygenerates the app icon.Tests/PerchCoreTests,Tests/PerchAppTests— unit tests (swift-testing), with recorded Herdr responses inFixtures/.Tests/E2E— end-to-end tests in Python (uv + pytest) against a disposable Herdr session.Tests/Support/PointerDriver.swift— posts mouse events and reads the notch through Accessibility, forperf.sh,smoke.shanddemo.py.
Perch needs Herdr 0.9.5 or later (socket protocol 22). Facts about the protocol that shaped the design:
- One request per connection. Herdr answers one NDJSON request and closes the connection; writing again fails with
EPIPE.events.subscribeis the only long-lived connection. Sockets setSO_NOSIGPIPE, and every request has a 2 s timeout. - Status changes have no global event.
idle → workingorworking → doneonly show up aspane.agent_status_changed, which must be subscribed per pane (a subscription withoutpane_id, or with an unknown pane, rejects the whole batch and closes the connection).SubscriptionPlantherefore subscribes to a set of global topology events plus status events for every pane in the snapshot, and resubscribes when the pane set changes. - Events are invalidation signals. Snapshots and events share no sequence number, and Herdr does not replay history (
events_lostmeans "start over"). The runtime subscribes first, then reads a snapshot and replaces its state wholesale; any event, of any name, just requests another snapshot. donebelongs to Herdr. An agent that finished in a tab nobody has looked at isdone; focusing the tab, in Herdr's TUI or through Perch's jump, turns it back intoidle. Perch keeps no "seen" state of its own.- Titles and labels come from Herdr. Row titles use
name, thentitle/terminal_title_stripped; subtitles usestate_labels. Perch does not read the screen.
Architecture invariant: Perch never writes to Herdr except workspace.focus, tab.focus and pane.focus, in that order, after a click, and agent.focus to the Herdr app (below). It installs no hooks, changes no configuration and starts no processes.
(absent) ──socket found, ping ok──▶ live ──snapshot fails──▶ stale (rows grey, "Reconnecting…")
▲ │
└──── snapshot ok ────────┤ 30 s
socket removed (any state) ─────────────▶ removed ◀────────────┘
- A protocol older than 22 gives a placeholder session with health
updateRequired. - Polling is only a fallback: every 3 s while the event stream is healthy, 0.5 s while it is not, and 1, 2, 4, 8, 10 s while the server is unreachable.
- A rejected subscription (usually a pane that just closed) triggers a refresh and a resubscribe with backoff; it does not mark the session stale.
- Targets: a new session appears within 1.5 s, a stopped one disappears within 1.5 s, a hung server is marked stale within 6 s.
Perch speaks protocol generation 1 (herdr-core 0.1). The API is documented in herdr-core's schema/README.md and hc schema. Facts that shaped the design:
- Discovery. The client socket is
<session>.sockin the session's state directory,~/.local/state/herdr-core/<session>/(or under$XDG_STATE_HOME). herdr-core prefers$XDG_RUNTIME_DIRand honoursHC_SOCKET; neither is set for a macOS GUI app, so Perch only scans the state home. Holder and SSH sockets sit in the same directory and are ignored. - One long connection.
hellochecks the generation;events.subscribe {}returns a snapshot with aseqand then carries only notifications. Unlike the Herdr TUI, events are facts: each is applied to the mirror in order, duplicates (seqnot above the last) are dropped, andmissedor a reconnect replaces everything with a fresh snapshot (seqrestarts with each core process). A heartbeat comes every 15 s; 20 s of silence counts as a dead connection. Reconnects back off 1, 2, 4, 8, 10 s. - Status is what the program reports through OSC 7501 (
idle,working,done,blocked,error); a program that never reports has no status and no row. Perch shows only live terminals with a status, including other machines' (box/t7) and sub-agents (parentset).erroris shown with the blocked agents. - Timing.
status_msin records is when the word last changed; status events carry no time, so the mirror stamps one when the word changes (not when only the message does). - Titles and places. The title is the terminal
name, then the report'stitle, then the terminal title; the status line is the report'smsg. The project is the Herdr app'swherelabel (space / tab), else the working folder. - Done. herdr-core has no idea whether a person looked; the Herdr app keeps that in memory (an agent that stops working while you aren't looking is
doneuntil you look). When the app runs, Perch reads its verdicts fromherdr-app ls— every second while the app is frontmost, once when it leaves the front, once when it starts — and while the app is frontmost a status change waits for a fresh verdict before it is shown, so an agent finishing in plain view never flashes Done or peeks. For agents the app doesn't show, or when it isn't running,SeenTurnsdecides: Done when the status isidleordoneand the terminal'sturnhas moved past the last one seen (first sight, a jump from Perch, or an app verdict ofidle).SeenTurnspersists in Application Support so a restart doesn't forget unseen finishes; it forgets a terminal only when a connected session no longer has it. - Jump. A click on a herdr-core row sends
agent.focusto the Herdr app's control socket and activates the app. Without the app, Perch says so; it does not open terminals.
Architecture invariant: Perch only reads herdr-core (hello, events.subscribe). It sets no labels, writes no documents, and starts nothing.
The notch is in one of four surfaces:
| Surface | Shows |
|---|---|
hidden |
Nothing: no agents in any session. |
collapsed |
The band around the camera housing: the ram (coloured by the most urgent agent) and a summary in the chosen style (Clean, Dots, Counts). |
peek |
440 pt wide: up to three cards for things that need attention, then "+N more". |
expanded(pinned:) |
640 pt wide: status counts, then agents grouped into Needs you, Done, Working and a folded Idle. |
Transitions, all in PresentationState:
- Hovering for 120 ms opens the list from
collapsedorpeek; leaving an unpinned list closes it after 280 ms. Clicking pins or unpins it. Clicking a row jumps and collapses. - Something new that needs attention (a newly blocked agent, a Herdr connection problem, or a newly finished agent when "Peek when an agent finishes" is on) moves
collapsedtopeekand adds a card. While the list is open, the matching row flashes instead. - A peek closes on its own: 8 s after the last blocked card arrived, 6 s for connection cards, 4 s for finished ones. A card leaves as soon as its reason does (the agent is no longer blocked, the session reconnects), and an empty peek collapses at once. Clicking outside does not dismiss it.
Architecture invariant: Peek is the only way Perch asks for attention. It never opens the full list by itself.
New events are found by diffing consecutive Attention values (blocked agents, finished agents, system alert). Stale rows and herdr-core sub-agents are left out: a sub-agent's parent speaks for it, as in the Herdr app. On the first update, finished agents are taken as a baseline, so agents that were already done at launch stay quiet. Cards are ordered blocked, then system, then finished; newest first within a kind.
The panel keeps a fixed canvas, large enough for the biggest shape plus its shadow, and only moves when the screen changes. Every size change is a SwiftUI animation inside that canvas, so AppKit frame changes never fight the spring. While collapsed, the panel ignores the mouse; global and local NSEvent monitors plus geometry produce pointer events, so clicks on menu bar items beside the notch go through. This approach comes from open-vibe-island.
On screens without a notch, the band is as tall as the menu bar (frame.maxY − visibleFrame.maxY) and the camera housing is replaced by a 190 pt floating center.
The look and motion follow Vibe Island, measured frame by frame from recordings of the app:
- Size:
spring(response: 0.36, dampingFraction: 0.9)opening and0.95closing — about 90% in 0.2 s, settled by 0.35 s, under 1% overshoot. - Corner radius 10 collapsed, 14 open (
easeOut, 0.3 s); fixed 6 pt concave shoulders outside the shape. - Layers fade by opacity only (0.15 s in, 0.1 s out) and are laid out at the shape's current width on every frame, so titles truncate to the moment's width instead of overlapping. No blur or scale.
- The centering frame must sit inside the size animation; otherwise the shape jumps to its final position while its width is still animating.
- The ears ride the shape's edges and fade within ~80 ms when opening.
- Pixel art is drawn on whole pixels: 1 pt cells (2 px on Retina), one path per colour so fractional scales leave no seams.
Only a blocked ram animates. Nothing animates while the notch is collapsed and every agent is idle or done.
- Unit tests (
swift test) cover every pure piece: protocol decoding against recorded fixtures, an in-process fake Herdr server for the client and runtime, refresh scheduling with an injected clock, row building, title cleaning, the presentation reducer, geometry and preferences. - End-to-end tests (
Tests/E2E) start a disposable Herdr session namedperch-e2eand drive agent states withpane.report_agent; the herdr-core ones start a disposable core (HC_SESSION=perch-e2ewith scratch XDG directories) and report states by printing OSC 7501 in a shell. No real agents are needed. They checkperchctl watchoutput for latency and lifecycle, only ever write to their own session, and always stop and delete it. - Smoke test (
scripts/smoke.sh) builds and launches the app against the default session read-only, and checks it stays out of the Dock, matchesherdr agent list, and quits cleanly. scripts/perf.shsamples CPU in five scenarios. It moves the pointer unless run with--static.- Test hooks: with
PERCH_TEST_HOOKS=1, the app listens for distributed notifications that expand or collapse the notch without pointer events.PERCH_HERDR_ROOTpoints the app at another directory, such as a single demo session;PERCH_CORE_ROOTdoes the same for herdr-core, and an empty value leaves herdr-core out. Both are off in normal launches.
The repository is public. Test fixtures, sample data, the settings previews and the README recordings use fictional agents, titles and projects only, never real ones from a developer's machine.
Each Herdr TUI session costs one subscription connection and a snapshot every 3 s while idle (well under a millisecond); each herdr-core session one connection and nothing while idle but a heartbeat. The Herdr app is only polled while it is frontmost. Animations run only while something is visible and moving. The idle target is under 0.5% CPU and 60 MB of memory.
Stored in UserDefaults under: compactStyle, displayPlacement, peekOnFinished, cleanTitles, followReduceMotion, launchAtLogin. Missing or unknown values fall back to defaults; keys from older versions are ignored. Settings change presentation only; nothing that affects correctness (polling, socket paths) is configurable.
Perch is GPL-3.0. Parts of the Herdr client and terminal activation derive from NotchAgent (Apache-2.0, see LICENSES/); the overlay window and pointer handling follow open-vibe-island (GPL-3.0). Derived files say so in a header, and NOTICE lists every source, including the agent marks.