mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-09-30 20:49:41 +02:00
Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4a33b91107 | ||
|
|
28b531fa5b | ||
|
|
68310619a7 | ||
|
|
055f18fb66 | ||
|
|
cf2a7f54bf | ||
|
|
beeec63f72 | ||
|
|
fad32eeaab | ||
|
|
c1458d8ab8 | ||
|
|
0be3d09603 | ||
|
|
96035ffa1f | ||
|
|
7dd7614760 | ||
|
|
9c986b2869 | ||
|
|
8c7a9781fa | ||
|
|
70378315da | ||
|
|
f8b2a2a347 | ||
|
|
dd449765de | ||
|
|
8a995cb9e3 |
@@ -1,5 +1,62 @@
|
||||
# aicodeman
|
||||
|
||||
## 0.9.13
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Auto-resume on usage limit ("token pause" control) plus a set of mobile-view fixes for regressions introduced in 0.9.8.
|
||||
|
||||
**Auto-resume on usage limit** — new opt-in checkbox at the top of the session Respawn tab (off by default). When Claude stops because a usage limit was reached, Codeman parses the reset time from the limit message, waits until the limit lifts (plus a 2-minute safety buffer), then dismisses the rate-limit dialog (Esc) and sends "continue" so the session picks its work back up automatically. All Claude Code message formats from 1.0.x through 2.1.x are recognized ("5-hour limit reached ∙ resets 8pm", "Limit reached · resets 1pm (America/Chicago) · /upgrade…", "You've hit your weekly limit · resets Mon 12:00am", weekly date forms, and the raw API `usage limit reached|<epoch>` form). Still-limited responses re-arm the scheduler (5-minute retry loop); a pending schedule persists across Codeman restarts and re-arms on boot; respawn cycles are blocked while a limit pause is active so the cycle's `/clear` cannot wipe the paused conversation. New endpoint `POST /api/sessions/:id/auto-resume`; new SSE events `session:limitPauseScheduled`, `session:limitResume`, `session:limitResumeCancelled`; toast/notification on pause and resume, plus a live "resumes at HH:MM" status line in the modal. The Respawn tab layout was also tidied: compact single-row Update/Kickstart prompt fields and a merged options row.
|
||||
|
||||
**Mobile fixes (0.9.8 regressions)**:
|
||||
- **Activity-based resize arbitration** — a desktop sizing claim now only blocks a phone's resize while that desktop has actually typed within the last 90 seconds. Previously any connected desktop tab (even one abandoned hours ago) silently discarded the phone's resize with no fallback, leaving the phone rendering a desktop-width stream in a narrow terminal: mid-word wraps, tmux dot-fill rows, overdrawn garbled text, and misplaced keyboard echo. Now an idle desktop yields the pane to the phone, and the next desktop keystroke automatically restores the desktop layout ("whoever is actively using the session wins"). Phones also re-send their dimensions every 30 seconds (visible tab only, skipped while the virtual keyboard is open) so attaching under a momentarily-active desktop self-corrects.
|
||||
- **Keyboard accessory bar and toolbar restored on iOS** — the lift offset is measured against the layout viewport (`window.innerHeight`) again instead of the keyboard-shrunken app element; on iOS the offset computed to 0, leaving both bars hidden behind the OS keyboard with a dead black gap above it.
|
||||
- **Removed the mobile header utility ("three dots") toggle** — the header-utilities tray stays collapsed on small viewports.
|
||||
|
||||
## 0.9.12
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Documentation refresh — README catches up with the Codex run mode, plus a CLAUDE.md correction.
|
||||
|
||||
**README (en + zh-CN)**: Codex is now listed as a third supported AI coding CLI everywhere the docs previously said "Claude Code or OpenCode": the install requirement in Quick Start (now "any combination works", linking to the official Codex CLI docs), the Windows/WSL setup note, the renamed **Multi-CLI** feature bullet (env-prefix gating now reads `CLAUDE_CODE_*` vs `OPENCODE_*` vs `CODEX_*`), the Zod schema-validation security bullet, and the architecture mermaid diagram. The header tagline was also finalized to "Claude Code • OpenCode • Codex — One Dashboard • Any Device" in both languages.
|
||||
|
||||
**CLAUDE.md**: fixed a stale "Local packages" line that claimed the xterm-zerolag-input local-echo overlay had a copy embedded in `app.js` — it is single-source in `packages/xterm-zerolag-input/`, bundled to the gitignored vendor file, and only consumed by `app.js`, matching the existing single-source gotcha.
|
||||
|
||||
## 0.9.11
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Fix a terminal freeze on hover (catastrophic regex backtracking) and a CSP violation that disabled the terminal's anti-throttling worker.
|
||||
|
||||
**Tab-freezing hover bug**: the terminal link provider's `cmdPattern` (which turns `tail -f /path`-style text into clickable links) used an empty-matchable, unbounded arg group — `(?:[^\s\/]*\s+)*` — that backtracks exponentially on real Claude output, e.g. wrapped `git commit -m "$(cat <<'EOF'` heredoc lines or aligned table rows. Hovering the mouse over such a line hung the page's main thread for minutes ("page unresponsive"). The pattern now uses non-empty tokens with bounded repetition (linear time); all intended command+path link forms still match. New `test/link-provider-regex.test.ts` extracts the shipped patterns from source and pins linear-time behavior on the killer line shapes.
|
||||
|
||||
**Blob worker CSP fix**: `worker-src 'self' blob:` is now always present in the CSP (previously only with `CODEMAN_GESTURE=1`). The terminal's `_safeYield` anti-throttling tick worker is created from a Blob URL and was silently blocked on every install, logging a CSP violation on each page load and disabling the worker leg of the render-yield fallback chain.
|
||||
|
||||
## 0.9.10
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Self-update now restarts automatically on headless Macs supervised by a system LaunchDaemon.
|
||||
|
||||
New `launchd-daemon` supervisor kind: when Codeman runs under a bootstrapped, KeepAlive system-level LaunchDaemon (`/Library/LaunchDaemons/com.codeman.web.plist` — the right setup for headless Macs, where LaunchAgents never start because there is no GUI login), the updater no longer ends with "Update staged — restart Codeman to apply". It restarts rootlessly: the update script kills the server PID (passed via `--server-pid`) and launchd respawns it on the freshly built `dist/`. Detection is conservative — the daemon must be bootstrapped in the system domain AND have `KeepAlive` enabled.
|
||||
|
||||
Also fixed: a lingering "restart Codeman to apply" status. After a manual restart of a staged update, boot reconciliation now flips `completed-needs-manual-restart` to `completed` once the running version matches the staged target, so the Updates tab stops showing the stale instruction.
|
||||
|
||||
## 0.9.9
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Codex (OpenAI CLI) run mode, Claude Model picker, and response-viewer button now opt-in.
|
||||
|
||||
**Codex (OpenAI CLI) run mode** (#114): new `codex` session mode alongside Claude Code and OpenCode. Sessions launch the Codex CLI via tmux with secrets injected through `tmux setenv` (`OPENAI_API_KEY`/`CODEX_API_KEY`/`CODEX_HOME` — never on the command line). Supports `--model`, `resume <id>`, and `--dangerously-bypass-approvals-and-sandbox` via the `codexConfig` payload or the new App Settings → Codex CLI tab (`codexDangerouslyBypassApprovals`). Availability surfaced at `GET /api/codex/status` with an install hint when the binary is missing. Frontend gets a "Run CX" run-mode option; Respawn/Ralph options stay Claude-only (session options open on the Summary tab for external-CLI sessions). `CODEX_*` env prefix added to the env-override allowlist.
|
||||
|
||||
**Claude Model picker**: App Settings → Claude CLI gains a "Claude Model" select (`claudeModel` setting) that pins the model for new Claude sessions via the case's `.claude/settings.local.json` — e.g. Fable 5 (1M context), Fable 5, Opus (1M), Opus, Sonnet, Haiku. It takes precedence over the legacy 1M Opus Context toggle. Fable 5 also added to the orchestrator default/phase model dropdowns.
|
||||
|
||||
**Response-viewer (eye) header button is now hidden by default** — existing users who relied on it can re-enable it under App Settings → Display → Response Viewer (`showResponseViewer`, per-device setting). A new Display toggle controls its visibility.
|
||||
|
||||
Also: tests made immune to a set `CODEMAN_GESTURE` env var; CLAUDE.md documents the Codex run mode and the eye-button toggle.
|
||||
|
||||
## 0.9.8
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -56,13 +56,13 @@ When user says "COM":
|
||||
|
||||
CI runs `npm run check:lockfile` on every push/PR, so lockfile drift fails the build even if the `version-packages` script is bypassed.
|
||||
|
||||
**Version**: 0.9.8 (must match `package.json`)
|
||||
**Version**: 0.9.13 (must match `package.json`)
|
||||
|
||||
## Project Overview
|
||||
|
||||
Codeman is a Claude Code session manager with web interface and autonomous Ralph Loop. Spawns Claude CLI via PTY, streams via SSE, supports respawn cycling for 24+ hour autonomous runs.
|
||||
|
||||
**Tech Stack**: TypeScript (ES2022/NodeNext, strict mode), Node.js, Fastify, node-pty, xterm.js. Supports both Claude Code and OpenCode AI CLIs via pluggable CLI resolvers.
|
||||
**Tech Stack**: TypeScript (ES2022/NodeNext, strict mode), Node.js, Fastify, node-pty, xterm.js. Supports Claude Code, OpenCode, and Codex (OpenAI) CLIs via pluggable CLI resolvers (`SessionMode = 'claude' | 'shell' | 'opencode' | 'codex'`).
|
||||
|
||||
**TypeScript Strictness** (see `tsconfig.json`): `noUnusedLocals`, `noUnusedParameters`, `noImplicitReturns`, `noImplicitOverride`, `noFallthroughCasesInSwitch`, `allowUnreachableCode: false`, `allowUnusedLabels: false`.
|
||||
|
||||
@@ -100,9 +100,9 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
||||
- **ESM only** — Never `require()`, use `await import()`. `tsx` masks CJS/ESM issues in dev but production breaks
|
||||
- **Package ≠ product name** — npm: `aicodeman`, product: **Codeman**. Release renames tags accordingly. Both `aicodeman` and `codeman` bin aliases are installed (`package.json` `bin`)
|
||||
- **Global regex `lastIndex`** — Shared `g`-flag patterns in loops must reset `lastIndex = 0` first, or use the `execPattern()` helper in `utils/regex-patterns.ts` (resets automatically)
|
||||
- **`envOverrides` flow `CLAUDE_CODE_*` / `OPENCODE_*` env vars** — Set via `POST /api/sessions { envOverrides }`, stored on `Session._envOverrides`, exported by `tmux-manager.buildEnvExports()` at spawn time, persisted in `SessionState.envOverrides`. **Do NOT** write these to `<case>/.claude/settings.local.json` — that's the old path and creates UI/disk drift
|
||||
- **`envOverrides` flow `CLAUDE_CODE_*` / `OPENCODE_*` / `CODEX_*` env vars** — Set via `POST /api/sessions { envOverrides }`, stored on `Session._envOverrides`, exported by `tmux-manager.buildEnvExports()` at spawn time, persisted in `SessionState.envOverrides`. **Do NOT** write these to `<case>/.claude/settings.local.json` — that's the old path and creates UI/disk drift
|
||||
- **Effort is NOT an env var** — never carry effort as `CLAUDE_CODE_EFFORT_LEVEL`: the env var hard-locks effort and blocks in-session `/effort` switching (incl. ultracode). It flows as the dedicated `effort` payload field → `Session._effort` → `claude --effort <level>` for regular levels incl. `max` (the settings `effortLevel` key is `enum(["low","medium","high","xhigh"]).catch(undefined)` — `max` gets SILENTLY dropped there), or `claude --settings '{"ultracode":true}'` for ultracode (rejected by `--effort`). Both are soft defaults the user can override anytime. Legacy env-var entries are auto-migrated by the Session constructor and unset from tmux sessions in `applyEnvOverrides()`. See `buildEffortCliArgs()` in `session-cli-builder.ts`, tests in `test/effort-injection.test.ts`
|
||||
- **Dual-CLI prefix discipline** — Codeman supports both Claude Code and OpenCode (`claude-cli-resolver.ts` / `opencode-cli-resolver.ts`); env-var prefix is CLI-specific (`CLAUDE_CODE_*` vs `OPENCODE_*`) and the allowlist in `schemas.ts` enforces this. When adding settings, decide which CLI(s) it applies to and gate the env export accordingly — don't blindly forward both prefixes. See `docs/opencode-integration.md` for the OpenCode resolver design
|
||||
- **Multi-CLI prefix discipline** — Codeman supports Claude Code, OpenCode, and Codex (`claude-cli-resolver.ts` / `opencode-cli-resolver.ts` / `codex-cli-resolver.ts`); env-var prefix is CLI-specific (`CLAUDE_CODE_*` vs `OPENCODE_*` vs `CODEX_*`) and the allowlist in `schemas.ts` enforces this. When adding settings, decide which CLI(s) it applies to and gate the env export accordingly — don't blindly forward all prefixes. See `docs/opencode-integration.md` for the OpenCode resolver design
|
||||
- **Zod `.optional()` rejects `null`** — accepts `undefined` only. When the frontend builds a request body with `JSON.stringify`, an explicit `null` field is preserved on the wire and fails validation with `INVALID_INPUT`. Convert `null` → `undefined` before stringifying (e.g. `field: value ?? undefined`), or declare the schema `.nullish()`. Real bugs caused: 0.6.4 (`durationMinutes` for ∞ respawn), and the same shape pattern hit `opusContext1mEnabled` in 0.6.3
|
||||
- **`xterm-zerolag-input` is single-source — edit the package, then rebuild the bundle** — the local-echo overlay source lives ONLY in `packages/xterm-zerolag-input/src/` (`zerolag-input-addon.ts`; also published to npm as a standalone library — see README "Published Packages"). It is bundled (esbuild → IIFE, with appended `window.LocalEchoOverlay` aliases) into the **gitignored** `src/web/public/vendor/xterm-zerolag-input.js` by `scripts/postinstall.js` (for dev/`tsx`) and into `dist/.../vendor/` by `scripts/build.mjs:50` (for prod). `app.js` only **consumes** it via `new LocalEchoOverlay(terminal)` — there is NO inline copy to keep in sync. So: change behavior in the package source, then re-run the bundle step (`npm install` reruns postinstall; `npm run build` for prod); **never hand-edit `app.js` for overlay behavior or commit the gitignored vendor bundle**. A public-API break in the package still warrants a separate `xterm-zerolag-input` version bump in the changeset. Always test on mobile after touching it. See `docs/local-echo-overlay-plan.md`.
|
||||
- **Default bind is loopback-only; non-loopback without a password starts but warns** — since COD-29 (PR #107) the web server defaults to `--host 127.0.0.1` (was `0.0.0.0`). As of **0.9.0** binding a non-loopback host (`--host`/`-H`/`CODEMAN_HOST`) without `CODEMAN_PASSWORD` **no longer refuses to start — it starts and prints a loud warning** listing the fixes (set `CODEMAN_PASSWORD`, bind loopback + tunnel/`tailscale serve`, or `--allow-unauthenticated-network` / `CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK=1` to acknowledge → terser note). Host classification is `isLoopbackBindHost()` in `network-auth-policy.ts`; the warn-vs-start logic is in `server.ts` `start()`; flags wired in `cli.ts`. ⚠️ Operational note: the production systemd unit runs `node dist/index.js web --https` with no `--host`, so it binds **localhost only** — reach it remotely via `tailscale serve`/tunnel to `127.0.0.1`, or add `Environment=CODEMAN_HOST=0.0.0.0` + `Environment=CODEMAN_PASSWORD=…` to `~/.config/systemd/user/codeman-web.service`. A loopback bind is reachable through a same-host tunnel (cloudflared/tailscale → `127.0.0.1`) but NOT by a browser hitting the box's LAN IP. Auth user defaults to `admin`. **Full model: `docs/security-architecture.md`.**
|
||||
@@ -117,7 +117,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
||||
| Domain | Key files | Notes |
|
||||
|--------|-----------|-------|
|
||||
| **Entry** | `src/index.ts`, `src/cli.ts` | |
|
||||
| **Session** | `src/session.ts` ★, `src/session-manager.ts`, `src/session-auto-ops.ts`, `src/session-cli-builder.ts`, `src/session-lifecycle-log.ts`, `src/session-task-cache.ts` | |
|
||||
| **Session** | `src/session.ts` ★, `src/session-manager.ts`, `src/session-auto-ops.ts`, `src/session-cli-builder.ts`, `src/session-lifecycle-log.ts`, `src/session-task-cache.ts`, `src/usage-limit-patterns.ts` | |
|
||||
| **Mux** | `src/mux-interface.ts`, `src/mux-factory.ts`, `src/tmux-manager.ts` ★ | |
|
||||
| **Respawn** | `src/respawn-controller.ts` ★ + 4 helpers (`-adaptive-timing`, `-health`, `-metrics`, `-patterns`) | Read `docs/respawn-state-machine.md` first |
|
||||
| **Ralph** | `src/ralph-tracker.ts` ★, `src/ralph-loop.ts` + 5 helpers (`-config`, `-fix-plan-watcher`, `-plan-tracker`, `-stall-detector`, `-status-parser`) | Read `docs/ralph-wiggum-guide.md` first |
|
||||
@@ -127,18 +127,18 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
||||
| **Tasks** | `src/task.ts`, `src/task-queue.ts`, `src/task-tracker.ts` | |
|
||||
| **State** | `src/state-store.ts`, `src/run-summary.ts`, `src/session-lifecycle-log.ts` | |
|
||||
| **Infra** | `src/hooks-config.ts`, `src/push-store.ts`, `src/tunnel-manager.ts`, `src/image-watcher.ts`, `src/file-stream-manager.ts` | |
|
||||
| **Plan** | `src/plan-orchestrator.ts`, `src/prompts/*.ts`, `src/templates/claude-md.ts` | |
|
||||
| **Plan** | `src/plan-orchestrator.ts`, `src/prompts/*.ts`, `src/templates/` (`claude-md.ts` + `case-template.md`, the CLAUDE.md scaffold generated into new cases) | |
|
||||
| **Web** | `src/web/server.ts` ★, `src/web/sse-events.ts`, `src/web/routes/*.ts` (15 route modules + barrel; `session-routes.ts` ★), `src/web/route-helpers.ts`, `src/web/ports/*.ts`, `src/web/middleware/auth.ts`, `src/web/schemas.ts`, `src/web/self-update.ts` | |
|
||||
| **Frontend** | `src/web/public/app.js` (~3.6K lines, core) + 5 infra modules (`constants.js`, `mobile-handlers.js`, `voice-input.js`, `notification-manager.js`, `keyboard-accessory.js`) + 7 domain modules (`terminal-ui.js`, `respawn-ui.js`, `ralph-panel.js`, `orchestrator-panel.js`, `settings-ui.js`, `panels-ui.js`, `session-ui.js`) + 5 feature modules (`ralph-wizard.js`, `api-client.js`, `subagent-windows.js`, `input-cjk.js`, `image-input.js`) + `sw.js` | |
|
||||
| **Types** | `src/types/index.ts` (barrel) → 15 domain files; also `src/types.ts` root re-export | See `@fileoverview` in index.ts |
|
||||
|
||||
★ = Large, central file (>50KB) — read its `@fileoverview` first. All files have `@fileoverview` JSDoc — read that before diving in. Discovery aid: `grep -l '@fileoverview' src/web/routes/*.ts` lists all route modules; same grep works for `src/types/`, `src/web/public/*.js`.
|
||||
|
||||
**Local packages**: `packages/xterm-zerolag-input/` — local echo overlay for xterm.js; copy embedded in `app.js`. `packages/gesture-control/` (`codeman-gesture-control`) — hand-tracking overlay source; built to `src/web/public/gesture/gesture-codeman.js` via `npm run build:gesture` (see Frontend → Gesture control).
|
||||
**Local packages**: `packages/xterm-zerolag-input/` — local echo overlay for xterm.js; single-source, bundled to the gitignored `vendor/xterm-zerolag-input.js` and consumed by `app.js` (see Gotchas). `packages/gesture-control/` (`codeman-gesture-control`) — hand-tracking overlay source; built to `src/web/public/gesture/gesture-codeman.js` via `npm run build:gesture` (see Frontend → Gesture control).
|
||||
|
||||
**Config**: `src/config/` — 10 files, no barrel (`index.ts`) exists; import from the specific file.
|
||||
|
||||
**Utilities**: `src/utils/` — re-exported via index. Key: `CleanupManager`, `LRUMap`, `StaleExpirationMap`, `BufferAccumulator`, `stripAnsi`, `Debouncer`, `KeyedDebouncer`. Also: `claude-cli-resolver`/`opencode-cli-resolver` (CLI path resolution), `string-similarity` (fuzzy matching), `regex-patterns` (ANSI/token/spinner patterns), `assertNever` (exhaustive checks), `token-validation` (auth tokens), `nice-wrapper` (process priority).
|
||||
**Utilities**: `src/utils/` — re-exported via index. Key: `CleanupManager`, `LRUMap`, `StaleExpirationMap`, `BufferAccumulator`, `stripAnsi`, `Debouncer`, `KeyedDebouncer`. Also: `claude-cli-resolver`/`opencode-cli-resolver`/`codex-cli-resolver` (CLI path resolution), `string-similarity` (fuzzy matching), `regex-patterns` (ANSI/token/spinner patterns), `assertNever` (exhaustive checks), `token-validation` (auth tokens), `nice-wrapper` (process priority).
|
||||
|
||||
### Data Flow
|
||||
|
||||
@@ -153,15 +153,19 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
|
||||
|
||||
**Idle detection**: Multi-layer (completion message → AI check → output silence → token stability). See `docs/respawn-state-machine.md`.
|
||||
|
||||
**Auto-resume on usage limit** ("token pause" control, opt-in per session, top of the Respawn tab): when Claude halts on a subscription limit ("5-hour limit reached ∙ resets 8pm" and all 1.0.x–2.1.x variants), `usage-limit-patterns.ts` (pure, unit-tested) parses the reset time from cleaned output; `SessionAutoOps` arms a timer for reset+2min, then sends Esc (dismisses the rate-limit dialog) + `continue`. Still-limited responses re-arm the loop (5-min retry on stale times); a `working` transition cancels it. Claude-mode only (detection rides `_processExpensiveParsers`). Persists/recovers via `SessionState.autoResumeEnabled`/`autoResumeAt`; respawn cycles are blocked while paused (`isLimitPaused` guard in `onIdleDetected` — prevents `/clear` from wiping the paused conversation). Endpoint: `POST /api/sessions/:id/auto-resume`; SSE: `session:limitPauseScheduled`/`limitResume`/`limitResumeCancelled`. Tests: `test/usage-limit-patterns.test.ts`, `test/session-auto-resume.test.ts`.
|
||||
|
||||
**Orchestrator**: State machine that turns a user goal into a phased plan and drives it to completion: `idle → planning → approval → executing → verifying → (replanning) → completed/failed`. `OrchestratorLoop` (engine) delegates plan generation to `orchestrator-planner` and per-phase verification gates to `orchestrator-verifier`, executing phases via team agents/`task-queue`. State persists under the `orchestrator` key in `state.json`. Distinct from Ralph (single-session autonomous loop) — orchestrator coordinates multi-phase, multi-agent execution. See `docs/orchestrator-loop-architecture.md`.
|
||||
|
||||
**Hook events**: Claude Code hooks trigger via `/api/hook-event`. Key events: `permission_prompt`, `elicitation_dialog`, `idle_prompt`, `stop`, `teammate_idle`, `task_completed`. See `src/hooks-config.ts`.
|
||||
**External CLI modes (OpenCode, Codex)**: `isExternalCliMode()` in `session.ts` gates Claude-specific behavior — Ralph tracker, BashToolParser, token/CLI-info parsing, and ❯-prompt readiness detection are all skipped (these CLIs render their own TUIs; readiness = output stabilization instead). Both modes **require tmux — no direct PTY fallback** — because secrets are injected via `tmux setenv`, never on the spawn command line: OpenCode gets `OPENCODE_CONFIG_CONTENT` etc., Codex gets `OPENAI_API_KEY`/`CODEX_API_KEY`/`CODEX_HOME` (`setCodexEnvVars` in `tmux-manager.ts`). Codex specifics: command built by `buildCodexCommand()` (`--model`, `resume <id>`, `--dangerously-bypass-approvals-and-sandbox` from the `codexConfig` payload / `codexDangerouslyBypassApprovals` app setting; `renderMode` is schema-coerced to `'hybrid'`, the only supported mode); tmux exports `COLORTERM=truecolor` + unsets `NO_COLOR` (other modes unset `COLORTERM`); availability via `GET /api/codex/status` — session/quick-start routes fail with `OPERATION_FAILED` and an install hint (`npm install -g @openai/codex`) when the binary is missing. Frontend: run-mode dropdown → `runCodex()` in `session-ui.js` ("Run CX" label), App Settings → Codex CLI tab; Respawn/Ralph options are Claude-only, so session options open on the Summary tab for external CLI sessions. Tests: `test/run-mode-ui.test.ts` (vm-sandbox harness, no real DOM).
|
||||
|
||||
**Hook events**: Claude Code hooks trigger via `/api/hook-event`. Key events: `permission_prompt`, `elicitation_dialog`, `idle_prompt`, `stop`, `teammate_idle`, `task_completed`. See `src/hooks-config.ts`; upstream hook semantics mirrored in `docs/claude-code-hooks-reference.md`.
|
||||
|
||||
**Agent Teams**: `TeamWatcher` polls `~/.claude/teams/`, matches to sessions via `leadSessionId`. Teammates are in-process threads appearing as subagents. Enable: `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1`. See `docs/agent-teams/`.
|
||||
|
||||
**Circuit breaker**: Prevents respawn thrashing. States: `CLOSED` → `HALF_OPEN` → `OPEN`. Reset: `/api/sessions/:id/ralph-circuit-breaker/reset`.
|
||||
|
||||
**Self-update** (App Settings → Updates): in-app updater for **git-clone installs** supervised by systemd/launchd. The update restarts the very process running it, so the real work runs in a DETACHED `scripts/self-update.sh` (`git checkout <release tag> && npm install && npm run build && restart`) that outlives the restart; it writes progress to `dataPath('update-status.json')`, which the browser polls across the connection drop. Channel = latest `codeman@X.Y.Z` release tag; dirty trees are auto-stashed. `src/web/self-update.ts` splits PURE helpers (semver/tag parsing, reconcile decision — unit-tested) from IO wrappers (`getInstallInfo`/`checkForUpdate`/`startUpdate`/`reconcileUpdateOnBoot`). Routes: `GET /api/system/update/check`, `POST /api/system/update`, `GET /api/system/update/status`. Types: `src/types/update.ts`. npm installs report as non-updatable.
|
||||
**Self-update** (App Settings → Updates): in-app updater for **git-clone installs** supervised by systemd/launchd. Supervisors: `systemd` (user unit), `launchd` (GUI LaunchAgent, gui-domain kickstart), `launchd-daemon` (KeepAlive system LaunchDaemon on headless Macs — restarts rootlessly by killing the server PID and letting launchd respawn it; detected only when the daemon is bootstrapped AND KeepAlive), else `none` → "restart manually" message; on next boot a manual-restart status auto-completes when the running version matches the target. The update restarts the very process running it, so the real work runs in a DETACHED `scripts/self-update.sh` (`git checkout <release tag> && npm install && npm run build && restart`) that outlives the restart; it writes progress to `dataPath('update-status.json')`, which the browser polls across the connection drop. Channel = latest `codeman@X.Y.Z` release tag; dirty trees are auto-stashed. `src/web/self-update.ts` splits PURE helpers (semver/tag parsing, reconcile decision — unit-tested) from IO wrappers (`getInstallInfo`/`checkForUpdate`/`startUpdate`/`reconcileUpdateOnBoot`). Routes: `GET /api/system/update/check`, `POST /api/system/update`, `GET /api/system/update/status`. Types: `src/types/update.ts`. npm installs report as non-updatable.
|
||||
|
||||
**Port interfaces**: Routes declare dependencies via port interfaces (`src/web/ports/`). Routes use intersection types (e.g., `SessionPort & EventPort`).
|
||||
|
||||
@@ -173,6 +177,8 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
|
||||
|
||||
**Multi-monitor button** (header, top-right; the notification bell it sits beside stays hidden — notifications live in Settings → Notifications). `app.launchMultiMonitor()` (in `panels-ui.js`) POSTs `/api/system/span-displays`, which spawns `scripts/span-codeman.sh` — a fresh, maximized browser `--app` window sized to the union of all displays (macOS; needs "Displays have separate Spaces" OFF). Supports the gesture layer's in-page floating session panels dragging across the physical monitor seam. **Opt-in:** hidden by default; enable under App Settings → Display → **Header Displays** ("Multi-monitor Button", `showMultiMonitorButton`). The button carries a `btn-multimonitor--hidden` class in the template; `renderIndexHtml` strips that class at render when the setting is on (a unique class token, not a brittle match on the aria-label/style copy), and `applyHeaderVisibilitySettings()` toggles the same class live on save. Solo (detached) windows hide it via `body.solo-mode`.
|
||||
|
||||
**Response-viewer (eye) button** (header) is likewise **hidden by default** — enable under App Settings → Display → **Response Viewer** (`showResponseViewer`). Purely client-side (no `renderIndexHtml` step): the template ships with `btn-response-viewer-header--hidden` and `applyHeaderVisibilitySettings()` (settings-ui.js) toggles it after settings load. Hiding must go through that marker class — the base rule is `display:inline-flex !important`, so an inline style can't override it. `showResponseViewer` is in the `displayKeys` per-device set (settings-ui.js), so it does NOT sync across devices.
|
||||
|
||||
**Gesture control** (the camera hand-tracking overlay) is **opt-in, default OFF**, under App Settings → Display → **Input** (`gestureControlEnabled`). `CODEMAN_GESTURE=1` makes the feature *available* on the instance (CSP widening + `/gesture/` assets) and sets `window.__codemanGestureAvailable` (the Input section only shows when set); the overlay bundle is injected by `renderIndexHtml` **only when the setting is enabled**, so that method is `async` and reads `settings.json` via `readSettings(true)` — the `true` forces a **fresh** read (bypassing the 2s `_settingsCache`), because a post-save reload happens within that TTL and the cached value would otherwise render the pre-toggle state. Toggling the setting reloads the page (the bundle is render-injected).
|
||||
|
||||
**Gesture-control source lives in-repo** at `packages/gesture-control/` (workspace package `codeman-gesture-control`, was the standalone `Ark0N/codeman-gesture-control` repo). The transport-agnostic core is `src/gesture/*` (MediaPipe GestureRecognizer → One-Euro-filtered cursor → pinch state machine); `src/codeman/entry.ts` is the Codeman *consumer* that maps grab/drag/drop onto real `.session-tab`/toolbar buttons and is the bundle entry. **Edit there, then run `npm run build:gesture`** (`scripts/build-gesture-bundle.mjs` → esbuild bundles `entry.ts`, MediaPipe JS included, into `src/web/public/gesture/gesture-codeman.js`) and **commit the regenerated bundle** — the committed bundle is what dev/`tsx` serves (no bundler at runtime), and `scripts/build.mjs` reruns the same step so prod always reflects current source. The MediaPipe **wasm + model** are NOT bundled — loaded at runtime from same-origin `/gesture/wasm` + `/gesture/gesture_recognizer.task`, fetched by `scripts/fetch-gesture-assets.mjs` (gitignored, see Gotchas). `entry.ts` mounts `window.__codemanGesture = new GestureBridge()` idempotently at module-eval. A standalone vite playground (`npm run dev` in the package — fake tabs, no Codeman) lets you iterate on gesture *feel* in isolation. ⚠️ Keep `MP_VERSION` in `fetch-gesture-assets.mjs` in sync with `@mediapipe/tasks-vision` in `packages/gesture-control/package.json`.
|
||||
@@ -196,7 +202,7 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
|
||||
| **Rate limit** | 10 failed auth/IP → 429 (15min decay). QR has separate limiter |
|
||||
| **Hook bypass** | `/api/hook-event` exempt from auth (localhost-only, schema-validated) |
|
||||
| **Env vars** | `CODEMAN_MUX` (managed session), `CODEMAN_API_URL` (auto-set for hooks), `CODEMAN_ALLOWED_HOSTS` (extra Host/Origin allowlist entries for reverse proxies, comma-separated; bare `.suffix` matches subdomains) |
|
||||
| **Validation** | Zod schemas, path allowlist regex, `CLAUDE_CODE_*` env prefix allowlist |
|
||||
| **Validation** | Zod schemas, path allowlist regex, env prefix allowlist (`CLAUDE_CODE_*`/`OPENCODE_*`/`CODEX_*`) |
|
||||
| **Headers** | CORS localhost-only, CSP, X-Frame-Options, HSTS if HTTPS |
|
||||
|
||||
### SSE Event Registry
|
||||
@@ -205,9 +211,9 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L
|
||||
|
||||
### API Routes
|
||||
|
||||
~134 handlers across 15 route files in `src/web/routes/`: system (40, incl. self-update `check`/`status`/`POST /api/system/update` + `POST /api/system/span-displays` → spawns `scripts/span-codeman.sh`), sessions (28), orchestrator (10), cases (9), ralph (9), plan (8), respawn (7), files (6), mux (5), push (4), scheduled (4), teams (2), hooks (1), clipboard (1), ws (1 WebSocket). Each file has `@fileoverview` with endpoint details.
|
||||
~136 handlers across 15 route files in `src/web/routes/`: system (41, incl. self-update `check`/`status`/`POST /api/system/update`, `POST /api/system/span-displays` → spawns `scripts/span-codeman.sh`, and `GET /api/codex/status`), sessions (29), orchestrator (10), cases (9), ralph (9), plan (8), respawn (7), files (6), mux (5), push (4), scheduled (4), teams (2), hooks (1), clipboard (1), ws (1 WebSocket). Each file has `@fileoverview` with endpoint details.
|
||||
|
||||
**HTTP contract** (stable since 0.9.x, see `docs/versioning-policy.md`): responses use the `ApiResponse<T>` envelope — `{ success: true, data? }` or `{ success: false, error, errorCode }` (`src/types/api.ts`). `/api/v1/*` is a versioned alias of `/api/*` (URL rewrite in `server.ts`).
|
||||
**HTTP contract** (stable since 0.9.x, see `docs/versioning-policy.md`; full envelope/status/error-code/SSE spec in `docs/api-reference.md`): responses use the `ApiResponse<T>` envelope — `{ success: true, data? }` or `{ success: false, error, errorCode }` (`src/types/api.ts`). `/api/v1/*` is a versioned alias of `/api/*` (URL rewrite in `server.ts`).
|
||||
|
||||
## Adding Features
|
||||
|
||||
@@ -245,7 +251,7 @@ Raw `npx vitest` skips `config/vitest.config.ts`; always use `npm test --` or pa
|
||||
|
||||
**Ports**: Pick unique ports manually. Search `const PORT =` before adding new tests.
|
||||
|
||||
**Respawn tests**: Use `MockSession` from `test/respawn-test-utils.ts`. **Route tests**: `app.inject({ method, url, payload })` in `test/routes/` — no live port needed. **Mobile tests**: Playwright suite in `test/mobile/` (135 device profiles).
|
||||
**Respawn tests**: Use `MockSession` from `test/respawn-test-utils.ts`. **Route tests**: `app.inject({ method, url, payload })` in `test/routes/` — no live port needed. **Mobile tests**: Playwright suite in `test/mobile/` (135 device profiles). Browser-testing infra and practices: `docs/browser-testing-guide.md`.
|
||||
|
||||
## Debugging
|
||||
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
<img src="docs/images/codeman-title.svg" alt="Codeman" height="60">
|
||||
</p>
|
||||
|
||||
<h2 align="center">The missing control plane for AI coding agents</h2>
|
||||
<h2 align="center">Mission control for AI coding agents</h2>
|
||||
|
||||
<p align="center">
|
||||
<em>Agent Visualization • Zero-Lag Input • Mobile-First UI • Hardened Security</em>
|
||||
<em>Claude Code • OpenCode • Codex — One Dashboard • Any Device</em>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -34,7 +34,7 @@ curl -fsSL https://raw.githubusercontent.com/Ark0N/Codeman/master/install.sh | b
|
||||
|
||||
This installs Node.js and tmux if missing, clones Codeman to `~/.codeman/app`, and builds it.
|
||||
|
||||
You'll need at least one AI coding CLI installed — [Claude Code](https://docs.anthropic.com/en/docs/claude-code) or [OpenCode](https://opencode.ai) (or both). After install:
|
||||
You'll need at least one AI coding CLI installed — [Claude Code](https://docs.anthropic.com/en/docs/claude-code), [OpenCode](https://opencode.ai), or [Codex](https://developers.openai.com/codex/cli) (any combination works). After install:
|
||||
|
||||
```bash
|
||||
codeman web
|
||||
@@ -103,7 +103,7 @@ launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.codeman.web.plist
|
||||
wsl bash -c "curl -fsSL https://raw.githubusercontent.com/Ark0N/Codeman/master/install.sh | bash"
|
||||
```
|
||||
|
||||
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) or [OpenCode](https://opencode.ai)). After installing, `http://localhost:3000` is accessible from your Windows browser.
|
||||
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.
|
||||
</details>
|
||||
|
||||
---
|
||||
@@ -293,7 +293,7 @@ PTY Output → 16ms Server Batch → DEC 2026 Wrap → SSE → Client rAF → xt
|
||||
## More Features
|
||||
|
||||
- **Self-update** — git-clone installs under systemd/launchd update in place from **App Settings → Updates**: it detects the latest release, auto-stashes a dirty tree, and streams build progress across the service restart (npm installs report as non-updatable)
|
||||
- **Dual-CLI** — run **Claude Code** or **OpenCode** per session; env-var prefixes auto-gate (`CLAUDE_CODE_*` vs `OPENCODE_*`). See [`docs/opencode-integration.md`](docs/opencode-integration.md)
|
||||
- **Multi-CLI** — run **Claude Code**, **OpenCode**, or **Codex** per session; env-var prefixes auto-gate (`CLAUDE_CODE_*` vs `OPENCODE_*` vs `CODEX_*`). See [`docs/opencode-integration.md`](docs/opencode-integration.md)
|
||||
- **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
|
||||
@@ -447,7 +447,7 @@ These run for **every** request — before auth, even on the default no-password
|
||||
|
||||
### Input, files & headers
|
||||
|
||||
- **Schema-validated inputs** — every API body is checked with Zod v4 schemas; a `CLAUDE_CODE_*` / `OPENCODE_*` env-prefix allowlist gates which settings each CLI can receive
|
||||
- **Schema-validated inputs** — every API body is checked with Zod v4 schemas; a `CLAUDE_CODE_*` / `OPENCODE_*` / `CODEX_*` env-prefix allowlist gates which settings each CLI can receive
|
||||
- **Path containment** — file routes `realpath` before boundary checks (no TOCTOU); `..`, absolute paths, and symlinks resolving outside the working dir are rejected. Caps: 10 MB text preview / 50 MB raw & download; `/api/download` blocklists sensitive paths (`.env`, `*credentials*`, `~/.ssh/`, `.aws/credentials`). SVG/HTML is served `octet-stream` + `nosniff` + attachment so it downloads rather than executes
|
||||
- **Security headers** — `Content-Security-Policy` (`default-src 'self'`, every exception enumerated), `X-Content-Type-Options: nosniff`, `X-Frame-Options: SAMEORIGIN`, HSTS over HTTPS, and CORS reflected **only** for `localhost` / `127.0.0.1` / `::1`
|
||||
|
||||
@@ -579,7 +579,7 @@ flowchart TB
|
||||
end
|
||||
|
||||
subgraph External["External"]
|
||||
CLI["AI CLI<br/><small>Claude Code / OpenCode</small>"]
|
||||
CLI["AI CLI<br/><small>Claude Code / OpenCode / Codex</small>"]
|
||||
BG["Background Agents<br/><small>(Task tool)</small>"]
|
||||
end
|
||||
end
|
||||
|
||||
+7
-7
@@ -2,10 +2,10 @@
|
||||
<img src="docs/images/codeman-title.svg" alt="Codeman" height="60">
|
||||
</p>
|
||||
|
||||
<h2 align="center">为 AI 编程智能体而生的「控制平面」</h2>
|
||||
<h2 align="center">AI 编程智能体的任务控制中心</h2>
|
||||
|
||||
<p align="center">
|
||||
<em>智能体可视化 • 零延迟输入 • 自主编排器 • 重生控制器 • 移动优先 UI • 安全加固</em>
|
||||
<em>Claude Code • OpenCode • Codex —— 统一仪表盘 • 任意设备</em>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -36,7 +36,7 @@ curl -fsSL https://raw.githubusercontent.com/Ark0N/Codeman/master/install.sh | b
|
||||
|
||||
该脚本会在缺失时自动安装 Node.js 和 tmux,把 Codeman 克隆到 `~/.codeman/app` 并完成构建。
|
||||
|
||||
你至少需要安装一个 AI 编程 CLI —— [Claude Code](https://docs.anthropic.com/en/docs/claude-code) 或 [OpenCode](https://opencode.ai)(两个都装也可以)。安装完成后:
|
||||
你至少需要安装一个 AI 编程 CLI —— [Claude Code](https://docs.anthropic.com/en/docs/claude-code)、[OpenCode](https://opencode.ai) 或 [Codex](https://developers.openai.com/codex/cli)(任意组合均可)。安装完成后:
|
||||
|
||||
```bash
|
||||
codeman web
|
||||
@@ -105,7 +105,7 @@ launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.codeman.web.plist
|
||||
wsl bash -c "curl -fsSL https://raw.githubusercontent.com/Ark0N/Codeman/master/install.sh | bash"
|
||||
```
|
||||
|
||||
Codeman 依赖 tmux,因此 Windows 用户需要 [WSL](https://learn.microsoft.com/en-us/windows/wsl/install)。如果还没装 WSL:在管理员 PowerShell 中运行 `wsl --install`,重启,打开 Ubuntu,然后在 WSL 内安装你偏好的 AI 编程 CLI([Claude Code](https://docs.anthropic.com/en/docs/claude-code) 或 [OpenCode](https://opencode.ai))。安装完成后,即可从 Windows 浏览器访问 `http://localhost:3000`。
|
||||
Codeman 依赖 tmux,因此 Windows 用户需要 [WSL](https://learn.microsoft.com/en-us/windows/wsl/install)。如果还没装 WSL:在管理员 PowerShell 中运行 `wsl --install`,重启,打开 Ubuntu,然后在 WSL 内安装你偏好的 AI 编程 CLI([Claude Code](https://docs.anthropic.com/en/docs/claude-code)、[OpenCode](https://opencode.ai) 或 [Codex](https://developers.openai.com/codex/cli))。安装完成后,即可从 Windows 浏览器访问 `http://localhost:3000`。
|
||||
</details>
|
||||
|
||||
---
|
||||
@@ -295,7 +295,7 @@ PTY 输出 → 16ms 服务端批处理 → DEC 2026 包裹 → SSE → 客户端
|
||||
## 更多特性
|
||||
|
||||
- **自更新** —— systemd/launchd 管理下的 git-clone 安装可在 **App Settings → Updates** 中原地更新:它会检测最新发行版,自动暂存(stash)脏工作树,并在服务重启期间流式展示构建进度(npm 安装会被报告为不可更新)
|
||||
- **双 CLI** —— 每个会话可选 **Claude Code** 或 **OpenCode**;环境变量前缀自动隔离(`CLAUDE_CODE_*` 与 `OPENCODE_*`)。详见 [`docs/opencode-integration.md`](docs/opencode-integration.md)
|
||||
- **多 CLI** —— 每个会话可选 **Claude Code**、**OpenCode** 或 **Codex**;环境变量前缀自动隔离(`CLAUDE_CODE_*`、`OPENCODE_*` 与 `CODEX_*`)。详见 [`docs/opencode-integration.md`](docs/opencode-integration.md)
|
||||
- **Effort 与 Ultracode** —— 设置每会话的默认 effort(`low`–`max`),或启用 **ultracode**(动态多智能体工作流)。这些都只是软默认值 —— 会话中可随时用 `/effort` 切换。扩展思考预算也可配置
|
||||
- **语音输入** —— 用 Deepgram Nova-3 口述提示(带 Web Speech API 回退):切换录音、自动静音停止、实时音量表(`Ctrl+Shift+V`)
|
||||
- **图像输入** —— 直接把图片粘贴或拖放进会话
|
||||
@@ -449,7 +449,7 @@ Codeman 用 `--dangerously-skip-permissions` 启动会话,因此 Web UI 在设
|
||||
|
||||
### 输入、文件与响应头
|
||||
|
||||
- **模式校验的输入** —— 每个 API 请求体都用 Zod v4 模式检查;一个 `CLAUDE_CODE_*` / `OPENCODE_*` 环境变量前缀允许列表把控每个 CLI 能接收哪些设置
|
||||
- **模式校验的输入** —— 每个 API 请求体都用 Zod v4 模式检查;一个 `CLAUDE_CODE_*` / `OPENCODE_*` / `CODEX_*` 环境变量前缀允许列表把控每个 CLI 能接收哪些设置
|
||||
- **路径限定** —— 文件路由在边界检查前先 `realpath`(无 TOCTOU);`..`、绝对路径、以及解析到工作目录之外的符号链接都会被拒绝。上限:10 MB 文本预览 / 50 MB 原始与下载;`/api/download` 对敏感路径(`.env`、`*credentials*`、`~/.ssh/`、`.aws/credentials`)做黑名单。SVG/HTML 以 `octet-stream` + `nosniff` + attachment 提供,因此会被下载而非执行
|
||||
- **安全响应头** —— `Content-Security-Policy`(`default-src 'self'`,每个例外都逐条列举)、`X-Content-Type-Options: nosniff`、`X-Frame-Options: SAMEORIGIN`、HTTPS 下的 HSTS,以及**仅**对 `localhost` / `127.0.0.1` / `::1` 反射的 CORS
|
||||
|
||||
@@ -581,7 +581,7 @@ flowchart TB
|
||||
end
|
||||
|
||||
subgraph External["外部"]
|
||||
CLI["AI CLI<br/><small>Claude Code / OpenCode</small>"]
|
||||
CLI["AI CLI<br/><small>Claude Code / OpenCode / Codex</small>"]
|
||||
BG["后台智能体<br/><small>(Task 工具)</small>"]
|
||||
end
|
||||
end
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "aicodeman",
|
||||
"version": "0.9.8",
|
||||
"version": "0.9.13",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "aicodeman",
|
||||
"version": "0.9.8",
|
||||
"version": "0.9.13",
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"workspaces": [
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "aicodeman",
|
||||
"version": "0.9.8",
|
||||
"description": "The missing control plane for AI coding agents - run 20 autonomous agents with real-time monitoring and session persistence",
|
||||
"version": "0.9.13",
|
||||
"description": "Mission control for AI coding agents - run 20 autonomous agents with real-time monitoring and session persistence",
|
||||
"type": "module",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
|
||||
@@ -39,7 +39,7 @@ Server echoes 'h' ←───────────────────
|
||||
|
||||
## Origin
|
||||
|
||||
This library was extracted from [Codeman](https://github.com/Ark0N/Codeman), the missing control plane for AI coding agents — multi-session management, real-time agent visualization, autonomous respawn loops, and a mobile-first web UI for Claude Code and OpenCode. The local echo system was built to make mobile and remote access feel instant, then battle-tested across thousands of hours of real usage. After 3 deep code audits, it was extracted into this standalone library with 78 tests covering every state transition.
|
||||
This library was extracted from [Codeman](https://github.com/Ark0N/Codeman), mission control for AI coding agents — multi-session management, real-time agent visualization, autonomous respawn loops, and a mobile-first web UI for Claude Code, OpenCode, and Codex. The local echo system was built to make mobile and remote access feel instant, then battle-tested across thousands of hours of real usage. After 3 deep code audits, it was extracted into this standalone library with 78 tests covering every state transition.
|
||||
|
||||
## Install
|
||||
|
||||
|
||||
@@ -31,6 +31,7 @@ export PUPPETEER_SKIP_DOWNLOAD="${PUPPETEER_SKIP_DOWNLOAD:-1}"
|
||||
REPO=""
|
||||
TAG=""
|
||||
SUPERVISOR="none"
|
||||
SERVER_PID=""
|
||||
STATUS_FILE=""
|
||||
UPDATE_ID=""
|
||||
FROM_VERSION=""
|
||||
@@ -50,6 +51,7 @@ while [[ $# -gt 0 ]]; do
|
||||
--node) NODE="$2"; shift 2 ;;
|
||||
--log) LOG="$2"; shift 2 ;;
|
||||
--prev-sha) PREV_SHA="$2"; shift 2 ;;
|
||||
--server-pid) SERVER_PID="$2"; shift 2 ;;
|
||||
--stash) DO_STASH=1; shift ;;
|
||||
*) shift ;;
|
||||
esac
|
||||
@@ -198,6 +200,19 @@ case "$SUPERVISOR" in
|
||||
|| fail "Build succeeded but launchd restart failed" "launchctl"
|
||||
}
|
||||
;;
|
||||
launchd-daemon)
|
||||
# System-level KeepAlive LaunchDaemon (headless Mac): kickstarting the system
|
||||
# domain needs root, but we don't need it — kill the server and launchd
|
||||
# respawns it on the new dist/ within ThrottleInterval seconds.
|
||||
if [[ -n "$SERVER_PID" ]] && kill "$SERVER_PID" 2>/dev/null; then
|
||||
: # respawn is launchd's job from here
|
||||
else
|
||||
MANUAL_CMD="sudo launchctl kickstart -k system/com.codeman.web"
|
||||
write_status "completed-needs-manual-restart" "Update staged — restart Codeman to apply v$TO_VERSION."
|
||||
echo "[self-update] launchd-daemon: could not signal server pid '$SERVER_PID' — manual restart required"
|
||||
exit 0
|
||||
fi
|
||||
;;
|
||||
*)
|
||||
MANUAL_CMD="pkill -f 'codeman.*web'; codeman web &"
|
||||
write_status "completed-needs-manual-restart" "Update staged — restart Codeman to apply v$TO_VERSION."
|
||||
|
||||
@@ -14,6 +14,7 @@ import type {
|
||||
ClaudeMode,
|
||||
SessionMode,
|
||||
OpenCodeConfig,
|
||||
CodexConfig,
|
||||
EffortLevel,
|
||||
} from './types.js';
|
||||
|
||||
@@ -62,6 +63,7 @@ export interface CreateSessionOptions {
|
||||
claudeMode?: ClaudeMode;
|
||||
allowedTools?: string;
|
||||
openCodeConfig?: OpenCodeConfig;
|
||||
codexConfig?: CodexConfig;
|
||||
/** When restoring after reboot, resume a previous Claude conversation by its session ID */
|
||||
resumeSessionId?: string;
|
||||
/** Extra env vars exported before launching the CLI (e.g., CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS). Ephemeral — not written to disk. */
|
||||
@@ -80,6 +82,7 @@ export interface RespawnPaneOptions {
|
||||
claudeMode?: ClaudeMode;
|
||||
allowedTools?: string;
|
||||
openCodeConfig?: OpenCodeConfig;
|
||||
codexConfig?: CodexConfig;
|
||||
/** Resume a previous Claude conversation when respawning */
|
||||
resumeSessionId?: string;
|
||||
/** Extra env vars exported before launching the CLI (preserved across respawns). */
|
||||
|
||||
@@ -8,3 +8,4 @@
|
||||
export { RESEARCH_AGENT_PROMPT } from './research-agent.js';
|
||||
export { PLANNER_PROMPT } from './planner.js';
|
||||
export { PHASE_EXECUTION_PROMPT, TEAM_LEAD_PROMPT, REPLAN_PROMPT, SINGLE_TASK_PROMPT } from './orchestrator.js';
|
||||
export { RALPH_STATUS_CONTRACT, buildRalphLoopPrompt, type RalphLoopPromptOptions } from './ralph.js';
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* @fileoverview Ralph Loop prompt construction
|
||||
*
|
||||
* Builds the full `@ralph_prompt.md` content written for a new Ralph loop
|
||||
* session, including the RALPH_STATUS block contract. The contract travels
|
||||
* with the loop prompt (not the generated CLAUDE.md) so every Ralph session
|
||||
* emits parseable status blocks regardless of the project's CLAUDE.md.
|
||||
*
|
||||
* @module prompts/ralph
|
||||
*/
|
||||
|
||||
/**
|
||||
* Structured status-reporting contract appended to every Ralph loop prompt.
|
||||
*
|
||||
* `RalphStatusParser` (src/ralph-status-parser.ts) parses this block from
|
||||
* session output — keep the field names and enum values in sync with its
|
||||
* patterns.
|
||||
*/
|
||||
export const RALPH_STATUS_CONTRACT = `## Status Reporting
|
||||
|
||||
End EVERY response with exactly this block — Codeman parses it to track the loop:
|
||||
|
||||
\`\`\`
|
||||
---RALPH_STATUS---
|
||||
STATUS: IN_PROGRESS | COMPLETE | BLOCKED
|
||||
TASKS_COMPLETED_THIS_LOOP: <number>
|
||||
FILES_MODIFIED: <number>
|
||||
TESTS_STATUS: PASSING | FAILING | NOT_RUN
|
||||
WORK_TYPE: IMPLEMENTATION | TESTING | DOCUMENTATION | REFACTORING
|
||||
EXIT_SIGNAL: false | true
|
||||
RECOMMENDATION: <one line: what to do next>
|
||||
---END_RALPH_STATUS---
|
||||
\`\`\`
|
||||
|
||||
Rules:
|
||||
- \`EXIT_SIGNAL: true\` only when ALL tasks are verifiably done — then also output the completion phrase
|
||||
- \`STATUS: BLOCKED\` when you need human input; describe the blocker in RECOMMENDATION
|
||||
- Never set \`EXIT_SIGNAL: true\` while tests are failing
|
||||
`;
|
||||
|
||||
export interface RalphLoopPromptOptions {
|
||||
/** The user's task description (becomes the prompt header) */
|
||||
taskDescription: string;
|
||||
/** Completion phrase the session must emit inside <promise></promise> */
|
||||
completionPhrase: string;
|
||||
/** Whether a @fix_plan.md task plan was generated for this loop */
|
||||
hasPlan: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the full Ralph loop prompt written to `@ralph_prompt.md`.
|
||||
*/
|
||||
export function buildRalphLoopPrompt({ taskDescription, completionPhrase, hasPlan }: RalphLoopPromptOptions): string {
|
||||
let fullPrompt = taskDescription + '\n\n---\n\n';
|
||||
if (hasPlan) {
|
||||
fullPrompt += '## Task Plan\n\n';
|
||||
fullPrompt += 'A task plan has been written to `@fix_plan.md`. Use this to track progress:\n';
|
||||
fullPrompt += '- Reference the plan at the start of each iteration\n';
|
||||
fullPrompt += '- Update task checkboxes as you complete items\n';
|
||||
fullPrompt += '- Work through items in priority order (P0 > P1 > P2)\n\n';
|
||||
}
|
||||
fullPrompt += '## Iteration Protocol\n\n';
|
||||
fullPrompt += 'This is an autonomous loop. Files from previous iterations persist. On each iteration:\n';
|
||||
fullPrompt += '1. Check what work has already been done\n';
|
||||
fullPrompt += '2. Make incremental progress toward completion\n';
|
||||
fullPrompt += '3. Commit meaningful changes with descriptive messages\n\n';
|
||||
fullPrompt += '## Verification\n\n';
|
||||
fullPrompt += 'After each significant change:\n';
|
||||
fullPrompt += '- Run tests to verify (npm test, pytest, etc.)\n';
|
||||
fullPrompt += '- Check for type/lint errors if applicable\n';
|
||||
fullPrompt += '- If tests fail, read the error, fix it, and retry\n\n';
|
||||
fullPrompt += '## Completion Criteria\n\n';
|
||||
fullPrompt += `Output \`<promise>${completionPhrase}</promise>\` when ALL of the following are true:\n`;
|
||||
fullPrompt += '- All requirements from the task description are implemented\n';
|
||||
fullPrompt += '- All tests pass\n';
|
||||
fullPrompt += '- Changes are committed\n\n';
|
||||
fullPrompt += '## If Stuck\n\n';
|
||||
fullPrompt += 'If you encounter the same error for 3+ iterations:\n';
|
||||
fullPrompt += "1. Document what you've tried\n";
|
||||
fullPrompt += '2. Identify the specific blocker\n';
|
||||
fullPrompt += '3. Try an alternative approach\n';
|
||||
fullPrompt += '4. If truly blocked, output `<promise>BLOCKED</promise>` with an explanation\n\n';
|
||||
fullPrompt += RALPH_STATUS_CONTRACT;
|
||||
return fullPrompt;
|
||||
}
|
||||
@@ -2779,6 +2779,19 @@ export class RespawnController extends EventEmitter {
|
||||
return;
|
||||
}
|
||||
|
||||
// Usage-limit pause: Claude can't work and the cycle's /clear would wipe
|
||||
// the paused conversation — the auto-resume scheduler owns recovery here.
|
||||
if (this.session.isLimitPaused) {
|
||||
this.log('Skipping respawn cycle - usage-limit pause active (auto-resume armed)');
|
||||
this.logAction('health', 'Respawn skipped: usage-limit pause (auto-resume armed)');
|
||||
this.emit('respawnBlocked', {
|
||||
reason: 'usage_limit',
|
||||
details: 'Usage limit reached — waiting for scheduled auto-resume',
|
||||
});
|
||||
this.setState('watching');
|
||||
return;
|
||||
}
|
||||
|
||||
// Start the respawn cycle
|
||||
this.cycleCount++;
|
||||
this.log(`Starting respawn cycle #${this.cycleCount}`);
|
||||
|
||||
+184
-1
@@ -1,15 +1,25 @@
|
||||
/**
|
||||
* @fileoverview Auto-compact and auto-clear automation for Session.
|
||||
* @fileoverview Auto-compact, auto-clear, and auto-resume automation for Session.
|
||||
*
|
||||
* Monitors token counts and triggers /compact or /clear commands when
|
||||
* configurable thresholds are reached. Waits for Claude to be idle
|
||||
* before sending commands, with retry logic and mutual exclusion
|
||||
* (compact and clear never run simultaneously).
|
||||
*
|
||||
* Also implements auto-resume on usage limit ("token pause" control):
|
||||
* when enabled and Claude stops on a usage-limit message ("5-hour limit
|
||||
* reached ∙ resets 8pm" and friends — see usage-limit-patterns.ts), a timer
|
||||
* is armed for the parsed reset time plus a safety buffer, then Escape
|
||||
* (dismisses the rate-limit options dialog if open) and a "continue" prompt
|
||||
* are sent so work resumes automatically. If the session is still limited,
|
||||
* the fresh limit message re-arms the scheduler — that retry loop is the
|
||||
* safety net for clock skew and parse imprecision.
|
||||
*
|
||||
* @module session-auto-ops
|
||||
*/
|
||||
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { detectUsageLimitPause } from './usage-limit-patterns.js';
|
||||
|
||||
// ============================================================================
|
||||
// Timing Constants
|
||||
@@ -78,6 +88,28 @@ async function executeWhenIdle(
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Auto-resume (usage-limit pause) constants
|
||||
// ============================================================================
|
||||
|
||||
/** Safety buffer after the stated reset time before resuming (2 minutes) */
|
||||
const RESUME_BUFFER_MS = 2 * 60_000;
|
||||
|
||||
/** Minimum delay before an overdue resume fires (lets output settle) */
|
||||
const RESUME_MIN_DELAY_MS = 5_000;
|
||||
|
||||
/** Retry interval when the reset time is stale/past (5 minutes) */
|
||||
const RESUME_RETRY_MS = 5 * 60_000;
|
||||
|
||||
/** Re-detections scheduling within this window of the current schedule are ignored */
|
||||
const RESUME_DEDUP_TOLERANCE_MS = 90_000;
|
||||
|
||||
/** Delay between Escape (dialog dismiss) and the resume prompt */
|
||||
const RESUME_ESC_DELAY_MS = 600;
|
||||
|
||||
/** Prompt sent to resume work after the limit resets */
|
||||
const RESUME_PROMPT = 'continue';
|
||||
|
||||
/** Minimum valid threshold for auto-clear/compact (1000 tokens) */
|
||||
const MIN_AUTO_THRESHOLD = 1000;
|
||||
|
||||
@@ -131,6 +163,16 @@ export class SessionAutoOps extends EventEmitter {
|
||||
private _isClearing: boolean = false;
|
||||
private _autoClearTimer: NodeJS.Timeout | null = null;
|
||||
|
||||
// Auto-resume (usage-limit pause) state
|
||||
private _autoResumeEnabled: boolean = false;
|
||||
private _autoResumeTimer: NodeJS.Timeout | null = null;
|
||||
/** Esc→continue gap timer; detections must NOT cancel a resume in flight */
|
||||
private _resumeFollowupTimer: NodeJS.Timeout | null = null;
|
||||
/** When the scheduled resume fires (epoch ms), null when not armed */
|
||||
private _autoResumeAt: number | null = null;
|
||||
private _limitPaused: boolean = false;
|
||||
private _resumeAttempts: number = 0;
|
||||
|
||||
private readonly callbacks: AutoOpsCallbacks;
|
||||
|
||||
constructor(callbacks: AutoOpsCallbacks, config?: { compactThreshold?: number; clearThreshold?: number }) {
|
||||
@@ -207,6 +249,145 @@ export class SessionAutoOps extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Auto-resume (usage-limit pause) — getters/setters
|
||||
// ============================================================================
|
||||
|
||||
get autoResumeEnabled(): boolean {
|
||||
return this._autoResumeEnabled;
|
||||
}
|
||||
|
||||
/** When the scheduled resume fires (epoch ms), or null when not armed. */
|
||||
get autoResumeAt(): number | null {
|
||||
return this._autoResumeAt;
|
||||
}
|
||||
|
||||
/** True while the session is believed to be paused on a usage limit. */
|
||||
get isLimitPaused(): boolean {
|
||||
return this._limitPaused;
|
||||
}
|
||||
|
||||
setAutoResume(enabled: boolean): void {
|
||||
this._autoResumeEnabled = enabled;
|
||||
if (!enabled) {
|
||||
this._cancelAutoResume('disabled');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore auto-resume state after a Codeman restart. A persisted pending
|
||||
* schedule is re-armed; an overdue one fires shortly after boot (the limit
|
||||
* footer won't reprint on its own, so without this the pause would stall).
|
||||
*/
|
||||
restoreAutoResume(enabled: boolean, resumeAt?: number): void {
|
||||
this._autoResumeEnabled = enabled;
|
||||
if (!enabled || !resumeAt) return;
|
||||
const now = Date.now();
|
||||
this._scheduleResume(Math.max(resumeAt, now + RESUME_MIN_DELAY_MS), resumeAt, 'restored');
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Auto-resume — detection and scheduling
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Scan cleaned terminal output for a usage-limit pause message and (re)arm
|
||||
* the resume schedule. Called from the session's throttled parser path.
|
||||
*/
|
||||
processCleanData(cleanData: string): void {
|
||||
if (!this._autoResumeEnabled || this.callbacks.isStopped()) return;
|
||||
// A resume is in flight (Esc sent, continue pending): output from our own
|
||||
// Escape can redraw the stale limit footer — don't let it re-arm and
|
||||
// cancel the continue. Fresh evidence arrives after the prompt is sent.
|
||||
if (this._resumeFollowupTimer) return;
|
||||
|
||||
const detection = detectUsageLimitPause(cleanData);
|
||||
if (!detection) return;
|
||||
|
||||
const now = Date.now();
|
||||
const overdue = detection.resetAt <= now;
|
||||
const fireAt = overdue
|
||||
? now + RESUME_RETRY_MS // stale reset time → gentle retry loop
|
||||
: Math.max(detection.resetAt + RESUME_BUFFER_MS, now + RESUME_MIN_DELAY_MS);
|
||||
|
||||
if (this._autoResumeTimer && this._autoResumeAt !== null) {
|
||||
// Already armed: the footer redraws constantly, so ignore re-detections
|
||||
// that land on (or later than) the current schedule. Only an EARLIER
|
||||
// parsed time replaces it — an overdue retry never preempts a real one.
|
||||
if (overdue || fireAt >= this._autoResumeAt - RESUME_DEDUP_TOLERANCE_MS) return;
|
||||
}
|
||||
|
||||
this._scheduleResume(fireAt, detection.resetAt, detection.matched);
|
||||
}
|
||||
|
||||
/**
|
||||
* Claude started working — the limit is lifted (or the user resumed
|
||||
* manually), so any pending auto-resume is obsolete.
|
||||
*/
|
||||
notifyWorking(): void {
|
||||
this._resumeAttempts = 0;
|
||||
if (!this._limitPaused && !this._autoResumeTimer && !this._resumeFollowupTimer) return;
|
||||
this._cancelAutoResume('working');
|
||||
}
|
||||
|
||||
private _scheduleResume(fireAt: number, resetAt: number, matched: string): void {
|
||||
if (this._autoResumeTimer) {
|
||||
clearTimeout(this._autoResumeTimer);
|
||||
this._autoResumeTimer = null;
|
||||
}
|
||||
this._limitPaused = true;
|
||||
this._autoResumeAt = fireAt;
|
||||
const delay = Math.max(fireAt - Date.now(), 0);
|
||||
console.log(
|
||||
`[SessionAutoOps ${this.callbacks.getSessionId()}] Usage-limit pause detected ("${matched.slice(0, 60)}"), auto-resume in ${Math.round(delay / 60000)}min`
|
||||
);
|
||||
this._autoResumeTimer = setTimeout(() => void this._fireResume(), delay);
|
||||
this.emit('limitPauseScheduled', { resetAt, resumeAt: fireAt, matched });
|
||||
}
|
||||
|
||||
private async _fireResume(): Promise<void> {
|
||||
this._autoResumeTimer = null;
|
||||
if (!this._autoResumeEnabled || this.callbacks.isStopped()) return;
|
||||
|
||||
if (this.callbacks.isWorking()) {
|
||||
// Session resumed on its own (or via the user) — nothing to do.
|
||||
this._cancelAutoResume('working');
|
||||
return;
|
||||
}
|
||||
|
||||
this._resumeAttempts++;
|
||||
const attempt = this._resumeAttempts;
|
||||
this._limitPaused = false; // optimistic: a fresh limit message re-arms us
|
||||
this._autoResumeAt = null;
|
||||
|
||||
// Escape first: dismisses the rate-limit options dialog if Claude opened
|
||||
// one (harmless at an idle prompt), then the resume prompt after a beat.
|
||||
await this.callbacks.writeCommand('\x1b');
|
||||
this._resumeFollowupTimer = setTimeout(() => {
|
||||
this._resumeFollowupTimer = null;
|
||||
if (this.callbacks.isStopped()) return;
|
||||
void this.callbacks.writeCommand(`${RESUME_PROMPT}\r`);
|
||||
this.emit('limitResume', { attempt });
|
||||
}, RESUME_ESC_DELAY_MS);
|
||||
}
|
||||
|
||||
private _cancelAutoResume(reason: 'disabled' | 'working' | 'stopped'): void {
|
||||
const wasArmed = this._autoResumeTimer !== null || this._resumeFollowupTimer !== null || this._limitPaused;
|
||||
if (this._autoResumeTimer) {
|
||||
clearTimeout(this._autoResumeTimer);
|
||||
this._autoResumeTimer = null;
|
||||
}
|
||||
if (this._resumeFollowupTimer) {
|
||||
clearTimeout(this._resumeFollowupTimer);
|
||||
this._resumeFollowupTimer = null;
|
||||
}
|
||||
this._limitPaused = false;
|
||||
this._autoResumeAt = null;
|
||||
if (wasArmed && reason !== 'stopped') {
|
||||
this.emit('limitResumeCancelled', { reason });
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Threshold checks
|
||||
// ============================================================================
|
||||
@@ -321,5 +502,7 @@ export class SessionAutoOps extends EventEmitter {
|
||||
this._autoClearTimer = null;
|
||||
}
|
||||
this._isClearing = false;
|
||||
|
||||
this._cancelAutoResume('stopped');
|
||||
}
|
||||
}
|
||||
|
||||
+128
-11
@@ -46,6 +46,7 @@ import {
|
||||
type ClaudeMode,
|
||||
type SessionMode,
|
||||
type OpenCodeConfig,
|
||||
type CodexConfig,
|
||||
type EffortLevel,
|
||||
} from './types.js';
|
||||
import type { TerminalMultiplexer, MuxSession } from './mux-interface.js';
|
||||
@@ -77,6 +78,7 @@ import {
|
||||
buildShellEnv,
|
||||
} from './session-cli-builder.js';
|
||||
import { SessionAutoOps } from './session-auto-ops.js';
|
||||
import { detectUsageLimitPause } from './usage-limit-patterns.js';
|
||||
import { SessionTaskCache } from './session-task-cache.js';
|
||||
|
||||
export type { BackgroundTask } from './task-tracker.js';
|
||||
@@ -123,6 +125,11 @@ const CTRL_L_PATTERN = /\x0c/g;
|
||||
/** Pattern to split by newlines (CR or LF) */
|
||||
const NEWLINE_SPLIT_PATTERN = /\r?\n/;
|
||||
|
||||
/** True for external-CLI run modes (non-Claude) that use their own TUI and output format. */
|
||||
export function isExternalCliMode(mode: SessionMode): boolean {
|
||||
return mode === 'opencode' || mode === 'codex';
|
||||
}
|
||||
|
||||
// Note: Claude CLI PATH resolution moved to session-cli-builder.ts (buildClaudeEnv)
|
||||
|
||||
/** PTY fallback geometry when tmux can't be queried (matches pre-#80 hardcoded values). */
|
||||
@@ -313,6 +320,8 @@ export class Session extends EventEmitter {
|
||||
|
||||
// OpenCode configuration (only for mode === 'opencode')
|
||||
private _openCodeConfig: OpenCodeConfig | undefined;
|
||||
// Codex configuration (only for mode === 'codex')
|
||||
private _codexConfig: CodexConfig | undefined;
|
||||
private _resumeSessionId: string | undefined;
|
||||
|
||||
// Ephemeral env overrides (e.g., CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS). Exported by tmux
|
||||
@@ -381,6 +390,8 @@ export class Session extends EventEmitter {
|
||||
allowedTools?: string;
|
||||
/** OpenCode configuration (only for mode === 'opencode') */
|
||||
openCodeConfig?: OpenCodeConfig;
|
||||
/** Codex configuration (only for mode === 'codex') */
|
||||
codexConfig?: CodexConfig;
|
||||
/** Resume a previous Claude conversation (used after server reboot) */
|
||||
resumeSessionId?: string;
|
||||
/** Extra env vars exported to the CLI at spawn time (no disk persistence) */
|
||||
@@ -434,6 +445,11 @@ export class Session extends EventEmitter {
|
||||
this._openCodeConfig = config.openCodeConfig;
|
||||
}
|
||||
|
||||
// Apply Codex configuration
|
||||
if (config.codexConfig) {
|
||||
this._codexConfig = config.codexConfig;
|
||||
}
|
||||
|
||||
// Apply env overrides (exported at spawn, not persisted to disk).
|
||||
// Legacy migration: pre-0.7.2 carried effort as the CLAUDE_CODE_EFFORT_LEVEL env var,
|
||||
// which hard-locks /effort switching. Extract it into _effort (--settings soft default)
|
||||
@@ -505,6 +521,9 @@ export class Session extends EventEmitter {
|
||||
this._totalOutputTokens = 0;
|
||||
this.emit('autoClear', data);
|
||||
});
|
||||
this._autoOps.on('limitPauseScheduled', (data) => this.emit('limitPauseScheduled', data));
|
||||
this._autoOps.on('limitResume', (data) => this.emit('limitResume', data));
|
||||
this._autoOps.on('limitResumeCancelled', (data) => this.emit('limitResumeCancelled', data));
|
||||
}
|
||||
|
||||
get status(): SessionStatus {
|
||||
@@ -696,6 +715,11 @@ export class Session extends EventEmitter {
|
||||
return this._allowedTools;
|
||||
}
|
||||
|
||||
/** Codex CLI configuration for this session. */
|
||||
get codexConfig(): CodexConfig | undefined {
|
||||
return this._codexConfig;
|
||||
}
|
||||
|
||||
// Note: _buildPermissionArgs removed — now using buildInteractiveArgs from session-cli-builder.ts
|
||||
|
||||
/**
|
||||
@@ -805,6 +829,39 @@ export class Session extends EventEmitter {
|
||||
this._autoOps.setAutoCompact(enabled, threshold, prompt);
|
||||
}
|
||||
|
||||
get autoResumeEnabled(): boolean {
|
||||
return this._autoOps.autoResumeEnabled;
|
||||
}
|
||||
|
||||
/** When the scheduled usage-limit auto-resume fires (epoch ms), or null. */
|
||||
get autoResumeAt(): number | null {
|
||||
return this._autoOps.autoResumeAt;
|
||||
}
|
||||
|
||||
/** True while the session is paused on a Claude usage limit (auto-resume armed). */
|
||||
get isLimitPaused(): boolean {
|
||||
return this._autoOps.isLimitPaused;
|
||||
}
|
||||
|
||||
setAutoResume(enabled: boolean): void {
|
||||
this._autoOps.setAutoResume(enabled);
|
||||
// Users typically enable this WHILE a session already sits paused — the
|
||||
// limit footer won't reprint on its own, so scan the recent buffer once.
|
||||
// Only a future reset time counts: stale scrollback must not arm a resume.
|
||||
if (enabled && !isExternalCliMode(this.mode)) {
|
||||
const tail = this._terminalBuffer.value.slice(-8192).replace(ANSI_ESCAPE_PATTERN_FULL, '');
|
||||
const detection = detectUsageLimitPause(tail);
|
||||
if (detection && detection.resetAt > Date.now()) {
|
||||
this._autoOps.processCleanData(tail);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Restore auto-resume state (and a pending schedule) after Codeman restart. */
|
||||
restoreAutoResume(enabled: boolean, resumeAt?: number): void {
|
||||
this._autoOps.restoreAutoResume(enabled, resumeAt);
|
||||
}
|
||||
|
||||
get imageWatcherEnabled(): boolean {
|
||||
return this._imageWatcherEnabled;
|
||||
}
|
||||
@@ -849,6 +906,8 @@ export class Session extends EventEmitter {
|
||||
autoCompactEnabled: this._autoOps.autoCompactEnabled,
|
||||
autoCompactThreshold: this._autoOps.autoCompactThreshold,
|
||||
autoCompactPrompt: this._autoOps.autoCompactPrompt,
|
||||
autoResumeEnabled: this._autoOps.autoResumeEnabled,
|
||||
autoResumeAt: this._autoOps.autoResumeAt ?? undefined,
|
||||
imageWatcherEnabled: this._imageWatcherEnabled,
|
||||
totalCost: this._totalCost,
|
||||
inputTokens: this._totalInputTokens,
|
||||
@@ -867,6 +926,7 @@ export class Session extends EventEmitter {
|
||||
cliAccountType: this._cliAccountType || undefined,
|
||||
cliLatestVersion: this._cliLatestVersion || undefined,
|
||||
openCodeConfig: this._openCodeConfig,
|
||||
codexConfig: this._codexConfig,
|
||||
resumeSessionId: this._resumeSessionId,
|
||||
effort: this._effort,
|
||||
// envOverrides intentionally NOT on the public SessionState type — they must not
|
||||
@@ -1045,7 +1105,7 @@ export class Session extends EventEmitter {
|
||||
|
||||
this._resetBuffers();
|
||||
|
||||
const modeLabel = this.mode === 'opencode' ? 'OpenCode' : 'Claude';
|
||||
const modeLabel = this.mode === 'opencode' ? 'OpenCode' : this.mode === 'codex' ? 'Codex' : 'Claude';
|
||||
console.log(
|
||||
`[Session] Starting interactive ${modeLabel} session` + (this._useMux ? ` (with ${this._mux!.backend})` : '')
|
||||
);
|
||||
@@ -1063,6 +1123,7 @@ export class Session extends EventEmitter {
|
||||
claudeMode: this._claudeMode,
|
||||
allowedTools: this._allowedTools,
|
||||
openCodeConfig: this._openCodeConfig,
|
||||
codexConfig: this._codexConfig,
|
||||
resumeSessionId: this._resumeSessionId,
|
||||
envOverrides: this._envOverrides,
|
||||
effort: this._effort,
|
||||
@@ -1077,6 +1138,7 @@ export class Session extends EventEmitter {
|
||||
claudeMode: this._claudeMode,
|
||||
allowedTools: this._allowedTools,
|
||||
openCodeConfig: this._openCodeConfig,
|
||||
codexConfig: this._codexConfig,
|
||||
resumeSessionId: this._resumeSessionId,
|
||||
envOverrides: this._envOverrides,
|
||||
effort: this._effort,
|
||||
@@ -1090,8 +1152,8 @@ export class Session extends EventEmitter {
|
||||
// For NEW mux sessions: wait for readiness then clean buffer
|
||||
// For RESTORED mux sessions: don't do anything - client will fetch buffer on tab switch
|
||||
if (!isRestored) {
|
||||
if (this.mode === 'opencode') {
|
||||
// OpenCode uses Bubble Tea TUI — no ❯ prompt to detect.
|
||||
if (isExternalCliMode(this.mode)) {
|
||||
// External CLIs use custom TUIs — no ❯ prompt to detect.
|
||||
// Wait for TUI to stabilize (output stops changing), then mark ready.
|
||||
// Don't clear the buffer — the TUI's initial render IS the useful content.
|
||||
// Emit needsRefresh so the client fetches the full buffer once the TUI has rendered.
|
||||
@@ -1146,6 +1208,10 @@ export class Session extends EventEmitter {
|
||||
if (this.mode === 'opencode') {
|
||||
throw new Error('OpenCode sessions require tmux. Direct PTY fallback is not supported.');
|
||||
}
|
||||
// Codex sessions require tmux for OPENAI_API_KEY injection via setenv
|
||||
if (this.mode === 'codex') {
|
||||
throw new Error('Codex sessions require tmux. Direct PTY fallback is not supported.');
|
||||
}
|
||||
try {
|
||||
// Pass --session-id to use the SAME ID as the Codeman session
|
||||
// This ensures subagents can be directly matched to the correct tab
|
||||
@@ -1223,6 +1289,7 @@ export class Session extends EventEmitter {
|
||||
this._isWorking = true;
|
||||
this._status = 'busy';
|
||||
this.emit('working');
|
||||
this._autoOps.notifyWorking();
|
||||
}
|
||||
this._awaitingIdleConfirmation = false;
|
||||
if (this.activityTimeout) clearTimeout(this.activityTimeout);
|
||||
@@ -1305,9 +1372,9 @@ export class Session extends EventEmitter {
|
||||
* PTY data chunk. Receives accumulated raw data to process in one batch.
|
||||
*/
|
||||
private _processExpensiveParsers(rawData: string): void {
|
||||
// Skip Claude-specific parsers for OpenCode sessions — Ralph tracker, BashToolParser,
|
||||
// token parsing, and CLI info parsing all depend on Claude's output format.
|
||||
if (this.mode === 'opencode') return;
|
||||
// Skip Claude-specific parsers for external CLI sessions (Ralph tracker,
|
||||
// BashToolParser, token + CLI-info parsing all depend on Claude's output format).
|
||||
if (isExternalCliMode(this.mode)) return;
|
||||
|
||||
// Lazy ANSI strip: only compute cleanData when a consumer actually needs it.
|
||||
let _cleanData: string | null = null;
|
||||
@@ -1329,6 +1396,11 @@ export class Session extends EventEmitter {
|
||||
this._bashToolParser.processCleanData(getCleanData());
|
||||
}
|
||||
|
||||
// Usage-limit pause detection (auto-resume on usage limit)
|
||||
if (this._autoOps.autoResumeEnabled) {
|
||||
this._autoOps.processCleanData(getCleanData());
|
||||
}
|
||||
|
||||
// Parse token count from status line (e.g., "123.4k tokens" or "5234 tokens")
|
||||
if (rawData.includes('token')) {
|
||||
this.parseTokensFromStatusLine(getCleanData());
|
||||
@@ -1357,6 +1429,7 @@ export class Session extends EventEmitter {
|
||||
this._isWorking = true;
|
||||
this._status = 'busy';
|
||||
this.emit('working');
|
||||
this._autoOps.notifyWorking();
|
||||
this._awaitingIdleConfirmation = false;
|
||||
if (this.activityTimeout) clearTimeout(this.activityTimeout);
|
||||
}
|
||||
@@ -2069,9 +2142,29 @@ export class Session extends EventEmitter {
|
||||
*/
|
||||
private _desktopSizeClaims = new Set<symbol>();
|
||||
|
||||
/**
|
||||
* A desktop sizing claim only blocks small-viewport resizes while the
|
||||
* desktop is RECENTLY ACTIVE (claim registration or typed input within this
|
||||
* window). An abandoned-but-connected desktop tab (left open at home, screen
|
||||
* locked) must not hold a phone's view hostage: without this, the phone
|
||||
* renders a desktop-width stream in a narrow xterm — mid-word wraps, tmux
|
||||
* dot-fill, and Ink overdraw soup (the 0.9.8–0.9.12 mobile regression).
|
||||
*/
|
||||
private static readonly DESKTOP_CLAIM_IDLE_MS = 90_000;
|
||||
|
||||
/** Last evidence of a live desktop user (claim registered / typed input). */
|
||||
private _lastDesktopActivityAt = 0;
|
||||
|
||||
/** Last desktop-typed dimensions, for re-asserting after a mobile override. */
|
||||
private _lastDesktopDims: { cols: number; rows: number } | null = null;
|
||||
|
||||
/** True while a small viewport reflowed the pane past an idle desktop claim. */
|
||||
private _mobileSizeOverride = false;
|
||||
|
||||
/** Register a live desktop sizing claim (see _desktopSizeClaims). */
|
||||
claimDesktopSizing(token: symbol): void {
|
||||
this._desktopSizeClaims.add(token);
|
||||
this._lastDesktopActivityAt = Date.now();
|
||||
}
|
||||
|
||||
/** Release a desktop sizing claim when its connection goes away. */
|
||||
@@ -2079,23 +2172,47 @@ export class Session extends EventEmitter {
|
||||
this._desktopSizeClaims.delete(token);
|
||||
}
|
||||
|
||||
/**
|
||||
* Record desktop user activity (typed input over a claim-holding socket).
|
||||
* If a phone reflowed the pane while the desktop was idle, the desktop
|
||||
* layout is restored — "whoever is actively using the session wins".
|
||||
*/
|
||||
noteDesktopActivity(): void {
|
||||
this._lastDesktopActivityAt = Date.now();
|
||||
if (this._mobileSizeOverride && this._lastDesktopDims) {
|
||||
this._mobileSizeOverride = false;
|
||||
this.resize(this._lastDesktopDims.cols, this._lastDesktopDims.rows, { viewportType: 'desktop' });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resizes the PTY terminal dimensions.
|
||||
* Skips the resize if dimensions haven't changed to avoid triggering
|
||||
* unnecessary Ink full-screen redraws (visible flicker on tab switch).
|
||||
*
|
||||
* Arbitration: while a desktop connection holds a sizing claim, resizes from
|
||||
* small viewports (mobile/tablet) are ignored entirely — shrink AND grow
|
||||
* would both reflow the desktop view. Without a desktop connected, small
|
||||
* viewports control the PTY size freely.
|
||||
* Arbitration: while a desktop connection holds a sizing claim AND has been
|
||||
* active within DESKTOP_CLAIM_IDLE_MS, resizes from small viewports
|
||||
* (mobile/tablet) are ignored — shrink AND grow would both reflow the
|
||||
* desktop view. Once the desktop goes idle, a phone may take the pane (the
|
||||
* desktop re-asserts its size on its next typed input via
|
||||
* noteDesktopActivity). Without a desktop connected, small viewports
|
||||
* control the PTY size freely.
|
||||
*
|
||||
* @param cols - Number of columns (width in characters)
|
||||
* @param rows - Number of rows (height in lines)
|
||||
*/
|
||||
resize(cols: number, rows: number, options: { viewportType?: ResizeViewportType } = {}): void {
|
||||
const isSmallViewport = options.viewportType === 'mobile' || options.viewportType === 'tablet';
|
||||
if (options.viewportType === 'desktop') {
|
||||
this._lastDesktopDims = { cols, rows };
|
||||
this._lastDesktopActivityAt = Date.now();
|
||||
this._mobileSizeOverride = false;
|
||||
}
|
||||
if (isSmallViewport && this._desktopSizeClaims.size > 0) {
|
||||
return;
|
||||
if (Date.now() - this._lastDesktopActivityAt < Session.DESKTOP_CLAIM_IDLE_MS) {
|
||||
return;
|
||||
}
|
||||
this._mobileSizeOverride = true;
|
||||
}
|
||||
if (this.ptyProcess && (cols !== this._ptyCols || rows !== this._ptyRows)) {
|
||||
this._ptyCols = cols;
|
||||
|
||||
+47
-450
@@ -1,461 +1,58 @@
|
||||
# CLAUDE.md - Project Configuration
|
||||
# CLAUDE.md
|
||||
|
||||
## Setup
|
||||
Copy these files to your new project:
|
||||
- `CLAUDE.md` → project root
|
||||
- `.claude/settings.json` → `.claude/settings.json`
|
||||
<!--
|
||||
Generated by Codeman on [DATE]. This file is loaded into context at the
|
||||
start of every Claude Code session in this project.
|
||||
|
||||
Then update the Project Overview section below.
|
||||
Keep it short (target: under 200 lines). For each line ask: "would removing
|
||||
this cause Claude to make mistakes?" If not, cut it. Don't document what
|
||||
Claude can infer from the code itself (file layout, standard conventions,
|
||||
APIs) — bloat causes Claude to ignore the rules that matter.
|
||||
|
||||
---
|
||||
HTML comments like this one are stripped before loading, so fill-in notes
|
||||
cost no context. If this file grows too big, split into path-scoped rules
|
||||
in .claude/rules/*.md or import other files with @path/to/file syntax.
|
||||
-->
|
||||
|
||||
This file guides Claude Code when working in this repository.
|
||||
|
||||
## Project
|
||||
|
||||
## Project Overview
|
||||
<!-- Update this section with project-specific details -->
|
||||
- **Project Name**: [PROJECT_NAME]
|
||||
- **Description**: [PROJECT_DESCRIPTION]
|
||||
- **Tech Stack**: [TECHNOLOGIES_USED]
|
||||
- **Last Updated**: [DATE]
|
||||
|
||||
---
|
||||
## Commands
|
||||
|
||||
<!-- List the exact commands Claude can't guess — fill in as the project
|
||||
takes shape, then delete this comment:
|
||||
|
||||
| Task | Command |
|
||||
|------|---------|
|
||||
| Dev server | `npm run dev` |
|
||||
| Test (single file) | `npm test -- test/<file>.test.ts` |
|
||||
| Lint | `npm run lint` |
|
||||
| Build | `npm run build` |
|
||||
-->
|
||||
|
||||
## Code Style
|
||||
|
||||
<!-- Only rules that differ from language/framework defaults, one line each:
|
||||
- Use 2-space indentation
|
||||
- ES modules only — never require()
|
||||
-->
|
||||
|
||||
## Workflow
|
||||
|
||||
- Full permissions are granted: read, write, edit, and execute without asking.
|
||||
- Commit after every meaningful change; never batch unrelated work.
|
||||
- Use conventional commits (`feat:` `fix:` `docs:` `refactor:` `test:` `chore:`); the message says what changed and why.
|
||||
- Run the tests and linter before declaring any task done.
|
||||
- Keep README and docs in sync with code changes.
|
||||
|
||||
## Codeman Environment
|
||||
|
||||
This session is managed by **Codeman** and runs within a tmux session.
|
||||
This session is managed by Codeman and runs inside tmux (`CODEMAN_MUX=1` confirms it).
|
||||
|
||||
**Important**: Check for `CODEMAN_MUX=1` environment variable to confirm.
|
||||
- Do NOT attempt to kill your own tmux session
|
||||
- The session persists across disconnects - your work is safe
|
||||
- Token usage, costs, and background tasks are tracked externally
|
||||
|
||||
---
|
||||
|
||||
## Work Principles
|
||||
|
||||
### Autonomy
|
||||
Full permissions granted. Act decisively without asking - read, write, edit, execute freely.
|
||||
|
||||
### Git Discipline
|
||||
- **Commit after every meaningful change** - never batch unrelated work
|
||||
- Use conventional commits: `feat:`, `fix:`, `docs:`, `refactor:`, `test:`, `chore:`
|
||||
- Commit message = what changed + why (not how)
|
||||
|
||||
### Documentation
|
||||
- Update README.md when adding features or changing setup
|
||||
- Update this file's session log after work sessions
|
||||
- Keep docs in sync with code changes
|
||||
|
||||
### Thinking
|
||||
Extended thinking is enabled. Use deep reasoning for complex architectural decisions, difficult bugs, and multi-file changes.
|
||||
|
||||
### Task Tracking (TodoWrite)
|
||||
**ALWAYS use TodoWrite** to track tasks. This is non-negotiable for anything beyond trivial single-step work.
|
||||
|
||||
**When to use TodoWrite:**
|
||||
- Multi-step tasks (3+ steps)
|
||||
- Bug fixes requiring investigation
|
||||
- Feature implementations
|
||||
- Any work where progress tracking helps
|
||||
- When the user provides multiple requests
|
||||
|
||||
**How to use it:**
|
||||
1. **Before starting**: Break down the work into discrete todos
|
||||
2. **During work**: Mark each todo `in_progress` before starting, `completed` when done
|
||||
3. **One at a time**: Only ONE todo should be `in_progress` at any moment
|
||||
4. **Immediately**: Mark todos complete the moment they're done - don't batch
|
||||
|
||||
**Why this matters:**
|
||||
- Gives the user visibility into your progress
|
||||
- Prevents forgetting tasks mid-work
|
||||
- Creates accountability checkpoints
|
||||
- Makes complex work manageable
|
||||
|
||||
**Example workflow:**
|
||||
```
|
||||
User: "Add user authentication with JWT"
|
||||
|
||||
→ TodoWrite:
|
||||
- [ ] Research existing auth patterns in codebase
|
||||
- [ ] Implement JWT token generation
|
||||
- [ ] Add login endpoint
|
||||
- [ ] Add token validation middleware
|
||||
- [ ] Add protected route example
|
||||
- [ ] Write tests
|
||||
|
||||
→ Mark "Research existing auth patterns" as in_progress
|
||||
→ Do the research
|
||||
→ Mark as completed, mark next as in_progress
|
||||
→ Continue until all done
|
||||
```
|
||||
|
||||
**Anti-patterns to avoid:**
|
||||
- Starting work without creating todos first
|
||||
- Having multiple todos `in_progress` simultaneously
|
||||
- Batching completions at the end
|
||||
- Skipping TodoWrite for "simple" multi-step tasks
|
||||
|
||||
---
|
||||
|
||||
## When to Use Agents
|
||||
|
||||
**Explore agent**: Codebase investigation, finding files, understanding architecture
|
||||
```
|
||||
"Use explore agent to find all authentication-related code"
|
||||
```
|
||||
|
||||
**Parallel agents**: Independent tasks that don't conflict
|
||||
```
|
||||
"Research auth, database, and API modules in parallel using separate agents"
|
||||
```
|
||||
|
||||
**Background execution**: Long-running operations (tests, builds)
|
||||
```
|
||||
"Run the test suite in the background while I continue"
|
||||
```
|
||||
|
||||
**Sequential chaining**: When second task depends on first
|
||||
```
|
||||
"Use code-reviewer to find issues, then use fixer to resolve them"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Planning Mode (Automatic)
|
||||
|
||||
**Automatically enter planning mode** when ANY of these conditions apply:
|
||||
- Multi-file changes (3+ files affected)
|
||||
- Architectural decisions
|
||||
- Unclear or evolving requirements
|
||||
- Risk mitigation on core systems
|
||||
- New feature implementation
|
||||
- Refactoring existing functionality
|
||||
|
||||
**Do NOT ask** whether to enter planning mode - just enter it when conditions are met.
|
||||
|
||||
Planning mode flow: read-only exploration → create plan → get approval → execute.
|
||||
|
||||
**Skip planning mode** only for:
|
||||
- Single-file bug fixes
|
||||
- Typo corrections
|
||||
- Simple config changes
|
||||
- Tasks with explicit step-by-step instructions from user
|
||||
|
||||
---
|
||||
|
||||
## Ralph Wiggum Loop (Autonomous Work Mode)
|
||||
|
||||
Ralph loops enable persistent, autonomous work on large tasks. When active, you continue iterating until completion criteria are met or the loop is cancelled.
|
||||
|
||||
### Starting a Ralph Loop
|
||||
- Start: `/ralph-loop:ralph-loop`
|
||||
- Cancel: `/ralph-loop:cancel-ralph`
|
||||
- Help: `/ralph-loop:help`
|
||||
|
||||
### Time-Aware Loops
|
||||
|
||||
When the user specifies a **minimum duration** (e.g., "optimize for 8 hours", "work on this for 2 hours"), the loop becomes time-aware:
|
||||
|
||||
**At loop start:**
|
||||
```bash
|
||||
# Record start time
|
||||
date +%s > /tmp/ralph_start_time
|
||||
echo "Loop started at $(date)"
|
||||
```
|
||||
|
||||
**Check elapsed time periodically:**
|
||||
```bash
|
||||
START=$(cat /tmp/ralph_start_time)
|
||||
NOW=$(date +%s)
|
||||
ELAPSED_HOURS=$(echo "scale=2; ($NOW - $START) / 3600" | bc)
|
||||
echo "Elapsed: $ELAPSED_HOURS hours"
|
||||
```
|
||||
|
||||
**Time-aware behavior:**
|
||||
1. Complete all primary tasks from the user's prompt
|
||||
2. After primary tasks done, check elapsed time
|
||||
3. If minimum duration NOT reached:
|
||||
- **Do NOT output completion phrase**
|
||||
- Self-generate additional related tasks
|
||||
- Continue working until minimum time elapsed
|
||||
4. Only output completion phrase when:
|
||||
- ALL primary tasks complete AND
|
||||
- Minimum duration reached (or exceeded)
|
||||
|
||||
**Self-generating additional tasks when time remains:**
|
||||
- Code optimization (performance, readability, DRY)
|
||||
- Test coverage improvements
|
||||
- Edge case handling
|
||||
- Error message improvements
|
||||
- Documentation gaps
|
||||
- Security hardening
|
||||
- Accessibility improvements
|
||||
- Code cleanup and dead code removal
|
||||
- Dependency updates
|
||||
- Type safety improvements
|
||||
|
||||
**Example time-aware prompt:**
|
||||
```
|
||||
"Optimize the API endpoints for the next 4 hours. Focus on performance first,
|
||||
then code quality. Minimum runtime: 4 hours."
|
||||
Completion phrase: <promise>TIME_COMPLETE</promise>
|
||||
```
|
||||
|
||||
**Time-aware loop behavior:**
|
||||
```
|
||||
[Start loop, record timestamp]
|
||||
[Complete primary optimization tasks - 2 hours elapsed]
|
||||
[Check time: 2/4 hours - NOT done yet]
|
||||
[Self-generate: "Add caching to database queries"]
|
||||
[Self-generate: "Optimize N+1 queries"]
|
||||
[Self-generate: "Add request batching"]
|
||||
[Continue working... 4.5 hours elapsed]
|
||||
[Check time: 4.5/4 hours - minimum reached]
|
||||
[All tasks complete, tests pass]
|
||||
<promise>TIME_COMPLETE</promise>
|
||||
```
|
||||
|
||||
### How You Know You're in a Ralph Loop
|
||||
|
||||
The user started the loop with a prompt containing:
|
||||
- Clear task requirements
|
||||
- A **completion phrase** (e.g., `<promise>COMPLETE</promise>`)
|
||||
- **Optional: minimum duration** (e.g., "for the next 4 hours")
|
||||
- Iteration limits (handled by the system)
|
||||
|
||||
Your job: Keep working until ALL requirements are verifiably done AND minimum time reached (if specified), then output the exact completion phrase.
|
||||
|
||||
### Core Behaviors During Ralph Loop
|
||||
|
||||
**1. Work Incrementally**
|
||||
- Complete one sub-task at a time
|
||||
- Verify it works before moving to the next
|
||||
- Don't try to do everything in one pass
|
||||
|
||||
**2. Commit Frequently**
|
||||
- Commit after each meaningful completion
|
||||
- Creates recovery points if something breaks
|
||||
- Shows progress in git history
|
||||
```
|
||||
git add . && git commit -m "feat(auth): add token refresh endpoint"
|
||||
```
|
||||
|
||||
**3. Self-Correct Relentlessly**
|
||||
```
|
||||
Loop:
|
||||
1. Implement/fix
|
||||
2. Run tests
|
||||
3. If tests fail → read error, fix, go to 1
|
||||
4. Run linter
|
||||
5. If lint errors → fix, go to 1
|
||||
6. Commit
|
||||
7. Continue to next task
|
||||
```
|
||||
|
||||
**4. Track Progress**
|
||||
Update the session log in this file as you complete tasks:
|
||||
```markdown
|
||||
| Date | Tasks Completed | Files Changed | Notes |
|
||||
|------|-----------------|---------------|-------|
|
||||
| YYYY-MM-DD | Add auth endpoint | auth.ts, routes.ts | Tests passing |
|
||||
```
|
||||
|
||||
**5. Use Git History When Stuck**
|
||||
If something isn't working:
|
||||
```bash
|
||||
git log --oneline -10
|
||||
git diff HEAD~1
|
||||
```
|
||||
See what you already tried. Don't repeat failed approaches.
|
||||
|
||||
**6. Completion Phrase = Contract**
|
||||
Only output the completion phrase (e.g., `<promise>COMPLETE</promise>`) when:
|
||||
- ALL requirements from the original prompt are done
|
||||
- ALL tests pass
|
||||
- ALL linting passes
|
||||
- Changes are committed
|
||||
|
||||
**Never output the completion phrase early.** The loop only ends when you say it's done.
|
||||
|
||||
### What Makes Good Completion Criteria
|
||||
|
||||
The user should provide criteria that are:
|
||||
- **Verifiable**: Tests pass, lint clean, build succeeds
|
||||
- **Measurable**: "5 endpoints", "all files in src/", "zero errors"
|
||||
- **Binary**: Done or not done, no ambiguity
|
||||
|
||||
If the original prompt has vague criteria, ask clarifying questions before starting heavy work.
|
||||
|
||||
### Self-Correction Pattern (Include in Your Work)
|
||||
|
||||
```
|
||||
FOR EACH TASK:
|
||||
1. Implement the change
|
||||
2. Run tests (npm test, pytest, go test, cargo test, etc.)
|
||||
- If fail → read error, fix, retry
|
||||
3. Run linter (npm run lint, ruff, golangci-lint, etc.)
|
||||
- If fail → fix, go to step 2
|
||||
4. Verify manually if needed
|
||||
5. Commit with descriptive message
|
||||
6. Update session log
|
||||
7. Move to next task
|
||||
|
||||
WHEN ALL TASKS DONE:
|
||||
1. Run full test suite
|
||||
2. Run full lint
|
||||
3. Verify build succeeds
|
||||
4. Review all changes: git diff main
|
||||
5. Only then output completion phrase
|
||||
```
|
||||
|
||||
### Example: How to Think During Ralph Loop
|
||||
|
||||
**Original prompt**: "Add CRUD endpoints for todos with validation"
|
||||
|
||||
**Your approach**:
|
||||
```
|
||||
Task breakdown:
|
||||
- [ ] GET /todos (list)
|
||||
- [ ] POST /todos (create with validation)
|
||||
- [ ] GET /todos/:id (single)
|
||||
- [ ] PUT /todos/:id (update with validation)
|
||||
- [ ] DELETE /todos/:id
|
||||
- [ ] Tests for all endpoints
|
||||
|
||||
Starting with GET /todos...
|
||||
[implement]
|
||||
[test - passes]
|
||||
[commit: "feat(todos): add GET /todos endpoint"]
|
||||
[update session log]
|
||||
|
||||
Moving to POST /todos...
|
||||
[implement]
|
||||
[test - fails: validation not working]
|
||||
[fix validation]
|
||||
[test - passes]
|
||||
[commit: "feat(todos): add POST /todos with validation"]
|
||||
[update session log]
|
||||
|
||||
...continue until all done...
|
||||
|
||||
Final verification:
|
||||
[npm test - all pass]
|
||||
[npm run lint - clean]
|
||||
[npm run build - succeeds]
|
||||
|
||||
<promise>COMPLETE</promise>
|
||||
```
|
||||
|
||||
### When to NOT Output Completion Phrase
|
||||
|
||||
- Tests are failing (even one)
|
||||
- Lint errors exist
|
||||
- Build is broken
|
||||
- You skipped a requirement
|
||||
- You're unsure if something works
|
||||
- **Minimum duration not reached** (for time-aware loops)
|
||||
|
||||
Instead: Fix the issue, verify, then complete. For time-aware loops: generate more tasks and keep improving until minimum time elapsed.
|
||||
|
||||
### RALPH_STATUS Block (Required During Ralph Loop)
|
||||
|
||||
At the **END of every response** during a Ralph Loop, output this structured status block:
|
||||
|
||||
```
|
||||
---RALPH_STATUS---
|
||||
STATUS: IN_PROGRESS | COMPLETE | BLOCKED
|
||||
TASKS_COMPLETED_THIS_LOOP: <number>
|
||||
FILES_MODIFIED: <number>
|
||||
TESTS_STATUS: PASSING | FAILING | NOT_RUN
|
||||
WORK_TYPE: IMPLEMENTATION | TESTING | DOCUMENTATION | REFACTORING
|
||||
EXIT_SIGNAL: false | true
|
||||
RECOMMENDATION: <one line summary of what to do next>
|
||||
---END_RALPH_STATUS---
|
||||
```
|
||||
|
||||
**Rules:**
|
||||
- Output this block at the end of **every** response, no exceptions
|
||||
- Set `EXIT_SIGNAL` to `true` ONLY when ALL tasks are verifiably done
|
||||
- Set `STATUS` to `BLOCKED` when you need human intervention
|
||||
- Do NOT continue with busy work when `EXIT_SIGNAL` should be `true`
|
||||
- Do NOT forget the status block — it is required for loop tracking
|
||||
|
||||
### Testing Limits
|
||||
|
||||
- **LIMIT testing to ~20% of total effort** per loop
|
||||
- PRIORITIZE: Implementation > Documentation > Tests
|
||||
- Only write tests for NEW functionality
|
||||
- Do NOT refactor existing tests unless broken
|
||||
- Do NOT run tests repeatedly without implementing new features
|
||||
|
||||
### Exit Scenarios (When to Set EXIT_SIGNAL)
|
||||
|
||||
| Scenario | STATUS | EXIT_SIGNAL | Action |
|
||||
|----------|--------|-------------|--------|
|
||||
| All tasks completed, tests pass | COMPLETE | true | Output completion phrase |
|
||||
| No work remaining, specs done | COMPLETE | true | Output completion phrase |
|
||||
| Making normal progress | IN_PROGRESS | false | Continue to next task |
|
||||
| Test-only loop (no implementation) | IN_PROGRESS | false | Warn and shift to implementation |
|
||||
| Stuck on same error repeatedly | BLOCKED | false | Describe blocker, request help |
|
||||
| Needs human decision/intervention | BLOCKED | false | Describe what's needed |
|
||||
|
||||
**Anti-patterns to avoid:**
|
||||
- Setting `EXIT_SIGNAL: true` when tests are failing
|
||||
- Continuing to work when all tasks are genuinely done (busy work)
|
||||
- Running the same failing test repeatedly without changing approach
|
||||
- Adding features not in the original specifications
|
||||
- Refactoring working code instead of completing assigned tasks
|
||||
|
||||
---
|
||||
|
||||
## Code Standards
|
||||
|
||||
### Before Writing
|
||||
- Read existing code in the area you're modifying
|
||||
- Follow existing patterns and conventions
|
||||
- Check for similar implementations to reference
|
||||
|
||||
### During Implementation
|
||||
- Keep changes focused and minimal
|
||||
- Don't over-engineer
|
||||
- Write tests for new functionality
|
||||
|
||||
### After Implementation
|
||||
- Run tests
|
||||
- Update docs if needed
|
||||
- Commit with descriptive message
|
||||
|
||||
---
|
||||
|
||||
## Hooks Awareness
|
||||
|
||||
This project may have hooks that auto-format code after writes or validate operations. If a tool call behaves unexpectedly, hooks are likely the cause. Continue working - they're intentional.
|
||||
|
||||
---
|
||||
|
||||
## Session Log
|
||||
|
||||
| Date | Tasks Completed | Files Changed | Notes |
|
||||
|------|-----------------|---------------|-------|
|
||||
| [DATE] | Project created | CLAUDE.md | Initial setup |
|
||||
|
||||
---
|
||||
|
||||
## Current Task Queue
|
||||
|
||||
### Active Ralph Loop
|
||||
**Status**: Not Active
|
||||
**Completion Phrase**: -
|
||||
|
||||
### Pending Tasks
|
||||
- [ ] <!-- Add tasks here -->
|
||||
|
||||
---
|
||||
|
||||
## Implementation Plans
|
||||
|
||||
<!-- Document plans before major implementations -->
|
||||
|
||||
---
|
||||
|
||||
## Notes & Decisions
|
||||
|
||||
<!-- Track important decisions and context -->
|
||||
- NEVER kill your own session: no `tmux kill-session`, `pkill tmux`, or `pkill claude`.
|
||||
- The session persists across disconnects — your work is safe.
|
||||
- Hooks may auto-format or validate after writes; unexpected tool behavior usually means a hook ran. Keep working.
|
||||
|
||||
@@ -15,18 +15,17 @@ import { fileURLToPath } from 'node:url';
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const BUNDLED_TEMPLATE_PATH = join(__dirname, 'case-template.md');
|
||||
|
||||
const MINIMAL_FALLBACK = `# CLAUDE.md - Project Configuration
|
||||
const MINIMAL_FALLBACK = `# CLAUDE.md
|
||||
|
||||
<!-- Generated by Codeman on [DATE]. Add the commands, code style rules, and
|
||||
workflow notes Claude can't infer from the code. Keep it short. -->
|
||||
|
||||
This file guides Claude Code when working in this repository.
|
||||
|
||||
## Project
|
||||
|
||||
## Project Overview
|
||||
- **Project Name**: [PROJECT_NAME]
|
||||
- **Description**: [PROJECT_DESCRIPTION]
|
||||
- **Last Updated**: [DATE]
|
||||
|
||||
## Session Log
|
||||
|
||||
| Date | Tasks Completed | Files Changed | Notes |
|
||||
|------|-----------------|---------------|-------|
|
||||
| [DATE] | Project created | CLAUDE.md | Initial setup |
|
||||
`;
|
||||
|
||||
/**
|
||||
|
||||
+78
-2
@@ -39,10 +39,11 @@ import {
|
||||
type ClaudeMode,
|
||||
type SessionMode,
|
||||
type OpenCodeConfig,
|
||||
type CodexConfig,
|
||||
type EffortLevel,
|
||||
} from './types.js';
|
||||
import { buildEffortCliArgs } from './session-cli-builder.js';
|
||||
import { wrapWithNice, SAFE_PATH_PATTERN, findClaudeDir, resolveOpenCodeDir } from './utils/index.js';
|
||||
import { wrapWithNice, SAFE_PATH_PATTERN, findClaudeDir, resolveOpenCodeDir, resolveCodexDir } from './utils/index.js';
|
||||
import type {
|
||||
TerminalMultiplexer,
|
||||
MuxSession,
|
||||
@@ -539,6 +540,32 @@ function buildOpenCodeCommand(config?: OpenCodeConfig): string {
|
||||
return parts.join(' ');
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the codex CLI command with appropriate flags.
|
||||
*
|
||||
* Codeman launches Codex's native TUI and handles replay/scrollback by
|
||||
* stripping destructive terminal sequences before xterm.js sees them.
|
||||
*/
|
||||
export function buildCodexCommand(config?: CodexConfig): string {
|
||||
const parts = ['codex'];
|
||||
|
||||
if (config?.dangerouslyBypassApprovals) {
|
||||
parts.push('--dangerously-bypass-approvals-and-sandbox');
|
||||
}
|
||||
|
||||
if (config?.model) {
|
||||
const safeModel = /^[a-zA-Z0-9._\-/]+$/.test(config.model) ? config.model : undefined;
|
||||
if (safeModel) parts.push('--model', safeModel);
|
||||
}
|
||||
|
||||
if (config?.resumeSessionId) {
|
||||
const safeId = /^[a-zA-Z0-9_-]+$/.test(config.resumeSessionId) ? config.resumeSessionId : undefined;
|
||||
if (safeId) parts.push('resume', safeId);
|
||||
}
|
||||
|
||||
return parts.join(' ');
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the spawn command for any session mode.
|
||||
* Shared by createSession() and respawnPane() to avoid duplication.
|
||||
@@ -564,6 +591,7 @@ function buildSpawnCommand(options: {
|
||||
claudeMode?: ClaudeMode;
|
||||
allowedTools?: string;
|
||||
openCodeConfig?: OpenCodeConfig;
|
||||
codexConfig?: CodexConfig;
|
||||
resumeSessionId?: string;
|
||||
effort?: EffortLevel;
|
||||
}): string {
|
||||
@@ -588,6 +616,9 @@ function buildSpawnCommand(options: {
|
||||
if (options.mode === 'opencode') {
|
||||
return buildOpenCodeCommand(options.openCodeConfig);
|
||||
}
|
||||
if (options.mode === 'codex') {
|
||||
return buildCodexCommand(options.codexConfig);
|
||||
}
|
||||
return '$SHELL';
|
||||
}
|
||||
|
||||
@@ -615,6 +646,29 @@ function setOpenCodeEnvVars(tmuxCmd: string, muxName: string): void {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set sensitive environment variables for Codex on a tmux session via setenv.
|
||||
* Codex (OpenAI CLI) needs OPENAI_API_KEY; we also forward CODEX_* keys.
|
||||
*/
|
||||
function setCodexEnvVars(tmuxCmd: string, muxName: string): void {
|
||||
const sensitiveVars = ['OPENAI_API_KEY', 'CODEX_API_KEY', 'CODEX_HOME'];
|
||||
for (const key of sensitiveVars) {
|
||||
const val = process.env[key];
|
||||
if (val) {
|
||||
const escaped = val.replace(/'/g, "'\\''");
|
||||
try {
|
||||
execSync(`${tmuxCmd} setenv -t '${muxName}' ${key} '${escaped}'`, {
|
||||
encoding: 'utf8',
|
||||
timeout: EXEC_TIMEOUT_MS,
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
});
|
||||
} catch {
|
||||
/* Non-critical — key may not be needed */
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set OPENCODE_CONFIG_CONTENT on a tmux session via setenv.
|
||||
* Uses tmux setenv to avoid shell metacharacter injection from user-supplied JSON.
|
||||
@@ -797,7 +851,8 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
const exports = [
|
||||
'export LANG=en_US.UTF-8',
|
||||
'export LC_ALL=en_US.UTF-8',
|
||||
'unset COLORTERM',
|
||||
mode === 'codex' ? 'export COLORTERM=truecolor' : 'unset COLORTERM',
|
||||
...(mode === 'codex' ? ['unset NO_COLOR'] : []),
|
||||
'export CODEMAN_MUX=1',
|
||||
`export CODEMAN_SESSION_ID=${sessionId}`,
|
||||
`export CODEMAN_MUX_NAME=${muxName}`,
|
||||
@@ -863,6 +918,10 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
const dir = resolveOpenCodeDir();
|
||||
return { pathExport: dir ? `export PATH="${dir}:$PATH" && ` : '', dir };
|
||||
}
|
||||
if (mode === 'codex') {
|
||||
const dir = resolveCodexDir();
|
||||
return { pathExport: dir ? `export PATH="${dir}:$PATH" && ` : '', dir };
|
||||
}
|
||||
return { pathExport: '', dir: null };
|
||||
}
|
||||
|
||||
@@ -877,6 +936,15 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
setOpenCodeConfigContent(tmuxCmd, muxName, openCodeConfig);
|
||||
}
|
||||
|
||||
/**
|
||||
* Configure Codex-specific environment on a tmux session.
|
||||
* Sets OPENAI_API_KEY (and related keys) via tmux setenv so secrets don't
|
||||
* appear in the bash command line.
|
||||
*/
|
||||
private _configureCodex(muxName: string): void {
|
||||
setCodexEnvVars(this.tmux(), muxName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new tmux session wrapping Claude CLI or a shell.
|
||||
* In test mode: creates an in-memory session only (no real tmux session).
|
||||
@@ -892,6 +960,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
claudeMode,
|
||||
allowedTools,
|
||||
openCodeConfig,
|
||||
codexConfig,
|
||||
resumeSessionId,
|
||||
envOverrides,
|
||||
effort,
|
||||
@@ -940,6 +1009,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
claudeMode,
|
||||
allowedTools,
|
||||
openCodeConfig,
|
||||
codexConfig,
|
||||
resumeSessionId,
|
||||
effort,
|
||||
});
|
||||
@@ -986,6 +1056,8 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
// (not visible in ps output or tmux history, inherited by panes)
|
||||
if (mode === 'opencode') {
|
||||
this._configureOpenCode(muxName, openCodeConfig);
|
||||
} else if (mode === 'codex') {
|
||||
this._configureCodex(muxName);
|
||||
}
|
||||
|
||||
// Apply user-supplied env overrides (e.g., CLAUDE_CODE_EFFORT_LEVEL) via tmux setenv
|
||||
@@ -1143,6 +1215,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
claudeMode,
|
||||
allowedTools,
|
||||
openCodeConfig,
|
||||
codexConfig,
|
||||
resumeSessionId,
|
||||
envOverrides,
|
||||
effort,
|
||||
@@ -1165,6 +1238,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
claudeMode,
|
||||
allowedTools,
|
||||
openCodeConfig,
|
||||
codexConfig,
|
||||
resumeSessionId,
|
||||
effort,
|
||||
});
|
||||
@@ -1176,6 +1250,8 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
// For OpenCode: set sensitive env vars via tmux setenv before respawn
|
||||
if (mode === 'opencode') {
|
||||
this._configureOpenCode(muxName, openCodeConfig);
|
||||
} else if (mode === 'codex') {
|
||||
this._configureCodex(muxName);
|
||||
}
|
||||
|
||||
// Re-apply user env overrides before respawn so the new shell inherits them.
|
||||
|
||||
+23
-2
@@ -8,7 +8,7 @@
|
||||
* - SessionConfig — creation-time config (id, workingDir, createdAt)
|
||||
* - SessionOutput — captured stdout/stderr/exitCode
|
||||
* - SessionStatus — 'idle' | 'busy' | 'stopped' | 'error'
|
||||
* - SessionMode — 'claude' | 'shell' | 'opencode' (which CLI backend)
|
||||
* - SessionMode — 'claude' | 'shell' | 'opencode' | 'codex' (which CLI backend)
|
||||
* - ClaudeMode — CLI permission mode ('dangerously-skip-permissions' | 'normal' | 'allowedTools')
|
||||
* - SessionColor — visual differentiation color
|
||||
* - OpenCodeConfig — OpenCode-specific settings (model, autoAllowTools, continueSession)
|
||||
@@ -38,7 +38,7 @@ export type SessionStatus = 'idle' | 'busy' | 'stopped' | 'error';
|
||||
export type ClaudeMode = 'dangerously-skip-permissions' | 'normal' | 'allowedTools';
|
||||
|
||||
/** Session mode: which CLI backend a session runs */
|
||||
export type SessionMode = 'claude' | 'shell' | 'opencode';
|
||||
export type SessionMode = 'claude' | 'shell' | 'opencode' | 'codex';
|
||||
|
||||
/**
|
||||
* Valid Claude CLI effort levels (claude >= 2.1.154).
|
||||
@@ -69,6 +69,21 @@ export interface OpenCodeConfig {
|
||||
configContent?: string;
|
||||
}
|
||||
|
||||
/** Codex (OpenAI CLI) browser rendering strategy. Hybrid TUI is the only supported mode. */
|
||||
export type CodexRenderMode = 'hybrid';
|
||||
|
||||
/** Codex (OpenAI CLI) session configuration */
|
||||
export interface CodexConfig {
|
||||
/** Model identifier (e.g., "gpt-5", "o4-mini"). Passed via --model. */
|
||||
model?: string;
|
||||
/** Resume a previous codex conversation by session id (passed via --resume) */
|
||||
resumeSessionId?: string;
|
||||
/** Bypass approval prompts (passes --dangerously-bypass-approvals-and-sandbox) */
|
||||
dangerouslyBypassApprovals?: boolean;
|
||||
/** Browser rendering strategy for Codex sessions. Hybrid TUI is the only supported mode. */
|
||||
renderMode?: CodexRenderMode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration for creating a new session
|
||||
*/
|
||||
@@ -118,6 +133,10 @@ export interface SessionState {
|
||||
autoCompactThreshold?: number;
|
||||
/** Auto-compact prompt */
|
||||
autoCompactPrompt?: string;
|
||||
/** Auto-resume on usage limit enabled */
|
||||
autoResumeEnabled?: boolean;
|
||||
/** Pending usage-limit auto-resume fire time (epoch ms), if armed */
|
||||
autoResumeAt?: number;
|
||||
/** Image watcher enabled for this session */
|
||||
imageWatcherEnabled?: boolean;
|
||||
/** Total cost in USD */
|
||||
@@ -158,6 +177,8 @@ export interface SessionState {
|
||||
cliLatestVersion?: string;
|
||||
/** OpenCode-specific configuration (only for mode === 'opencode') */
|
||||
openCodeConfig?: OpenCodeConfig;
|
||||
/** Codex-specific configuration (only for mode === 'codex') */
|
||||
codexConfig?: CodexConfig;
|
||||
/** Claude conversation session ID to resume after reboot (set by restore script) */
|
||||
resumeSessionId?: string;
|
||||
/** Claude CLI effort level (soft default via --settings, switchable in-session via /effort) */
|
||||
|
||||
+6
-2
@@ -13,8 +13,12 @@
|
||||
* @module types/update
|
||||
*/
|
||||
|
||||
/** Which init system supervises the running server (decides how we restart it). */
|
||||
export type SupervisorKind = 'systemd' | 'launchd' | 'none';
|
||||
/**
|
||||
* Which init system supervises the running server (decides how we restart it).
|
||||
* `launchd-daemon` = a KeepAlive system-level LaunchDaemon (headless Macs, no GUI
|
||||
* login): restart works by killing the server and letting launchd respawn it.
|
||||
*/
|
||||
export type SupervisorKind = 'systemd' | 'launchd' | 'launchd-daemon' | 'none';
|
||||
|
||||
/** How Codeman was installed — only `git` installs can self-update in place. */
|
||||
export type InstallKind = 'git' | 'npm' | 'unknown';
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
/**
|
||||
* @fileoverview Pure detection of Claude Code usage-limit pause messages.
|
||||
*
|
||||
* When a Claude subscription limit (5-hour rolling window, weekly, Opus weekly,
|
||||
* or extra-usage balance) is hit, the Claude Code TUI stops working and prints a
|
||||
* status line with the reset time. These helpers detect that state in cleaned
|
||||
* (ANSI-stripped) terminal output and parse the reset time, so the session
|
||||
* auto-resume feature (SessionAutoOps) can schedule a "continue" nudge.
|
||||
*
|
||||
* Message shapes covered (observed across Claude Code 1.0.x–2.1.x, 2025–2026):
|
||||
* - `5-hour limit reached ∙ resets 8pm` (v1.0.109+ footer)
|
||||
* - `Session limit reached ∙ resets 8pm`
|
||||
* - `Weekly limit reached ∙ resets 6pm`
|
||||
* - `Opus weekly limit reached ∙ resets Oct 6, 1pm`
|
||||
* - `Limit reached · resets 1pm (America/Chicago) · /upgrade to Max…` (v2.0.55+)
|
||||
* - `You've hit your limit · resets 1:40pm (America/New_York)` (v2.1.x)
|
||||
* - `You've hit your weekly limit · resets Mon 12:00am`
|
||||
* - `You've hit your limit · resets May 5 at 9pm (America/New_York)`
|
||||
* - `You're out of extra usage · resets 1pm (America/Los_Angeles)`
|
||||
* - `Claude usage limit reached. Your limit will reset at 2pm (America/New_York)` (v1.0.x inline)
|
||||
* - `Claude AI usage limit reached|1755309600` (raw API, epoch seconds)
|
||||
*
|
||||
* Deliberately conservative: a limit phrase WITHOUT a parseable reset time is
|
||||
* ignored (returns null) so ordinary conversation text mentioning "limit
|
||||
* reached" can't arm the scheduler. The downstream retry loop (re-detection
|
||||
* after each resume attempt) compensates for any parsing imprecision.
|
||||
*
|
||||
* All functions are pure (caller passes `now`) for testability.
|
||||
*
|
||||
* @module usage-limit-patterns
|
||||
*/
|
||||
|
||||
/** Result of scanning terminal output for a usage-limit pause. */
|
||||
export interface UsageLimitDetection {
|
||||
/**
|
||||
* Epoch ms when the limit resets. May be in the past when the matched
|
||||
* message is stale (caller should treat past values as "retry soon").
|
||||
*/
|
||||
resetAt: number;
|
||||
/** Matched message snippet (for logging and UI). */
|
||||
matched: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Limit phrases that indicate Claude stopped on a usage limit.
|
||||
* `\blimit reached` covers all "<X> limit reached" footer variants.
|
||||
*/
|
||||
const LIMIT_PHRASE_PATTERN =
|
||||
/(?:\blimit\s+reached\b|you'?ve\s+hit\s+your\s+(?:\w+\s+)?limit\b|you'?re\s+out\s+of\s+extra\s+usage\b)/gi;
|
||||
|
||||
/**
|
||||
* Reset-time spec following a limit phrase. Captures:
|
||||
* 1 month (weekly resets >1 day out: "Oct 6, 1pm" / "May 5 at 9pm")
|
||||
* 2 day-of-month
|
||||
* 3 day-of-week ("Mon 12:00am")
|
||||
* 4 hour (12h) 5 minutes 6 am/pm 7 IANA timezone in parens (optional)
|
||||
* `resets?` + optional `at` also covers the v1.0.x "will reset at 2pm" form.
|
||||
*/
|
||||
const RESET_TIME_PATTERN =
|
||||
/\bresets?\s+(?:at\s+)?(?:(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\s+(\d{1,2})(?:\s*,\s*|\s+at\s+)|(sun|mon|tue|wed|thu|fri|sat)[a-z]*\s+)?(\d{1,2})(?::(\d{2}))?\s*(am|pm)\b(?:\s*\(([^()\n]{1,64})\))?/i;
|
||||
|
||||
/** Raw API form: `Claude AI usage limit reached|1755309600` (epoch seconds). */
|
||||
const EPOCH_LIMIT_PATTERN = /\busage\s+limit\s+reached\|(\d{9,11})\b/gi;
|
||||
|
||||
/** How far after a limit phrase the reset-time spec may appear (chars). */
|
||||
const RESET_TIME_WINDOW = 160;
|
||||
|
||||
/** Parsed reset spec must not be further out than this (weekly max ≈ 7 days). */
|
||||
const MAX_RESET_HORIZON_MS = 8 * 24 * 60 * 60 * 1000;
|
||||
|
||||
const MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
|
||||
const WEEKDAYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
|
||||
|
||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* Current UTC offset of an IANA timezone in ms, or null if unresolvable
|
||||
* (e.g. the `(Etc/Unknown)` failure variant Claude Code can print).
|
||||
* DST transitions inside the wait window can skew the result by an hour;
|
||||
* the auto-resume retry loop absorbs that.
|
||||
*/
|
||||
function zoneOffsetMs(timeZone: string, at: number): number | null {
|
||||
try {
|
||||
const dtf = new Intl.DateTimeFormat('en-US', { timeZone, timeZoneName: 'longOffset' });
|
||||
const name = dtf.formatToParts(at).find((p) => p.type === 'timeZoneName')?.value;
|
||||
if (!name) return null;
|
||||
const m = /^GMT(?:([+-])(\d{1,2})(?::(\d{2}))?)?$/.exec(name);
|
||||
if (!m) return null;
|
||||
if (!m[1]) return 0; // plain "GMT"
|
||||
const sign = m[1] === '-' ? -1 : 1;
|
||||
return sign * (parseInt(m[2], 10) * 60 + (m[3] ? parseInt(m[3], 10) : 0)) * 60_000;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
interface ResetSpec {
|
||||
month?: number; // 0-11
|
||||
dayOfMonth?: number; // 1-31
|
||||
dayOfWeek?: number; // 0-6 (Sun-Sat)
|
||||
hour: number; // 0-23
|
||||
minute: number; // 0-59
|
||||
timeZone?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute the epoch ms for a parsed reset spec. Times are wall-clock in the
|
||||
* given IANA timezone when present (and resolvable), otherwise server-local —
|
||||
* Claude CLI runs on the same host as Codeman, so local time is the right
|
||||
* default. Returns null when the spec is implausible (> ~8 days out).
|
||||
*/
|
||||
function resolveResetSpec(spec: ResetSpec, now: number): number | null {
|
||||
const offset = spec.timeZone ? zoneOffsetMs(spec.timeZone, now) : null;
|
||||
|
||||
// Wall-clock view of "now": shifted-UTC when a zone offset is known,
|
||||
// server-local otherwise. Read/build components with the matching API.
|
||||
const useZone = offset !== null;
|
||||
const wallNow = useZone ? new Date(now + offset) : new Date(now);
|
||||
const get = {
|
||||
year: () => (useZone ? wallNow.getUTCFullYear() : wallNow.getFullYear()),
|
||||
month: () => (useZone ? wallNow.getUTCMonth() : wallNow.getMonth()),
|
||||
date: () => (useZone ? wallNow.getUTCDate() : wallNow.getDate()),
|
||||
day: () => (useZone ? wallNow.getUTCDay() : wallNow.getDay()),
|
||||
};
|
||||
const build = (y: number, mo: number, d: number): number => {
|
||||
const wall = useZone
|
||||
? Date.UTC(y, mo, d, spec.hour, spec.minute)
|
||||
: new Date(y, mo, d, spec.hour, spec.minute).getTime();
|
||||
return useZone ? wall - offset : wall;
|
||||
};
|
||||
|
||||
let ts: number;
|
||||
if (spec.month !== undefined && spec.dayOfMonth !== undefined) {
|
||||
// Explicit date ("Oct 6, 1pm"). More than 2 days in the past → assume year
|
||||
// rollover (message seen near New Year); slightly past → stale, keep as-is.
|
||||
ts = build(get.year(), spec.month, spec.dayOfMonth);
|
||||
if (ts < now - 2 * DAY_MS) {
|
||||
ts = build(get.year() + 1, spec.month, spec.dayOfMonth);
|
||||
}
|
||||
} else if (spec.dayOfWeek !== undefined) {
|
||||
// Day-of-week ("Mon 12:00am") → next occurrence.
|
||||
const delta = (spec.dayOfWeek - get.day() + 7) % 7;
|
||||
ts = build(get.year(), get.month(), get.date() + delta);
|
||||
if (ts <= now) ts += 7 * DAY_MS;
|
||||
} else {
|
||||
// Time-only ("resets 8pm") → next occurrence within 24h.
|
||||
ts = build(get.year(), get.month(), get.date());
|
||||
if (ts <= now) ts += DAY_MS;
|
||||
}
|
||||
|
||||
if (ts > now + MAX_RESET_HORIZON_MS) return null;
|
||||
return ts;
|
||||
}
|
||||
|
||||
/** Parse the reset-time spec found within `window`, or null. */
|
||||
function parseResetTime(window: string, now: number): number | null {
|
||||
const m = RESET_TIME_PATTERN.exec(window);
|
||||
if (!m) return null;
|
||||
|
||||
const hour12 = parseInt(m[4], 10);
|
||||
const minute = m[5] ? parseInt(m[5], 10) : 0;
|
||||
if (hour12 < 1 || hour12 > 12 || minute > 59) return null;
|
||||
const pm = m[6].toLowerCase() === 'pm';
|
||||
const hour = (hour12 % 12) + (pm ? 12 : 0);
|
||||
|
||||
const spec: ResetSpec = { hour, minute };
|
||||
if (m[1] && m[2]) {
|
||||
spec.month = MONTHS.indexOf(m[1].toLowerCase());
|
||||
spec.dayOfMonth = parseInt(m[2], 10);
|
||||
if (spec.dayOfMonth < 1 || spec.dayOfMonth > 31) return null;
|
||||
} else if (m[3]) {
|
||||
spec.dayOfWeek = WEEKDAYS.indexOf(m[3].toLowerCase());
|
||||
}
|
||||
if (m[7]) spec.timeZone = m[7].trim();
|
||||
|
||||
return resolveResetSpec(spec, now);
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan cleaned (ANSI-stripped) terminal output for a usage-limit pause message
|
||||
* with a parseable reset time. Returns the LAST parseable occurrence in the
|
||||
* chunk (most recent on screen), or null when none is found.
|
||||
*/
|
||||
export function detectUsageLimitPause(cleanData: string, now: number = Date.now()): UsageLimitDetection | null {
|
||||
if (!cleanData || !/limit|extra usage/i.test(cleanData)) return null;
|
||||
|
||||
let result: UsageLimitDetection | null = null;
|
||||
|
||||
// Raw API epoch form
|
||||
EPOCH_LIMIT_PATTERN.lastIndex = 0;
|
||||
let em: RegExpExecArray | null;
|
||||
while ((em = EPOCH_LIMIT_PATTERN.exec(cleanData)) !== null) {
|
||||
const resetAt = parseInt(em[1], 10) * 1000;
|
||||
if (resetAt > now + MAX_RESET_HORIZON_MS) continue;
|
||||
result = { resetAt, matched: em[0] };
|
||||
}
|
||||
|
||||
// TUI phrase + "resets <time>" forms
|
||||
LIMIT_PHRASE_PATTERN.lastIndex = 0;
|
||||
let pm: RegExpExecArray | null;
|
||||
while ((pm = LIMIT_PHRASE_PATTERN.exec(cleanData)) !== null) {
|
||||
const window = cleanData.slice(pm.index, pm.index + RESET_TIME_WINDOW);
|
||||
const resetAt = parseResetTime(window, now);
|
||||
if (resetAt !== null) {
|
||||
result = { resetAt, matched: window.slice(0, 80).trim() };
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* @fileoverview Resolve the Codex (OpenAI) CLI binary across common install paths.
|
||||
*
|
||||
* Mirrors opencode-cli-resolver.ts pattern. Finds the `codex` binary
|
||||
* and provides an augmented PATH string for tmux sessions.
|
||||
*
|
||||
* @module utils/codex-cli-resolver
|
||||
*/
|
||||
|
||||
import { execSync } from 'node:child_process';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import { EXEC_TIMEOUT_MS } from '../config/exec-timeout.js';
|
||||
|
||||
/** Common directories where the Codex CLI binary may be installed */
|
||||
const CODEX_SEARCH_DIRS = [
|
||||
join(homedir(), '.codex', 'bin'), // Default install location
|
||||
join(homedir(), '.local', 'bin'), // Alternative install location
|
||||
'/usr/local/bin', // Homebrew / system
|
||||
join(homedir(), '.bun', 'bin'), // Bun global
|
||||
join(homedir(), '.npm-global', 'bin'), // npm global
|
||||
join(homedir(), 'bin'), // User bin
|
||||
];
|
||||
|
||||
/** Cached directory containing the codex binary (empty string = searched but not found) */
|
||||
let _codexDir: string | null = null;
|
||||
|
||||
/**
|
||||
* Finds the directory containing the `codex` binary.
|
||||
* Checks `which codex` first, then falls back to common install locations.
|
||||
* Result is cached for subsequent calls.
|
||||
*
|
||||
* @returns Directory path, or null if not found
|
||||
*/
|
||||
export function resolveCodexDir(): string | null {
|
||||
if (_codexDir !== null) return _codexDir || null;
|
||||
|
||||
// Try `which` first (respects current PATH)
|
||||
try {
|
||||
const result = execSync('which codex', {
|
||||
encoding: 'utf-8',
|
||||
timeout: EXEC_TIMEOUT_MS,
|
||||
}).trim();
|
||||
if (result && existsSync(result)) {
|
||||
_codexDir = dirname(result);
|
||||
return _codexDir;
|
||||
}
|
||||
} catch {
|
||||
// Codex not in PATH, will check common locations
|
||||
}
|
||||
|
||||
for (const dir of CODEX_SEARCH_DIRS) {
|
||||
if (existsSync(join(dir, 'codex'))) {
|
||||
_codexDir = dir;
|
||||
return _codexDir;
|
||||
}
|
||||
}
|
||||
|
||||
_codexDir = ''; // mark as searched, not found
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if Codex CLI is available on the system.
|
||||
*/
|
||||
export function isCodexAvailable(): boolean {
|
||||
return resolveCodexDir() !== null;
|
||||
}
|
||||
@@ -28,3 +28,4 @@ export { assertNever } from './type-safety.js';
|
||||
export { wrapWithNice } from './nice-wrapper.js';
|
||||
export { findClaudeDir, getAugmentedPath } from './claude-cli-resolver.js';
|
||||
export { resolveOpenCodeDir } from './opencode-cli-resolver.js';
|
||||
export { resolveCodexDir, isCodexAvailable } from './codex-cli-resolver.js';
|
||||
|
||||
@@ -205,7 +205,12 @@ export function registerSecurityHeaders(app: FastifyInstance, https: boolean): v
|
||||
const scriptSrc =
|
||||
"script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net" + (gesture ? " 'wasm-unsafe-eval'" : '');
|
||||
const connectSrc = "connect-src 'self' wss://api.deepgram.com";
|
||||
const workerSrc = gesture ? "; worker-src 'self' blob:" : '';
|
||||
// blob: workers are needed unconditionally: terminal-ui's _safeYield tick
|
||||
// worker (throttling escape) is created from a Blob URL. Without this, every
|
||||
// page load logs a CSP violation and the worker leg of _safeYield is dead.
|
||||
// Risk is minimal — only same-origin scripts (already governed by script-src)
|
||||
// can construct blob workers.
|
||||
const workerSrc = "; worker-src 'self' blob:";
|
||||
const csp =
|
||||
`default-src 'self'; ${scriptSrc}; style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; ` +
|
||||
`img-src 'self' data: blob:; ${connectSrc}; font-src 'self' https://cdn.jsdelivr.net; frame-ancestors 'self'${workerSrc}`;
|
||||
|
||||
+72
-4
@@ -153,6 +153,9 @@ const _SSE_HANDLER_MAP = [
|
||||
[SSE_EVENTS.SESSION_IDLE, '_onSessionIdle'],
|
||||
[SSE_EVENTS.SESSION_WORKING, '_onSessionWorking'],
|
||||
[SSE_EVENTS.SESSION_AUTO_CLEAR, '_onSessionAutoClear'],
|
||||
[SSE_EVENTS.SESSION_LIMIT_PAUSE_SCHEDULED, '_onSessionLimitPauseScheduled'],
|
||||
[SSE_EVENTS.SESSION_LIMIT_RESUME, '_onSessionLimitResume'],
|
||||
[SSE_EVENTS.SESSION_LIMIT_RESUME_CANCELLED, '_onSessionLimitResumeCancelled'],
|
||||
[SSE_EVENTS.SESSION_CLI_INFO, '_onSessionCliInfo'],
|
||||
|
||||
// Scheduled runs
|
||||
@@ -576,7 +579,6 @@ class CodemanApp {
|
||||
// Apply keyboard bar mode from settings
|
||||
const _kbSettings = this.loadAppSettingsFromStorage();
|
||||
if (_kbSettings.extendedKeyboardBar) KeyboardAccessoryBar.setMode('extended');
|
||||
this.bindMobileHeaderUtilityToggle?.();
|
||||
this.applyHeaderVisibilitySettings();
|
||||
this.applyTabWrapSettings();
|
||||
this.applyMonitorVisibility();
|
||||
@@ -1768,6 +1770,33 @@ class CodemanApp {
|
||||
this._notifySession(data.sessionId, 'info', 'auto-clear', 'Auto-Cleared', `Context reset at ${(data.tokens || 0).toLocaleString()} tokens`);
|
||||
}
|
||||
|
||||
_onSessionLimitPauseScheduled(data) {
|
||||
const session = this.sessions.get(data.sessionId);
|
||||
if (session) session.autoResumeAt = data.resumeAt;
|
||||
const at = new Date(data.resumeAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
if (data.sessionId === this.activeSessionId) {
|
||||
this.showToast(`Usage limit reached — auto-resume at ${at}`, 'warning');
|
||||
}
|
||||
this._notifySession(data.sessionId, 'warning', 'limit-pause', 'Usage Limit Reached', `Auto-resume scheduled for ${at}`);
|
||||
this.updateAutoResumeStatus(data.sessionId);
|
||||
}
|
||||
|
||||
_onSessionLimitResume(data) {
|
||||
const session = this.sessions.get(data.sessionId);
|
||||
if (session) session.autoResumeAt = undefined;
|
||||
if (data.sessionId === this.activeSessionId) {
|
||||
this.showToast('Usage limit reset — work resumed automatically', 'success');
|
||||
}
|
||||
this._notifySession(data.sessionId, 'info', 'limit-resume', 'Auto-Resumed', 'Usage limit reset — continuing work');
|
||||
this.updateAutoResumeStatus(data.sessionId);
|
||||
}
|
||||
|
||||
_onSessionLimitResumeCancelled(data) {
|
||||
const session = this.sessions.get(data.sessionId);
|
||||
if (session) session.autoResumeAt = undefined;
|
||||
this.updateAutoResumeStatus(data.sessionId);
|
||||
}
|
||||
|
||||
_onSessionCliInfo(data) {
|
||||
const session = this.sessions.get(data.sessionId);
|
||||
if (session) {
|
||||
@@ -1843,6 +1872,7 @@ class CodemanApp {
|
||||
// selectSession's earlier resizes ran before this WS existed, so they
|
||||
// went over HTTP, which never claims (see ws-routes sizingToken).
|
||||
this.sendResize(sessionId)?.catch?.(() => {});
|
||||
this._startMobileResizeRetry(sessionId);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1868,6 +1898,7 @@ class CodemanApp {
|
||||
this._ws = null;
|
||||
this._wsSessionId = null;
|
||||
this._wsReady = false;
|
||||
this._stopMobileResizeRetry();
|
||||
|
||||
// Reconnect on unexpected close (server restart, network blip, ping timeout).
|
||||
// Don't reconnect if we intentionally disconnected (_disconnectWs nulls onclose)
|
||||
@@ -1893,6 +1924,7 @@ class CodemanApp {
|
||||
_disconnectWs() {
|
||||
this._clearTimer('_wsReconnectTimer');
|
||||
this._wsReconnectAttempts = 0;
|
||||
this._stopMobileResizeRetry();
|
||||
if (this._ws) {
|
||||
this._ws.onclose = null; // Prevent re-entrant cleanup
|
||||
this._ws.close();
|
||||
@@ -1902,6 +1934,41 @@ class CodemanApp {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Small-viewport claim-idle retry. While a desktop sizing claim is "hot",
|
||||
* the server ignores this device's resize (Session.DESKTOP_CLAIM_IDLE_MS),
|
||||
* and the single resize sent on attach is deduped client-side — without a
|
||||
* retry, a phone that attached under an active desktop would render a
|
||||
* desktop-width stream forever. Re-send the current dims periodically (a
|
||||
* server-side no-op once the pane already matches) so the pane reflows to
|
||||
* this device shortly after the desktop goes idle. Visible-tab only: a
|
||||
* phone in a pocket must not steal the pane from an active desktop.
|
||||
*/
|
||||
_startMobileResizeRetry(sessionId) {
|
||||
this._stopMobileResizeRetry();
|
||||
const type =
|
||||
typeof MobileDetection !== 'undefined' && MobileDetection.getDeviceType
|
||||
? MobileDetection.getDeviceType()
|
||||
: 'desktop';
|
||||
if (type === 'desktop') return;
|
||||
this._mobileResizeRetryTimer = setInterval(() => {
|
||||
if (document.visibilityState !== 'visible') return;
|
||||
if (!this._wsReady || this._wsSessionId !== sessionId) return;
|
||||
// Same guard as throttledResize: while the virtual keyboard is up, a
|
||||
// fit()+SIGWINCH at the shrunken row count makes Ink re-render garbage
|
||||
// and shifts the accessory toolbar mid-typing. Retry after it closes.
|
||||
if (typeof KeyboardHandler !== 'undefined' && KeyboardHandler.keyboardVisible) return;
|
||||
this.sendResize(sessionId)?.catch?.(() => {});
|
||||
}, MOBILE_RESIZE_RETRY_MS);
|
||||
}
|
||||
|
||||
_stopMobileResizeRetry() {
|
||||
if (this._mobileResizeRetryTimer) {
|
||||
clearInterval(this._mobileResizeRetryTimer);
|
||||
this._mobileResizeRetryTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send input to server without blocking the keystroke flush cycle.
|
||||
* Uses a sequential promise chain to preserve character ordering
|
||||
@@ -2093,7 +2160,6 @@ class CodemanApp {
|
||||
KeyboardHandler.cleanup();
|
||||
MobileDetection.init();
|
||||
KeyboardHandler.init();
|
||||
this.bindMobileHeaderUtilityToggle?.();
|
||||
// Clear tab alerts
|
||||
this.tabAlerts.clear();
|
||||
// Clear shown completions (used for duplicate notification prevention)
|
||||
@@ -2572,7 +2638,7 @@ class CodemanApp {
|
||||
<span class="tab-status ${status}" aria-hidden="true"></span>
|
||||
<span class="tab-info">
|
||||
<span class="tab-name-row">
|
||||
${mode === 'shell' ? '<span class="tab-mode shell" aria-hidden="true">sh</span>' : mode === 'opencode' ? '<span class="tab-mode opencode" aria-hidden="true">oc</span>' : ''}
|
||||
${mode === 'shell' ? '<span class="tab-mode shell" aria-hidden="true">sh</span>' : mode === 'opencode' ? '<span class="tab-mode opencode" aria-hidden="true">oc</span>' : mode === 'codex' ? '<span class="tab-mode codex" aria-hidden="true">cx</span>' : ''}
|
||||
<span class="tab-name" data-session-id="${id}">${(() => { const p = parseSessionPrefix(name); return p && p.suffix ? '<span class="tab-prefix">' + escapeHtml(p.prefix) + '</span><span class="tab-suffix">: ' + escapeHtml(p.suffix) + '</span>' : escapeHtml(name); })()}</span>
|
||||
<span class="tab-detached-badge" aria-hidden="true">detached</span>
|
||||
</span>
|
||||
@@ -3374,7 +3440,9 @@ class CodemanApp {
|
||||
if (killTitle) {
|
||||
killTitle.textContent = session.mode === 'opencode'
|
||||
? 'Kill Tmux & OpenCode'
|
||||
: 'Kill Tmux & Claude Code';
|
||||
: session.mode === 'codex'
|
||||
? 'Kill Tmux & Codex'
|
||||
: 'Kill Tmux & Claude Code';
|
||||
}
|
||||
|
||||
document.getElementById('closeConfirmModal').classList.add('active');
|
||||
|
||||
@@ -51,6 +51,7 @@ const GROUPING_TIMEOUT_MS = 5000; // 5 seconds - notification grouping
|
||||
const NOTIFICATION_LIST_CAP = 100; // Max notifications in list
|
||||
const TITLE_FLASH_INTERVAL_MS = 1500; // Title flash rate
|
||||
const BROWSER_NOTIF_RATE_LIMIT_MS = 3000; // Rate limit for browser notifications
|
||||
const MOBILE_RESIZE_RETRY_MS = 30000; // Small-viewport resize re-send while a desktop sizing claim is hot
|
||||
const AUTO_CLOSE_NOTIFICATION_MS = 8000; // Auto-close browser notifications
|
||||
const THROTTLE_DELAY_MS = 100; // General UI throttle delay
|
||||
const TERMINAL_CHUNK_SIZE = 32 * 1024; // 32KB chunks for terminal buffer loading
|
||||
@@ -243,6 +244,9 @@ const SSE_EVENTS = {
|
||||
SESSION_WORKING: 'session:working',
|
||||
SESSION_AUTO_CLEAR: 'session:autoClear',
|
||||
SESSION_AUTO_COMPACT: 'session:autoCompact',
|
||||
SESSION_LIMIT_PAUSE_SCHEDULED: 'session:limitPauseScheduled',
|
||||
SESSION_LIMIT_RESUME: 'session:limitResume',
|
||||
SESSION_LIMIT_RESUME_CANCELLED: 'session:limitResumeCancelled',
|
||||
SESSION_CLI_INFO: 'session:cliInfo',
|
||||
SESSION_MESSAGE: 'session:message',
|
||||
SESSION_INTERACTIVE: 'session:interactive',
|
||||
|
||||
+60
-19
@@ -69,10 +69,6 @@
|
||||
<span class="logo" onclick="app.goHome()" title="Go to main page">Codeman</span>
|
||||
</div>
|
||||
|
||||
<button class="mobile-header-utility-toggle" id="mobileHeaderUtilityToggle" type="button" aria-label="Toggle header utilities" aria-controls="headerRight" aria-expanded="false" title="Header utilities">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/><circle cx="5" cy="12" r="1"/></svg>
|
||||
</button>
|
||||
|
||||
<!-- Session Tabs -->
|
||||
<div class="session-tabs" id="sessionTabs" role="tablist" aria-label="Session tabs">
|
||||
</div>
|
||||
@@ -110,7 +106,7 @@
|
||||
<span class="stat-value" id="statMem">--</span>
|
||||
</div>
|
||||
</div>
|
||||
<button class="btn-icon-header btn-response-viewer-header" onclick="app.toggleResponseViewer()" title="View last response" aria-label="View last response"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></button>
|
||||
<button class="btn-icon-header btn-response-viewer-header btn-response-viewer-header--hidden" onclick="app.toggleResponseViewer()" title="View last response" aria-label="View last response"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></button>
|
||||
<button class="btn-icon-header btn-multimonitor btn-multimonitor--hidden" onclick="app.launchMultiMonitor()" title="Open Codeman across all displays" aria-label="Open Codeman across all displays"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="2" y="4" width="13" height="9" rx="1.5"/><rect x="11" y="9" width="11" height="8" rx="1.5"/></svg></button>
|
||||
<button class="btn-icon-header btn-notifications" onclick="app.toggleNotifications()" title="Notifications" aria-label="Toggle notifications" style="display:none;">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>
|
||||
@@ -384,6 +380,9 @@
|
||||
<button class="run-mode-option" data-mode="opencode" onclick="app.setRunMode('opencode')">
|
||||
<span class="run-mode-dot opencode"></span>OpenCode
|
||||
</button>
|
||||
<button class="run-mode-option" data-mode="codex" onclick="app.setRunMode('codex')">
|
||||
<span class="run-mode-dot codex"></span>Codex
|
||||
</button>
|
||||
<div class="run-mode-sep"></div>
|
||||
<div class="run-mode-header">Recent Sessions</div>
|
||||
<div class="run-mode-history" id="runModeHistory"></div>
|
||||
@@ -616,6 +615,15 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="auto-resume-box">
|
||||
<label class="checkbox-inline">
|
||||
<input type="checkbox" id="modalAutoResumeEnabled" onchange="app.autoSaveAutoResume()">
|
||||
<span>Auto-resume when usage limit resets</span>
|
||||
</label>
|
||||
<span class="auto-resume-status" id="autoResumeStatus"></span>
|
||||
<span class="form-hint">If Claude pauses on a usage limit ("limit reached · resets 3pm"), Codeman waits for the reset time and automatically continues the work. Independent of the respawn loop below.</span>
|
||||
</div>
|
||||
|
||||
<div class="form-row">
|
||||
<label>Duration</label>
|
||||
<div class="duration-presets">
|
||||
@@ -655,7 +663,7 @@
|
||||
<div class="form-section-header">Respawn Cycle</div>
|
||||
<div class="form-row">
|
||||
<label>1. Update Prompt</label>
|
||||
<textarea id="modalRespawnPrompt" rows="3" placeholder="Prompt to send when idle" onchange="app.autoSaveRespawnConfig()" style="resize: vertical; min-height: 60px;">update all the docs and CLAUDE.md</textarea>
|
||||
<textarea id="modalRespawnPrompt" rows="1" placeholder="Prompt to send when idle" onchange="app.autoSaveRespawnConfig()" style="resize: vertical; min-height: 30px;">update all the docs and CLAUDE.md</textarea>
|
||||
</div>
|
||||
|
||||
<div class="respawn-options-row" style="margin: 8px 0;">
|
||||
@@ -667,22 +675,17 @@
|
||||
<input type="checkbox" id="modalRespawnSendInit" checked onchange="app.autoSaveRespawnConfig()">
|
||||
<span>3. Send /init</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="form-row">
|
||||
<label>4. Kickstart Prompt</label>
|
||||
<textarea id="modalRespawnKickstart" rows="2" placeholder="Optional: prompt if /init doesn't trigger work" onchange="app.autoSaveRespawnConfig()" style="resize: vertical; min-height: 40px;"></textarea>
|
||||
<span class="form-hint">Sent only when /init completes but Claude stays idle</span>
|
||||
</div>
|
||||
|
||||
<div class="form-section-header">Behavior</div>
|
||||
<div class="respawn-options-row">
|
||||
<label class="checkbox-inline">
|
||||
<label class="checkbox-inline" title="Presses Enter for plan approvals and default question options">
|
||||
<input type="checkbox" id="modalRespawnAutoAccept" checked onchange="app.autoSaveRespawnConfig()">
|
||||
<span>Auto-accept prompts</span>
|
||||
</label>
|
||||
</div>
|
||||
<span class="form-hint">Auto-accept presses Enter for plan approvals and default question options</span>
|
||||
|
||||
<div class="form-row">
|
||||
<label>4. Kickstart Prompt</label>
|
||||
<textarea id="modalRespawnKickstart" rows="1" placeholder="Optional: prompt if /init doesn't trigger work" onchange="app.autoSaveRespawnConfig()" style="resize: vertical; min-height: 30px;"></textarea>
|
||||
<span class="form-hint">Sent only when /init completes but Claude stays idle · Auto-accept presses Enter for plan approvals and default options</span>
|
||||
</div>
|
||||
</div>
|
||||
</div><!-- End respawn-tab -->
|
||||
|
||||
@@ -895,6 +898,7 @@
|
||||
<div class="modal-tabs">
|
||||
<button class="modal-tab-btn active" data-tab="settings-display">Display</button>
|
||||
<button class="modal-tab-btn" data-tab="settings-claude">Claude CLI</button>
|
||||
<button class="modal-tab-btn" data-tab="settings-codex">Codex CLI</button>
|
||||
<button class="modal-tab-btn" data-tab="settings-models">Models</button>
|
||||
<button class="modal-tab-btn" data-tab="settings-paths">Paths</button>
|
||||
<button class="modal-tab-btn" data-tab="settings-notifications">Notifications</button>
|
||||
@@ -985,6 +989,13 @@
|
||||
<span class="slider"></span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="settings-item" title="Show the response viewer (eye) button in header">
|
||||
<span class="settings-item-label">Response Viewer</span>
|
||||
<label class="switch switch-sm">
|
||||
<input type="checkbox" id="appSettingsShowResponseViewer">
|
||||
<span class="slider"></span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="settings-item" title="Show the multi-monitor button in the header (opens Codeman spanned across all displays)">
|
||||
<span class="settings-item-label">Multi-monitor Button</span>
|
||||
<label class="switch switch-sm">
|
||||
@@ -1137,13 +1148,26 @@
|
||||
</label>
|
||||
<span class="form-hint">Enable experimental Agent Teams for all new Claude sessions (disabled by default)</span>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label>Claude Model</label>
|
||||
<select id="appSettingsClaudeModel" class="form-select">
|
||||
<option value="">Default (CLI setting)</option>
|
||||
<option value="claude-fable-5[1m]">Fable 5 (1M context)</option>
|
||||
<option value="claude-fable-5">Fable 5</option>
|
||||
<option value="opus[1m]">Opus (1M context)</option>
|
||||
<option value="opus">Opus</option>
|
||||
<option value="sonnet">Sonnet</option>
|
||||
<option value="haiku">Haiku</option>
|
||||
</select>
|
||||
<span class="form-hint">Model for new Claude sessions (pinned via the case's .claude/settings.local.json) — takes precedence over the 1M Opus toggle below</span>
|
||||
</div>
|
||||
<div class="form-row form-row-switch">
|
||||
<label>1M Opus Context</label>
|
||||
<label class="switch">
|
||||
<input type="checkbox" id="appSettingsOpusContext1m">
|
||||
<span class="slider"></span>
|
||||
</label>
|
||||
<span class="form-hint">Use 1M token context window (model: opus[1m]) for all new sessions</span>
|
||||
<span class="form-hint">Use 1M token context window (model: opus[1m]) for all new sessions — ignored when a Claude Model is selected above</span>
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label>Thinking Effort</label>
|
||||
@@ -1174,12 +1198,25 @@
|
||||
<span class="form-hint">Process priority (-20 to 19, higher = lower priority, default: 10)</span>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Codex CLI Tab -->
|
||||
<div class="modal-tab-content hidden" id="settings-codex">
|
||||
<div class="form-section-header">Codex CLI</div>
|
||||
<div class="form-row form-row-switch">
|
||||
<label>Bypass Approvals and Sandbox</label>
|
||||
<label class="switch">
|
||||
<input type="checkbox" id="appSettingsCodexDangerouslyBypassApprovals">
|
||||
<span class="slider"></span>
|
||||
</label>
|
||||
<span class="form-hint">Start new Codex sessions with --dangerously-bypass-approvals-and-sandbox</span>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Models Tab -->
|
||||
<div class="modal-tab-content hidden" id="settings-models">
|
||||
<div class="form-row">
|
||||
<label>Default Model</label>
|
||||
<select id="appSettingsDefaultModel" class="form-select">
|
||||
<option value="">Default (CLI default)</option>
|
||||
<option value="claude-fable-5">Fable 5 (Most powerful)</option>
|
||||
<option value="opus">Opus (Most capable)</option>
|
||||
<option value="sonnet">Sonnet (Balanced)</option>
|
||||
<option value="haiku">Haiku (Fast & cheap)</option>
|
||||
@@ -1203,6 +1240,7 @@
|
||||
<option value="haiku">Haiku</option>
|
||||
<option value="sonnet">Sonnet</option>
|
||||
<option value="opus">Opus</option>
|
||||
<option value="claude-fable-5">Fable 5</option>
|
||||
</select>
|
||||
<span class="form-hint">Quick searches, codebase exploration</span>
|
||||
</div>
|
||||
@@ -1213,6 +1251,7 @@
|
||||
<option value="haiku">Haiku</option>
|
||||
<option value="sonnet">Sonnet</option>
|
||||
<option value="opus">Opus</option>
|
||||
<option value="claude-fable-5">Fable 5</option>
|
||||
</select>
|
||||
<span class="form-hint">Code writing, feature implementation</span>
|
||||
</div>
|
||||
@@ -1223,6 +1262,7 @@
|
||||
<option value="haiku">Haiku</option>
|
||||
<option value="sonnet">Sonnet</option>
|
||||
<option value="opus">Opus</option>
|
||||
<option value="claude-fable-5">Fable 5</option>
|
||||
</select>
|
||||
<span class="form-hint">Writing and running tests</span>
|
||||
</div>
|
||||
@@ -1233,6 +1273,7 @@
|
||||
<option value="haiku">Haiku</option>
|
||||
<option value="sonnet">Sonnet</option>
|
||||
<option value="opus">Opus</option>
|
||||
<option value="claude-fable-5">Fable 5</option>
|
||||
</select>
|
||||
<span class="form-hint">Code review, quality checks</span>
|
||||
</div>
|
||||
|
||||
@@ -304,8 +304,16 @@ const KeyboardHandler = {
|
||||
// translate up so it sits at the bottom of the visual viewport.
|
||||
// This formula accounts for iOS scrolling the visual viewport (offsetTop)
|
||||
// when the user types in xterm's hidden textarea.
|
||||
const appEl = document.querySelector('.app');
|
||||
const layoutHeight = appEl?.getBoundingClientRect().bottom || window.innerHeight;
|
||||
//
|
||||
// MUST measure against the LAYOUT viewport (window.innerHeight): the
|
||||
// bars are position:fixed, which anchors to the layout viewport — on
|
||||
// iOS that keeps its full height while the keyboard is open. Measuring
|
||||
// the shrunken .app instead (its height tracks --app-height = visual
|
||||
// viewport) made the offset compute to 0 on iOS, leaving the toolbar
|
||||
// and accessory bar behind the OS keyboard (0.9.8 regression). On
|
||||
// Android the layout viewport itself shrinks with the keyboard, so
|
||||
// innerHeight === visualBottom and the offset is naturally 0 there.
|
||||
const layoutHeight = window.innerHeight;
|
||||
const visualBottom = window.visualViewport.offsetTop + window.visualViewport.height;
|
||||
const keyboardOffset = Math.max(0, layoutHeight - visualBottom);
|
||||
|
||||
|
||||
@@ -94,30 +94,6 @@ html.mobile-init .file-browser-panel {
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.mobile-header-utility-toggle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
padding: 0;
|
||||
margin: -4px 0.2rem -4px 0;
|
||||
background: transparent;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
color: var(--text-muted);
|
||||
order: -1;
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.mobile-header-utility-toggle.active,
|
||||
.mobile-header-utility-toggle:active {
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.header-right {
|
||||
position: fixed;
|
||||
top: calc(52px + var(--safe-area-top));
|
||||
@@ -474,25 +450,6 @@ html.mobile-init .file-browser-panel {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.mobile-header-utility-toggle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
padding: 0;
|
||||
margin: -6px 0.15rem -6px 0;
|
||||
background: transparent;
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
color: var(--text-muted);
|
||||
order: -1;
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
flex-shrink: 0;
|
||||
border-left: none;
|
||||
}
|
||||
|
||||
/* Smaller header buttons on mobile */
|
||||
.btn-icon-header {
|
||||
width: 26px;
|
||||
|
||||
@@ -378,7 +378,10 @@ Object.assign(CodemanApp.prototype, {
|
||||
prompt += `Output \`<promise>${config.completionPhrase}</promise>\` when done\n\n`;
|
||||
|
||||
prompt += '## If Stuck\n';
|
||||
prompt += 'Output `<promise>BLOCKED</promise>` with explanation';
|
||||
prompt += 'Output `<promise>BLOCKED</promise>` with explanation\n\n';
|
||||
|
||||
prompt += '## Status Reporting\n';
|
||||
prompt += '• End every response with a `RALPH_STATUS` block (parsed by Codeman)';
|
||||
|
||||
// Show preview with highlighting (escape first, then apply formatting)
|
||||
const escapedPrompt = escapeHtml(prompt);
|
||||
|
||||
@@ -151,17 +151,21 @@ Object.assign(CodemanApp.prototype, {
|
||||
return this.run();
|
||||
},
|
||||
|
||||
/** Run using the selected mode (Claude Code or OpenCode) */
|
||||
/** Run using the selected mode (Claude Code, OpenCode, or Codex) */
|
||||
async run() {
|
||||
const mode = this._runMode || 'claude';
|
||||
if (mode === 'opencode') {
|
||||
return this.runOpenCode();
|
||||
}
|
||||
if (mode === 'codex') {
|
||||
return this.runCodex();
|
||||
}
|
||||
return this.runClaude();
|
||||
},
|
||||
|
||||
/** Get/set the run mode, persisted in localStorage */
|
||||
get runMode() { return this._runMode || 'claude'; },
|
||||
// Note: `runMode` is an accessor defined via Object.defineProperty at the bottom of
|
||||
// this file — an object-literal getter here would be flattened to a static value by
|
||||
// Object.assign (it copies values, not accessor descriptors).
|
||||
|
||||
setRunMode(mode) {
|
||||
this._runMode = mode;
|
||||
@@ -253,7 +257,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
gearBtn.className = `btn-toolbar btn-run-gear mode-${mode}`;
|
||||
}
|
||||
if (label) {
|
||||
label.textContent = mode === 'opencode' ? 'Run OC' : 'Run';
|
||||
label.textContent = mode === 'opencode' ? 'Run OC' : mode === 'codex' ? 'Run CX' : 'Run';
|
||||
}
|
||||
},
|
||||
|
||||
@@ -350,8 +354,10 @@ Object.assign(CodemanApp.prototype, {
|
||||
const envOverrides = this.buildEnvOverrides(caseSettings, globalSettings);
|
||||
const hasEnvOverrides = Object.keys(envOverrides).length > 0;
|
||||
const effort = this.getEffortSetting(globalSettings);
|
||||
// Explicit Claude Model choice (App Settings) wins over the legacy 1M Opus
|
||||
// toggles; both flow as `modelOverride` → the case's .claude/settings.local.json
|
||||
const useOpus1m = caseSettings.opusContext1m || globalSettings.opusContext1mEnabled;
|
||||
const modelOverride = useOpus1m ? 'opus[1m]' : '';
|
||||
const modelOverride = globalSettings.claudeModel || (useOpus1m ? 'opus[1m]' : '');
|
||||
|
||||
// Step 1: Create all sessions in parallel
|
||||
this.terminal.writeln(`\x1b[90m Creating ${tabCount} session(s)...\x1b[0m`);
|
||||
@@ -580,6 +586,53 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
},
|
||||
|
||||
async runCodex() {
|
||||
const caseName = document.getElementById('quickStartCase').value || 'testcase';
|
||||
|
||||
this.terminal.clear();
|
||||
this.terminal.writeln(`\x1b[1;32m Starting Codex session in ${caseName}...\x1b[0m`);
|
||||
this.terminal.writeln('');
|
||||
this.terminal.focus();
|
||||
|
||||
try {
|
||||
const statusRes = await fetch('/api/codex/status');
|
||||
const status = (await statusRes.json()).data;
|
||||
if (!status.available) {
|
||||
this.terminal.writeln('\x1b[1;31m Codex CLI not found.\x1b[0m');
|
||||
this.terminal.writeln('\x1b[90m Install with: npm install -g @openai/codex\x1b[0m');
|
||||
return;
|
||||
}
|
||||
|
||||
const globalSettings = this.loadAppSettingsFromStorage();
|
||||
const envOverrides = this.buildEnvOverrides(this.getCaseSettings(caseName), globalSettings);
|
||||
const res = await fetch('/api/quick-start', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
caseName,
|
||||
mode: 'codex',
|
||||
codexConfig: {
|
||||
dangerouslyBypassApprovals: globalSettings.codexDangerouslyBypassApprovals ?? false,
|
||||
renderMode: 'hybrid',
|
||||
},
|
||||
...(Object.keys(envOverrides).length > 0 ? { envOverrides } : {}),
|
||||
})
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!data.success) throw new Error(data.error || 'Failed to start Codex');
|
||||
|
||||
// Switch to the new session (don't pre-set activeSessionId — selectSession
|
||||
// early-returns when IDs match, skipping buffer load and sendResize)
|
||||
if (data.data.sessionId) {
|
||||
await this.selectSession(data.data.sessionId);
|
||||
}
|
||||
|
||||
this.terminal.focus();
|
||||
} catch (err) {
|
||||
this.terminal.writeln(`\x1b[1;31m Error: ${err.message}\x1b[0m`);
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// Session Options Modal
|
||||
@@ -592,7 +645,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
this.editingSessionId = sessionId;
|
||||
|
||||
// Reset to an appropriate tab — Summary for OpenCode (Respawn/Ralph are Claude-only)
|
||||
this.switchOptionsTab(session.mode === 'opencode' ? 'summary' : 'respawn');
|
||||
this.switchOptionsTab(session.mode === 'opencode' || session.mode === 'codex' ? 'summary' : 'respawn');
|
||||
|
||||
// Update respawn status display and buttons
|
||||
const respawnStatus = document.getElementById('sessionRespawnStatus');
|
||||
@@ -621,7 +674,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
|
||||
// Hide Claude-specific options for OpenCode sessions
|
||||
const isOpenCode = session.mode === 'opencode';
|
||||
const isOpenCode = session.mode === 'opencode' || session.mode === 'codex';
|
||||
const claudeOnlyEls = document.querySelectorAll('[data-claude-only]');
|
||||
claudeOnlyEls.forEach(el => { el.style.display = isOpenCode ? 'none' : ''; });
|
||||
|
||||
@@ -637,6 +690,10 @@ Object.assign(CodemanApp.prototype, {
|
||||
document.getElementById('modalAutoCompactPrompt').value = session.autoCompactPrompt ?? '';
|
||||
document.getElementById('modalAutoClearEnabled').checked = session.autoClearEnabled ?? false;
|
||||
document.getElementById('modalAutoClearThreshold').value = session.autoClearThreshold ?? 140000;
|
||||
|
||||
// Populate auto-resume on usage limit (token pause control)
|
||||
document.getElementById('modalAutoResumeEnabled').checked = session.autoResumeEnabled ?? false;
|
||||
this.updateAutoResumeStatus(sessionId);
|
||||
document.getElementById('modalImageWatcherEnabled').checked = session.imageWatcherEnabled ?? true;
|
||||
document.getElementById('modalFlickerFilterEnabled').checked = session.flickerFilterEnabled ?? false;
|
||||
|
||||
@@ -737,6 +794,39 @@ Object.assign(CodemanApp.prototype, {
|
||||
} catch { /* silent */ }
|
||||
},
|
||||
|
||||
async autoSaveAutoResume() {
|
||||
if (!this.editingSessionId) return;
|
||||
const enabled = document.getElementById('modalAutoResumeEnabled').checked;
|
||||
try {
|
||||
await this._apiPost(`/api/sessions/${this.editingSessionId}/auto-resume`, { enabled });
|
||||
const session = this.sessions.get(this.editingSessionId);
|
||||
if (session) {
|
||||
session.autoResumeEnabled = enabled;
|
||||
if (!enabled) session.autoResumeAt = undefined;
|
||||
}
|
||||
this.updateAutoResumeStatus(this.editingSessionId);
|
||||
this.showToast(`Auto-resume on usage limit ${enabled ? 'enabled' : 'disabled'}`, 'success');
|
||||
} catch (err) {
|
||||
this.showToast('Failed to toggle auto-resume: ' + err.message, 'error');
|
||||
}
|
||||
},
|
||||
|
||||
// Show "resumes at HH:MM" in the session options modal while a usage-limit
|
||||
// pause is armed for the session being edited
|
||||
updateAutoResumeStatus(sessionId) {
|
||||
const el = document.getElementById('autoResumeStatus');
|
||||
if (!el || this.editingSessionId !== sessionId) return;
|
||||
const session = this.sessions.get(sessionId);
|
||||
if (session?.autoResumeAt && session.autoResumeAt > Date.now()) {
|
||||
const at = new Date(session.autoResumeAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
el.textContent = `Usage limit pause active — resumes at ${at}`;
|
||||
el.classList.add('active');
|
||||
} else {
|
||||
el.textContent = '';
|
||||
el.classList.remove('active');
|
||||
}
|
||||
},
|
||||
|
||||
async toggleSessionImageWatcher() {
|
||||
if (!this.editingSessionId) return;
|
||||
const enabled = document.getElementById('modalImageWatcherEnabled').checked;
|
||||
@@ -1474,3 +1564,14 @@ Object.assign(CodemanApp.prototype, {
|
||||
setTimeout(() => modal.classList.remove('from-mobile'), 300);
|
||||
},
|
||||
});
|
||||
|
||||
Object.defineProperty(CodemanApp.prototype, 'runMode', {
|
||||
configurable: true,
|
||||
enumerable: true,
|
||||
get() {
|
||||
return this._runMode || 'claude';
|
||||
},
|
||||
set(mode) {
|
||||
this._runMode = mode === 'opencode' || mode === 'codex' || mode === 'claude' ? mode : 'claude';
|
||||
},
|
||||
});
|
||||
|
||||
@@ -308,6 +308,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
document.getElementById('appSettingsShowTokenCount').checked = settings.showTokenCount ?? defaults.showTokenCount ?? true;
|
||||
document.getElementById('appSettingsShowCost').checked = settings.showCost ?? defaults.showCost ?? false;
|
||||
document.getElementById('appSettingsShowLifecycleLog').checked = settings.showLifecycleLog ?? defaults.showLifecycleLog ?? true;
|
||||
document.getElementById('appSettingsShowResponseViewer').checked = settings.showResponseViewer ?? defaults.showResponseViewer ?? false;
|
||||
document.getElementById('appSettingsShowMonitor').checked = settings.showMonitor ?? defaults.showMonitor ?? false;
|
||||
document.getElementById('appSettingsShowProjectInsights').checked = settings.showProjectInsights ?? defaults.showProjectInsights ?? false;
|
||||
document.getElementById('appSettingsShowFileBrowser').checked = settings.showFileBrowser ?? defaults.showFileBrowser ?? false;
|
||||
@@ -339,8 +340,12 @@ Object.assign(CodemanApp.prototype, {
|
||||
claudeModeSelect.onchange = () => {
|
||||
allowedToolsRow.style.display = claudeModeSelect.value === 'allowedTools' ? '' : 'none';
|
||||
};
|
||||
// Codex CLI settings
|
||||
document.getElementById('appSettingsCodexDangerouslyBypassApprovals').checked =
|
||||
settings.codexDangerouslyBypassApprovals ?? false;
|
||||
// Claude Permissions settings
|
||||
document.getElementById('appSettingsAgentTeams').checked = settings.agentTeamsEnabled ?? false;
|
||||
document.getElementById('appSettingsClaudeModel').value = settings.claudeModel ?? '';
|
||||
document.getElementById('appSettingsOpusContext1m').checked = settings.opusContext1mEnabled ?? false;
|
||||
document.getElementById('appSettingsThinkingEffort').value = settings.thinkingEffort ?? '';
|
||||
// CPU Priority settings
|
||||
@@ -1323,6 +1328,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
showTokenCount: document.getElementById('appSettingsShowTokenCount').checked,
|
||||
showCost: document.getElementById('appSettingsShowCost').checked,
|
||||
showLifecycleLog: document.getElementById('appSettingsShowLifecycleLog').checked,
|
||||
showResponseViewer: document.getElementById('appSettingsShowResponseViewer').checked,
|
||||
showMonitor: document.getElementById('appSettingsShowMonitor').checked,
|
||||
showProjectInsights: document.getElementById('appSettingsShowProjectInsights').checked,
|
||||
showFileBrowser: document.getElementById('appSettingsShowFileBrowser').checked,
|
||||
@@ -1340,8 +1346,11 @@ Object.assign(CodemanApp.prototype, {
|
||||
// Claude CLI settings
|
||||
claudeMode: document.getElementById('appSettingsClaudeMode').value,
|
||||
allowedTools: document.getElementById('appSettingsAllowedTools').value.trim(),
|
||||
// Codex CLI settings
|
||||
codexDangerouslyBypassApprovals: document.getElementById('appSettingsCodexDangerouslyBypassApprovals').checked,
|
||||
// Claude Permissions settings
|
||||
agentTeamsEnabled: document.getElementById('appSettingsAgentTeams').checked,
|
||||
claudeModel: document.getElementById('appSettingsClaudeModel').value,
|
||||
opusContext1mEnabled: document.getElementById('appSettingsOpusContext1m').checked,
|
||||
thinkingEffort: document.getElementById('appSettingsThinkingEffort').value,
|
||||
// CPU Priority settings
|
||||
@@ -1670,6 +1679,14 @@ Object.assign(CodemanApp.prototype, {
|
||||
lifecycleBtn.style.display = showLifecycleLog ? '' : 'none';
|
||||
}
|
||||
|
||||
// Hide the response viewer (eye) button when setting is disabled.
|
||||
// Marker class, not inline style — the base rule is display:inline-flex !important.
|
||||
const showResponseViewer = settings.showResponseViewer ?? defaults.showResponseViewer ?? false;
|
||||
const responseViewerBtn = document.querySelector('.btn-response-viewer-header');
|
||||
if (responseViewerBtn) {
|
||||
responseViewerBtn.classList.toggle('btn-response-viewer-header--hidden', !showResponseViewer);
|
||||
}
|
||||
|
||||
// Multi-monitor button — hidden by default (App Settings → Display → "Header
|
||||
// Displays"). The server renders the correct initial state on every reload;
|
||||
// this handles a live toggle from a settings save (no reload). Toggle the
|
||||
@@ -1694,70 +1711,6 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
},
|
||||
|
||||
toggleMobileHeaderUtilities() {
|
||||
const tray = document.getElementById('headerRight');
|
||||
const toggle = document.getElementById('mobileHeaderUtilityToggle');
|
||||
if (!tray) return;
|
||||
|
||||
const expanded = tray.classList.toggle('mobile-collapsed') === false;
|
||||
if (toggle) {
|
||||
toggle.classList.toggle('active', expanded);
|
||||
toggle.setAttribute('aria-expanded', expanded ? 'true' : 'false');
|
||||
}
|
||||
},
|
||||
|
||||
handleMobileHeaderUtilityToggle(event) {
|
||||
if (event) {
|
||||
event.preventDefault?.();
|
||||
event.stopPropagation?.();
|
||||
|
||||
const now = Date.now();
|
||||
if ((event.type === 'click' || event.type === 'touchend') && this._lastMobileHeaderUtilityPointerAt) {
|
||||
if (now - this._lastMobileHeaderUtilityPointerAt < 500) return;
|
||||
}
|
||||
if (event.type === 'click' && this._lastMobileHeaderUtilityTouchAt) {
|
||||
if (now - this._lastMobileHeaderUtilityTouchAt < 500) return;
|
||||
}
|
||||
if (event.type === 'touchend') {
|
||||
this._lastMobileHeaderUtilityTouchAt = now;
|
||||
}
|
||||
if (event.type === 'pointerup') {
|
||||
this._lastMobileHeaderUtilityPointerAt = now;
|
||||
}
|
||||
}
|
||||
|
||||
this.toggleMobileHeaderUtilities();
|
||||
},
|
||||
|
||||
bindMobileHeaderUtilityToggle() {
|
||||
const toggle = document.getElementById('mobileHeaderUtilityToggle');
|
||||
if (!toggle || this._mobileHeaderUtilityToggleEl === toggle) return;
|
||||
|
||||
if (this._mobileHeaderUtilityToggleEl && this._mobileHeaderUtilityToggleHandler) {
|
||||
this._mobileHeaderUtilityToggleEl.removeEventListener('click', this._mobileHeaderUtilityToggleHandler);
|
||||
this._mobileHeaderUtilityToggleEl.removeEventListener('touchend', this._mobileHeaderUtilityToggleHandler);
|
||||
this._mobileHeaderUtilityToggleEl.removeEventListener('pointerup', this._mobileHeaderUtilityToggleHandler);
|
||||
}
|
||||
|
||||
this._mobileHeaderUtilityToggleEl = toggle;
|
||||
this._mobileHeaderUtilityToggleHandler = (event) => this.handleMobileHeaderUtilityToggle(event);
|
||||
toggle.addEventListener('click', this._mobileHeaderUtilityToggleHandler);
|
||||
toggle.addEventListener('touchend', this._mobileHeaderUtilityToggleHandler, { passive: false });
|
||||
toggle.addEventListener('pointerup', this._mobileHeaderUtilityToggleHandler);
|
||||
},
|
||||
|
||||
closeMobileHeaderUtilities() {
|
||||
const tray = document.getElementById('headerRight');
|
||||
const toggle = document.getElementById('mobileHeaderUtilityToggle');
|
||||
if (!tray || tray.classList.contains('mobile-collapsed')) return;
|
||||
|
||||
tray.classList.add('mobile-collapsed');
|
||||
if (toggle) {
|
||||
toggle.classList.remove('active');
|
||||
toggle.setAttribute('aria-expanded', 'false');
|
||||
}
|
||||
},
|
||||
|
||||
applyTabWrapSettings() {
|
||||
const settings = this.loadAppSettingsFromStorage();
|
||||
const defaults = this.getDefaultSettings();
|
||||
@@ -1937,6 +1890,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
// are NOT display keys — they control server-side behavior and must sync from server.
|
||||
const displayKeys = new Set([
|
||||
'showFontControls', 'showSystemStats', 'showTokenCount', 'showCost',
|
||||
'showLifecycleLog', 'showResponseViewer',
|
||||
'showMonitor', 'showProjectInsights', 'showFileBrowser', 'showSubagents',
|
||||
'subagentActiveTabOnly', 'tabTwoRows', 'localEchoEnabled', 'cjkInputEnabled', 'extendedKeyboardBar',
|
||||
]);
|
||||
|
||||
@@ -190,12 +190,6 @@ body {
|
||||
filter: brightness(1.1);
|
||||
}
|
||||
|
||||
/* Mobile-only header utility toggle — hidden by default; the mobile/tablet
|
||||
media queries in mobile.css (max-width: 768px) re-enable it as flex. */
|
||||
.mobile-header-utility-toggle {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Session Tabs */
|
||||
.session-tabs {
|
||||
display: flex;
|
||||
@@ -1064,6 +1058,11 @@ body.solo-mode .btn-lifecycle-log {
|
||||
color: #10b981;
|
||||
}
|
||||
|
||||
.session-tab .tab-mode.codex {
|
||||
background: rgba(168, 85, 247, 0.2);
|
||||
color: #a855f7;
|
||||
}
|
||||
|
||||
/* Timer Banner - Compact */
|
||||
.timer-banner {
|
||||
display: flex;
|
||||
@@ -2745,6 +2744,22 @@ body.solo-mode .btn-lifecycle-log {
|
||||
color: #a7f3d0;
|
||||
}
|
||||
|
||||
/* Codex mode colors */
|
||||
.btn-toolbar.btn-run.mode-codex,
|
||||
.btn-toolbar.btn-run-gear.mode-codex {
|
||||
background: linear-gradient(135deg, #2a0a3e 0%, #350b4d 50%, #400d5e 100%);
|
||||
border-color: rgba(168, 85, 247, 0.5);
|
||||
color: #d8b4fe;
|
||||
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.2), inset 0 1px 0 rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
.btn-toolbar.btn-run.mode-codex:hover,
|
||||
.btn-toolbar.btn-run-gear.mode-codex:hover {
|
||||
background: linear-gradient(135deg, #400d5e 0%, #581c87 50%, #6b21a8 100%);
|
||||
box-shadow: 0 0 12px rgba(168, 85, 247, 0.35), 0 2px 8px rgba(168, 85, 247, 0.2), inset 0 1px 0 rgba(255, 255, 255, 0.08);
|
||||
border-color: rgba(192, 132, 252, 0.6);
|
||||
color: #e9d5ff;
|
||||
}
|
||||
|
||||
/* Dropdown menu */
|
||||
.run-mode-menu {
|
||||
display: none;
|
||||
@@ -2797,6 +2812,7 @@ body.solo-mode .btn-lifecycle-log {
|
||||
}
|
||||
.run-mode-dot.claude { background: #3b82f6; }
|
||||
.run-mode-dot.opencode { background: #10b981; }
|
||||
.run-mode-dot.codex { background: #a855f7; }
|
||||
|
||||
.run-mode-sep {
|
||||
height: 1px;
|
||||
@@ -4654,6 +4670,39 @@ body.solo-mode .btn-lifecycle-log {
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
/* Auto-resume on usage limit (token pause control) */
|
||||
.auto-resume-box {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.3rem;
|
||||
margin: 0.75rem 0;
|
||||
padding: 0.6rem 0.75rem;
|
||||
background: rgba(59, 130, 246, 0.07);
|
||||
border: 1px solid rgba(59, 130, 246, 0.35);
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.auto-resume-box .checkbox-inline {
|
||||
font-size: 0.85rem;
|
||||
font-weight: 500;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.auto-resume-box .form-hint {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.auto-resume-status {
|
||||
display: none;
|
||||
font-size: 0.7rem;
|
||||
font-weight: 600;
|
||||
color: var(--accent-hover);
|
||||
}
|
||||
|
||||
.auto-resume-status.active {
|
||||
display: block;
|
||||
}
|
||||
|
||||
/* Respawn actions in modal */
|
||||
.respawn-actions {
|
||||
display: flex;
|
||||
@@ -8115,6 +8164,12 @@ kbd {
|
||||
display: inline-flex !important;
|
||||
}
|
||||
|
||||
/* "Response Viewer" header toggle (App Settings → Display) — must out-specify
|
||||
the inline-flex !important above */
|
||||
.btn-response-viewer-header.btn-response-viewer-header--hidden {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.response-viewer {
|
||||
display: none;
|
||||
position: fixed;
|
||||
|
||||
@@ -839,7 +839,11 @@ Object.assign(CodemanApp.prototype, {
|
||||
|
||||
// Pattern 1: Commands with file paths (tail -f, cat, head, grep pattern, etc.)
|
||||
// Handles: tail -f /path, grep pattern /path, cat -n /path
|
||||
const cmdPattern = /(tail|cat|head|less|grep|watch|vim|nano)\s+(?:[^\s\/]*\s+)*(\/[^\s"'<>|;&\n\x00-\x1f]+)/g;
|
||||
// ⚠ The arg group must stay linear-time: `(?:[^\s\/]*\s+)*` (empty-matchable
|
||||
// token, unbounded) backtracks exponentially on lines with a trigger word
|
||||
// followed by multi-space runs (e.g. wrapped heredoc/table output) — froze
|
||||
// the whole tab on hover. Non-empty token + bounded reps is O(n).
|
||||
const cmdPattern = /\b(tail|cat|head|less|grep|watch|vim|nano)\s+(?:[^\s\/]+\s+){0,4}(\/[^\s"'<>|;&\n\x00-\x1f]+)/g;
|
||||
|
||||
// Pattern 2: Paths with common extensions
|
||||
const extPattern =
|
||||
|
||||
@@ -9,13 +9,14 @@ import { join, dirname, resolve, relative, isAbsolute } from 'node:path';
|
||||
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
|
||||
import fs from 'node:fs/promises';
|
||||
import { ApiErrorCode, createErrorResponse, getErrorMessage, type ApiResponse } from '../../types.js';
|
||||
import { Session } from '../../session.js';
|
||||
import { Session, isExternalCliMode } from '../../session.js';
|
||||
import { RespawnController } from '../../respawn-controller.js';
|
||||
import { RalphConfigSchema, FixPlanImportSchema, RalphPromptWriteSchema, RalphLoopStartSchema } from '../schemas.js';
|
||||
import { SseEvent } from '../sse-events.js';
|
||||
import { autoConfigureRalph, CASES_DIR, SETTINGS_PATH, findSessionOrFail, parseBody } from '../route-helpers.js';
|
||||
import { writeHooksConfig, stripCaseEnvKeys } from '../../hooks-config.js';
|
||||
import { generateClaudeMd } from '../../templates/claude-md.js';
|
||||
import { buildRalphLoopPrompt } from '../../prompts/index.js';
|
||||
import { getLifecycleLog } from '../../session-lifecycle-log.js';
|
||||
import type { SessionPort, EventPort, RespawnPort, ConfigPort, InfraPort } from '../ports/index.js';
|
||||
import { MAX_CONCURRENT_SESSIONS } from '../../config/map-limits.js';
|
||||
@@ -44,9 +45,12 @@ export function registerRalphRoutes(
|
||||
};
|
||||
const session = findSessionOrFail(ctx, id);
|
||||
|
||||
// Ralph tracker is not supported for opencode sessions
|
||||
if (session.mode === 'opencode') {
|
||||
return createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Ralph tracker is not supported for opencode sessions');
|
||||
// Ralph tracker is not supported for external-CLI sessions (opencode/codex)
|
||||
if (isExternalCliMode(session.mode)) {
|
||||
return createErrorResponse(
|
||||
ApiErrorCode.INVALID_INPUT,
|
||||
`Ralph tracker is not supported for ${session.mode} sessions`
|
||||
);
|
||||
}
|
||||
|
||||
// Handle reset first (before other config)
|
||||
@@ -379,37 +383,12 @@ export function registerRalphRoutes(
|
||||
writeFileSync(fixPlanPath, planContent, 'utf-8');
|
||||
}
|
||||
|
||||
// Build full prompt
|
||||
const hasPlan = enabledItems.length > 0;
|
||||
let fullPrompt = taskDescription + '\n\n---\n\n';
|
||||
if (hasPlan) {
|
||||
fullPrompt += '## Task Plan\n\n';
|
||||
fullPrompt += 'A task plan has been written to `@fix_plan.md`. Use this to track progress:\n';
|
||||
fullPrompt += '- Reference the plan at the start of each iteration\n';
|
||||
fullPrompt += '- Update task checkboxes as you complete items\n';
|
||||
fullPrompt += '- Work through items in priority order (P0 > P1 > P2)\n\n';
|
||||
}
|
||||
fullPrompt += '## Iteration Protocol\n\n';
|
||||
fullPrompt += 'This is an autonomous loop. Files from previous iterations persist. On each iteration:\n';
|
||||
fullPrompt += '1. Check what work has already been done\n';
|
||||
fullPrompt += '2. Make incremental progress toward completion\n';
|
||||
fullPrompt += '3. Commit meaningful changes with descriptive messages\n\n';
|
||||
fullPrompt += '## Verification\n\n';
|
||||
fullPrompt += 'After each significant change:\n';
|
||||
fullPrompt += '- Run tests to verify (npm test, pytest, etc.)\n';
|
||||
fullPrompt += '- Check for type/lint errors if applicable\n';
|
||||
fullPrompt += '- If tests fail, read the error, fix it, and retry\n\n';
|
||||
fullPrompt += '## Completion Criteria\n\n';
|
||||
fullPrompt += `Output \`<promise>${completionPhrase}</promise>\` when ALL of the following are true:\n`;
|
||||
fullPrompt += '- All requirements from the task description are implemented\n';
|
||||
fullPrompt += '- All tests pass\n';
|
||||
fullPrompt += '- Changes are committed\n\n';
|
||||
fullPrompt += '## If Stuck\n\n';
|
||||
fullPrompt += 'If you encounter the same error for 3+ iterations:\n';
|
||||
fullPrompt += "1. Document what you've tried\n";
|
||||
fullPrompt += '2. Identify the specific blocker\n';
|
||||
fullPrompt += '3. Try an alternative approach\n';
|
||||
fullPrompt += '4. If truly blocked, output `<promise>BLOCKED</promise>` with an explanation\n';
|
||||
// Build full prompt (includes the RALPH_STATUS contract)
|
||||
const fullPrompt = buildRalphLoopPrompt({
|
||||
taskDescription,
|
||||
completionPhrase,
|
||||
hasPlan: enabledItems.length > 0,
|
||||
});
|
||||
|
||||
// Write prompt to file
|
||||
const promptPath = join(casePath, '@ralph_prompt.md');
|
||||
|
||||
@@ -11,6 +11,7 @@ import { SseEvent } from '../sse-events.js';
|
||||
import { findSessionOrFail, autoConfigureRalph, parseBody } from '../route-helpers.js';
|
||||
import type { SessionPort, EventPort, RespawnPort, ConfigPort, InfraPort } from '../ports/index.js';
|
||||
import { getLifecycleLog } from '../../session-lifecycle-log.js';
|
||||
import { isExternalCliMode } from '../../session.js';
|
||||
import {
|
||||
AI_CHECK_MODEL,
|
||||
AI_IDLE_CHECK_MAX_CONTEXT,
|
||||
@@ -88,9 +89,9 @@ export function registerRespawnRoutes(
|
||||
}
|
||||
const session = findSessionOrFail(ctx, id);
|
||||
|
||||
// Respawn is not supported for opencode sessions
|
||||
if (session.mode === 'opencode') {
|
||||
return createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Respawn is not supported for opencode sessions');
|
||||
// Respawn is not supported for external-CLI sessions (opencode/codex)
|
||||
if (isExternalCliMode(session.mode)) {
|
||||
return createErrorResponse(ApiErrorCode.INVALID_INPUT, `Respawn is not supported for ${session.mode} sessions`);
|
||||
}
|
||||
|
||||
// Create or get existing controller
|
||||
@@ -231,9 +232,9 @@ export function registerRespawnRoutes(
|
||||
return createErrorResponse(ApiErrorCode.SESSION_BUSY, 'Session is busy');
|
||||
}
|
||||
|
||||
// Respawn is not supported for opencode sessions
|
||||
if (session.mode === 'opencode') {
|
||||
return createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Respawn is not supported for opencode sessions');
|
||||
// Respawn is not supported for external-CLI sessions (opencode/codex)
|
||||
if (isExternalCliMode(session.mode)) {
|
||||
return createErrorResponse(ApiErrorCode.INVALID_INPUT, `Respawn is not supported for ${session.mode} sessions`);
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -296,9 +297,9 @@ export function registerRespawnRoutes(
|
||||
const body = reResult.data as { config?: Partial<RespawnConfig>; durationMinutes?: number };
|
||||
const session = findSessionOrFail(ctx, id);
|
||||
|
||||
// Respawn is not supported for opencode sessions
|
||||
if (session.mode === 'opencode') {
|
||||
return createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Respawn is not supported for opencode sessions');
|
||||
// Respawn is not supported for external-CLI sessions (opencode/codex)
|
||||
if (isExternalCliMode(session.mode)) {
|
||||
return createErrorResponse(ApiErrorCode.INVALID_INPUT, `Respawn is not supported for ${session.mode} sessions`);
|
||||
}
|
||||
|
||||
// Check if session is running (has a PID)
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
ResizeSchema,
|
||||
AutoClearSchema,
|
||||
AutoCompactSchema,
|
||||
AutoResumeSchema,
|
||||
ImageWatcherSchema,
|
||||
FlickerFilterSchema,
|
||||
QuickRunSchema,
|
||||
@@ -282,6 +283,17 @@ export function registerSessionRoutes(
|
||||
}
|
||||
}
|
||||
|
||||
// Check Codex availability if requested
|
||||
if (body.mode === 'codex') {
|
||||
const { isCodexAvailable } = await import('../../utils/codex-cli-resolver.js');
|
||||
if (!isCodexAvailable()) {
|
||||
return createErrorResponse(
|
||||
ApiErrorCode.OPERATION_FAILED,
|
||||
'Codex CLI not found. Install with: npm install -g @openai/codex'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Pre-validate resumeSessionId: check that the conversation file actually exists
|
||||
// in Claude's projects directory. If not, skip resume to avoid confusing
|
||||
// "No conversation found" errors from Claude CLI.
|
||||
@@ -318,9 +330,11 @@ export function registerSessionRoutes(
|
||||
const model =
|
||||
mode === 'opencode'
|
||||
? body.openCodeConfig?.model
|
||||
: mode !== 'shell'
|
||||
? modelConfig?.defaultModel || undefined
|
||||
: undefined;
|
||||
: mode === 'codex'
|
||||
? body.codexConfig?.model
|
||||
: mode !== 'shell'
|
||||
? modelConfig?.defaultModel || undefined
|
||||
: undefined;
|
||||
const claudeModeConfig = await ctx.getClaudeModeConfig();
|
||||
const session = new Session({
|
||||
workingDir,
|
||||
@@ -333,6 +347,7 @@ export function registerSessionRoutes(
|
||||
claudeMode: claudeModeConfig.claudeMode,
|
||||
allowedTools: claudeModeConfig.allowedTools,
|
||||
openCodeConfig: mode === 'opencode' ? body.openCodeConfig : undefined,
|
||||
codexConfig: mode === 'codex' ? body.codexConfig : undefined,
|
||||
resumeSessionId: validatedResumeId,
|
||||
envOverrides: body.envOverrides,
|
||||
effort: body.effort,
|
||||
@@ -989,6 +1004,27 @@ export function registerSessionRoutes(
|
||||
};
|
||||
});
|
||||
|
||||
// ========== Auto-Resume (usage-limit pause) ==========
|
||||
|
||||
app.post('/api/sessions/:id/auto-resume', async (req) => {
|
||||
const { id } = req.params as { id: string };
|
||||
const body = parseBody(AutoResumeSchema, req.body, 'Invalid request body');
|
||||
const session = findSessionOrFail(ctx, id);
|
||||
|
||||
session.setAutoResume(body.enabled);
|
||||
persistAndBroadcastSession(ctx, session);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
autoResume: {
|
||||
enabled: session.autoResumeEnabled,
|
||||
resumeAt: session.autoResumeAt ?? undefined,
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
// ========== Image Watcher ==========
|
||||
|
||||
app.post('/api/sessions/:id/image-watcher', async (req) => {
|
||||
@@ -1112,6 +1148,7 @@ export function registerSessionRoutes(
|
||||
caseName = 'testcase',
|
||||
mode = 'claude',
|
||||
openCodeConfig,
|
||||
codexConfig,
|
||||
envOverrides,
|
||||
effort,
|
||||
} = parseBody(QuickStartSchema, req.body);
|
||||
@@ -1127,6 +1164,17 @@ export function registerSessionRoutes(
|
||||
}
|
||||
}
|
||||
|
||||
// Check Codex availability if requested
|
||||
if (mode === 'codex') {
|
||||
const { isCodexAvailable } = await import('../../utils/codex-cli-resolver.js');
|
||||
if (!isCodexAvailable()) {
|
||||
return createErrorResponse(
|
||||
ApiErrorCode.OPERATION_FAILED,
|
||||
'Codex CLI not found. Install with: npm install -g @openai/codex'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve case path: check linked-cases registry first, then fall back to CASES_DIR.
|
||||
// This mirrors the behaviour of resolveCasePath() in case-routes so that linked
|
||||
// external project directories are honoured by quick-start just like regular case routes.
|
||||
@@ -1179,9 +1227,11 @@ export function registerSessionRoutes(
|
||||
const qsModel =
|
||||
mode === 'opencode'
|
||||
? openCodeConfig?.model
|
||||
: mode !== 'shell'
|
||||
? qsModelConfig?.defaultModel || undefined
|
||||
: undefined;
|
||||
: mode === 'codex'
|
||||
? codexConfig?.model
|
||||
: mode !== 'shell'
|
||||
? qsModelConfig?.defaultModel || undefined
|
||||
: undefined;
|
||||
const qsClaudeModeConfig = await ctx.getClaudeModeConfig();
|
||||
const session = new Session({
|
||||
workingDir: casePath,
|
||||
@@ -1193,6 +1243,7 @@ export function registerSessionRoutes(
|
||||
claudeMode: qsClaudeModeConfig.claudeMode,
|
||||
allowedTools: qsClaudeModeConfig.allowedTools,
|
||||
openCodeConfig: mode === 'opencode' ? openCodeConfig : undefined,
|
||||
codexConfig: mode === 'codex' ? codexConfig : undefined,
|
||||
envOverrides,
|
||||
effort,
|
||||
});
|
||||
|
||||
@@ -341,6 +341,14 @@ export function registerSystemRoutes(
|
||||
};
|
||||
});
|
||||
|
||||
app.get('/api/codex/status', async () => {
|
||||
const { isCodexAvailable, resolveCodexDir } = await import('../../utils/codex-cli-resolver.js');
|
||||
return {
|
||||
available: isCodexAvailable(),
|
||||
path: resolveCodexDir(),
|
||||
};
|
||||
});
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// State & Lifecycle (cleanup, lifecycle log, stats)
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
|
||||
@@ -114,6 +114,7 @@ export function registerWsRoutes(app: FastifyInstance, ctx: SessionPort, getHost
|
||||
// can ignore small-viewport resizes only while a desktop is actually
|
||||
// connected (see Session._desktopSizeClaims).
|
||||
const sizingToken = Symbol('ws-desktop-sizing');
|
||||
let holdsDesktopClaim = false;
|
||||
|
||||
// Attach message handler synchronously BEFORE any async work
|
||||
// (@fastify/websocket requirement to avoid dropped messages).
|
||||
@@ -122,6 +123,9 @@ export function registerWsRoutes(app: FastifyInstance, ctx: SessionPort, getHost
|
||||
const msg = JSON.parse(String(raw));
|
||||
if (msg.t === 'i' && typeof msg.d === 'string') {
|
||||
if (msg.d.length > MAX_INPUT_LENGTH) return;
|
||||
// Typed input from a claim-holding desktop keeps the claim "hot"
|
||||
// and re-asserts the desktop layout after a mobile override.
|
||||
if (holdsDesktopClaim) session.noteDesktopActivity();
|
||||
session.write(msg.d);
|
||||
} else if (
|
||||
msg.t === 'z' &&
|
||||
@@ -135,10 +139,12 @@ export function registerWsRoutes(app: FastifyInstance, ctx: SessionPort, getHost
|
||||
const viewportType = msg.v === 'mobile' || msg.v === 'tablet' || msg.v === 'desktop' ? msg.v : undefined;
|
||||
if (viewportType === 'desktop') {
|
||||
session.claimDesktopSizing(sizingToken);
|
||||
holdsDesktopClaim = true;
|
||||
} else if (viewportType) {
|
||||
// The connection's viewport can change (e.g. browser window
|
||||
// narrowed past the tablet breakpoint) — drop a stale claim.
|
||||
session.releaseDesktopSizing(sizingToken);
|
||||
holdsDesktopClaim = false;
|
||||
}
|
||||
if (viewportType) {
|
||||
session.resize(msg.c, msg.r, { viewportType });
|
||||
|
||||
+37
-4
@@ -46,7 +46,7 @@ const safePathSchema = z.string().max(1000).refine(isValidWorkingDir, {
|
||||
// ========== Env Var Allowlist ==========
|
||||
|
||||
/** Allowlisted env var key prefixes */
|
||||
const ALLOWED_ENV_PREFIXES = ['CLAUDE_CODE_', 'OPENCODE_'];
|
||||
const ALLOWED_ENV_PREFIXES = ['CLAUDE_CODE_', 'OPENCODE_', 'CODEX_'];
|
||||
|
||||
/** Env var keys that are always blocked (security-sensitive) */
|
||||
const BLOCKED_ENV_KEYS = new Set([
|
||||
@@ -76,7 +76,7 @@ const safeEnvOverridesSchema = z
|
||||
},
|
||||
{
|
||||
message:
|
||||
'envOverrides contains blocked or disallowed env var keys. Only CLAUDE_CODE_* and OPENCODE_* keys are allowed.',
|
||||
'envOverrides contains blocked or disallowed env var keys. Only CLAUDE_CODE_*, OPENCODE_*, and CODEX_* keys are allowed.',
|
||||
}
|
||||
);
|
||||
|
||||
@@ -128,9 +128,30 @@ const OpenCodeConfigSchema = z
|
||||
})
|
||||
.optional();
|
||||
|
||||
/** Schema for Codex (OpenAI CLI)-specific configuration */
|
||||
const CodexConfigSchema = z
|
||||
.object({
|
||||
model: z
|
||||
.string()
|
||||
.max(100)
|
||||
.regex(/^[a-zA-Z0-9._\-/]+$/)
|
||||
.optional(),
|
||||
resumeSessionId: z
|
||||
.string()
|
||||
.max(100)
|
||||
.regex(/^[a-zA-Z0-9_-]+$/)
|
||||
.optional(),
|
||||
dangerouslyBypassApprovals: z.boolean().optional(),
|
||||
renderMode: z
|
||||
.enum(['scrollback', 'hybrid'])
|
||||
.optional()
|
||||
.transform(() => 'hybrid' as const),
|
||||
})
|
||||
.optional();
|
||||
|
||||
export const CreateSessionSchema = z.object({
|
||||
workingDir: safePathSchema.optional(),
|
||||
mode: z.enum(['claude', 'shell', 'opencode']).optional(),
|
||||
mode: z.enum(['claude', 'shell', 'opencode', 'codex']).optional(),
|
||||
name: z.string().max(100).optional(),
|
||||
envOverrides: safeEnvOverridesSchema,
|
||||
/** Claude CLI effort level (soft default via --settings, switchable in-session via /effort) */
|
||||
@@ -138,6 +159,7 @@ export const CreateSessionSchema = z.object({
|
||||
/** Model override to write to .claude/settings.local.json (e.g., "opus[1m]"). Empty string clears. */
|
||||
modelOverride: z.string().max(50).optional(),
|
||||
openCodeConfig: OpenCodeConfigSchema,
|
||||
codexConfig: CodexConfigSchema,
|
||||
/** Resume a previous Claude conversation by its session ID (used for reboot recovery) */
|
||||
resumeSessionId: z
|
||||
.string()
|
||||
@@ -188,8 +210,9 @@ export const QuickStartSchema = z.object({
|
||||
.string()
|
||||
.regex(/^[a-zA-Z0-9_-]+$/, 'Invalid case name format. Use only letters, numbers, hyphens, underscores.')
|
||||
.optional(),
|
||||
mode: z.enum(['claude', 'shell', 'opencode']).optional(),
|
||||
mode: z.enum(['claude', 'shell', 'opencode', 'codex']).optional(),
|
||||
openCodeConfig: OpenCodeConfigSchema,
|
||||
codexConfig: CodexConfigSchema,
|
||||
envOverrides: safeEnvOverridesSchema,
|
||||
/** Claude CLI effort level (soft default via --settings, switchable in-session via /effort) */
|
||||
effort: effortLevelSchema,
|
||||
@@ -282,6 +305,8 @@ export const SettingsUpdateSchema = z
|
||||
tunnelEnabled: z.boolean().optional(),
|
||||
tabTwoRows: z.boolean().optional(),
|
||||
agentTeamsEnabled: z.boolean().optional(),
|
||||
/** Model for new Claude sessions (e.g. "claude-fable-5[1m]", "opus[1m]"); takes precedence over opusContext1mEnabled */
|
||||
claudeModel: z.string().max(50).optional(),
|
||||
opusContext1mEnabled: z.boolean().optional(),
|
||||
thinkingEffort: z.string().max(20).optional(),
|
||||
// UI visibility
|
||||
@@ -290,6 +315,7 @@ export const SettingsUpdateSchema = z
|
||||
showTokenCount: z.boolean().optional(),
|
||||
showCost: z.boolean().optional(),
|
||||
showLifecycleLog: z.boolean().optional(),
|
||||
showResponseViewer: z.boolean().optional(),
|
||||
showMonitor: z.boolean().optional(),
|
||||
showProjectInsights: z.boolean().optional(),
|
||||
showFileBrowser: z.boolean().optional(),
|
||||
@@ -300,6 +326,8 @@ export const SettingsUpdateSchema = z
|
||||
// Claude CLI settings
|
||||
claudeMode: z.string().max(50).optional(),
|
||||
allowedTools: z.string().max(2000).optional(),
|
||||
// Codex CLI settings
|
||||
codexDangerouslyBypassApprovals: z.boolean().optional(),
|
||||
// CPU priority
|
||||
nice: z
|
||||
.object({
|
||||
@@ -422,6 +450,11 @@ export const AutoCompactSchema = z.object({
|
||||
prompt: z.string().max(10000).optional(),
|
||||
});
|
||||
|
||||
/** POST /api/sessions/:id/auto-resume */
|
||||
export const AutoResumeSchema = z.object({
|
||||
enabled: z.boolean(),
|
||||
});
|
||||
|
||||
/** POST /api/sessions/:id/image-watcher */
|
||||
export const ImageWatcherSchema = z.object({
|
||||
enabled: z.boolean(),
|
||||
|
||||
+28
-1
@@ -161,7 +161,9 @@ export function parseGitHubRepo(remoteUrl: string): { owner: string; repo: strin
|
||||
* persist — or null to leave it untouched.
|
||||
*
|
||||
* Rules (see plan "Hardening"):
|
||||
* - Terminal phases → untouched.
|
||||
* - Terminal phases → untouched, EXCEPT `completed-needs-manual-restart`: once we
|
||||
* boot into the staged target version the manual restart evidently happened, so
|
||||
* it flips to `completed` (otherwise the stale instruction lingers in the UI).
|
||||
* - Only the `restarting` marker (written right before the updater triggers our
|
||||
* restart) flips to completed/failed by comparing running version vs. target.
|
||||
* - Other in-flight phases are owned by the still-running updater scope — leave
|
||||
@@ -174,6 +176,17 @@ export function reconcileStatusDecision(
|
||||
now: number
|
||||
): UpdateStatus | null {
|
||||
if (!status) return null;
|
||||
|
||||
// A staged update that asked for a manual restart: if we're now running the
|
||||
// target version, the user (or supervisor) did restart — mark it completed so
|
||||
// the UI stops showing the stale "restart Codeman to apply" instruction.
|
||||
if (status.phase === 'completed-needs-manual-restart') {
|
||||
if (status.toVersion && runningVersion === status.toVersion) {
|
||||
return { ...status, phase: 'completed', message: `Updated to v${runningVersion}`, updatedAt: now };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!IN_FLIGHT_PHASES.has(status.phase)) return null;
|
||||
|
||||
if (status.phase === 'restarting') {
|
||||
@@ -275,6 +288,16 @@ function detectInstallKind(dir: string): InstallKind {
|
||||
export function detectSupervisor(): SupervisorKind {
|
||||
if (process.platform === 'darwin') {
|
||||
if (existsSync(join(homedir(), 'Library', 'LaunchAgents', `${LAUNCHD_LABEL}.plist`))) return 'launchd';
|
||||
// Headless Macs (no GUI login → no gui domain) run Codeman as a system-level
|
||||
// LaunchDaemon instead. Restarting one needs no root IF it has KeepAlive: the
|
||||
// updater just kills the server and launchd respawns it on the new build. Only
|
||||
// claim this supervisor when the daemon is actually bootstrapped and KeepAlive.
|
||||
const daemonPlist = join('/Library/LaunchDaemons', `${LAUNCHD_LABEL}.plist`);
|
||||
if (existsSync(daemonPlist)) {
|
||||
const loaded = tryExec('launchctl', ['print', `system/${LAUNCHD_LABEL}`]) !== null;
|
||||
const keepAlive = tryExec('plutil', ['-extract', 'KeepAlive', 'raw', '-o', '-', daemonPlist]);
|
||||
if (loaded && keepAlive === 'true') return 'launchd-daemon';
|
||||
}
|
||||
return 'none';
|
||||
}
|
||||
if (process.platform === 'linux') {
|
||||
@@ -535,6 +558,10 @@ export async function startUpdate(): Promise<StartUpdateResult> {
|
||||
process.execPath,
|
||||
'--log',
|
||||
logFile,
|
||||
// For the launchd-daemon restart path: the updater kills this PID and the
|
||||
// KeepAlive daemon respawns the server on the freshly built dist/.
|
||||
'--server-pid',
|
||||
String(process.pid),
|
||||
];
|
||||
if (prevSha) args.push('--prev-sha', prevSha);
|
||||
if (info.dirty) args.push('--stash');
|
||||
|
||||
+19
-13
@@ -42,7 +42,7 @@ import { execSync } from 'node:child_process';
|
||||
import { hostname as getHostname } from 'node:os';
|
||||
import { dataPath } from '../config/instance.js';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { Session, type BackgroundTask } from '../session.js';
|
||||
import { Session, isExternalCliMode, type BackgroundTask } from '../session.js';
|
||||
import type { ClaudeMode, SessionState } from '../types.js';
|
||||
import { RespawnController, RespawnConfig } from '../respawn-controller.js';
|
||||
import type { TerminalMultiplexer } from '../mux-interface.js';
|
||||
@@ -1189,8 +1189,8 @@ export class WebServer extends EventEmitter {
|
||||
this.runSummaryTrackers.set(session.id, summaryTracker);
|
||||
summaryTracker.recordSessionStarted(session.mode, session.workingDir);
|
||||
|
||||
// Set working directory for Ralph tracker to auto-load @fix_plan.md (not supported for opencode sessions)
|
||||
if (session.mode !== 'opencode') {
|
||||
// Set working directory for Ralph tracker to auto-load @fix_plan.md (not supported for external CLIs)
|
||||
if (!isExternalCliMode(session.mode)) {
|
||||
session.ralphTracker.setWorkingDir(session.workingDir);
|
||||
}
|
||||
|
||||
@@ -1993,6 +1993,12 @@ export class WebServer extends EventEmitter {
|
||||
if (savedState.autoClearEnabled !== undefined || savedState.autoClearThreshold !== undefined) {
|
||||
session.setAutoClear(savedState.autoClearEnabled ?? false, savedState.autoClearThreshold);
|
||||
}
|
||||
// Auto-resume on usage limit (re-arms a pending schedule; an
|
||||
// overdue one fires shortly after boot — the limit footer won't
|
||||
// reprint on its own, so the pause would otherwise stall)
|
||||
if (savedState.autoResumeEnabled) {
|
||||
session.restoreAutoResume(true, savedState.autoResumeAt);
|
||||
}
|
||||
// Token tracking
|
||||
if (
|
||||
savedState.inputTokens !== undefined ||
|
||||
@@ -2016,8 +2022,8 @@ export class WebServer extends EventEmitter {
|
||||
);
|
||||
}
|
||||
}
|
||||
// Ralph / Todo tracker (not supported for opencode sessions)
|
||||
if (session.mode !== 'opencode') {
|
||||
// Ralph / Todo tracker (not supported for external-CLI sessions)
|
||||
if (!isExternalCliMode(session.mode)) {
|
||||
if (savedState.ralphAutoEnableDisabled) {
|
||||
session.ralphTracker.disableAutoEnable();
|
||||
console.log(`[Server] Restored Ralph auto-enable disabled for session ${session.id}`);
|
||||
@@ -2046,8 +2052,8 @@ export class WebServer extends EventEmitter {
|
||||
if (savedState.flickerFilterEnabled !== undefined) {
|
||||
session.flickerFilterEnabled = savedState.flickerFilterEnabled;
|
||||
}
|
||||
// Respawn controller (not supported for opencode sessions)
|
||||
if (session.mode !== 'opencode' && savedState.respawnEnabled && savedState.respawnConfig) {
|
||||
// Respawn controller (not supported for external-CLI sessions)
|
||||
if (!isExternalCliMode(session.mode) && savedState.respawnEnabled && savedState.respawnConfig) {
|
||||
try {
|
||||
this.restoreRespawnController(session, savedState.respawnConfig, 'state.json');
|
||||
} catch (err) {
|
||||
@@ -2056,9 +2062,9 @@ export class WebServer extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: restore respawn from mux-sessions.json if state.json didn't have it (not supported for opencode)
|
||||
// Fallback: restore respawn from mux-sessions.json if state.json didn't have it (not supported for external CLIs)
|
||||
if (
|
||||
session.mode !== 'opencode' &&
|
||||
!isExternalCliMode(session.mode) &&
|
||||
!this.respawnControllers.has(session.id) &&
|
||||
muxSession.respawnConfig?.enabled
|
||||
) {
|
||||
@@ -2073,9 +2079,9 @@ export class WebServer extends EventEmitter {
|
||||
}
|
||||
|
||||
// Fallback: restore Ralph state from state-inner.json if not already set and not explicitly disabled
|
||||
// Ralph tracker is not supported for opencode sessions
|
||||
// Ralph tracker is not supported for external-CLI sessions
|
||||
if (
|
||||
session.mode !== 'opencode' &&
|
||||
!isExternalCliMode(session.mode) &&
|
||||
!session.ralphTracker.enabled &&
|
||||
!session.ralphTracker.autoEnableDisabled
|
||||
) {
|
||||
@@ -2086,9 +2092,9 @@ export class WebServer extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: auto-detect completion phrase from CLAUDE.md (not supported for opencode)
|
||||
// Fallback: auto-detect completion phrase from CLAUDE.md (not supported for external CLIs)
|
||||
if (
|
||||
session.mode !== 'opencode' &&
|
||||
!isExternalCliMode(session.mode) &&
|
||||
session.ralphTracker.enabled &&
|
||||
!session.ralphTracker.loopState.completionPhrase
|
||||
) {
|
||||
|
||||
@@ -45,6 +45,9 @@ export interface SessionListenerRefs {
|
||||
taskFailed: (task: BackgroundTask, error: string) => void;
|
||||
autoClear: (data: { tokens: number; threshold: number }) => void;
|
||||
autoCompact: (data: { tokens: number; threshold: number; prompt?: string }) => void;
|
||||
limitPauseScheduled: (data: { resetAt: number; resumeAt: number; matched: string }) => void;
|
||||
limitResume: (data: { attempt: number }) => void;
|
||||
limitResumeCancelled: (data: { reason: string }) => void;
|
||||
cliInfoUpdated: (data: { version?: string; model?: string; accountType?: string; latestVersion?: string }) => void;
|
||||
ralphLoopUpdate: (state: RalphTrackerState) => void;
|
||||
ralphTodoUpdate: (todos: RalphTodoItem[]) => void;
|
||||
@@ -243,6 +246,28 @@ export function createSessionListeners(session: Session, deps: SessionListenerDe
|
||||
if (tracker) tracker.recordAutoCompact(data.tokens, data.threshold);
|
||||
},
|
||||
|
||||
/** Broadcasts `session:limitPauseScheduled` — usage-limit pause detected, auto-resume armed.
|
||||
* Persisted so a pending schedule survives a Codeman restart. */
|
||||
limitPauseScheduled: (data: { resetAt: number; resumeAt: number; matched: string }) => {
|
||||
deps.broadcast(SseEvent.SessionLimitPauseScheduled, { sessionId: session.id, ...data });
|
||||
deps.broadcastSessionStateDebounced(session.id);
|
||||
deps.persistSessionState(session);
|
||||
},
|
||||
|
||||
/** Broadcasts `session:limitResume` — auto-resume prompt sent after limit reset */
|
||||
limitResume: (data: { attempt: number }) => {
|
||||
deps.broadcast(SseEvent.SessionLimitResume, { sessionId: session.id, ...data });
|
||||
deps.broadcastSessionStateDebounced(session.id);
|
||||
deps.persistSessionState(session);
|
||||
},
|
||||
|
||||
/** Broadcasts `session:limitResumeCancelled` — pending auto-resume no longer needed */
|
||||
limitResumeCancelled: (data: { reason: string }) => {
|
||||
deps.broadcast(SseEvent.SessionLimitResumeCancelled, { sessionId: session.id, ...data });
|
||||
deps.broadcastSessionStateDebounced(session.id);
|
||||
deps.persistSessionState(session);
|
||||
},
|
||||
|
||||
// ─── CLI Info ────────────────────────────────────────────
|
||||
|
||||
/** Broadcasts `session:cliInfo` — Claude Code version, model, account type parsed from terminal */
|
||||
@@ -350,6 +375,9 @@ export function attachSessionListeners(session: Session, refs: SessionListenerRe
|
||||
session.on('taskFailed', refs.taskFailed);
|
||||
session.on('autoClear', refs.autoClear);
|
||||
session.on('autoCompact', refs.autoCompact);
|
||||
session.on('limitPauseScheduled', refs.limitPauseScheduled);
|
||||
session.on('limitResume', refs.limitResume);
|
||||
session.on('limitResumeCancelled', refs.limitResumeCancelled);
|
||||
session.on('cliInfoUpdated', refs.cliInfoUpdated);
|
||||
session.on('ralphLoopUpdate', refs.ralphLoopUpdate);
|
||||
session.on('ralphTodoUpdate', refs.ralphTodoUpdate);
|
||||
@@ -379,6 +407,9 @@ export function detachSessionListeners(session: Session, refs: SessionListenerRe
|
||||
session.off('taskFailed', refs.taskFailed);
|
||||
session.off('autoClear', refs.autoClear);
|
||||
session.off('autoCompact', refs.autoCompact);
|
||||
session.off('limitPauseScheduled', refs.limitPauseScheduled);
|
||||
session.off('limitResume', refs.limitResume);
|
||||
session.off('limitResumeCancelled', refs.limitResumeCancelled);
|
||||
session.off('cliInfoUpdated', refs.cliInfoUpdated);
|
||||
session.off('ralphLoopUpdate', refs.ralphLoopUpdate);
|
||||
session.off('ralphTodoUpdate', refs.ralphTodoUpdate);
|
||||
|
||||
@@ -73,6 +73,12 @@ export const SessionWorking = 'session:working' as const;
|
||||
export const SessionAutoClear = 'session:autoClear' as const;
|
||||
/** Auto-compact triggered for the session. */
|
||||
export const SessionAutoCompact = 'session:autoCompact' as const;
|
||||
/** Usage-limit pause detected; auto-resume scheduled. */
|
||||
export const SessionLimitPauseScheduled = 'session:limitPauseScheduled' as const;
|
||||
/** Auto-resume prompt sent after a usage-limit reset. */
|
||||
export const SessionLimitResume = 'session:limitResume' as const;
|
||||
/** Pending usage-limit auto-resume cancelled (session resumed or feature disabled). */
|
||||
export const SessionLimitResumeCancelled = 'session:limitResumeCancelled' as const;
|
||||
/** CLI version/model info detected from session output. */
|
||||
export const SessionCliInfo = 'session:cliInfo' as const;
|
||||
/** General session message (e.g. status text). */
|
||||
@@ -361,6 +367,9 @@ export const SseEvent = {
|
||||
SessionWorking,
|
||||
SessionAutoClear,
|
||||
SessionAutoCompact,
|
||||
SessionLimitPauseScheduled,
|
||||
SessionLimitResume,
|
||||
SessionLimitResumeCancelled,
|
||||
SessionCliInfo,
|
||||
SessionMessage,
|
||||
SessionInteractive,
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* @fileoverview Regression guard for the terminal link-provider regexes in
|
||||
* `src/web/public/terminal-ui.js`.
|
||||
*
|
||||
* The link provider runs its patterns against every hovered terminal line
|
||||
* (logical lines — xterm re-joins wrapped rows, so inputs reach multiple KB).
|
||||
* A pattern with ambiguous backtracking freezes the entire tab on hover:
|
||||
* 0.9.10's `cmdPattern` used `(?:[^\s\/]*\s+)*` (empty-matchable token,
|
||||
* unbounded), which went exponential on real Claude output — wrapped
|
||||
* `git commit -m "$(cat <<'EOF'` heredoc lines hung the main thread for
|
||||
* minutes per hover.
|
||||
*
|
||||
* This test extracts the pattern literals FROM THE SHIPPED SOURCE (no copies
|
||||
* that can drift) and asserts they stay linear-time on those killer shapes,
|
||||
* and that `cmdPattern` still links the command+path forms it exists for.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { readFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
|
||||
const SOURCE = readFileSync(join(__dirname, '..', 'src', 'web', 'public', 'terminal-ui.js'), 'utf-8');
|
||||
|
||||
/** Extract `const <name> = /.../g;` from the shipped source and build the RegExp. */
|
||||
function shippedPattern(name: string): RegExp {
|
||||
const m = SOURCE.match(new RegExp(`const ${name} =\\s*\\n?\\s*(/(?:[^/\\\\\\n]|\\\\.)+/[a-z]*)`));
|
||||
if (!m) throw new Error(`pattern ${name} not found in terminal-ui.js`);
|
||||
const lit = m[1];
|
||||
const lastSlash = lit.lastIndexOf('/');
|
||||
return new RegExp(lit.slice(1, lastSlash), lit.slice(lastSlash + 1));
|
||||
}
|
||||
|
||||
const PATTERN_NAMES = ['urlPattern', 'cmdPattern', 'extPattern', 'bashPattern'];
|
||||
|
||||
/** Lines that made 0.9.10's cmdPattern backtrack exponentially (>2s each). */
|
||||
const KILLER_LINES = [
|
||||
// wrapped git-commit heredoc from real Claude tool output (the 0.9.10 freeze)
|
||||
` /Users/arbbot/codeman-cases/topagent-control commit -m "$(cat <<'EOF'${' '.repeat(3000)}`,
|
||||
// aligned table row: trigger word + multi-space-separated columns + mid-token slash
|
||||
'watch ' + 'col '.repeat(40) + ' BTC/USDT',
|
||||
// trigger word followed by many tokens and no token-initial path
|
||||
'cat ' + 'word '.repeat(800) + 'no-path-here',
|
||||
// long URL-ish and path-ish soup for the other patterns
|
||||
'https://example.com/' + 'a/'.repeat(1500) + ' ' + '/home/x/'.repeat(400) + '.'.repeat(2000),
|
||||
'Bash(' + 'x'.repeat(4000),
|
||||
];
|
||||
|
||||
describe('terminal link-provider regexes (shipped source)', () => {
|
||||
it('all patterns stay linear-time on killer lines', () => {
|
||||
const patterns = PATTERN_NAMES.map((n) => [n, shippedPattern(n)] as const);
|
||||
const start = Date.now();
|
||||
for (const [, re] of patterns) {
|
||||
for (const line of KILLER_LINES) {
|
||||
re.lastIndex = 0;
|
||||
while (re.exec(line) !== null) {
|
||||
/* drain all matches like the provider does */
|
||||
}
|
||||
}
|
||||
}
|
||||
const elapsed = Date.now() - start;
|
||||
// 20 pattern×line runs over multi-KB inputs: linear patterns finish in a few
|
||||
// ms; the 0.9.10 cmdPattern alone needed minutes for ONE line.
|
||||
expect(elapsed).toBeLessThan(500);
|
||||
});
|
||||
|
||||
it('cmdPattern still links command + path forms', () => {
|
||||
const cmd = shippedPattern('cmdPattern');
|
||||
const cases: Array<[string, string]> = [
|
||||
['tail -f /var/log/app.log', '/var/log/app.log'],
|
||||
['cat -n /tmp/x.json', '/tmp/x.json'],
|
||||
['grep -rn pattern /home/user/src', '/home/user/src'],
|
||||
['watch ls /opt/data', '/opt/data'],
|
||||
['head -c 100 /etc/hosts', '/etc/hosts'],
|
||||
];
|
||||
for (const [line, want] of cases) {
|
||||
cmd.lastIndex = 0;
|
||||
const m = cmd.exec(line);
|
||||
expect(m, line).not.toBeNull();
|
||||
expect(m![2]).toBe(want);
|
||||
}
|
||||
});
|
||||
|
||||
it('cmdPattern arg group cannot match empty tokens (the exponential trigger)', () => {
|
||||
// structural guard: the dangerous construct is an empty-matchable token
|
||||
// inside a repeated group — `[^\s\/]*\s+` repeated. Check the pattern
|
||||
// literal itself (not the whole file — the warning comment quotes it).
|
||||
const lit = shippedPattern('cmdPattern').source;
|
||||
expect(lit).not.toContain('[^\\s\\/]*\\s+)*');
|
||||
});
|
||||
});
|
||||
@@ -132,54 +132,23 @@ describe('Tab Navigation', () => {
|
||||
expect(modalClass).toMatch(/active/);
|
||||
});
|
||||
|
||||
it('top-left mobile menu button opens the header utility tray', async () => {
|
||||
it('header has no utility toggle and the tray stays collapsed on mobile', async () => {
|
||||
// The three-dot header utility toggle was removed (owner decision,
|
||||
// 2026-06-10): nothing interactive may occupy the top-left corner, and
|
||||
// the headerRight tray stays collapsed (hidden) on small viewports.
|
||||
await page.evaluate(() => {
|
||||
document.querySelectorAll('.modal.active').forEach((modal) => modal.classList.remove('active'));
|
||||
document.getElementById('headerRight')?.classList.add('mobile-collapsed');
|
||||
const toggle = document.getElementById('mobileHeaderUtilityToggle');
|
||||
toggle?.classList.remove('active');
|
||||
toggle?.setAttribute('aria-expanded', 'false');
|
||||
});
|
||||
|
||||
const topLeftElements = await page.evaluate(() => {
|
||||
return document.elementsFromPoint(16, 16).map((el) => ({
|
||||
tag: el.tagName,
|
||||
id: el.id,
|
||||
className: String(el.className),
|
||||
closestButtonId: el.closest('button')?.id ?? '',
|
||||
}));
|
||||
});
|
||||
const toggleCount = await page.locator('#mobileHeaderUtilityToggle').count();
|
||||
expect(toggleCount).toBe(0);
|
||||
|
||||
expect(topLeftElements[0]?.closestButtonId).toBe('mobileHeaderUtilityToggle');
|
||||
|
||||
const toggleBox = await page.locator('#mobileHeaderUtilityToggle').boundingBox();
|
||||
expect(toggleBox?.width ?? 0).toBeGreaterThanOrEqual(44);
|
||||
expect(toggleBox?.height ?? 0).toBeGreaterThanOrEqual(44);
|
||||
|
||||
await page.touchscreen.tap(
|
||||
(toggleBox?.x ?? 0) + (toggleBox?.width ?? 0) / 2,
|
||||
(toggleBox?.y ?? 0) + (toggleBox?.height ?? 0) / 2
|
||||
);
|
||||
await page.waitForTimeout(150);
|
||||
|
||||
const trayClass = await page.locator('#headerRight').getAttribute('class');
|
||||
const expanded = await page.locator('#mobileHeaderUtilityToggle').getAttribute('aria-expanded');
|
||||
const trayBox = await page.locator('#headerRight').boundingBox();
|
||||
const topTrayElement = await page.evaluate(() => {
|
||||
const trayVisible = await page.evaluate(() => {
|
||||
const tray = document.getElementById('headerRight');
|
||||
const rect = tray?.getBoundingClientRect();
|
||||
if (!rect) return '';
|
||||
return (
|
||||
document
|
||||
.elementsFromPoint(rect.left + Math.min(24, rect.width / 2), rect.top + Math.min(24, rect.height / 2))
|
||||
.find((el) => el.id === 'headerRight' || el.closest?.('#headerRight'))
|
||||
?.closest?.('#headerRight')?.id ?? ''
|
||||
);
|
||||
return tray ? getComputedStyle(tray).display !== 'none' : false;
|
||||
});
|
||||
expect(trayClass).not.toMatch(/mobile-collapsed/);
|
||||
expect(expanded).toBe('true');
|
||||
expect(trayBox?.x ?? 9999).toBeLessThanOrEqual((toggleBox?.x ?? 0) + (toggleBox?.width ?? 0) + 8);
|
||||
expect(topTrayElement).toBe('headerRight');
|
||||
expect(trayVisible).toBe(false);
|
||||
});
|
||||
|
||||
it('tabs remain visible on large phone and tablet headers', async () => {
|
||||
|
||||
@@ -222,6 +222,15 @@ export class MockSession extends EventEmitter {
|
||||
};
|
||||
}
|
||||
|
||||
/** Auto-resume on usage limit (token pause control) */
|
||||
autoResumeEnabled: boolean = false;
|
||||
autoResumeAt: number | null = null;
|
||||
isLimitPaused: boolean = false;
|
||||
setAutoResume = vi.fn((enabled: boolean) => {
|
||||
this.autoResumeEnabled = enabled;
|
||||
if (!enabled) this.autoResumeAt = null;
|
||||
});
|
||||
|
||||
/** Check if session is busy */
|
||||
isBusy = vi.fn(() => false);
|
||||
|
||||
@@ -239,6 +248,7 @@ export class MockSession extends EventEmitter {
|
||||
/** Stubs for the desktop sizing claims used by resize arbitration */
|
||||
claimDesktopSizing = vi.fn();
|
||||
releaseDesktopSizing = vi.fn();
|
||||
noteDesktopActivity = vi.fn();
|
||||
|
||||
/** Stub for runPrompt */
|
||||
runPrompt = vi.fn(async () => {});
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* @fileoverview Tests for Ralph loop prompt construction
|
||||
*
|
||||
* Verifies buildRalphLoopPrompt() output, and that the RALPH_STATUS contract
|
||||
* embedded in the prompt stays in sync with what RalphStatusParser parses.
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { buildRalphLoopPrompt, RALPH_STATUS_CONTRACT } from '../src/prompts/ralph.js';
|
||||
import { RalphStatusParser } from '../src/ralph-status-parser.js';
|
||||
|
||||
describe('buildRalphLoopPrompt', () => {
|
||||
const baseOptions = {
|
||||
taskDescription: 'Add CRUD endpoints for todos',
|
||||
completionPhrase: 'COMPLETE',
|
||||
hasPlan: false,
|
||||
};
|
||||
|
||||
it('starts with the task description', () => {
|
||||
const prompt = buildRalphLoopPrompt(baseOptions);
|
||||
|
||||
expect(prompt.startsWith('Add CRUD endpoints for todos\n\n---\n\n')).toBe(true);
|
||||
});
|
||||
|
||||
it('embeds the completion phrase in the completion criteria', () => {
|
||||
const prompt = buildRalphLoopPrompt({ ...baseOptions, completionPhrase: 'ALL_DONE' });
|
||||
|
||||
expect(prompt).toContain('<promise>ALL_DONE</promise>');
|
||||
expect(prompt).toContain('## Completion Criteria');
|
||||
});
|
||||
|
||||
it('includes the task plan section only when a plan exists', () => {
|
||||
const withPlan = buildRalphLoopPrompt({ ...baseOptions, hasPlan: true });
|
||||
const withoutPlan = buildRalphLoopPrompt(baseOptions);
|
||||
|
||||
expect(withPlan).toContain('## Task Plan');
|
||||
expect(withPlan).toContain('@fix_plan.md');
|
||||
expect(withoutPlan).not.toContain('## Task Plan');
|
||||
});
|
||||
|
||||
it('always appends the RALPH_STATUS contract', () => {
|
||||
const prompt = buildRalphLoopPrompt(baseOptions);
|
||||
|
||||
expect(prompt).toContain(RALPH_STATUS_CONTRACT);
|
||||
expect(prompt).toContain('---RALPH_STATUS---');
|
||||
expect(prompt).toContain('---END_RALPH_STATUS---');
|
||||
});
|
||||
|
||||
it('documents every field RalphStatusParser expects', () => {
|
||||
for (const field of [
|
||||
'STATUS: IN_PROGRESS | COMPLETE | BLOCKED',
|
||||
'TASKS_COMPLETED_THIS_LOOP: <number>',
|
||||
'FILES_MODIFIED: <number>',
|
||||
'TESTS_STATUS: PASSING | FAILING | NOT_RUN',
|
||||
'WORK_TYPE: IMPLEMENTATION | TESTING | DOCUMENTATION | REFACTORING',
|
||||
'EXIT_SIGNAL: false | true',
|
||||
'RECOMMENDATION:',
|
||||
]) {
|
||||
expect(RALPH_STATUS_CONTRACT).toContain(field);
|
||||
}
|
||||
});
|
||||
|
||||
it('teaches a block format that RalphStatusParser actually parses', () => {
|
||||
// A response following the contract to the letter
|
||||
const conformingBlock = [
|
||||
'---RALPH_STATUS---',
|
||||
'STATUS: IN_PROGRESS',
|
||||
'TASKS_COMPLETED_THIS_LOOP: 2',
|
||||
'FILES_MODIFIED: 5',
|
||||
'TESTS_STATUS: PASSING',
|
||||
'WORK_TYPE: IMPLEMENTATION',
|
||||
'EXIT_SIGNAL: false',
|
||||
'RECOMMENDATION: Continue with the next endpoint',
|
||||
'---END_RALPH_STATUS---',
|
||||
];
|
||||
|
||||
const parser = new RalphStatusParser();
|
||||
for (const line of conformingBlock) {
|
||||
parser.processLine(line);
|
||||
}
|
||||
|
||||
const block = parser.lastStatusBlock;
|
||||
expect(block).not.toBeNull();
|
||||
expect(block?.status).toBe('IN_PROGRESS');
|
||||
expect(block?.tasksCompletedThisLoop).toBe(2);
|
||||
expect(block?.filesModified).toBe(5);
|
||||
expect(block?.testsStatus).toBe('PASSING');
|
||||
expect(block?.workType).toBe('IMPLEMENTATION');
|
||||
expect(block?.exitSignal).toBe(false);
|
||||
expect(block?.recommendation).toBe('Continue with the next endpoint');
|
||||
});
|
||||
});
|
||||
@@ -144,6 +144,42 @@ describe('RespawnController', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('Usage-limit pause guard', () => {
|
||||
it('blocks the cycle while the session is paused on a usage limit', async () => {
|
||||
let cycleStarted = false;
|
||||
let blockedReason: string | null = null;
|
||||
controller.on('respawnCycleStarted', () => {
|
||||
cycleStarted = true;
|
||||
});
|
||||
controller.on('respawnBlocked', (data: { reason: string }) => {
|
||||
blockedReason = data.reason;
|
||||
});
|
||||
|
||||
session.isLimitPaused = true;
|
||||
controller.start();
|
||||
session.simulateCompletionMessage();
|
||||
await new Promise((resolve) => setTimeout(resolve, 250));
|
||||
|
||||
expect(cycleStarted).toBe(false);
|
||||
expect(blockedReason).toBe('usage_limit');
|
||||
expect(controller.state).toBe('watching');
|
||||
});
|
||||
|
||||
it('cycles normally when the pause is not active', async () => {
|
||||
let cycleStarted = false;
|
||||
controller.on('respawnCycleStarted', () => {
|
||||
cycleStarted = true;
|
||||
});
|
||||
|
||||
session.isLimitPaused = false;
|
||||
controller.start();
|
||||
session.simulateCompletionMessage();
|
||||
await new Promise((resolve) => setTimeout(resolve, 250));
|
||||
|
||||
expect(cycleStarted).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Respawn Cycle', () => {
|
||||
it('should start cycle when completion message detected and confirmed', async () => {
|
||||
let cycleStarted = false;
|
||||
|
||||
@@ -263,6 +263,63 @@ describe('session-routes', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ========== POST /api/sessions/:id/auto-resume ==========
|
||||
|
||||
describe('POST /api/sessions/:id/auto-resume', () => {
|
||||
it('enables auto-resume on usage limit', async () => {
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: `/api/sessions/${harness.ctx._sessionId}/auto-resume`,
|
||||
payload: { enabled: true },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.data.autoResume.enabled).toBe(true);
|
||||
const session = harness.ctx.sessions.get(harness.ctx._sessionId)!;
|
||||
expect(session.setAutoResume).toHaveBeenCalledWith(true);
|
||||
expect(harness.ctx.persistSessionState).toHaveBeenCalled();
|
||||
expect(harness.ctx.broadcast).toHaveBeenCalledWith('session:updated', expect.anything());
|
||||
});
|
||||
|
||||
it('disables auto-resume', async () => {
|
||||
const session = harness.ctx.sessions.get(harness.ctx._sessionId)!;
|
||||
session.autoResumeEnabled = true;
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: `/api/sessions/${harness.ctx._sessionId}/auto-resume`,
|
||||
payload: { enabled: false },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.data.autoResume.enabled).toBe(false);
|
||||
expect(session.setAutoResume).toHaveBeenCalledWith(false);
|
||||
});
|
||||
|
||||
it('rejects invalid body', async () => {
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: `/api/sessions/${harness.ctx._sessionId}/auto-resume`,
|
||||
payload: { enabled: 'yes' },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(false);
|
||||
expect(body.errorCode).toBe(ApiErrorCode.INVALID_INPUT);
|
||||
});
|
||||
|
||||
it('returns 404 for unknown session', async () => {
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/sessions/nonexistent/auto-resume',
|
||||
payload: { enabled: true },
|
||||
});
|
||||
expect(res.statusCode).toBe(404);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ========== POST /api/sessions/:id/input ==========
|
||||
|
||||
describe('POST /api/sessions/:id/input', () => {
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
/**
|
||||
* @fileoverview Unit tests for the Codex run-mode UI surface in session-ui.js /
|
||||
* settings-ui.js / index.html. Loads the browser modules into a vm sandbox (no
|
||||
* real DOM) and exercises run-mode selection + Codex quick-start wiring.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
function loadRunModeHarness() {
|
||||
const elements: Record<string, any> = {};
|
||||
const storage = new Map<string, string>();
|
||||
const CodemanApp = function CodemanApp(this: any) {};
|
||||
|
||||
const context = vm.createContext({
|
||||
CodemanApp,
|
||||
VoiceInput: {},
|
||||
localStorage: {
|
||||
getItem: (key: string) => storage.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => storage.set(key, value),
|
||||
},
|
||||
document: {
|
||||
getElementById: (id: string) => elements[id] ?? null,
|
||||
},
|
||||
console,
|
||||
});
|
||||
|
||||
const settingsUi = readFileSync(resolve(import.meta.dirname, '../src/web/public/settings-ui.js'), 'utf8');
|
||||
const sessionUi = readFileSync(resolve(import.meta.dirname, '../src/web/public/session-ui.js'), 'utf8');
|
||||
vm.runInContext(settingsUi, context, { filename: 'settings-ui.js' });
|
||||
vm.runInContext(sessionUi, context, { filename: 'session-ui.js' });
|
||||
|
||||
const runModeMenu = { classList: { remove: () => {} } };
|
||||
const gearBtn = { className: '' };
|
||||
const runBtn = { className: '', nextElementSibling: gearBtn };
|
||||
const runBtnLabel = { textContent: '' };
|
||||
elements.runModeMenu = runModeMenu;
|
||||
elements.runBtn = runBtn;
|
||||
elements.runBtnLabel = runBtnLabel;
|
||||
|
||||
const app = new (CodemanApp as any)();
|
||||
app.loadAppSettingsFromStorage = () => ({});
|
||||
app.saveAppSettingsToStorage = () => {};
|
||||
app._apiPut = () => Promise.resolve();
|
||||
|
||||
return { app, storage, runBtnLabel };
|
||||
}
|
||||
|
||||
describe('run mode UI', () => {
|
||||
it('updates the visible mode when selecting Claude after server sync set Codex', async () => {
|
||||
const { app, storage, runBtnLabel } = loadRunModeHarness();
|
||||
|
||||
storage.set('codeman_runMode', 'claude');
|
||||
await app.loadAppSettingsFromServer(Promise.resolve({ runMode: 'codex' }));
|
||||
expect(app.runMode).toBe('codex');
|
||||
expect(runBtnLabel.textContent).toBe('Run CX');
|
||||
|
||||
app.setRunMode('claude');
|
||||
|
||||
expect(app.runMode).toBe('claude');
|
||||
expect(runBtnLabel.textContent).toBe('Run');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Codex quick start settings', () => {
|
||||
it('renders Codex CLI settings in a dedicated app settings tab', () => {
|
||||
const html = readFileSync(resolve(import.meta.dirname, '../src/web/public/index.html'), 'utf8');
|
||||
|
||||
expect(html).toContain('data-tab="settings-codex">Codex CLI</button>');
|
||||
|
||||
const claudeTab = html.match(
|
||||
/<div class="modal-tab-content hidden" id="settings-claude">([\s\S]*?)<!-- Codex CLI Tab -->/
|
||||
);
|
||||
expect(claudeTab?.[1]).not.toContain('appSettingsCodexDangerouslyBypassApprovals');
|
||||
|
||||
const codexTab = html.match(
|
||||
/<div class="modal-tab-content hidden" id="settings-codex">([\s\S]*?)<\/div>\s*<!-- Models Tab -->/
|
||||
);
|
||||
expect(codexTab?.[1]).toContain('appSettingsCodexDangerouslyBypassApprovals');
|
||||
expect(codexTab?.[1]).not.toContain('appSettingsCodexRenderMode');
|
||||
});
|
||||
|
||||
it('passes global Codex settings into quick-start config for new sessions', async () => {
|
||||
const elements: Record<string, any> = {
|
||||
quickStartCase: { value: 'codex-case' },
|
||||
};
|
||||
const requests: Array<{ url: string; body?: any }> = [];
|
||||
const CodemanApp = function CodemanApp(this: any) {};
|
||||
|
||||
const context = vm.createContext({
|
||||
CodemanApp,
|
||||
localStorage: {
|
||||
getItem: () => null,
|
||||
setItem: () => {},
|
||||
},
|
||||
document: {
|
||||
getElementById: (id: string) => elements[id] ?? null,
|
||||
},
|
||||
// Mock responses use the real wire shape: the global preSerialization hook in
|
||||
// server.ts wraps route payloads into the { success, data } envelope.
|
||||
fetch: async (url: string, init?: { body?: string }) => {
|
||||
requests.push({ url, body: init?.body ? JSON.parse(init.body) : undefined });
|
||||
if (url === '/api/codex/status') return { json: async () => ({ success: true, data: { available: true } }) };
|
||||
if (url === '/api/quick-start') return { json: async () => ({ success: true, data: { sessionId: 'sess-1' } }) };
|
||||
throw new Error(`unexpected fetch: ${url}`);
|
||||
},
|
||||
console,
|
||||
});
|
||||
|
||||
const sessionUi = readFileSync(resolve(import.meta.dirname, '../src/web/public/session-ui.js'), 'utf8');
|
||||
vm.runInContext(sessionUi, context, { filename: 'session-ui.js' });
|
||||
|
||||
const app = new (CodemanApp as any)();
|
||||
app.terminal = { clear: () => {}, writeln: () => {}, focus: () => {} };
|
||||
app.loadAppSettingsFromStorage = () => ({
|
||||
codexDangerouslyBypassApprovals: true,
|
||||
});
|
||||
app.getCaseSettings = () => ({});
|
||||
app.buildEnvOverrides = () => ({});
|
||||
const selected: string[] = [];
|
||||
app.selectSession = async (id: string) => {
|
||||
selected.push(id);
|
||||
};
|
||||
|
||||
await app.runCodex();
|
||||
|
||||
expect(requests.find((req) => req.url === '/api/quick-start')?.body).toMatchObject({
|
||||
caseName: 'codex-case',
|
||||
mode: 'codex',
|
||||
codexConfig: { dangerouslyBypassApprovals: true, renderMode: 'hybrid' },
|
||||
});
|
||||
expect(selected).toEqual(['sess-1']);
|
||||
});
|
||||
});
|
||||
@@ -153,4 +153,17 @@ describe('reconcileStatusDecision (boot handoff state machine)', () => {
|
||||
expect(out?.phase).toBe('failed');
|
||||
expect(out?.error).toContain('building');
|
||||
});
|
||||
|
||||
it('needs-manual-restart + now running the target version → completed', () => {
|
||||
const out = reconcileStatusDecision(base({ phase: 'completed-needs-manual-restart' }), '0.9.4', NOW);
|
||||
expect(out?.phase).toBe('completed');
|
||||
expect(out?.message).toContain('0.9.4');
|
||||
expect(out?.updatedAt).toBe(NOW);
|
||||
});
|
||||
|
||||
it('needs-manual-restart + still on the old version → untouched (restart pending)', () => {
|
||||
expect(reconcileStatusDecision(base({ phase: 'completed-needs-manual-restart' }), '0.9.3', NOW)).toBeNull();
|
||||
const noTarget = base({ phase: 'completed-needs-manual-restart', toVersion: undefined });
|
||||
expect(reconcileStatusDecision(noTarget, '0.9.4', NOW)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
/**
|
||||
* Tests for SessionAutoOps auto-resume on usage limit (token pause control).
|
||||
*
|
||||
* Uses fake timers; the SessionAutoOps callbacks are plain mocks, so no
|
||||
* real session, tmux, or ports are involved. Port: N/A
|
||||
*/
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { SessionAutoOps } from '../src/session-auto-ops.js';
|
||||
import { Session } from '../src/session.js';
|
||||
|
||||
const BUFFER_MS = 2 * 60_000; // RESUME_BUFFER_MS in session-auto-ops.ts
|
||||
const ESC_DELAY_MS = 600; // RESUME_ESC_DELAY_MS
|
||||
|
||||
function limitLine(resetInMs: number): string {
|
||||
// Raw API epoch form gives exact control over the parsed reset time
|
||||
const epoch = Math.floor((Date.now() + resetInMs) / 1000);
|
||||
return `Claude AI usage limit reached|${epoch}`;
|
||||
}
|
||||
|
||||
describe('SessionAutoOps auto-resume', () => {
|
||||
let ops: SessionAutoOps;
|
||||
let writeCommand: ReturnType<typeof vi.fn>;
|
||||
let working: boolean;
|
||||
let stopped: boolean;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
// Whole-second clock: limitLine() floors to epoch seconds, and a fractional
|
||||
// start time would shift the fire point by up to 999ms (flaky assertions)
|
||||
vi.setSystemTime(Math.floor(Date.now() / 1000) * 1000);
|
||||
writeCommand = vi.fn(async () => true);
|
||||
working = false;
|
||||
stopped = false;
|
||||
ops = new SessionAutoOps({
|
||||
writeCommand,
|
||||
isWorking: () => working,
|
||||
isStopped: () => stopped,
|
||||
getTotalTokens: () => 0,
|
||||
getSessionId: () => 'test-session',
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
ops.destroy();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('does nothing when disabled', () => {
|
||||
ops.processCleanData(limitLine(60 * 60_000));
|
||||
expect(ops.isLimitPaused).toBe(false);
|
||||
expect(ops.autoResumeAt).toBeNull();
|
||||
});
|
||||
|
||||
it('arms a schedule at reset time + buffer when enabled', () => {
|
||||
ops.setAutoResume(true);
|
||||
const scheduled = vi.fn();
|
||||
ops.on('limitPauseScheduled', scheduled);
|
||||
|
||||
ops.processCleanData(limitLine(60 * 60_000)); // resets in 1h
|
||||
|
||||
expect(ops.isLimitPaused).toBe(true);
|
||||
expect(ops.autoResumeAt).not.toBeNull();
|
||||
const expected = Date.now() + 60 * 60_000 + BUFFER_MS;
|
||||
expect(Math.abs(ops.autoResumeAt! - expected)).toBeLessThan(2000);
|
||||
expect(scheduled).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('dedups repeated footer redraws of the same limit message', () => {
|
||||
ops.setAutoResume(true);
|
||||
const scheduled = vi.fn();
|
||||
ops.on('limitPauseScheduled', scheduled);
|
||||
|
||||
const line = limitLine(30 * 60_000);
|
||||
ops.processCleanData(line);
|
||||
ops.processCleanData(line);
|
||||
ops.processCleanData(line);
|
||||
|
||||
expect(scheduled).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('reschedules when an EARLIER reset time appears', () => {
|
||||
ops.setAutoResume(true);
|
||||
const scheduled = vi.fn();
|
||||
ops.on('limitPauseScheduled', scheduled);
|
||||
|
||||
ops.processCleanData(limitLine(60 * 60_000));
|
||||
const firstAt = ops.autoResumeAt!;
|
||||
ops.processCleanData(limitLine(10 * 60_000));
|
||||
|
||||
expect(scheduled).toHaveBeenCalledTimes(2);
|
||||
expect(ops.autoResumeAt!).toBeLessThan(firstAt);
|
||||
});
|
||||
|
||||
it('keeps the schedule when a LATER/stale time appears', () => {
|
||||
ops.setAutoResume(true);
|
||||
ops.processCleanData(limitLine(10 * 60_000));
|
||||
const firstAt = ops.autoResumeAt!;
|
||||
ops.processCleanData(limitLine(60 * 60_000)); // later → ignored
|
||||
ops.processCleanData(limitLine(-5 * 60_000)); // overdue → never preempts
|
||||
expect(ops.autoResumeAt).toBe(firstAt);
|
||||
});
|
||||
|
||||
it('fires Escape then the continue prompt at the scheduled time', async () => {
|
||||
ops.setAutoResume(true);
|
||||
const resumed = vi.fn();
|
||||
ops.on('limitResume', resumed);
|
||||
|
||||
ops.processCleanData(limitLine(10 * 60_000));
|
||||
await vi.advanceTimersByTimeAsync(10 * 60_000 + BUFFER_MS + 100);
|
||||
|
||||
expect(writeCommand).toHaveBeenCalledWith('\x1b');
|
||||
expect(resumed).not.toHaveBeenCalled(); // continue still pending
|
||||
|
||||
await vi.advanceTimersByTimeAsync(ESC_DELAY_MS + 50);
|
||||
expect(writeCommand).toHaveBeenCalledWith('continue\r');
|
||||
expect(resumed).toHaveBeenCalledTimes(1);
|
||||
expect(ops.isLimitPaused).toBe(false);
|
||||
expect(ops.autoResumeAt).toBeNull();
|
||||
});
|
||||
|
||||
it('ignores stale-footer re-detections while the resume is in flight', async () => {
|
||||
ops.setAutoResume(true);
|
||||
ops.processCleanData(limitLine(10 * 60_000));
|
||||
await vi.advanceTimersByTimeAsync(10 * 60_000 + BUFFER_MS + 100);
|
||||
|
||||
// Esc sent; before the continue fires, the stale footer redraws
|
||||
ops.processCleanData(limitLine(-1000));
|
||||
expect(ops.isLimitPaused).toBe(false); // not re-armed mid-resume
|
||||
|
||||
await vi.advanceTimersByTimeAsync(ESC_DELAY_MS + 50);
|
||||
expect(writeCommand).toHaveBeenCalledWith('continue\r');
|
||||
});
|
||||
|
||||
it('re-arms a retry when still limited after a resume attempt', async () => {
|
||||
ops.setAutoResume(true);
|
||||
ops.processCleanData(limitLine(10 * 60_000));
|
||||
await vi.advanceTimersByTimeAsync(10 * 60_000 + BUFFER_MS + ESC_DELAY_MS + 200);
|
||||
expect(writeCommand).toHaveBeenCalledWith('continue\r');
|
||||
|
||||
// The submit echoes a fresh limit line with an already-past reset → retry path
|
||||
const scheduled = vi.fn();
|
||||
ops.on('limitPauseScheduled', scheduled);
|
||||
ops.processCleanData(limitLine(-1000));
|
||||
expect(scheduled).toHaveBeenCalledTimes(1);
|
||||
expect(ops.isLimitPaused).toBe(true);
|
||||
// Retry fires within RESUME_RETRY_MS (5 min)
|
||||
expect(ops.autoResumeAt! - Date.now()).toBeLessThanOrEqual(5 * 60_000 + 1000);
|
||||
});
|
||||
|
||||
it('skips the resume when Claude is already working at fire time', async () => {
|
||||
ops.setAutoResume(true);
|
||||
const cancelled = vi.fn();
|
||||
ops.on('limitResumeCancelled', cancelled);
|
||||
|
||||
ops.processCleanData(limitLine(10 * 60_000));
|
||||
working = true;
|
||||
await vi.advanceTimersByTimeAsync(10 * 60_000 + BUFFER_MS + ESC_DELAY_MS + 200);
|
||||
|
||||
expect(writeCommand).not.toHaveBeenCalled();
|
||||
expect(cancelled).toHaveBeenCalledWith({ reason: 'working' });
|
||||
expect(ops.isLimitPaused).toBe(false);
|
||||
});
|
||||
|
||||
it('cancels the pending schedule when Claude starts working', () => {
|
||||
ops.setAutoResume(true);
|
||||
const cancelled = vi.fn();
|
||||
ops.on('limitResumeCancelled', cancelled);
|
||||
|
||||
ops.processCleanData(limitLine(10 * 60_000));
|
||||
expect(ops.isLimitPaused).toBe(true);
|
||||
|
||||
ops.notifyWorking();
|
||||
expect(ops.isLimitPaused).toBe(false);
|
||||
expect(ops.autoResumeAt).toBeNull();
|
||||
expect(cancelled).toHaveBeenCalledWith({ reason: 'working' });
|
||||
});
|
||||
|
||||
it('notifyWorking is a no-op when nothing is armed', () => {
|
||||
ops.setAutoResume(true);
|
||||
const cancelled = vi.fn();
|
||||
ops.on('limitResumeCancelled', cancelled);
|
||||
ops.notifyWorking();
|
||||
expect(cancelled).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('disabling cancels the pending schedule', () => {
|
||||
ops.setAutoResume(true);
|
||||
ops.processCleanData(limitLine(10 * 60_000));
|
||||
|
||||
ops.setAutoResume(false);
|
||||
expect(ops.isLimitPaused).toBe(false);
|
||||
expect(ops.autoResumeAt).toBeNull();
|
||||
|
||||
// and detection stays off
|
||||
ops.processCleanData(limitLine(10 * 60_000));
|
||||
expect(ops.isLimitPaused).toBe(false);
|
||||
});
|
||||
|
||||
it('destroy clears timers without emitting', () => {
|
||||
ops.setAutoResume(true);
|
||||
const cancelled = vi.fn();
|
||||
ops.on('limitResumeCancelled', cancelled);
|
||||
ops.processCleanData(limitLine(10 * 60_000));
|
||||
|
||||
ops.destroy();
|
||||
expect(ops.isLimitPaused).toBe(false);
|
||||
expect(cancelled).not.toHaveBeenCalled();
|
||||
|
||||
vi.advanceTimersByTime(60 * 60_000);
|
||||
expect(writeCommand).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not fire after the session stops', async () => {
|
||||
ops.setAutoResume(true);
|
||||
ops.processCleanData(limitLine(10 * 60_000));
|
||||
stopped = true;
|
||||
await vi.advanceTimersByTimeAsync(10 * 60_000 + BUFFER_MS + ESC_DELAY_MS + 200);
|
||||
expect(writeCommand).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
describe('Session wiring (terminal output → detection → events)', () => {
|
||||
it('detects a limit message flowing through the expensive-parser path', () => {
|
||||
const session = new Session({ workingDir: '/tmp' }); // mode 'claude'
|
||||
const scheduled = vi.fn();
|
||||
session.on('limitPauseScheduled', scheduled);
|
||||
session.setAutoResume(true);
|
||||
|
||||
// Same choke-point the claude-mode PTY handler uses (throttled batch)
|
||||
(session as unknown as { _processExpensiveParsers(d: string): void })._processExpensiveParsers(
|
||||
'5-hour limit reached ∙ resets 8pm'
|
||||
);
|
||||
|
||||
expect(session.isLimitPaused).toBe(true);
|
||||
expect(session.autoResumeAt).not.toBeNull();
|
||||
expect(scheduled).toHaveBeenCalledTimes(1);
|
||||
expect(session.toState().autoResumeEnabled).toBe(true);
|
||||
expect(session.toState().autoResumeAt).toBe(session.autoResumeAt!);
|
||||
session.setAutoResume(false); // clears the armed timer
|
||||
});
|
||||
|
||||
it('catches an already-displayed limit message when enabling mid-pause', () => {
|
||||
const session = new Session({ workingDir: '/tmp' });
|
||||
// limit footer already on screen before the user finds the checkbox
|
||||
(session as unknown as { _terminalBuffer: { append(d: string): void } })._terminalBuffer.append(
|
||||
'\x1b[33m5-hour limit reached ∙ resets 8pm\x1b[0m'
|
||||
);
|
||||
session.setAutoResume(true);
|
||||
expect(session.isLimitPaused).toBe(true);
|
||||
session.setAutoResume(false);
|
||||
});
|
||||
|
||||
it('ignores stale scrollback (past reset time) when enabling', () => {
|
||||
const session = new Session({ workingDir: '/tmp' });
|
||||
const pastEpoch = Math.floor(Date.now() / 1000) - 3600;
|
||||
(session as unknown as { _terminalBuffer: { append(d: string): void } })._terminalBuffer.append(
|
||||
`Claude AI usage limit reached|${pastEpoch}`
|
||||
);
|
||||
session.setAutoResume(true);
|
||||
expect(session.isLimitPaused).toBe(false);
|
||||
session.setAutoResume(false);
|
||||
});
|
||||
|
||||
it('stays inert when the checkbox is disabled (default)', () => {
|
||||
const session = new Session({ workingDir: '/tmp' });
|
||||
(session as unknown as { _processExpensiveParsers(d: string): void })._processExpensiveParsers(
|
||||
'5-hour limit reached ∙ resets 8pm'
|
||||
);
|
||||
expect(session.isLimitPaused).toBe(false);
|
||||
expect(session.toState().autoResumeEnabled).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('restoreAutoResume (recovery after Codeman restart)', () => {
|
||||
it('re-arms a future schedule', () => {
|
||||
ops.restoreAutoResume(true, Date.now() + 30 * 60_000);
|
||||
expect(ops.autoResumeEnabled).toBe(true);
|
||||
expect(ops.isLimitPaused).toBe(true);
|
||||
expect(ops.autoResumeAt! - Date.now()).toBeGreaterThan(29 * 60_000);
|
||||
});
|
||||
|
||||
it('fires an overdue schedule shortly after boot', async () => {
|
||||
ops.restoreAutoResume(true, Date.now() - 60_000);
|
||||
expect(ops.isLimitPaused).toBe(true);
|
||||
await vi.advanceTimersByTimeAsync(5_000 + ESC_DELAY_MS + 200);
|
||||
expect(writeCommand).toHaveBeenCalledWith('\x1b');
|
||||
expect(writeCommand).toHaveBeenCalledWith('continue\r');
|
||||
});
|
||||
|
||||
it('enables without arming when no schedule was persisted', () => {
|
||||
ops.restoreAutoResume(true);
|
||||
expect(ops.autoResumeEnabled).toBe(true);
|
||||
expect(ops.isLimitPaused).toBe(false);
|
||||
expect(ops.autoResumeAt).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,9 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { Session } from '../src/session.js';
|
||||
|
||||
/** Must exceed Session.DESKTOP_CLAIM_IDLE_MS (90s) */
|
||||
const PAST_IDLE_MS = 91_000;
|
||||
|
||||
type ResizeableSessionInternals = {
|
||||
ptyProcess: { resize: (cols: number, rows: number) => void };
|
||||
_ptyCols: number;
|
||||
@@ -109,4 +112,64 @@ describe('Session resize arbitration', () => {
|
||||
|
||||
expect(resize).toHaveBeenCalledWith(100, 30);
|
||||
});
|
||||
|
||||
describe('idle-desktop override (whoever is active wins)', () => {
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('lets a mobile client take the pane once the desktop claim goes idle', () => {
|
||||
vi.useFakeTimers();
|
||||
const session = new Session({ workingDir: '/tmp', mode: 'shell' });
|
||||
const resize = attachFakePty(session, 160, 48);
|
||||
|
||||
session.claimDesktopSizing(Symbol('desktop-conn'));
|
||||
session.resize(48, 28, { viewportType: 'mobile' });
|
||||
expect(resize).not.toHaveBeenCalled(); // fresh claim → ignored
|
||||
|
||||
vi.advanceTimersByTime(PAST_IDLE_MS);
|
||||
session.resize(48, 28, { viewportType: 'mobile' });
|
||||
expect(resize).toHaveBeenCalledWith(48, 28); // idle desktop → applied
|
||||
});
|
||||
|
||||
it('keeps blocking mobile while the desktop stays active via typed input', () => {
|
||||
vi.useFakeTimers();
|
||||
const session = new Session({ workingDir: '/tmp', mode: 'shell' });
|
||||
const resize = attachFakePty(session, 160, 48);
|
||||
|
||||
session.claimDesktopSizing(Symbol('desktop-conn'));
|
||||
vi.advanceTimersByTime(PAST_IDLE_MS - 10_000);
|
||||
session.noteDesktopActivity(); // user typed on desktop
|
||||
vi.advanceTimersByTime(20_000); // idle since claim, but not since input
|
||||
|
||||
session.resize(48, 28, { viewportType: 'mobile' });
|
||||
expect(resize).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('re-asserts the desktop layout on desktop input after a mobile override', () => {
|
||||
vi.useFakeTimers();
|
||||
const session = new Session({ workingDir: '/tmp', mode: 'shell' });
|
||||
const resize = attachFakePty(session, 160, 48);
|
||||
|
||||
session.resize(208, 45, { viewportType: 'desktop' }); // desktop sizes the pane
|
||||
session.claimDesktopSizing(Symbol('desktop-conn'));
|
||||
vi.advanceTimersByTime(PAST_IDLE_MS);
|
||||
|
||||
session.resize(48, 28, { viewportType: 'mobile' }); // phone takes over
|
||||
expect(resize).toHaveBeenLastCalledWith(48, 28);
|
||||
|
||||
session.noteDesktopActivity(); // desktop user types again
|
||||
expect(resize).toHaveBeenLastCalledWith(208, 45); // layout restored
|
||||
});
|
||||
|
||||
it('does not re-assert when no mobile override happened', () => {
|
||||
const session = new Session({ workingDir: '/tmp', mode: 'shell' });
|
||||
const resize = attachFakePty(session, 160, 48);
|
||||
|
||||
session.resize(208, 45, { viewportType: 'desktop' });
|
||||
resize.mockClear();
|
||||
session.noteDesktopActivity();
|
||||
expect(resize).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -14,6 +14,10 @@ import { afterEach, vi } from 'vitest';
|
||||
|
||||
delete process.env.CODEMAN_PASSWORD;
|
||||
delete process.env.CODEMAN_USERNAME;
|
||||
// Gesture availability changes renderIndexHtml output (injects the
|
||||
// __codemanGestureAvailable flag), breaking byte-identity assertions
|
||||
// (test/server-index-title.test.ts) when the shell exports CODEMAN_GESTURE=1.
|
||||
delete process.env.CODEMAN_GESTURE;
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
+25
-30
@@ -51,7 +51,7 @@ describe('generateClaudeMd', () => {
|
||||
const today = new Date().toISOString().split('T')[0];
|
||||
const result = generateClaudeMd('my-project');
|
||||
|
||||
expect(result).toContain(`**Last Updated**: ${today}`);
|
||||
expect(result).toContain(`Generated by Codeman on ${today}`);
|
||||
});
|
||||
|
||||
it('should include Codeman environment section', () => {
|
||||
@@ -61,55 +61,47 @@ describe('generateClaudeMd', () => {
|
||||
expect(result).toContain('CODEMAN_MUX=1');
|
||||
});
|
||||
|
||||
it('should include work principles', () => {
|
||||
it('should include workflow rules', () => {
|
||||
const result = generateClaudeMd('my-project');
|
||||
|
||||
expect(result).toContain('## Work Principles');
|
||||
expect(result).toContain('### Autonomy');
|
||||
expect(result).toContain('### Git Discipline');
|
||||
expect(result).toContain('## Workflow');
|
||||
expect(result).toContain('conventional commits');
|
||||
});
|
||||
|
||||
it('should include TodoWrite guidance', () => {
|
||||
it('should stay under the 200-line CLAUDE.md guidance', () => {
|
||||
const result = generateClaudeMd('my-project');
|
||||
|
||||
expect(result).toContain('### Task Tracking (TodoWrite)');
|
||||
expect(result).toContain('**ALWAYS use TodoWrite**');
|
||||
expect(result.split('\n').length).toBeLessThan(200);
|
||||
});
|
||||
|
||||
it('should include Ralph Wiggum Loop section', () => {
|
||||
it('should not include legacy bloat sections', () => {
|
||||
const result = generateClaudeMd('my-project');
|
||||
|
||||
expect(result).toContain('## Ralph Wiggum Loop');
|
||||
expect(result).toContain('/ralph-loop:ralph-loop');
|
||||
expect(result).toContain('/ralph-loop:cancel-ralph');
|
||||
});
|
||||
|
||||
it('should include planning mode section', () => {
|
||||
const result = generateClaudeMd('my-project');
|
||||
|
||||
expect(result).toContain('## Planning Mode');
|
||||
expect(result).toContain('Multi-file changes');
|
||||
});
|
||||
|
||||
it('should include session log table', () => {
|
||||
const result = generateClaudeMd('my-project');
|
||||
|
||||
expect(result).toContain('## Session Log');
|
||||
expect(result).toContain('| Date | Tasks Completed | Files Changed | Notes |');
|
||||
expect(result).not.toContain('## Session Log');
|
||||
expect(result).not.toContain('TodoWrite');
|
||||
expect(result).not.toContain('## Planning Mode');
|
||||
expect(result).not.toContain('[TECHNOLOGIES_USED]');
|
||||
// Ralph loop instructions live in the loop prompt (wizard) and plugin,
|
||||
// not in every project's CLAUDE.md
|
||||
expect(result).not.toContain('RALPH_STATUS');
|
||||
expect(result).not.toContain('/ralph-loop:');
|
||||
});
|
||||
});
|
||||
|
||||
describe('custom template', () => {
|
||||
it('should use custom template when provided and exists', () => {
|
||||
const templatePath = join(testDir, 'custom-template.md');
|
||||
writeFileSync(templatePath, `
|
||||
writeFileSync(
|
||||
templatePath,
|
||||
`
|
||||
# [PROJECT_NAME]
|
||||
|
||||
Description: [PROJECT_DESCRIPTION]
|
||||
Date: [DATE]
|
||||
|
||||
Custom content here.
|
||||
`);
|
||||
`
|
||||
);
|
||||
|
||||
const result = generateClaudeMd('my-project', 'Test desc', templatePath);
|
||||
|
||||
@@ -120,11 +112,14 @@ Custom content here.
|
||||
|
||||
it('should replace all placeholder occurrences', () => {
|
||||
const templatePath = join(testDir, 'multi-placeholder.md');
|
||||
writeFileSync(templatePath, `
|
||||
writeFileSync(
|
||||
templatePath,
|
||||
`
|
||||
[PROJECT_NAME] is a project.
|
||||
The name is [PROJECT_NAME].
|
||||
About [PROJECT_NAME]: [PROJECT_DESCRIPTION]
|
||||
`);
|
||||
`
|
||||
);
|
||||
|
||||
const result = generateClaudeMd('awesome-app', 'Cool stuff', templatePath);
|
||||
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
/**
|
||||
* Tests for usage-limit pause detection (auto-resume on usage limit).
|
||||
*
|
||||
* Message corpus mirrors real Claude Code output observed across
|
||||
* 1.0.x–2.1.x (GitHub issues + official error docs). Time expectations are
|
||||
* computed with the same local-Date APIs the implementation uses, so the
|
||||
* tests are timezone-independent.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { detectUsageLimitPause } from '../src/usage-limit-patterns.js';
|
||||
|
||||
/** Fixed "now" for deterministic tests: a real timestamp, any value works. */
|
||||
const NOW = new Date(2026, 5, 10, 14, 0, 0).getTime(); // local Jun 10 2026, 2:00pm
|
||||
|
||||
/** Expected epoch ms for the next local occurrence of hour:minute after NOW. */
|
||||
function nextLocal(hour: number, minute = 0, from = NOW): number {
|
||||
const d = new Date(from);
|
||||
let ts = new Date(d.getFullYear(), d.getMonth(), d.getDate(), hour, minute).getTime();
|
||||
if (ts <= from) ts += 24 * 60 * 60 * 1000;
|
||||
return ts;
|
||||
}
|
||||
|
||||
describe('detectUsageLimitPause', () => {
|
||||
describe('era 2 footer forms (v1.0.109+, ∙ separator, no timezone)', () => {
|
||||
it.each([
|
||||
['5-hour limit reached ∙ resets 8pm', 20, 0],
|
||||
['Session limit reached ∙ resets 8pm', 20, 0],
|
||||
['Weekly limit reached ∙ resets 6pm', 18, 0],
|
||||
['5-hour limit reached ∙ resets 10:30pm', 22, 30],
|
||||
['5-hour limit reached ∙ resets 3am', 3, 0],
|
||||
['5-hour limit reached ∙ resets 12am', 0, 0],
|
||||
['5-hour limit reached ∙ resets 12pm', 12, 0],
|
||||
])('parses "%s"', (msg, hour, minute) => {
|
||||
const det = detectUsageLimitPause(msg, NOW);
|
||||
expect(det).not.toBeNull();
|
||||
expect(det!.resetAt).toBe(nextLocal(hour, minute));
|
||||
});
|
||||
|
||||
it('rolls over to tomorrow when the time already passed today', () => {
|
||||
// NOW is 2:00pm local; "resets 9am" must be tomorrow 9am
|
||||
const det = detectUsageLimitPause('5-hour limit reached ∙ resets 9am', NOW);
|
||||
expect(det!.resetAt).toBe(nextLocal(9, 0));
|
||||
expect(det!.resetAt).toBeGreaterThan(NOW);
|
||||
});
|
||||
});
|
||||
|
||||
describe('era 3 forms (v2.0.55+, · separator, IANA timezone, action hints)', () => {
|
||||
it('parses with timezone and /upgrade suffix', () => {
|
||||
const det = detectUsageLimitPause(
|
||||
'5-hour limit reached · resets 3pm (Europe/Stockholm) · /upgrade to Max 20x or turn on /extra-usage',
|
||||
NOW
|
||||
);
|
||||
expect(det).not.toBeNull();
|
||||
// 3pm in Stockholm (UTC+2 in June) = 13:00 UTC
|
||||
const d = new Date(det!.resetAt);
|
||||
expect(d.getUTCHours()).toBe(13);
|
||||
expect(det!.resetAt).toBeGreaterThan(NOW);
|
||||
});
|
||||
|
||||
it('parses generic "Limit reached" with minutes and timezone', () => {
|
||||
const det = detectUsageLimitPause(
|
||||
'Limit reached · resets 11:30am (Asia/Calcutta) · /upgrade to Max or turn on /extra-usage',
|
||||
NOW
|
||||
);
|
||||
expect(det).not.toBeNull();
|
||||
// 11:30am IST (UTC+5:30) = 06:00 UTC
|
||||
const d = new Date(det!.resetAt);
|
||||
expect(d.getUTCHours()).toBe(6);
|
||||
expect(d.getUTCMinutes()).toBe(0);
|
||||
});
|
||||
|
||||
it('falls back to local time for unresolvable timezone (Etc/Unknown)', () => {
|
||||
const det = detectUsageLimitPause('Limit reached · resets 5pm (Etc/Unknown)', NOW);
|
||||
expect(det).not.toBeNull();
|
||||
expect(det!.resetAt).toBe(nextLocal(17, 0));
|
||||
});
|
||||
|
||||
it('parses weekly date form "Dec 2, 7pm"', () => {
|
||||
const det = detectUsageLimitPause('Weekly limit reached · resets Dec 2, 7pm (Europe/Moscow) ·', NOW);
|
||||
// Dec 2 is >8 days from Jun 10 → implausible horizon → rejected
|
||||
expect(det).toBeNull();
|
||||
});
|
||||
|
||||
it('parses near-future date form within the horizon', () => {
|
||||
const det = detectUsageLimitPause('Weekly limit reached ∙ resets Jun 15, 1pm', NOW);
|
||||
expect(det).not.toBeNull();
|
||||
const expected = new Date(2026, 5, 15, 13, 0).getTime();
|
||||
expect(det!.resetAt).toBe(expected);
|
||||
});
|
||||
|
||||
it('parses malformed separator-less render', () => {
|
||||
const det = detectUsageLimitPause('Limit reached resets 1:30pm (Asia/Calcutta) ·', NOW);
|
||||
expect(det).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('era 4 forms (v2.1.x, "You\'ve hit your limit")', () => {
|
||||
it.each([
|
||||
["You've hit your limit · resets 1:40pm (UTC)", 13, 40],
|
||||
["You've hit your session limit · resets 3:45pm", 15, 45],
|
||||
["You've hit your Opus limit · resets 3:45pm", 15, 45],
|
||||
])('parses "%s"', (msg) => {
|
||||
const det = detectUsageLimitPause(msg, NOW);
|
||||
expect(det).not.toBeNull();
|
||||
expect(det!.resetAt).toBeGreaterThan(NOW);
|
||||
});
|
||||
|
||||
it('parses day-of-week form "resets Mon 12:00am"', () => {
|
||||
const det = detectUsageLimitPause("You've hit your weekly limit · resets Mon 12:00am", NOW);
|
||||
expect(det).not.toBeNull();
|
||||
const d = new Date(det!.resetAt);
|
||||
expect(d.getDay()).toBe(1); // Monday
|
||||
expect(d.getHours()).toBe(0);
|
||||
expect(det!.resetAt).toBeGreaterThan(NOW);
|
||||
expect(det!.resetAt).toBeLessThanOrEqual(NOW + 8 * 24 * 60 * 60 * 1000);
|
||||
});
|
||||
|
||||
it('parses "May 5 at 9pm" date-with-at form (next-year rollover)', () => {
|
||||
// NOW is Jun 10 2026 — "May 5" is >2 days past → next year → beyond horizon → null
|
||||
const det = detectUsageLimitPause("You've hit your limit · resets May 5 at 9pm (UTC)", NOW);
|
||||
expect(det).toBeNull();
|
||||
});
|
||||
|
||||
it('parses "Jun 12 at 9pm" date-with-at form within horizon', () => {
|
||||
const det = detectUsageLimitPause("You've hit your limit · resets Jun 12 at 9pm", NOW);
|
||||
expect(det).not.toBeNull();
|
||||
expect(det!.resetAt).toBe(new Date(2026, 5, 12, 21, 0).getTime());
|
||||
});
|
||||
|
||||
it('parses extra-usage form "You\'re out of extra usage"', () => {
|
||||
const det = detectUsageLimitPause("You're out of extra usage · resets 1pm (UTC)", NOW);
|
||||
expect(det).not.toBeNull();
|
||||
const d = new Date(det!.resetAt);
|
||||
expect(d.getUTCHours()).toBe(13);
|
||||
});
|
||||
});
|
||||
|
||||
describe('era 1 inline form (v1.0.x)', () => {
|
||||
it('parses "Your limit will reset at 2pm (America/New_York)"', () => {
|
||||
const det = detectUsageLimitPause(
|
||||
'Claude usage limit reached. Your limit will reset at 2pm (America/New_York)',
|
||||
NOW
|
||||
);
|
||||
expect(det).not.toBeNull();
|
||||
// 2pm EDT (UTC-4 in June) = 18:00 UTC
|
||||
expect(new Date(det!.resetAt).getUTCHours()).toBe(18);
|
||||
});
|
||||
});
|
||||
|
||||
describe('raw API epoch form', () => {
|
||||
it('parses "Claude AI usage limit reached|<epoch>"', () => {
|
||||
const epoch = Math.floor(NOW / 1000) + 3600; // resets in 1h
|
||||
const det = detectUsageLimitPause(`Claude AI usage limit reached|${epoch}`, NOW);
|
||||
expect(det).not.toBeNull();
|
||||
expect(det!.resetAt).toBe(epoch * 1000);
|
||||
});
|
||||
|
||||
it('returns past epoch as-is (stale message → caller retries soon)', () => {
|
||||
const epoch = Math.floor(NOW / 1000) - 600;
|
||||
const det = detectUsageLimitPause(`Claude AI usage limit reached|${epoch}`, NOW);
|
||||
expect(det).not.toBeNull();
|
||||
expect(det!.resetAt).toBeLessThan(NOW);
|
||||
});
|
||||
});
|
||||
|
||||
describe('transcript and multi-line contexts', () => {
|
||||
it('detects the ⎿-prefixed transcript echo', () => {
|
||||
const det = detectUsageLimitPause(
|
||||
"⎿ You've hit your limit · resets 6pm (Asia/Bangkok)\n /upgrade to increase your usage limit.",
|
||||
NOW
|
||||
);
|
||||
expect(det).not.toBeNull();
|
||||
});
|
||||
|
||||
it('returns the LAST parseable occurrence in a chunk', () => {
|
||||
const chunk = [
|
||||
'5-hour limit reached ∙ resets 3pm',
|
||||
'some scrollback text',
|
||||
'5-hour limit reached ∙ resets 5pm',
|
||||
].join('\n');
|
||||
const det = detectUsageLimitPause(chunk, NOW);
|
||||
expect(det!.resetAt).toBe(nextLocal(17, 0));
|
||||
});
|
||||
});
|
||||
|
||||
describe('false-positive guards', () => {
|
||||
it.each([
|
||||
'the rate limit reached in tests was 30/min',
|
||||
'limit reached',
|
||||
'Usage limit reached', // bare banner: no reset time → not actionable
|
||||
'we reset at dawn',
|
||||
'resets 3pm', // time without a limit phrase
|
||||
'The speed limit reached 120 km/h before it resets',
|
||||
'5-hour limit reached ∙ resets 25pm', // invalid hour
|
||||
'limit reached ∙ resets 99:99pm',
|
||||
])('ignores "%s"', (msg) => {
|
||||
expect(detectUsageLimitPause(msg, NOW)).toBeNull();
|
||||
});
|
||||
|
||||
it('ignores empty and irrelevant data', () => {
|
||||
expect(detectUsageLimitPause('', NOW)).toBeNull();
|
||||
expect(detectUsageLimitPause('compiling project...', NOW)).toBeNull();
|
||||
});
|
||||
|
||||
it('requires the reset time within the window after the phrase', () => {
|
||||
const farApart = 'limit reached' + ' x'.repeat(200) + ' resets 3pm';
|
||||
expect(detectUsageLimitPause(farApart, NOW)).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user