herdr-web-ui / server
AGENTS.md459 starsChanged 2 months agoMITView on GitHub
Bun backend: HTTP API + WebSocket fan-out over herdr's unix-socket API, plus the PTY attach sidecar. The attachment lifecycle and transport quirks live here and nowhere else.
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.
Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository2 other files it gives its agents.
- AGENTS.mdAGENTS.md
- src/AGENTS.mdAGENTS.md
The file
We split this AGENTS.md into the rules it gives an agent
5 rules. About 0 are common, 0 are distinctive, and 5 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
5
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 6
Never let an attachment outlive its last client.
- Very specific: line 7
Never attachments.set outside spawnAttachment, and never await between that set and new PtySession(...): the record's pty is a placeholder …
- Very specific: line 8
Never add the client to attachment.clients before checking client.data.attached still holds the pane after the await.
- Very specific: line 9
Always resize the pty from the geometry of an INTERACT client's attach (attach handler calls resizePty when mode === "interact").
- Very specific: line 11
Keep herdr/ free of HTTP concepts — it speaks only herdr's socket protocol.
≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
server/
Bun backend: HTTP API + WebSocket fan-out over herdr's unix-socket API, plus the PTY attach sidecar. The attachment lifecycle and transport quirks live here and nowhere else.
ANTI-PATTERNS
- Never let an attachment outlive its last client. Cleanup paths:
detach/closefor members (detach()closes on an empty client set),releaseUnclaimedfor an attach cancelled mid-creation,onExitfor a pty that died,stop()for everything. - Never
attachments.setoutsidespawnAttachment, and never await between thatsetandnew PtySession(...): the record'sptyis a placeholder until then. - Never add the client to
attachment.clientsbefore checkingclient.data.attachedstill holds the pane after the await. - Always resize the pty from the geometry of an INTERACT client's attach (
attachhandler callsresizePtywhenmode === "interact"); an observe attach never resizes. Never spawnherdr terminal attachwithout cols/rows. - Answer in-band: handler failures are sent as
{type:"error"}frames. The only deliberate closes are 4008 (output stall/overflow), 1008 (device revoked) and 1012 (relay/PC gone). - Keep
herdr/free of HTTP concepts — it speaks only herdr's socket protocol; HTTP shaping belongs in index.ts.
CONVENTIONS
attachments: Map<paneId, PaneAttachment>holds{ pty, clients, cols, rows, replay }.cols/rowsare the pty's current grid:resizePtyupdates them and broadcastspane-geometryto the pane's clients whenever they change.replayis a bounded 256KB tail sent to clients that attach late;pty-exitbroadcasts first, then closes the attachment.createServerstartsstartStatusCollector(collector.ts): per-paneagent_status_changedfor EVERY pane in the snapshot plus a global pane.created/pane.closed/pane.exited subscription. Every stream reopens itself when herdr closes it (events_lost, restart) with 250 ms→5 s backoff; a lifecycle stream that comes back reconciles, and a lost status stream resyncs from a snapshot taken after the new subscription started. Its callbacksbroadcastAllpane-status/pane-exited/session-changedto every connected client —pane-statusno longer depends on attachment. The client set is tracked in aclientsSet (open/close).- Sidecar protocol (pty-host.mjs): argv
<cols> <rows> <command> [args...]; stdin newline-JSON frames —{"t":"i","d":"<text>"}writes,{"t":"r","c":cols,"r":rows}resizes; stdout is raw pty bytes unmodified; exit mirrors the child's code; sidecar clamps cols/rows to 1..1000. - Output control adds
{"t":"p","paused":true|false}. Parent pause and stdout backpressure are independent; both must clear to resume. Kill resumes the reader to observe EOF and has a bounded forced cleanup. PtySession awaits stdout EOF before reporting process exit. - ACK-capable attaches carry
flow_control:"ack";pty-data.flowidentifies the subscription and cumulative UTF-8 byte offset.pty-ackreleases only already-sent credit in that subscription. Pause at 256 KiB, resume at <=64 KiB, close consumers blocked for 2s with code 4008; 1 MiB hard application/transport budgets.-1from Bun send is already queued, never retransmit it. Legacy clients have the transport cap only. See docs/terminal-flow-control.md and server/output.contract.test.ts. HerdrError.code→ HTTP status (http.tserrorResponse):connect_failed/timeout→ 502; other HerdrError codes → 404; anything else → 500internal_error.- Auth: auth.ts
isAuthenticatedaccepts theherdr_web_tokencookie or an Authorization Bearer (length-safe compare); access.tsdecideAccess(token → device cookie → Tailscale owner → loopback local → pairing) runs for /ws and every /api/* route except /api/health, /api/auth and /api/devices/pair; static files stay open. - An unauthenticated /ws upgrade is refused with a plain-text 401
unauthorized(the WS client never parses a body); every other refusal is the JSON envelope. terminalInfoForresolves pane_id →{ terminalId, rect }from one freshsession.snapshot(rect = the pane'slayouts[].panes[].rect, null when absent); missing pane →pane_not_found, pane without terminal →no_terminal.- The layout
rectis NOT the terminal's current size (measured on herdr 0.9.3): it stayed 120x40 while aterminal attachsized the pane 100x30, then 140x40, and the pane kept 140x40 after that attach left. Only the attached client's size is real; nothing in the API tells another bridge's size. An attachment started again (held retry, live handoff) therefore reuses its own cachedcols/rows(#363 review). - Attachment creation:
ensureAttachmentreturns the existing record, else joins the in-flight creation inpendingAttachments(cleared infinally), else startsspawnAttachment. An observe-first creation spawns at the pane's rect (fallback 80x24), never the observer's grid; an interact-first one at the client's grid. - The
attachhandler records the pane inclient.data.attachedBEFORE awaiting the creation, so adetach(the client's pane switch sends detach-old then attach-new) orcloselanding mid-creation cancels it; on resume a cancelled attach callsreleaseUnclaimed, which closes the record only if it has no clients AND no other client still has the pane inattached(a joiner of the same creation that has not resumed yet). A failed creation removes the pane fromattachedagain. closeAttachmentremoves the pane from every member'sattached: after a pty exit the members sit on "terminal ended" and a stale entry would read as a live claim inreleaseUnclaimed.- An attach exit (not a read race,
attach_heldor a retired refusal) is not yet the pane's end:endedlooks the pane up every 100 ms forATTACH_RELOOKUP_FOR_MS(5 s). A newterminal_id(herdr live handoff) starts a new attach for the same clients; a gone pane getspty-exitat once; the same terminal or an unreachable herdr gets it at the deadline. The timer isattachment.relookup, cleared incloseAttachment(#370). - SocketData holds
attached,mode, per-paneoutputwindows and aclosingflag. An observe connection'sinput/keys/resizeanswer{type:"error", code:"read_only"}, and itsattachnever resizes the pty — it receives the currentpane-geometryand adopts it. Observers can acknowledge output. - WS
keysmessages go through herdr RPC (pane.send_keys), not the pty;inputgoes straight into the pty. - Malformed client frames get
{type:"error", code:"invalid_json"}back; the connection is never dropped for a bad frame. - Malformed roles (
rolewith anything but interact/observe) and impossible geometry (non-integer or outside 1..1000 cols/rows) answerinvalid_role/invalid_geometryerror frames. - On
openevery client immediately receivessnapshot; if that herdr call fails it gets anerrorframe carrying the herdr code orsnapshot_failed. createServer({ port: 0, stateDir })boots on an ephemeral port (how the contract tests run it, always with a temp stateDir);stop()closes every attachment beforeserver.stop(true).- Push state (push.ts): VAPID keys load-or-generate lazily on first need; subscriptions keyed by endpoint, persisted via temp+rename 0600; 404/410 → delete + persist, other failures → log + keep.
seed(panes)replaces titles and only FILLS missing status baselines (an event is newer than any snapshot). Payload = shared/protocol.tsPushPayload; TTL 12h; urgency high for blocked. - The collector calls
onBaseline(snapshot.panes)on EVERY reconcile (before the same-set early return): without it the first status event after a restart has no baseline and is dropped as a first sighting.
REMOTE BRIDGES
- Machine proxy forwards only allowlisted pane/workspace routes and its own bridge bearer credential. Never forward browser cookies/Authorization or remote Set-Cookie.
- SSH askpass secrets are in memory through private Unix sockets; persistent private keys and registries are 0600. Host-key changes fail closed.
- Remote process replacement requires explicit setup update approval, authenticated bridge/PID verification and managed_remote ownership. Never stop herdr itself or an independent bridge.
- Bundled runtime releases are immutable checksum-addressed directories. MachineRelay carries ACKs unchanged; never acknowledge remote output before the browser has parsed it.
WHERE TO LOOK
| Task | Location | Notes |
| SSH remote PCs | machines.ts + ssh.ts + machine-api.ts + machine-relay.ts; shared/machines.ts | PC-scoped APIs/SSE/WS; private versioned runtimes, same-socket bridge reuse, explicit setup/update approval; docs/remote-pcs.md |
| HTTP routing / static serving | index.ts createServer().fetch | route order matters (root AGENTS.md); /api/machines/local/* rewrites to /api/*; handler modules return a Response, or null to fall through |
| Updating herdr itself | herdr-update.ts (HerdrUpdater, handleHerdrUpdateRequest) + GET/POST /api/herdr/update in index.ts | runs herdr update --handoff with every HERDR_* variable removed, stdin closed and HERDR_SOCKET_PATH set to this server's herdr, then herdr server live-handoff when herdr status --json says the binary differs from the server; only the real entrypoint passes herdrUpdate, so tests offer nothing unless they pass a stand-in herdr. NEVER run the real herdr update in a test: it replaces the herdr on PATH (#373) |
| App updates | managed.ts (launcher) + supervisor.ts + updater.ts + update-api.ts + update-state.ts | launcher runs the active release's supervisor and falls back if it dies before ready; supervisor owns Git/build/restart and exits 75 (HANDOVER_EXIT) after an install so the new supervisor takes over; bridge relays status/commands over IPC; /api/updates* gated + POST custom-header/same-origin guard; no update side effects in createServer tests; real Git/build/IPC/rollback tests in updater.test.ts |
| Workspace / agent HTTP endpoints | index.ts + herdr/client.ts | /api/agents and /api/workspace/create/rename/move/close; creation validates cwd and may start an agent in the root pane |
| Slash-command discovery | commands.ts + GET /api/pane/commands in index.ts | per-agent built-ins; Claude user/project .claude/commands/**/*.md |
| File mention search | files.ts + GET /api/pane/files in index.ts | git inventory or bounded walk, ranked filtering, 5s cwd cache |
| Chat-lens transcripts | conversation.ts + codex.ts + GET /api/pane/conversation in index.ts | Codex native rollouts: session metadata/open descriptors first, unique substantial pane-text match for shared app-server TUIs; canonical store paths only, no subagent sessions, no cwd-recency guess. createServer({ codexHome }) isolates test stores. claude/omp use agent.get; omo uses its process tree + own store. Cache compares inode/size/mtime; end_ts records actual assistant activity. |
| Interactive pane prompts | prompt.ts + /api/pane/prompt routes in index.ts | visible-screen parser and responder-specific key/text answers; prompt hashes prevent stale answers |
| Model / reasoning metadata | conversation-metadata.ts + conversation.ts cache | Latest recorded settings only: Codex turn_context, omp/omo model_change + thinking_level_change, Claude message.model. HTTP metadata.model / metadata.reasoning_effort use null for unknown values; never infer effort from thinking text. |
| Background task state | conversation.ts taskNotice / placeStrayNotices | Claude's <task-notification> (a user turn, a queue-operation enqueue, or a queued_command attachment) sets task: { status, summary } on the tool part its <tool-use-id> names and never shows as a turn. The newest page parses in stretches, so notices a stretch cannot place are matched to earlier stretches by tool_use id (kept in a WeakMap, off the wire). Older pages are not revisited. |
| PTY spawn/write/resize/kill | pty/session.ts (PtySession) + pty/pty-host.mjs | sidecar protocol above |
| Web push | push.ts (createPushService, handlePushRequest) | wired in index.ts: collector onStatus/onPaneEnded → push.onStatus/onEnded (rejections logged, never unhandled), onBaseline → push.seed, onResync (after a lost status stream) → push.resync; lookupTitle = fresh session.snapshot |
| Image paste | paste.ts (savePaneImage, PasteImageError) | POST /api/pane/image (index.ts): file under <pane cwd>/.herdr-web-ui/ (0600, tmpdir fallback when cwd is null), or under HERDR_WEB_PASTE_DIR when the server's environment sets it (pasteDirectory, read on every save: ~/… is the home directory, a relative value resolves against the server's cwd), ≤8MB png/jpeg/gif/webp; PasteImageError carries its own status (413/415/400) which the route maps to the shared envelope; unknown pane is the usual herdr pane_not_found |
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

