diff --git a/README.md b/README.md index 0f0610b2..ad2e2c88 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,7 @@ codeman web Run as a background service **Linux (systemd):** + ```bash mkdir -p ~/.config/systemd/user cat > ~/.config/systemd/user/codeman-web.service << EOF @@ -67,6 +68,7 @@ loginctl enable-linger $USER ``` **macOS (launchd):** + ```bash mkdir -p ~/Library/LaunchAgents cat > ~/Library/LaunchAgents/com.codeman.web.plist << EOF @@ -94,6 +96,7 @@ cat > ~/Library/LaunchAgents/com.codeman.web.plist << EOF EOF launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.codeman.web.plist ``` +
@@ -104,6 +107,7 @@ wsl bash -c "curl -fsSL https://raw.githubusercontent.com/Ark0N/Codeman/master/i ``` Codeman requires tmux, so Windows users need [WSL](https://learn.microsoft.com/en-us/windows/wsl/install). If you don't have WSL yet: run `wsl --install` in an admin PowerShell, reboot, open Ubuntu, then install your preferred AI coding CLI inside WSL ([Claude Code](https://docs.anthropic.com/en/docs/claude-code), [OpenCode](https://opencode.ai), or [Codex](https://developers.openai.com/codex/cli)). After installing, `http://localhost:3000` is accessible from your Windows browser. +
--- @@ -127,12 +131,12 @@ Open the printed URL. The page is a single dashboard; everything below happens t Click **+ New Session** (or **Quick Start**). A session is one AI CLI running in its own tmux-backed terminal. You choose: -| Field | What it does | -|-------|--------------| -| **Working directory / case** | The folder the agent operates in. A "case" is just a named working dir Codeman remembers. | -| **CLI / run mode** | `Claude` (default), `OpenCode`, `Codex`, `Gemini`, or `Terminal` (plain shell). | -| **Model** | Per-session model (App Settings → Claude Model). A soft default — `/model` still works in-session. | -| **Effort / Ultracode** | Reasoning effort (`low`–`max`) or `ultracode` for dynamic multi-agent workflows. Switchable anytime with `/effort`. | +| Field | What it does | +| ---------------------------- | ------------------------------------------------------------------------------------------------------------------- | +| **Working directory / case** | The folder the agent operates in. A "case" is just a named working dir Codeman remembers. | +| **CLI / run mode** | `Claude` (default), `OpenCode`, `Codex`, `Gemini`, or `Terminal` (plain shell). | +| **Model** | Per-session model (App Settings → Claude Model). A soft default — `/model` still works in-session. | +| **Effort / Ultracode** | Reasoning effort (`low`–`max`) or `ultracode` for dynamic multi-agent workflows. Switchable anytime with `/effort`. | Hit start — Codeman spawns the CLI via a real PTY and streams it to your browser over SSE. @@ -151,13 +155,13 @@ Hit start — Codeman spawns the CLI via a real PTY and streams it to your brows ### 5. Make it autonomous -| Mode | Use it for | Where | -|------|-----------|-------| -| **Respawn** | Long unattended runs — auto-restarts the CLI on idle/limit, with adaptive timing. Presets: `solo-work`, `overnight-autonomous`, … | Respawn tab | -| **Ralph / Todo** | A self-driving loop that tracks a todo list and keeps working until done. | Ralph tab | -| **Orchestrator** | Turn one goal into a phased plan and drive it to completion across agents. | Orchestrator panel | -| **Cron** | Saved, named jobs on a schedule (`once`/`interval`/`daily`/`weekly`) that spawn a session and send a prompt when due. | ⏰ Cron button | -| **Auto-resume** | Automatically continue after a subscription rate-limit resets. | Respawn tab (top) | +| Mode | Use it for | Where | +| ---------------- | --------------------------------------------------------------------------------------------------------------------------------- | ------------------ | +| **Respawn** | Long unattended runs — auto-restarts the CLI on idle/limit, with adaptive timing. Presets: `solo-work`, `overnight-autonomous`, … | Respawn tab | +| **Ralph / Todo** | A self-driving loop that tracks a todo list and keeps working until done. | Ralph tab | +| **Orchestrator** | Turn one goal into a phased plan and drive it to completion across agents. | Orchestrator panel | +| **Cron** | Saved, named jobs on a schedule (`once`/`interval`/`daily`/`weekly`) that spawn a session and send a prompt when due. | ⏰ Cron button | +| **Auto-resume** | Automatically continue after a subscription rate-limit resets. | Respawn tab (top) | ### 6. Reach it from anywhere @@ -171,7 +175,7 @@ Hit start — Codeman spawns the CLI via a real PTY and streams it to your brows - **Self-update** — git-clone installs update in place from **Settings → Updates**. - **Deploy your own changes** — see [Development](#development). -> ⚠️ **Safety:** if you're working *inside* a Codeman-managed session (`echo $CODEMAN_MUX` → `1`), never run `tmux kill-session` / `pkill claude` directly — use the web UI or `./scripts/tmux-manager.sh`. +> ⚠️ **Safety:** if you're working _inside_ a Codeman-managed session (`echo $CODEMAN_MUX` → `1`), never run `tmux kill-session` / `pkill claude` directly — use the web UI or `./scripts/tmux-manager.sh`. --- @@ -281,7 +285,7 @@ WATCHING → IDLE DETECTED → SEND UPDATE → /clear → /init → CONTINUE → ``` - **Multi-layer idle detection** — completion messages, AI-powered idle check, output silence, token stability -- **Auto-resume on usage limit** *(opt-in, off by default)* — when Claude halts on a subscription limit ("You've hit your limit · resets 3pm"), Codeman parses the reset time, waits it out plus a 2-minute safety buffer, then dismisses the rate-limit dialog and sends `continue` — so an overnight run survives the 5-hour window instead of stalling until morning. Recognizes every Claude Code limit-message format, retries if still limited, survives Codeman restarts, and holds respawn cycles while paused so `/clear` can't wipe the waiting conversation. Enable per session at the top of the Respawn tab +- **Auto-resume on usage limit** _(opt-in, off by default)_ — when Claude halts on a subscription limit ("You've hit your limit · resets 3pm"), Codeman parses the reset time, waits it out plus a 2-minute safety buffer, then dismisses the rate-limit dialog and sends `continue` — so an overnight run survives the 5-hour window instead of stalling until morning. Recognizes every Claude Code limit-message format, retries if still limited, survives Codeman restarts, and holds respawn cycles while paused so `/clear` can't wipe the waiting conversation. Enable per session at the top of the Respawn tab - **Circuit breaker** — prevents respawn thrashing when Claude is stuck (CLOSED -> HALF_OPEN -> OPEN states, tracks consecutive no-progress and repeated errors) - **Health scoring** — 0-100 health score with component scores for cycle success, circuit breaker state, iteration progress, and stuck recovery - **Built-in presets** — `solo-work` (3s idle, 60min), `subagent-workflow` (45s, 240min), `team-lead` (90s, 480min), `ralph-todo` (8s, 480min), `overnight-autonomous` (10s, 480min) @@ -327,10 +331,10 @@ The title is templated into the served HTML on first byte, so it's correct from ### Smart Token Management -| Threshold | Action | Result | -|-----------|--------|--------| +| Threshold | Action | Result | +| --------------- | --------------- | ---------------------------------- | | **110k tokens** | Auto `/compact` | Context summarized, work continues | -| **140k tokens** | Auto `/clear` | Fresh start with `/init` | +| **140k tokens** | Auto `/clear` | Fresh start with `/init` | ### Notifications @@ -365,8 +369,8 @@ PTY Output → 16ms Server Batch → DEC 2026 Wrap → SSE → Client rAF → xt - **Effort & Ultracode** — set a per-session default effort (`low`–`max`) or enable **ultracode** (dynamic multi-agent workflows). Soft defaults only — switchable anytime with `/effort` in-session. Extended-thinking budget is configurable too - **Voice input** — dictate prompts with Deepgram Nova-3 (Web Speech API fallback): toggle recording, auto-silence stop, live level meter (`Ctrl+Shift+V`) - **Image input** — paste or drag-and-drop images straight into a session -- **Gesture control** *(opt-in)* — a MediaPipe hand-tracking overlay to grab/drag session windows and pinch buttons, hands-free. Enable with `CODEMAN_GESTURE=1` + App Settings → Display -- **Multi-monitor span** *(macOS)* — one click opens a browser window maximized across all displays, so floating agent/gesture panels can cross the physical seam +- **Gesture control** _(opt-in)_ — a MediaPipe hand-tracking overlay to grab/drag session windows and pinch buttons, hands-free. Enable with `CODEMAN_GESTURE=1` + App Settings → Display +- **Multi-monitor span** _(macOS)_ — one click opens a browser window maximized across all displays, so floating agent/gesture panels can cross the physical seam - **CJK / IME input** — full composition support for Chinese / Japanese / Korean - **OS notifications & hostname-aware titles** — desktop alerts and tab titles are prefixed `codeman:` so multi-host setups stay unambiguous @@ -439,14 +443,14 @@ Every **60 seconds**, the server automatically rotates to a fresh token. The pre The design is informed by ["Demystifying the (In)Security of QR Code-based Login"](https://www.usenix.org/conference/usenixsecurity25/presentation/zhang-xin) (USENIX Security 2025), which found 47 of the top-100 websites vulnerable to QR auth attacks due to 6 critical design flaws across 42 CVEs. Codeman addresses all six: -| USENIX Flaw | Mitigation | -|-------------|------------| -| **Flaw-1**: Missing single-use enforcement | Token atomically consumed on first scan — replays always fail | -| **Flaw-2**: Long-lived tokens | 60s TTL with 90s grace, auto-rotation via timer | -| **Flaw-3**: Predictable token generation | `crypto.randomBytes(32)` — 256-bit entropy. Short codes use rejection sampling to eliminate modulo bias | -| **Flaw-4**: Client-side token generation | Server-side only — tokens never leave the server until embedded in the QR | -| **Flaw-5**: Missing status notification | Desktop toast: *"Device [IP] authenticated via QR (Safari). Not you? [Revoke]"* — real-time QRLjacking detection | -| **Flaw-6**: Inadequate session binding | IP + User-Agent stored for audit. Manual session revocation via API. HttpOnly + Secure + SameSite=lax cookies | +| USENIX Flaw | Mitigation | +| ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------- | +| **Flaw-1**: Missing single-use enforcement | Token atomically consumed on first scan — replays always fail | +| **Flaw-2**: Long-lived tokens | 60s TTL with 90s grace, auto-rotation via timer | +| **Flaw-3**: Predictable token generation | `crypto.randomBytes(32)` — 256-bit entropy. Short codes use rejection sampling to eliminate modulo bias | +| **Flaw-4**: Client-side token generation | Server-side only — tokens never leave the server until embedded in the QR | +| **Flaw-5**: Missing status notification | Desktop toast: _"Device [IP] authenticated via QR (Safari). Not you? [Revoke]"_ — real-time QRLjacking detection | +| **Flaw-6**: Inadequate session binding | IP + User-Agent stored for audit. Manual session revocation via API. HttpOnly + Secure + SameSite=lax cookies | #### Timing-Safe Lookup @@ -471,23 +475,23 @@ When someone authenticates via QR, the desktop shows a notification toast with t #### Threat Coverage -| Threat | Why it doesn't work | -|--------|-------------------| -| **QR screenshot shared** | Single-use: consumed on first scan. 60s TTL: expired before the attacker can act. Desktop notification alerts you immediately. | -| **Replay attack** | Atomic single-use consumption + 60s TTL. Old URLs always return 401. | -| **Cloudflare edge logs** | Short code is an opaque 6-char lookup key, not the real 256-bit token. Single-use means replaying from logs always fails. | -| **Brute force** | 56.8 billion combinations, ~2 valid at any time, dual-layer rate limiting blocks well before statistical feasibility. | -| **QRLjacking** | 60s rotation forces real-time relay. Desktop toast provides instant detection. Self-hosted single-user context makes phishing implausible. | -| **Timing attack** | Hash-based Map lookup — no string comparison timing leak. | -| **Session cookie theft** | HttpOnly + Secure + SameSite=lax + 24h TTL. Manual revocation at `POST /api/auth/revoke`. | +| Threat | Why it doesn't work | +| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ | +| **QR screenshot shared** | Single-use: consumed on first scan. 60s TTL: expired before the attacker can act. Desktop notification alerts you immediately. | +| **Replay attack** | Atomic single-use consumption + 60s TTL. Old URLs always return 401. | +| **Cloudflare edge logs** | Short code is an opaque 6-char lookup key, not the real 256-bit token. Single-use means replaying from logs always fails. | +| **Brute force** | 56.8 billion combinations, ~2 valid at any time, dual-layer rate limiting blocks well before statistical feasibility. | +| **QRLjacking** | 60s rotation forces real-time relay. Desktop toast provides instant detection. Self-hosted single-user context makes phishing implausible. | +| **Timing attack** | Hash-based Map lookup — no string comparison timing leak. | +| **Session cookie theft** | HttpOnly + Secure + SameSite=lax + 24h TTL. Manual revocation at `POST /api/auth/revoke`. | #### How It Compares -| Platform | Model | Comparison | -|----------|-------|------------| -| **Discord** | Long-lived token, no confirmation, [repeatedly exploited](https://owasp.org/www-community/attacks/Qrljacking) | Codeman: single-use + TTL + notification | -| **WhatsApp Web** | Phone confirms "Link device?", ~60s rotation | Comparable rotation; WhatsApp adds explicit confirmation (acceptable tradeoff for single-user) | -| **Signal** | Ephemeral public key, E2E encrypted channel | Stronger crypto, but [exploited by Russian state actors in 2025](https://cloud.google.com/blog/topics/threat-intelligence/russia-targeting-signal-messenger) via social engineering despite it | +| Platform | Model | Comparison | +| ---------------- | ------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Discord** | Long-lived token, no confirmation, [repeatedly exploited](https://owasp.org/www-community/attacks/Qrljacking) | Codeman: single-use + TTL + notification | +| **WhatsApp Web** | Phone confirms "Link device?", ~60s rotation | Comparable rotation; WhatsApp adds explicit confirmation (acceptable tradeoff for single-user) | +| **Signal** | Ephemeral public key, E2E encrypted channel | Stronger crypto, but [exploited by Russian state actors in 2025](https://cloud.google.com/blog/topics/threat-intelligence/russia-targeting-signal-messenger) via social engineering despite it | > Full design rationale, security analysis, and implementation details: [`docs/qr-auth-plan.md`](docs/qr-auth-plan.md) @@ -495,20 +499,20 @@ When someone authenticates via QR, the desktop shows a notification toast with t ## Security -Codeman launches sessions with `--dangerously-skip-permissions`, so the web UI is by design a remote-code-execution surface for whoever can reach it — the whole security model exists to control *who* that is. Recent hardening (v0.9.0 + v0.9.5) closes the browser-driven attack paths that bite self-hosted dev tools. Full model: [`docs/security-architecture.md`](docs/security-architecture.md). **Found a vulnerability?** See [`SECURITY.md`](SECURITY.md) for private disclosure and the list of known limitations. +Codeman launches sessions with `--dangerously-skip-permissions`, so the web UI is by design a remote-code-execution surface for whoever can reach it — the whole security model exists to control _who_ that is. Recent hardening (v0.9.0 + v0.9.5) closes the browser-driven attack paths that bite self-hosted dev tools. Full model: [`docs/security-architecture.md`](docs/security-architecture.md). **Found a vulnerability?** See [`SECURITY.md`](SECURITY.md) for private disclosure and the list of known limitations. ### Network & access -- **Loopback by default** — binds `127.0.0.1`, reachable only from the same machine, so the no-password default is safe out of the box. Binding a non-loopback host without `CODEMAN_PASSWORD` *starts but prints a loud warning* with three concrete fixes (set a password, loopback + an authenticated tunnel, or explicitly acknowledge with `--allow-unauthenticated-network`) +- **Loopback by default** — binds `127.0.0.1`, reachable only from the same machine, so the no-password default is safe out of the box. Binding a non-loopback host without `CODEMAN_PASSWORD` _starts but prints a loud warning_ with three concrete fixes (set a password, loopback + an authenticated tunnel, or explicitly acknowledge with `--allow-unauthenticated-network`) - **Optional auth, real sessions** — HTTP Basic via `CODEMAN_USERNAME` (default `admin`) / `CODEMAN_PASSWORD`. Success issues an opaque 256-bit `codeman_session` cookie (`randomBytes(32)`) — validated server-side, not client-signed, so it can't be forged offline (24h TTL, auto-extend, device-context audit log) -- **Per-IP rate limiting** — 10 failed attempts → `429` with `Retry-After` (15-min decay). A valid cookie or correct password recovers *immediately* even while an attacker hammers the same IP — important because all tunnel traffic shares one loopback IP. QR auth has its own separate limiter +- **Per-IP rate limiting** — 10 failed attempts → `429` with `Retry-After` (15-min decay). A valid cookie or correct password recovers _immediately_ even while an attacker hammers the same IP — important because all tunnel traffic shares one loopback IP. QR auth has its own separate limiter ### Always-on browser hardening (v0.9.5) These run for **every** request — before auth, even on the default no-password loopback install: - **Host-header allowlist → blocks DNS rebinding.** A custom domain rebound to `127.0.0.1` is rejected with `403 host not allowed` before any handler runs. Allowed: `localhost`, any IP literal, the bind host, `.ts.net` / `.trycloudflare.com` / `.cfargotunnel.com`, the active managed tunnel, and `CODEMAN_ALLOWED_HOSTS` (add custom reverse-proxy domains here — comma-separated; exact host or leading-dot `.suffix` for subdomains) -- **Cross-site Origin / CSRF guard.** On state-changing methods (`POST`/`PUT`/`PATCH`/`DELETE`) the `Origin` must pass the same allowlist, else `403 cross-site request blocked`. A *missing* Origin is allowed (so `curl`, the CLI, and Claude Code hooks keep working); only a present-but-foreign or opaque `null` origin is rejected +- **Cross-site Origin / CSRF guard.** On state-changing methods (`POST`/`PUT`/`PATCH`/`DELETE`) the `Origin` must pass the same allowlist, else `403 cross-site request blocked`. A _missing_ Origin is allowed (so `curl`, the CLI, and Claude Code hooks keep working); only a present-but-foreign or opaque `null` origin is rejected - **Raw `text/plain` bodies.** The global parser no longer JSON-parses `text/plain`, closing the CORS "simple request" CSRF vector where a cross-site `fetch` could smuggle JSON into a write route with no preflight - **WebSocket origin validation.** The terminal WS upgrade runs the same Host + Origin check and closes with code `4003` on failure (anti-CSWSH) - **XSS-escaped agent output.** AI-derived strings (tool names, command arguments, subagent descriptions) are HTML-escaped at every injection site before rendering in the subagent / activity panels @@ -546,37 +550,38 @@ Single-digit selection (1-9), color-coded status, token counts, auto-refresh. De > Ctrl bindings also accept Cmd on macOS. -| Shortcut | Action | -|----------|--------| -| `Ctrl/Cmd+W` | Kill active session | -| `Ctrl/Cmd+Tab` | Next session | -| `Alt/Option+[` / `Alt/Option+]` | Previous / next session | -| `Alt/Option+1`-`Alt/Option+9` | Switch to tab N (physical keys, so macOS Option layouts work) | -| `Ctrl+Shift+{` / `Ctrl+Shift+}` | Move active tab left / right | -| `Ctrl/Cmd+L` | Clear terminal | -| `Ctrl+Shift+R` | Restore terminal size | -| `Ctrl+Shift+V` | Toggle voice input | -| `Ctrl/Cmd +` / `-` | Font size | -| `Ctrl/Cmd+?` | Keyboard help | -| `Shift+Enter` | Insert newline (sent to terminal) | -| `Escape` | Close panels & modals | +| Shortcut | Action | +| ------------------------------- | ------------------------------------------------------------- | +| `Ctrl/Cmd+W` | Kill active session | +| `Ctrl/Cmd/Option+K` | Find open session or start a new one | +| `Ctrl/Cmd+Tab` | Next session | +| `Alt/Option+[` / `Alt/Option+]` | Previous / next session | +| `Alt/Option+1`-`Alt/Option+9` | Switch to tab N (physical keys, so macOS Option layouts work) | +| `Ctrl+Shift+{` / `Ctrl+Shift+}` | Move active tab left / right | +| `Ctrl/Cmd+L` | Clear terminal | +| `Ctrl+Shift+R` | Restore terminal size | +| `Ctrl+Shift+V` | Toggle voice input | +| `Ctrl/Cmd +` / `-` | Font size | +| `Ctrl/Cmd+?` | Keyboard help | +| `Shift+Enter` | Insert newline (sent to terminal) | +| `Escape` | Close panels & modals | --- ## Driving Codeman from an Agent — Programmatic Guide -For AI agents and automation that control Codeman without a browser: an agent that spins up worker sessions, a CI bot, or **Claude Code running *inside* a Codeman session orchestrating other sessions**. Everything the UI does is HTTP + a CLI, so an agent can do it too. +For AI agents and automation that control Codeman without a browser: an agent that spins up worker sessions, a CI bot, or **Claude Code running _inside_ a Codeman session orchestrating other sessions**. Everything the UI does is HTTP + a CLI, so an agent can do it too. ### Detect that you're inside Codeman When a CLI runs in a Codeman-managed session, these environment variables are set — read them instead of hardcoding anything: -| Variable | Meaning | -|----------|---------| -| `CODEMAN_MUX=1` | You're in a managed tmux session. **Never** `tmux kill-session` / `pkill claude` / `pkill tmux` — you'll kill yourself or a sibling. | -| `CODEMAN_API_URL` | Base URL of the API (e.g. `https://127.0.0.1:3000`). Use it for every call below. | -| `CODEMAN_SESSION_ID` | *Your own* session id. Use it to avoid acting on yourself. | -| `CODEMAN_HOOK_SECRET_FILE` | Path to the hook secret (required on `/api/hook-event` while a managed tunnel is up). | +| Variable | Meaning | +| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| `CODEMAN_MUX=1` | You're in a managed tmux session. **Never** `tmux kill-session` / `pkill claude` / `pkill tmux` — you'll kill yourself or a sibling. | +| `CODEMAN_API_URL` | Base URL of the API (e.g. `https://127.0.0.1:3000`). Use it for every call below. | +| `CODEMAN_SESSION_ID` | _Your own_ session id. Use it to avoid acting on yourself. | +| `CODEMAN_HOOK_SECRET_FILE` | Path to the hook secret (required on `/api/hook-event` while a managed tunnel is up). | ### Rules of the road (read before you POST) @@ -640,7 +645,7 @@ codeman ralph start --min-hours 8 # (r) launch the autonomous loop codeman attach # attach a Claude hook context ``` -### Hooks (events flowing *back* to Codeman) +### Hooks (events flowing _back_ to Codeman) Codeman registers Claude Code hooks that `POST /api/hook-event` (`permission_prompt`, `idle_prompt`, `stop`, `task_completed`, …) so the dashboard reacts in real time. This endpoint is auth-exempt on loopback but, under a managed tunnel, requires the `X-Codeman-Hook-Secret` header (read it from `$CODEMAN_HOOK_SECRET_FILE`). You normally don't call this by hand — Codeman wires it up — but it's how the autonomy layers "see" what the agent is doing. @@ -653,62 +658,69 @@ Codeman registers Claude Code hooks that `POST /api/hook-event` (`permission_pro REST over Fastify — **~160 handlers across 18 route modules**, plus an SSE stream and a WebSocket terminal channel. All responses use the `ApiResponse` envelope (`{success, data}` / `{success, error, errorCode}`); `/api/v1/*` is a stable alias. A representative subset: ### Sessions -| Method | Endpoint | Description | -|--------|----------|-------------| -| `GET` | `/api/sessions` | List all | -| `POST` | `/api/quick-start` | Create case + start session (`{caseName?, mode?, effort?, envOverrides?}`) | -| `POST` | `/api/sessions/:id/input` | Send input (`{input, useMux?, clientId?, seq?}` — `clientId`+`seq` = exactly-once) | -| `GET` | `/api/sessions/:id/output` | Read terminal output | -| `DELETE` | `/api/sessions/:id` | Delete session | + +| Method | Endpoint | Description | +| -------- | -------------------------- | ---------------------------------------------------------------------------------- | +| `GET` | `/api/sessions` | List all | +| `POST` | `/api/quick-start` | Create case + start session (`{caseName?, mode?, effort?, envOverrides?}`) | +| `POST` | `/api/sessions/:id/input` | Send input (`{input, useMux?, clientId?, seq?}` — `clientId`+`seq` = exactly-once) | +| `GET` | `/api/sessions/:id/output` | Read terminal output | +| `DELETE` | `/api/sessions/:id` | Delete session | ### Respawn -| Method | Endpoint | Description | -|--------|----------|-------------| + +| Method | Endpoint | Description | +| ------ | ---------------------------------- | -------------------------- | | `POST` | `/api/sessions/:id/respawn/enable` | Enable with config + timer | -| `POST` | `/api/sessions/:id/respawn/stop` | Stop controller | -| `PUT` | `/api/sessions/:id/respawn/config` | Update config | +| `POST` | `/api/sessions/:id/respawn/stop` | Stop controller | +| `PUT` | `/api/sessions/:id/respawn/config` | Update config | ### Ralph / Todo -| Method | Endpoint | Description | -|--------|----------|-------------| -| `GET` | `/api/sessions/:id/ralph-state` | Get loop state + todos | -| `POST` | `/api/sessions/:id/ralph-config` | Configure tracking | + +| Method | Endpoint | Description | +| ------ | -------------------------------- | ---------------------- | +| `GET` | `/api/sessions/:id/ralph-state` | Get loop state + todos | +| `POST` | `/api/sessions/:id/ralph-config` | Configure tracking | ### Orchestrator -| Method | Endpoint | Description | -|--------|----------|-------------| -| `POST` | `/api/orchestrator/start` | Start orchestration from a goal | -| `POST` | `/api/orchestrator/approve` | Approve the generated plan | -| `GET` | `/api/orchestrator/status` | Current phase + progress | -| `POST` | `/api/orchestrator/stop` | Stop and clean up | + +| Method | Endpoint | Description | +| ------ | --------------------------- | ------------------------------- | +| `POST` | `/api/orchestrator/start` | Start orchestration from a goal | +| `POST` | `/api/orchestrator/approve` | Approve the generated plan | +| `GET` | `/api/orchestrator/status` | Current phase + progress | +| `POST` | `/api/orchestrator/stop` | Stop and clean up | ### Cron (scheduled jobs) -| Method | Endpoint | Description | -|--------|----------|-------------| -| `GET` / `POST` | `/api/cron/jobs` | List / create cron jobs | -| `PUT` / `DELETE` | `/api/cron/jobs/:id` | Update / delete a job | -| `PUT` | `/api/cron/jobs/:id/enabled` | Enable / disable | -| `POST` | `/api/cron/jobs/:id/run` | Run now | -| `GET` | `/api/cron/jobs/:id/runs` | Run history | + +| Method | Endpoint | Description | +| ---------------- | ---------------------------- | ----------------------- | +| `GET` / `POST` | `/api/cron/jobs` | List / create cron jobs | +| `PUT` / `DELETE` | `/api/cron/jobs/:id` | Update / delete a job | +| `PUT` | `/api/cron/jobs/:id/enabled` | Enable / disable | +| `POST` | `/api/cron/jobs/:id/run` | Run now | +| `GET` | `/api/cron/jobs/:id/runs` | Run history | ### Subagents -| Method | Endpoint | Description | -|--------|----------|-------------| -| `GET` | `/api/subagents` | List all background agents | -| `GET` | `/api/subagents/:id` | Agent info and status | -| `GET` | `/api/subagents/:id/transcript` | Full activity transcript | -| `DELETE` | `/api/subagents/:id` | Kill agent process | + +| Method | Endpoint | Description | +| -------- | ------------------------------- | -------------------------- | +| `GET` | `/api/subagents` | List all background agents | +| `GET` | `/api/subagents/:id` | Agent info and status | +| `GET` | `/api/subagents/:id/transcript` | Full activity transcript | +| `DELETE` | `/api/subagents/:id` | Kill agent process | ### System -| Method | Endpoint | Description | -|--------|----------|-------------| -| `GET` | `/api/events` | SSE stream | -| `GET` | `/api/status` | Full app state | -| `POST` | `/api/hook-event` | Hook callbacks | -| `GET` | `/api/system/update/check` | Check for a new release | -| `POST` | `/api/system/update` | Self-update (git-clone installs) | -| `POST` | `/api/clipboard` | Push text to all connected browsers (`{text}`) | -| `GET` | `/api/sessions/:id/run-summary` | Timeline + stats | + +| Method | Endpoint | Description | +| ------ | ------------------------------- | ---------------------------------------------- | +| `GET` | `/api/events` | SSE stream | +| `GET` | `/api/status` | Full app state | +| `POST` | `/api/hook-event` | Hook callbacks | +| `GET` | `/api/system/update/check` | Check for a new release | +| `POST` | `/api/system/update` | Self-update (git-clone installs) | +| `POST` | `/api/clipboard` | Push text to all connected browsers (`{text}`) | +| `GET` | `/api/sessions/:id/run-summary` | Timeline + stats | --- @@ -786,14 +798,14 @@ See [CLAUDE.md](./CLAUDE.md) for full documentation. The codebase went through a comprehensive 7-phase refactoring that eliminated god objects, centralized configuration, and established modular architecture: -| Phase | What changed | Impact | -|-------|-------------|--------| -| **Performance** | Cached endpoints, SSE adaptive batching, buffer chunking | Sub-16ms terminal latency | -| **Route extraction** | `server.ts` split into 15 domain route modules + auth middleware + port interfaces | **−67%** server.ts LOC (6,736 → 2,254) | -| **Domain splitting** | `types.ts` → 16 domain files, `ralph-tracker` → 7 files, `respawn-controller` → 5 files, `session` → 6 files | No more god files | -| **Frontend modules** | `app.js` → 18 extracted modules across infra, domain & feature layers | app.js core down to **~3.4K LOC** | -| **Config consolidation** | ~70 scattered magic numbers → 10 domain-focused config files | Zero cross-file duplicates | -| **Test infrastructure** | Shared mock library, 12 route test files, consolidated MockSession | Testable route handlers via `app.inject()` | +| Phase | What changed | Impact | +| ------------------------ | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------ | +| **Performance** | Cached endpoints, SSE adaptive batching, buffer chunking | Sub-16ms terminal latency | +| **Route extraction** | `server.ts` split into 15 domain route modules + auth middleware + port interfaces | **−67%** server.ts LOC (6,736 → 2,254) | +| **Domain splitting** | `types.ts` → 16 domain files, `ralph-tracker` → 7 files, `respawn-controller` → 5 files, `session` → 6 files | No more god files | +| **Frontend modules** | `app.js` → 18 extracted modules across infra, domain & feature layers | app.js core down to **~3.4K LOC** | +| **Config consolidation** | ~70 scattered magic numbers → 10 domain-focused config files | Zero cross-file duplicates | +| **Test infrastructure** | Shared mock library, 12 route test files, consolidated MockSession | Testable route handlers via `app.inject()` | Full details: [`docs/archive/code-structure-findings.md`](docs/archive/code-structure-findings.md) diff --git a/src/web/public/app.js b/src/web/public/app.js index a95e824f..7304c4f3 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -305,6 +305,134 @@ function parseSessionPrefix(name) { return null; } +const DEFAULT_SHORTCUTS = [ + { + id: 'show-shortcuts', + group: 'Panels', + label: 'Show Shortcuts', + bindings: [ + { modifiers: ['ctrl'], key: '?', code: 'Slash' }, + { modifiers: ['ctrl', 'shift'], key: '?' }, + { modifiers: ['alt'], key: '?', code: 'Slash' }, + ], + action: 'showShortcutOverlay', + }, + { + id: 'close-session', + group: 'Session', + label: 'Close Session', + bindings: [{ modifiers: ['ctrl'], key: 'w' }], + action: 'killActiveSession', + }, + { + id: 'next-session', + group: 'Session', + label: 'Next Session', + bindings: [{ modifiers: ['ctrl'], key: 'Tab' }], + action: 'nextSession', + }, + { + id: 'clear-terminal', + group: 'Terminal', + label: 'Clear Terminal', + bindings: [{ modifiers: ['ctrl'], key: 'l' }], + action: 'clearTerminal', + }, + { + id: 'increase-font', + group: 'Terminal', + label: 'Increase Font', + bindings: [ + { modifiers: ['ctrl'], key: '=', code: 'Equal' }, + { modifiers: ['ctrl'], key: '+', code: 'Equal' }, + ], + action: 'increaseFontSize', + }, + { + id: 'decrease-font', + group: 'Terminal', + label: 'Decrease Font', + bindings: [{ modifiers: ['ctrl'], key: '-', code: 'Minus' }], + action: 'decreaseFontSize', + }, + { + id: 'voice-input', + group: 'Terminal', + label: 'Voice Input', + bindings: [{ modifiers: ['ctrl', 'shift'], key: 'V' }], + action: 'toggleVoiceInput', + }, + { + id: 'restore-terminal-size', + group: 'Terminal', + label: 'Restore Terminal Size', + bindings: [{ modifiers: ['ctrl', 'shift'], key: 'R' }], + action: 'restoreTerminalSize', + }, + { + id: 'move-tab-left', + group: 'Tabs', + label: 'Move Active Tab Left', + bindings: [{ modifiers: ['ctrl', 'shift'], key: '{', code: 'BracketLeft' }], + action: 'moveActiveTabLeft', + }, + { + id: 'move-tab-right', + group: 'Tabs', + label: 'Move Active Tab Right', + bindings: [{ modifiers: ['ctrl', 'shift'], key: '}', code: 'BracketRight' }], + action: 'moveActiveTabRight', + }, + { + id: 'command-palette', + group: 'Session', + label: 'Find Open Session', + bindings: [ + { modifiers: ['ctrl'], key: 'k', code: 'KeyK' }, + { modifiers: ['meta'], key: 'k', code: 'KeyK' }, + { modifiers: ['alt'], key: 'k', code: 'KeyK' }, + ], + action: 'openCommandPalette', + }, + { + id: 'previous-next-session', + group: 'Session', + label: 'Previous / Next Session', + displayBindings: ['Alt/Option+[', 'Alt/Option+]'], + }, + { + id: 'switch-tab-n', + group: 'Session', + label: 'Switch to Tab N', + displayBindings: ['Alt/Option+1-9'], + }, + { + id: 'focus-tabs', + group: 'Tabs', + label: 'Focus Tabs', + displayBindings: ['ArrowLeft', 'ArrowRight', 'Home', 'End'], + }, + { + id: 'activate-focused-tab', + group: 'Tabs', + label: 'Activate Focused Tab', + displayBindings: ['Enter', 'Space'], + }, + { + id: 'insert-newline', + group: 'Terminal', + label: 'Insert Newline', + displayBindings: ['Shift+Enter', 'Ctrl+Enter'], + }, + { + id: 'close-panels', + group: 'Panels', + label: 'Close Panels', + displayBindings: ['Escape'], + }, +]; + + // ═══════════════════════════════════════════════════════════════ // CodemanApp Class — constructor and global state // ═══════════════════════════════════════════════════════════════ @@ -807,32 +935,43 @@ class CodemanApp { // ═══════════════════════════════════════════════════════════════ setupEventListeners() { - // Keyboard shortcut lookup table — data-driven to avoid 12 separate if-blocks. - // Each entry: { key, altKey? (alternative key match), ctrl? (require Ctrl/Cmd), - // shift? (require Shift), action }. - const SHORTCUTS = [ - { key: '?', altKey: '/', ctrl: true, action: () => this.showHelp() }, - { key: 'w', ctrl: true, action: () => this.killActiveSession() }, - { key: 'Tab', ctrl: true, action: () => this.nextSession() }, - { key: 'l', ctrl: true, action: () => this.clearTerminal() }, - { key: 'R', ctrl: true, shift: true, action: () => this.restoreTerminalSize() }, - { key: '=', altKey: '+', ctrl: true, action: () => this.increaseFontSize() }, - { key: '-', ctrl: true, action: () => this.decreaseFontSize() }, - { key: 'V', ctrl: true, shift: true, action: () => VoiceInput.toggle() }, - { key: '{', ctrl: true, shift: true, action: () => this.moveActiveTabLeft() }, - { key: '}', ctrl: true, shift: true, action: () => this.moveActiveTabRight() }, - ]; + // Action name → handler map for the shortcut registry (DEFAULT_SHORTCUTS + + // user overrides from settings.shortcutOverrides, merged by + // getShortcutRegistry()). The command palette chord is deliberately NOT in + // this map — shouldOpenCommandPaletteFromShortcut() dispatches it above with + // focus-target awareness (it must fire from the terminal but not from inputs). + const SHORTCUT_ACTIONS = { + showShortcutOverlay: () => this.showShortcutOverlay(), + killActiveSession: () => this.killActiveSession(), + nextSession: () => this.nextSession(), + clearTerminal: () => this.clearTerminal(), + restoreTerminalSize: () => this.restoreTerminalSize(), + increaseFontSize: () => this.increaseFontSize(), + decreaseFontSize: () => this.decreaseFontSize(), + toggleVoiceInput: () => VoiceInput.toggle(), + moveActiveTabLeft: () => this.moveActiveTabLeft(), + moveActiveTabRight: () => this.moveActiveTabRight(), + }; // Use capture to handle before terminal document.addEventListener('keydown', (e) => { // Don't intercept keys during CJK IME composition if (e.isComposing || e.keyCode === 229) return; + if (this.shouldOpenCommandPaletteFromShortcut?.(e)) { + e.preventDefault(); + this.openCommandPalette(); + return; + } + // Escape - close panels and modals (different logic: no preventDefault, no return) if (e.key === 'Escape') { this.closeAllPanels(); this.closeHelp(); if (this.attachmentHistoryDrawerOpen) this.closeAttachmentHistory(); + this.closeSessionManager(); + this.closeCommandPalette?.(); + this.closeShortcutOverlay?.(); } // Option/Alt session navigation uses physical key CODES, not e.key, so macOS @@ -862,14 +1001,18 @@ class CodemanApp { } } - // Match against shortcut table - for (const s of SHORTCUTS) { - const keyMatch = e.key === s.key || (s.altKey && e.key === s.altKey); - const ctrlMatch = s.ctrl ? (e.ctrlKey || e.metaKey) : true; - const shiftMatch = s.shift ? e.shiftKey : !e.shiftKey; - if (keyMatch && ctrlMatch && shiftMatch) { + // Match against the shortcut registry so user rebinds and per-shortcut + // disables (App Settings → Shortcuts) take effect. Every dispatchable + // binding requires Ctrl/Cmd/Alt (capture enforces the same), so plain + // typing exits early without touching the registry. + if (!e.ctrlKey && !e.metaKey && !e.altKey) return; + for (const shortcut of this.getShortcutRegistry()) { + if (shortcut.disabled || !shortcut.action) continue; + const action = SHORTCUT_ACTIONS[shortcut.action]; + if (!action) continue; + if (this.matchesShortcutEvent(e, shortcut)) { e.preventDefault(); - s.action(); + action(); return; } } @@ -4252,6 +4395,91 @@ class CodemanApp { } } + // ─── Shortcut Registry ─────────────────────────────────────────────────────── + // Returns the merged shortcut list: DEFAULT_SHORTCUTS with any per-shortcut + // overrides from settings.shortcutOverrides applied on top. + + getShortcutRegistry() { + const settings = this.loadAppSettingsFromStorage(); + const shortcutOverrides = settings.shortcutOverrides || {}; + return DEFAULT_SHORTCUTS.map((shortcut) => { + const override = shortcutOverrides[shortcut.id]; + if (!override) return shortcut; + // Only binding-shaped fields may come from storage — id/label/group/action + // stay trusted so persisted data can never redirect a shortcut's action or + // spoof another row in the settings/overlay renderers. + const merged = { ...shortcut }; + if (Array.isArray(override.bindings)) { + merged.bindings = override.bindings; + delete merged.displayBindings; // show the override, not the stale default label + } + if (typeof override.disabled === 'boolean') merged.disabled = override.disabled; + return merged; + }); + } + + matchesShortcutEvent(e, shortcut) { + if (!shortcut || !Array.isArray(shortcut.bindings)) return false; + return shortcut.bindings.some((binding) => { + const mods = binding.modifiers || []; + // Ctrl and Cmd are interchangeable as the primary modifier (parity with + // the legacy shortcut table), but every OTHER pressed modifier must be + // declared by the binding — a plain Ctrl+K binding must not also swallow + // Ctrl+Shift+K (the Firefox devtools chord). + const wantsPrimary = mods.includes('ctrl') || mods.includes('meta'); + if (wantsPrimary !== !!(e.ctrlKey || e.metaKey)) return false; + if (mods.includes('shift') !== !!e.shiftKey) return false; + if (mods.includes('alt') !== !!e.altKey) return false; + // Match the physical key when the binding pins one (layout-independent), + // or the produced character otherwise (layout-dependent keys like '+'). + if (binding.code && e.code === binding.code) return true; + if (binding.key && typeof e.key === 'string' && e.key.toLowerCase() === binding.key.toLowerCase()) return true; + return false; + }); + } + + // ─── Shortcut Overlay Modal ─────────────────────────────────────────────────── + // Ctrl/Alt+? opens a floating overlay listing all keyboard shortcuts, grouped + // by category. Uses the merged registry so user overrides are reflected. + + showShortcutOverlay() { + const modal = document.getElementById('shortcutOverlayModal'); + if (!modal) return; + this.renderShortcutOverlay(); + modal.classList.add('active'); + modal.focus?.(); + } + + renderShortcutOverlay() { + const list = document.getElementById('shortcutOverlayList'); + if (!list) return; + const registry = this.getShortcutRegistry(); + const groups = {}; + for (const shortcut of registry) { + const g = shortcut.group || 'General'; + if (!groups[g]) groups[g] = []; + groups[g].push(shortcut); + } + const fmtBindings = (s) => { + if (s.displayBindings) return s.displayBindings.map((b) => `${escapeHtml(b)}`).join(' / '); + if (!s.bindings) return ''; + return s.bindings.map((b) => { + const parts = [...(b.modifiers || []).map((m) => m.charAt(0).toUpperCase() + m.slice(1)), b.key || b.code || '']; + return `${escapeHtml(parts.join('+'))}`; + }).join(' / '); + }; + list.innerHTML = Object.entries(groups).map(([group, items]) => + `
${escapeHtml(group)}
` + + items.map((s) => `
${escapeHtml(s.label)}${fmtBindings(s)}
`).join('') + + `
` + ).join(''); + } + + closeShortcutOverlay() { + const modal = document.getElementById('shortcutOverlayModal'); + if (modal) modal.classList.remove('active'); + } + } // ═══════════════════════════════════════════════════════════════ diff --git a/src/web/public/index.html b/src/web/public/index.html index b3b91f08..79d5ab8b 100644 --- a/src/web/public/index.html +++ b/src/web/public/index.html @@ -358,7 +358,7 @@

Resume Conversation

-

Or press Ctrl+Enter to start

+

Or click Run to start

@@ -427,7 +427,7 @@
- @@ -469,7 +469,22 @@
- + +
+ @@ -555,19 +570,49 @@
@@ -1091,6 +1136,7 @@ + + + +
@@ -1712,6 +1771,23 @@
+ + + + + + + + + +