hydra-ensemble

A cross-platform desktop app that runs coding-agent sessions in parallel, each in its own PTY, git worktree and config directory.

TypeScript · Tauripersonalopen source (MIT)Stack Tauri v2, Rust, React, TypeScriptLicense MITPlatforms Linux, Windows, macOSTerminal xterm.js over portable-ptygithub.com/javabetatester/hydra-ensemble

Overview

hydra ensemble is a desktop terminal for running several coding agents side by side. Each session is a real PTY running a provider CLI (claude, codex, copilot, cursor, grok), usually inside its own git worktree, with its own configuration directory.

The problem it solves is collision. Two agents in one checkout overwrite each other's files, and two sessions sharing one config directory share logins, locks and JSONL histories. Hydra gives every session a branch and a config dir of its own, so parallel work stays separable.

On top of that it watches each session. It classifies the PTY stream into a live state, tails the CLI's JSONL transcript for tokens and cost, and surfaces the result as a status pill per session. It also bundles a CodeMirror 6 editor with LSP, a toolkit of one-click commands, a floating quick terminal and a PR inspector.

AreaWhat it does
TerminalMulti-tab xterm.js with ANSI, true color, mouse and resize
IsolationOne git worktree and one provider config dir per session
Statusthinking, generating, idle, needs-attention from the PTY stream
CostToken and cost data read from the CLI's JSONL transcript
EditorCodeMirror 6 with LSP diagnostics, hover, completions and formatting
PR inspectorLists and diffs open GitHub PRs through the gh CLI

Install and run

Releases ship a .deb or AppImage on Linux, an NSIS .exe on Windows and a .dmg on macOS. To build from source you need a stable Rust toolchain, Node 22 as the renderer build tool, npm and git. Node is not a runtime dependency: the shipped app is a native Tauri binary.

Linux build prerequisites (Debian/Ubuntu)bash
sudo apt-get install libwebkit2gtk-4.1-dev libgtk-3-dev librsvg2-dev patchelf
Run from sourcebash
git clone https://github.com/javabetatester/hydra-ensemble.git
cd hydra-ensemble
nvm use
npm install
npm run tauri:dev
Production build and the Arch packagebash
npm run tauri:build
./scripts/install-arch.sh

Installers land in src-tauri/target/release/bundle/. On Arch the script builds a native .pkg.tar.zst into dist/arch/ and installs it, system-wide with --system or into ~/.local without sudo.

RequirementNeeded for
Claude Code (or another provider CLI) on PATHRunning sessions
gh, installed and authenticatedPR inspector
typescript-language-server, gopls, pyright-langserver, rust-analyzerEditor LSP per language; plain highlighting otherwise
WebView2 RuntimeWindows; preinstalled on 11, bundled with the installer on 10
SettingEffect
HYDRA_USER_DATAOverrides the user data directory, including keybindings.json
~/.hydra-ensemble/keybindings.jsonUser keybindings; a command starting with - removes a shortcut
portable.txt or data/ sentinelRedirects the sessions and accounts roots next to the binary
HYDRA_MCP=1Enables the MCP control plane
Quality gatesbash
npm run typecheck
npm run lint
npm test
npm run build
cd src-tauri && cargo check

Architecture

ptybranch aptybranch bptybranch c
Every session is a terminal wired to its own PTY and its own worktree branch.

A Rust core owns processes, files and git. A React renderer in the platform WebView owns the UI. They meet at one module, src/renderer/tauri-api, the only place that imports @tauri-apps/*.

text
WebView (React + zustand)
  views -> stores -> tauri-api (invoke / listen / Channel)
                          |
 Tauri core (Rust, src-tauri/src)
  commands + events (generate_handler! in lib.rs)
   |-- pty/        portable-pty, scrollback, coalescer
   |-- analyzer/   PTY stream -> session state
   |-- claude/     JSONL watcher, transcript parser
   |-- session/    lifecycle, config isolation, binding
   |-- git/        worktrees, status, diff, remote
   |-- accounts/   per-account config dirs
   '-- forge/      PR data via gh
                          |
   agent CLI in a worktree, own config dir, writes JSONL
  • Each Tauri command lives in its domain module and must be registered in the generate_handler! list in lib.rs.
  • Hot streams (pty data, LSP messages) use a Channel per window label; other events use AppHandle::emit.
  • Session state has two sources: the PTY analyzer and the JSONL watcher, which is authoritative.
  • Shared TypeScript contracts live in src/shared and are mirrored by serde camelCase structs in Rust.
  • Secrets go through the OS keychain (keyring crate) and never reach the renderer.

Session lifecycle

  1. 1Worktreegit_create_worktree runs git worktree add -b <name> under <repo>/.hydra-ensemble/worktrees/, based on the given or detected default branch. If the branch exists it retries without -b.
  2. 2Config isolationcreate_isolated_session writes ~/.hydra-ensemble/sessions/<id>/meta.json and picks a config dir: a saved account first, then a fresh per-session dir, then the host login.
  3. 3SpawnPtyManager::spawn starts the provider CLI in a portable-pty pair with a sanitized environment and the config dir variable exported on the launch line.
  4. 4StreamReader output is decoded, coalesced and sent to the window over a Channel; the same text is fed to the analyzer.
  5. 5TrackThe analyzer emits session:state; the JSONL watcher resolves the transcript and emits authoritative state, tokens and cost.
  6. 6TeardownKill drops the scrollback; destroy_isolated_session removes the session directory; git_remove_worktree runs git worktree remove --force.

State detection

ptyjsonlthinkinggeneratingidleattention
The analyzer reads the PTY text and lights one lamp per session; the JSONL ledger overrides it.

PtyStreamAnalyzer reads the ANSI-stripped tail of the output and compares the freshest position of four phrase families: working, thinking, idle and attention. The families are per provider (AnalyzerProfileId: Claude, Cursor, Grok, Generic). For Claude, working is for example "esc to interrupt".

  • States are SessionState: idle, thinking, generating, userInput, needsAttention.
  • Analysis is frame-throttled at THROTTLE_MS = 80 and looks at a recent-text window of 8000 characters.
  • A submit mark lives 8 s (SUBMIT_MARK_TTL_MS) and at most 45 s.
  • classify_pty_failure reads the same tail for refusal, quota and login failures.

Analyzer output alone can latch a wrong state, so the JSONL watcher overrides it. AnalyzerManager runs a watchdog every 2 s. A latched authoritative state older than 8 s (AUTHORITATIVE_STALE_MS) with a working state is re-evaluated, which reclaims sessions that stopped writing.

PTY streaming

The coalescer exists because of a measurement recorded in the code (spike F00.2): the cost of tauri::ipc::Channel is the message count, not the bytes. 2 KB chunks at a high rate froze WebKitGTK at 0.4 to 0.7 FPS, while the same volume in 32 KB messages ran fluidly at 165 MB/s.

ConstantValueRole
WINDOW12 msFlush even a small buffer so keystrokes stay interactive
FLUSH_BYTES32 KBSize flush; bounds memory
CHANNEL_CAPACITY256Reader to coalescer queue; each item at most one 64 KiB chunk
SCROLLBACK_CAP_BYTES4 MiBPer-session replay ring

Backpressure is the bounded channel: when the consumer stalls, the reader blocks, the kernel PTY buffer fills and the child slows down. The window starts at the first byte and is not reset by later chunks, so latency is bounded by WINDOW.

PtyScrollback assigns a monotonic seq to each chunk. A snapshot carries its seq and the renderer drops live chunks with seq <= snapSeq, so no boundary byte is written twice: a duplicated byte inside an ANSI escape corrupts the frame. A respawn resets the ring and seq returns to 0.

pty/env.rs strips LD_PRELOAD, LD_LIBRARY_PATH, LD_AUDIT, the DYLD_* injection variables and NODE_OPTIONS from every spawned environment.

JSONL and cost

opussonnethaikujsonlcost
The watcher tails the JSONL ledger and prices tokens by model rate into the cost meter.

JsonlWatcher tails Claude's <uuid>.jsonl, accumulating tokens, cost and context, deriving turn state, the CLI's session name and the resume id. A launch passes --session-id <uuid>, so resolving the file is a direct lookup; a recency scan is the fallback after a window.

  • Cadences: RESOLVE_POLL 3000 ms, TAIL_POLL 5000 ms, with notify as the primary signal.
  • Re-pin: /clear and --fork-session create a new jsonl in the same project dir. Re-pinning needs evidence from session::binding::arbitrate (fork lineage or a typed /clear within 30 s); a newer external session is never adopted.
  • Claims: a shared uuid to session map stops two sessions in one cwd from adopting the same file.
  • Safe catch-up: on attach or re-pin, working states derived from older lines are not emitted, so a file that ended on a tool_use cannot latch Generating on a stopped session.
ModelInput / output per million tokens
opus15 / 75
sonnet (and fallback)3 / 15
haiku0.25 / 1.25

These are hardcoded constants in jsonl_watcher.rs, not live prices. Cache creation is priced at 1.25 times input and cache read at 0.1 times.

Config isolation

fresh dirfresh diraccountCLAUDE_CONFIG_DIR per session
Each session gets its own config directory; a saved account is shared by its sessions.

Config-dir precedence in create_isolated_session is: saved account, then fresh per-session dir, then host login. Only the last leaves the config variable unset.

CaseConfig dir
Saved account~/.hydra-ensemble/accounts/<provider>/<accountId>/, persistent and shared by its sessions
Fresh config~/.hydra-ensemble/sessions/<id>/<provider>/, ephemeral
NeitherHost dir such as ~/.claude, ~/.codex, ~/.copilot, ~/.cursor, ~/.grok

Each session also gets HYDRA_ENSEMBLE_SESSION_ID in its environment. The provider variable (CLAUDE_CONFIG_DIR for Claude, CODEX_HOME for Codex) is exported on the launch line. For Grok, the resolver prefers the candidate directory that holds auth.json over an empty inherited GROK_HOME.

Persistent state goes to store.json: 2-space indented, written with a 300 ms debounce, flushed on shutdown, with .bak.v{N} snapshots on schema migration and corruption quarantine.

Worktrees and canvas

A worktree is "managed" when its realpath contains /.hydra-ensemble/worktrees/, normalized for Windows separators and long-path prefixes. The first entry of git worktree list --porcelain is the main one.

The canvas surface runs multi-agent orchestration. Each node is a live CLI terminal; nodes are wired with arrows and coordinate through an on-disk file bus: BRIEFING.md, an inbox, [HYDRA:*] sentinels and hydra-send and hydra-await helpers, with server-side chaining of workflow steps. Timers and thresholds are constants at the top of orchestration/bus.rs. A legacy team orchestrator (orchestra/) still exists as an overlay.

The PR inspector shells out to gh from forge/ and git/query.rs.

Decisions and limits

DecisionChosenRejectedWhy
ShellTauri v2 with a Rust coreElectronElectron is no longer part of the project; native binary, no Node runtime
PTYportable-ptynode-ptySame crate WezTerm uses; runs in the Rust core
IPC for outputCoalesced Channel messagesOne event per readMessage count was the measured cost (spike F00.2)
State sourcePTY analyzer plus authoritative JSONLPTY text alonePhrase matching can latch; transcripts are the truth
IsolationWorktree plus config dir per sessionShared checkout and loginPrevents file, lock and history collisions
CostHardcoded per-model ratesNot stated in the repoRates live in code, so they can go stale
Forge accessgh CLINot stated in the repoReuses the user's existing gh login

Known limits: PTY state depends on provider phrases, so a CLI wording change needs a marker update. GitHub Releases do not yet ship Linux Arch assets. The e2e harness is blocked; the smoke check is the MCP scenario 09-canvas. The plugin platform RFC is marked pending review.

Files