Merge branch 'master' into feat/codex-resume

master and this branch both rewrote the two `_claudeSessionId` resets inside
`start()`, so `src/session.ts` conflicted at both of them.

master's commit ccfda623 puts `restoredConversation` at the head of each
fallback chain. A restored mux attach means the CLI never stopped, so a
`/clear` before the Codeman restart may already have moved it to a
conversation the launch id knows nothing about. The persisted chain's tail is
that conversation, and the CLI's own hook reported it first-hand.

This branch adds `this._codexConfig?.resumeSessionId` to the same two chains,
so a resumed codex session keeps its thread-id alias across every mux reattach
and boot recovery.

Both fixes belong. Each chain now reads restoredConversation, then
_resumeSessionId, then omp's alias, then codex's alias, then the launch id.
The comments from both sides are kept.

test/session-claude-conversation-chain.test.ts pins the shape of those two
assignments by matching the source text, and its pattern named omp's alias as
the last term before `this.id`. Codex's alias now sits between the two, so the
pattern widens to pin the ends of the chain and let the middle grow. A `[^;]`
run cannot cross a statement boundary, so each match is still one assignment.

Checked on the merged tree: typecheck, lint, prettier and the frontend syntax
check all pass, and the CI suite runs 6721 tests green across 349 files.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Michael Grundberg
2026-09-07 08:48:31 +02:00
co-authored by Claude Opus 5
86 changed files with 7928 additions and 262 deletions
+24
View File
@@ -1,5 +1,29 @@
# aicodeman
## 1.25.0
### Minor Changes
- Codeman can be mounted under a sub-path behind a reverse proxy (#381, @mtiller). `--base-url /codeman` (or `CODEMAN_BASE_URL`) makes the server strip the prefix on the way in, rebase redirects on the way out, inject `<base>` and `window.__CODEMAN_BASE__` into the shell, and route web-tab proxying and WebSocket upgrades under the mount, so one TLS name can front several apps. A root install is byte-identical to before. Applied on top: the crash-diag beacon stays under the mount (sendBeacon is not fetch, so the base-aware wrapper never saw it), the test suite strips `CODEMAN_BASE_URL`, and a wiring test boots a real server under a prefix.
A case can attach to a container that is already running (#357, @dignfei). `DockerCase.owned:false` mirrors the remote-SSH attach contract: Codeman only execs into such a container, never creates, starts, stops, removes, pauses or commits it, with the refusal enforced at string-construction time so no caller bug can reach `docker stop`. The Add Case dialog gets an attach panel with a container picker, the run menu takes its mode availability from the CLIs actually present in the container, and adoption is admin-only in multi-user mode. Three gaps closed after review: export no longer pauses or commits an adopted container, a freshly linked owned case no longer hides every agent mode behind a probe of a container that does not exist yet, and multi-user gating is explicit.
The Claude response viewer renders one message per model message (#369, @shenlvkang-collab). The reader used to fuse every assistant row between two human prompts into one card and never read the attachment rows that hold a prompt typed mid-turn; measured over 57 real transcripts it now shows 1,806 messages instead of 356 and recovers 162 absorbed user prompts, with the assistant text unchanged row for row.
A Claude pane learns its live conversation from the CLI's own `UserPromptSubmit` hook (#367, @shenlvkang-collab). The conversation id used to be re-derived by correlating `~/.claude/history.jsonl` against a stamp only Codeman's own input path set, so a pane driven straight from tmux stayed pinned to its launch conversation forever. The hook reports the id first-hand, addressed by the pane's own `$CODEMAN_SESSION_ID`, and the chain of conversations is persisted so a restart re-pins the right one. The new `hook:prompt_submitted` SSE event is registered (158 = 158), and it lands in the run summary only when the conversation actually moved.
The Add Case modal can be submitted from a phone again (#368, @shenlvkang-collab). Since 1.16.4 the layout below 860px hid the modal footer, which held the only Create/Clone/Link button. A header submit button now sits beside the close button, dims while a submit is pending, and a static test pins the contract so it cannot silently disappear again.
The Link Existing case picker opens in the Codeman Cases directory instead of Home (#383, @opticon454). Under Docker the two are unrelated trees and Home holds nothing but dot directories, so the picker showed no cases at all. The fallback chain is now Current Folder, then Codeman Cases, then `/mnt/d`, then the first root.
A PR review bot for the maintainer (`scripts/pr-bot/`, guide in `docs/pr-bot.md`). It reviews every open pull request in its own Codeman session inside a private clone and reports the verdict, ranked findings and a recommendation to Telegram with action buttons; merge, close, post-comment and approve-CI happen only from a confirmed tap. Maintainer tooling, not part of the server or the CLI.
### Thanks
- @mtiller for the reverse-proxy base URL (#381).
- @dignfei for attaching cases to running containers (#357).
- @shenlvkang-collab for the response viewer fix (#369), the first-hand conversation hook (#367) and the phone Add Case fix (#368).
- @opticon454 for the case picker default (#383).
## 1.24.7
### Patch Changes
+10 -4
View File
File diff suppressed because one or more lines are too long
+1
View File
@@ -4,6 +4,7 @@
"scripts/*.mjs",
"scripts/*.js",
"scripts/watch-subagents.ts",
"scripts/pr-bot/main.ts",
"scripts/remotion/Root.tsx",
"scripts/remotion/index.ts",
"test/**/*.test.ts",
+11
View File
@@ -0,0 +1,11 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"rootDir": "..",
"noEmit": true,
"declaration": false,
"declarationMap": false,
"sourceMap": false
},
"include": ["../scripts/pr-bot/**/*.ts"]
}
File diff suppressed because one or more lines are too long
+43
View File
@@ -78,6 +78,49 @@ curl -X POST localhost:3000/api/cases/docker-link -d '{"name":"sandbox","hostId"
curl -X POST localhost:3000/api/quick-start -d '{"caseName":"sandbox","mode":"claude"}'
```
## Attach to a container you already run
The tab's **Attach to an existing container** toggle points a case at a container **you**
built and run. Codeman only ever `docker exec`s into it: it never creates, starts, stops,
restarts or removes it, and it seeds no credentials into it, so the CLIs inside must already
be installed and logged in. A missing or stopped container is an error to report, not a state
to fix — start it yourself and reopen the session.
- **Container Name** is a picker over the engine's containers that you can also type into
(the engine may be remote, or the container may not exist yet when you fill the form).
Stopped containers are listed too, sorted last and labelled, so "mine isn't here" is never
a dead end.
- **Container Workdir** is a path that must already exist **inside** the container. Adoption
mounts nothing, so it need not match the host workspace path; **Browse** lists directories
inside the container itself. Without this check, a wrong path fails at launch as a bare
`execvp failed` inside the pane.
- **Workspace Path** is still a real host directory. It backs file previews, attachments and
watchers exactly as it does for an owned case, but here it is only a mirror: nothing is
bind-mounted, so point it at whatever host directory your container already exposes.
- **Check container** runs a read-only preflight and reports what is inside before you commit
to a case name (running or not, tmux present, which CLIs resolved).
- **Run modes come from the container**, not the host: a host with no `claude` still offers
Claude if the container ships it, and a mode the container lacks is hidden.
- Claude is launched **without** `--dangerously-skip-permissions` when the container's exec
user is root, because Claude Code refuses that flag as root and the refusal is only visible
inside the container.
- Image, network and resource settings disappear from the form: they describe a
`docker create` that adoption never runs.
Recreate is refused for an adopted case, full-image export is refused (it would commit a
container that is not ours), unlinking the case leaves the container running, and the boot
reaper skips it. Workspace-only export still works and never pauses the container.
Equivalent API:
```bash
curl -X POST localhost:3000/api/docker-cases/adopt-preflight -d '{"hostId":"local","container":"my-dev-box","containerWorkdir":"/workspace"}'
curl -X POST localhost:3000/api/cases/docker-adopt -d '{"name":"devbox","hostId":"local","container":"my-dev-box","hostWorkspacePath":"/home/you/projects/devbox","containerWorkdir":"/workspace"}'
```
In multi-user mode adoption is **admin-only**, unlike `docker-link`: an adopted container's
mounts belong to whoever built it, so one mounting `/` would hand the adopter the whole host.
## Lifecycle
- **Reconnect after a Codeman restart** lands back in the same live agent (the in-container tmux survives).
+145
View File
@@ -0,0 +1,145 @@
# PR bot: automatic pull-request reviews, reported over Telegram
The PR bot is maintainer tooling that lives in `scripts/pr-bot/`. It watches the
repository's open pull requests, reviews each one in a Codeman claude session running in
a private clone of the repository, and sends the verdict to a Telegram chat with the ranked
findings, a recommendation and action buttons. The maintainer decides what happens next
from the phone: merge, post the drafted review comment, close, approve a waiting CI run,
or ask the reviewer session a follow-up question.
It reviews on its own. It never writes to GitHub on its own.
## How a review runs
1. Every poll (default 10 minutes) the bot lists open PRs with `gh`. A PR is queued
when its head commit differs from the one last reviewed, so a push re-reviews and an
untouched PR is never reviewed twice. Draft PRs and bot PRs are skipped. The backlog
is ordered mergeable-and-small first, conflicting-and-huge last.
2. The PR head is fetched into a private ref (`refs/pr-bot/<n>`) of the main repository
and checked out (detached) in a private clone under
`~/.codeman/pr-bot/worktrees/pr-<n>`, made with `git clone --shared` so the object
store stays shared and nothing is duplicated. The maintainer's own checkout is never
checked out or reset by the bot. A clone rather than a linked worktree because Claude
Code reads a linked worktree's project settings from the MAIN checkout, whose model
pin would silently override the bot's. `node_modules` is a symlink to the main
checkout's tree when the PR itself leaves the dependency files untouched (judged
against the PR's merge base, not against current master), and a real `npm ci`
otherwise (the symlink is unlinked first, so npm can never write through it; an
install interrupted by a restart is discarded, never reused).
3. A review brief is written to `~/.codeman/pr-bot/jobs/pr-<n>/brief.md`: the PR
metadata, CI state, mergeability, the file list, the body verbatim, the ground rules
(nothing reaches GitHub, no installs, no builds, no services, never port 3000), the
review protocol (CLAUDE.md and CONTRIBUTING first, then correctness, security,
invariants, tests, contract, scope), the checks to run, the verdict vocabulary and
the exact JSON to produce.
4. A Codeman session named `prbot-<n>` is created in the clone over the HTTP API,
the composer is awaited (the folder-trust dialog is read off the screen and answered
one key at a time), and one prompt points the session at the brief. The bot waits on
the `stop`/`blocked`/`exit` hook signals, never on the heuristic `idle`, with a hard
timeout (default 40 minutes).
5. The session writes `report.json` and `report.md` next to the brief and replies
`REVIEW COMPLETE`. The bot parses the JSON leniently, records the Claude session id
for follow-ups, deletes the Codeman session, keeps the clone, and sends the
summary to Telegram. Reviews run one at a time.
Verdicts: `merge`, `merge-with-fixes`, `request-changes`, `close`, `needs-discussion`.
Findings are ranked `blocker` / `major` / `minor` / `nit`, each with file and line.
## The Telegram side
Each review arrives as one message: PR number and title, author, size, CI state,
mergeability, the verdict with confidence, the summary, the top findings, the checks
that were run, the recommendation, and buttons:
| Button / command | What it does |
| --- | --- |
| 📄 Full report · `/report N` | Sends `report.md` (as a file when long). |
| 💬 Draft comment · `/draft N` | Shows the comment drafted for the contributor. Nothing is posted. |
| 📮 Post comment · `/post N` | Shows the draft again and asks for confirmation, then posts it under your GitHub account. |
| ✅ Merge · `/merge N` | Re-checks mergeability and CI, lists warnings (red CI, new commits since the review, a non-merge verdict), asks for confirmation, then merges with a merge commit. Refuses a conflicting PR. |
| 🗑 Close · `/close N reason` | Asks for the closing comment if none was given, asks for confirmation, then closes with that comment. |
| ▶️ Approve CI run · `/approve N` | Approves a workflow run that GitHub holds for a first-time contributor. Shown only when one is waiting. |
| 🔁 Re-review · `/review N` | Queues a fresh review at the front of the queue. |
| `/ask N question`, or reply to any review message | Resumes the reviewer's Claude conversation in the same clone and relays the answer. It can inspect, run checks, or make uncommitted changes there; it still never pushes. |
| `/status` · `/scan` · `/pause` · `/resume` · `/help` | Housekeeping. |
Merge, close and post always take a second tap. Confirmations expire after 15 minutes.
Only messages from the configured chat are acted on; anyone else gets silence.
When a PR is merged or closed, the bot announces it, removes the clone and the
private ref, and keeps the record.
## Setup
Requirements on the machine that runs the bot: a running Codeman (the sessions are
spawned there), `gh` logged in as the account that should merge and comment, `git`,
Node 22, and the repository checkout with its `node_modules`.
Config is `~/.codeman/pr-bot.env` (`KEY=VALUE`, keep it mode 0600). The Telegram token
and chat id are read from the existing notifier bot's env file
(`~/codeman-cases/telegram/.env`) when present, so on the maintainer's machine no key
has to be copied; set them here to use a different bot.
| Key | Default | Meaning |
| --- | --- | --- |
| `TELEGRAM_BOT_TOKEN` | from the shared env file | BotFather token. |
| `TELEGRAM_CHAT_ID` | from the shared env file | The one chat that receives reports and may issue commands. |
| `GITHUB_REPO` | `Ark0N/Codeman` | `owner/name`. |
| `CODEMAN_API_URL` | `https://127.0.0.1:3000` | The Codeman that spawns the review sessions. A self-signed certificate is accepted. |
| `CODEMAN_USERNAME` / `CODEMAN_PASSWORD` | unset | Only when that Codeman has a password. |
| `PR_BOT_POLL_INTERVAL` | `600` | Seconds between GitHub polls (minimum 60). |
| `PR_BOT_MAIN_CHECKOUT` | the repo this script is in | The repository the clones share objects with and fetch from. |
| `PR_BOT_DATA_DIR` | `~/.codeman/pr-bot` | State, briefs, reports, clones. |
| `PR_BOT_MODEL` | unset (the session default) | Codeman `modelOverride` for the review sessions, e.g. `claude-fable-5-1`. |
| `PR_BOT_EFFORT` | unset | Codeman `effort` for the review sessions. |
| `PR_BOT_REVIEW_TIMEOUT` | `40` | Minutes before a review is abandoned. |
| `PR_BOT_FOLLOWUP_TIMEOUT` | `20` | Minutes before a follow-up is abandoned. |
| `PR_BOT_AUTO_REVIEW` | `1` | `0` reviews only on `/review N`. |
| `PR_BOT_REVIEW_DRAFTS` | `0` | `1` reviews draft PRs too. |
| `PR_BOT_TELEGRAM_ENV_FILE` | `~/codeman-cases/telegram/.env` | Where the shared token and chat id are read from. |
```bash
npm run pr-bot -- check # config, gh, git, Codeman, Telegram, open PR count
npm run pr-bot -- scan # the open PRs in review order, with what is new
npm run pr-bot -- review 383 --no-telegram # one review now, printed instead of sent
npm run pr-bot -- run # the daemon
npm run pr-bot -- install-service # systemd user unit codeman-pr-bot, enabled and started
npm run pr-bot -- status # what the state file knows
tail -f ~/.codeman/pr-bot/bot.log # the service logs to a file, not the journal
```
## Safety properties worth knowing before changing it
- **GitHub writes happen in exactly one place** (`runConfirmed` in `bot.ts`) and only
after a confirmation tap on a nonce that expires. The review session's brief forbids
`gh` writes, pushes and merges, and the session has no reason to have the token
anyway: it runs as the same user as the maintainer's own sessions, so the prompt rule
is the guard, and the clone's checkout is detached so an accidental push has no
branch to land on.
- **The maintainer's checkout is shared with other agent sessions**, so the bot never
runs `git checkout`, `reset`, `stash` or `clean` there. It only fetches into
`refs/pr-bot/*` there; everything else happens inside the per-PR clone.
- **The clones are `git clone --shared`.** Their objects live in the main checkout, so
the `refs/pr-bot/<n>` ref there is what keeps a PR's commits safe from `git gc`; it
is deleted together with the clone when the PR closes.
- **`node_modules` may be a symlink into the live checkout.** The brief forbids
installs, and `worktree.ts` unlinks the symlink before any `npm ci`. `src/web/public/vendor`
is copied per file, never linked, because postinstall regenerates it in place.
- **Sessions are named `prbot-<n>`** and tracked by id; the bot deletes only those, on
completion, on shutdown, and (by name) as a sweep at startup after a crash. It never
touches the maintainer's `w<n>-*` sessions.
- **Readiness and end-of-turn follow the codeman skill's rules**: composer first
(`shift+tab` in the pane), trust dialog read from the screen, `stop,blocked,exit`
signals rather than `idle`. A session that asks a question is reported as a failed
review with the pane's last lines, not left hanging.
- **Telegram input is data.** Command parsing is a fixed grammar; free text is only ever
relayed to a reviewer session as the maintainer's own follow-up, or used as a closing
comment after confirmation.
Tests: `test/pr-bot-report.test.ts` (parsing, formatting, CI classification, command
grammar, trust-dialog reader, config), `test/pr-bot-state.test.ts`, and
`test/pr-bot-commands.test.ts` (the command and confirmation flows against a stubbed
`gh` and Telegram: a GitHub write happens once, after the tap, never for a foreign chat
or a reused nonce). Type-checked by
`npm run typecheck` through `config/tsconfig.pr-bot.json`, linted and formatted with
the main sources.
+1
View File
@@ -529,6 +529,7 @@ A saved dashboard URL renders as a tab, served through Codeman's own origin at `
| `CODEMAN_PASSWORD` (+ `CODEMAN_USERNAME`) | Enable HTTP Basic auth |
| `--host` / `CODEMAN_HOST` | Bind host (default `127.0.0.1`) |
| `CODEMAN_ALLOWED_HOSTS` | Extra `Host`/`Origin` allowlist entries for reverse proxies (comma‑separated; exact host, or leading‑dot `.suffix` for subdomains) — see §3 |
| `--base-url` / `CODEMAN_BASE_URL` | Sub‑path prefix Codeman is mounted under behind a reverse proxy, e.g. `/codeman` (default `/`); the proxy must forward the prefix unchanged. Independent of `CODEMAN_ALLOWED_HOSTS` |
| `--allow-unauthenticated-network` / `CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK` | Acknowledge an unauthenticated non‑loopback bind (downgrades the warning) |
| `--https` | Enable TLS (adds HSTS) |
| `CODEMAN_INSTANCE` | Scope tmux socket + data dir for isolation |
+42
View File
@@ -167,6 +167,47 @@ and is not one.
Also make sure the proxy forwards WebSocket upgrades. The terminal is a WebSocket, and the
upgrade runs the same Host and Origin checks, closing with code `4003` on failure.
### Mounting under a sub-path
By default Codeman assumes it is served at the origin root (`/`). To mount it under a
sub-path — e.g. `https://example.com/codeman/` — start it with `--base-url` (or the
`CODEMAN_BASE_URL` env var):
```bash
codeman web --base-url /codeman
# or
CODEMAN_BASE_URL=/codeman codeman web
```
The value is a plain path prefix; `/` (the default) means "mounted at the root". With a
prefix set, Codeman emits every URL — the HTML shell and its assets, API/SSE/WebSocket
calls, redirects, the PWA manifest and the service worker — under that prefix, so a browser
loading `https://example.com/codeman/` stays inside the mount.
**Forward the prefix unchanged — do NOT strip it.** Codeman expects the proxy to pass the
full path (including `/codeman/`) straight through. A minimal nginx block:
```nginx
location /codeman/ {
proxy_pass http://127.0.0.1:3000; # note: no trailing slash — keep the /codeman/ prefix
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header Upgrade $http_upgrade; # WebSocket
proxy_set_header Connection "upgrade";
}
```
Notes and current limits:
- The prefix must still be paired with `CODEMAN_ALLOWED_HOSTS` for your domain, exactly as
above — the two are independent.
- Health checks, Claude Code hooks and the docker bridge connect to the raw port directly
(bypassing the proxy), so Codeman also keeps answering at the un-prefixed paths on the port
itself. Nothing about those flows changes.
- **Web-tab (dashboard) proxying** is base-path aware: proxied dashboards have their injected
`<base>` tag, root-absolute asset rewrites, runtime `fetch`/XHR shim, `Set-Cookie` paths, and
redirects all rebased onto the mount, so they load the same under `--base-url` as at the root.
## Session cookies and rate limits
The first request prompts for HTTP Basic credentials. On success the server issues an opaque
@@ -198,6 +239,7 @@ for the full guide.
| Symptom | Cause and fix |
| ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| `403 host not allowed` | Your domain is not in the allowlist. Set `CODEMAN_ALLOWED_HOSTS`. |
| Assets 404 / blank page under a sub-path | Start Codeman with `--base-url /<prefix>` and have the proxy forward the prefix unchanged (don't strip it). |
| Phone shows the login page but the terminal never connects | The proxy is not forwarding WebSocket upgrades. |
| Browser warns about the certificate | Expected with `--https` and its self-signed certificate. Tailscale gives you a real one instead. |
| LAN IP does not respond, but a tunnel to the same box works | The server is bound to loopback. That is the default. A tunnel reaches it; a LAN browser cannot. |
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "aicodeman",
"version": "1.24.7",
"version": "1.25.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "aicodeman",
"version": "1.24.7",
"version": "1.25.0",
"hasInstallScript": true,
"license": "MIT",
"workspaces": [
+8 -7
View File
@@ -1,6 +1,6 @@
{
"name": "aicodeman",
"version": "1.24.7",
"version": "1.25.0",
"description": "Mission control for AI coding agents - run 20 autonomous agents with real-time monitoring and session persistence",
"type": "module",
"main": "dist/index.js",
@@ -28,18 +28,19 @@
"test:mobile": "vitest run --config test/mobile/vitest.config.ts",
"check:frontend-syntax": "node scripts/check-frontend-syntax.mjs",
"fix:node-pty": "node scripts/fix-node-pty.mjs",
"typecheck": "tsc --noEmit",
"lint": "eslint --config config/eslint.config.js 'src/**/*.ts'",
"lint:fix": "eslint --config config/eslint.config.js 'src/**/*.ts' --fix",
"format": "prettier --write 'src/**/*.ts' 'src/web/public/**/*.{js,css,html,json}'",
"format:check": "prettier --check 'src/**/*.ts' 'src/web/public/**/*.{js,css,html,json}'",
"typecheck": "tsc --noEmit && tsc -p config/tsconfig.pr-bot.json",
"lint": "eslint --config config/eslint.config.js 'src/**/*.ts' 'scripts/pr-bot/**/*.ts'",
"lint:fix": "eslint --config config/eslint.config.js 'src/**/*.ts' 'scripts/pr-bot/**/*.ts' --fix",
"format": "prettier --write 'src/**/*.ts' 'scripts/pr-bot/**/*.ts' 'src/web/public/**/*.{js,css,html,json}'",
"format:check": "prettier --check 'src/**/*.ts' 'scripts/pr-bot/**/*.ts' 'src/web/public/**/*.{js,css,html,json}'",
"check:public-assets": "node scripts/check-public-assets.mjs",
"capture:subagents": "node scripts/capture-subagent-screenshots.mjs",
"changeset": "changeset",
"version-packages": "changeset version && npm install --package-lock-only && node scripts/check-lockfile-sync.mjs",
"check:lockfile": "node scripts/check-lockfile-sync.mjs",
"knip": "npx --yes knip@latest --config config/knip.json",
"release": "changeset publish"
"release": "changeset publish",
"pr-bot": "tsx scripts/pr-bot/main.ts"
},
"prettier": {
"singleQuote": true,
File diff suppressed because it is too large Load Diff
+268
View File
@@ -0,0 +1,268 @@
/**
* @fileoverview Codeman HTTP client for the PR bot: spawn a claude session in a
* directory, wait until its composer is up, run one prompt to the END of its turn,
* read the answer, delete the session.
*
* This is the `skills/codeman` §0 preamble translated to TypeScript, and it keeps
* the traps that preamble documents:
* - readiness is the rendered composer (`shift+tab` in the pane), never `idle`;
* - the folder-trust dialog is READ off the screen and answered one keystroke at a
* time (Claude Code 2.1.252 highlights "No, exit" by default, so a blind Enter kills
* the session);
* - send-and-wait waits on `stop,blocked,exit`, never on the flapping `idle`, with a
* short first wait, one Enter nudge for a stranded prompt, and tagged-duplicate
* resends that re-wait without retyping (the server treats an already-applied
* (clientId, seq) frame as "wait only");
* - the bot deletes only sessions it created, by exact id.
*
* The production server is HTTPS with a self-signed certificate on loopback, so the
* undici Agent skips certificate verification for that one connection.
*/
import { Agent, fetch as undiciFetch } from 'undici';
export interface CodemanClientOptions {
apiUrl: string;
username?: string;
password?: string;
}
export interface CreateSessionOptions {
workingDir: string;
name: string;
modelOverride?: string;
effort?: string;
resumeSessionId?: string;
}
export interface WaitResult {
ended: boolean;
timedOut: boolean;
signal?: string;
}
export interface SessionRecord {
id: string;
name: string;
status: string;
pid: number | null;
claudeSessionId?: string | null;
workingDir: string;
mode: string;
}
export type TurnOutcome = { kind: 'stop' } | { kind: 'blocked' } | { kind: 'exit' } | { kind: 'timeout' };
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
export function stripAnsi(text: string): string {
// eslint-disable-next-line no-control-regex
return text.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, '').replace(/\x1b[()][AB0]/g, '');
}
/** Which key answers the trust dialog right now, read from the rendered pane. */
export function trustDialogKey(screen: string): 'confirm' | 'move' | null {
const compact = stripAnsi(screen).replace(/\s+/g, '');
const matches = compact.match(/❯[0-9.]*(yes,itrustthisfolder|no,exit)/gi);
if (!matches || matches.length === 0) return null;
const last = matches[matches.length - 1].toLowerCase();
return last.includes('yes,') ? 'confirm' : 'move';
}
export class CodemanClient {
// headersTimeout/bodyTimeout default to 300 s in undici, which is shorter than one
// long-poll slice on the wait endpoints (up to 580 s): the first review died at
// exactly five minutes with a bare "fetch failed". The per-request AbortSignal is
// the only ceiling here.
private readonly agent = new Agent({ connect: { rejectUnauthorized: false }, headersTimeout: 0, bodyTimeout: 0 });
private readonly authHeader?: string;
constructor(private readonly opts: CodemanClientOptions) {
if (opts.password) {
this.authHeader = 'Basic ' + Buffer.from(`${opts.username || 'admin'}:${opts.password}`).toString('base64');
}
}
private async request<T>(
method: string,
path: string,
body?: unknown,
query?: Record<string, string | number | undefined>,
timeoutMs = 60_000
): Promise<T> {
const url = new URL(this.opts.apiUrl + path);
for (const [k, v] of Object.entries(query ?? {})) if (v !== undefined) url.searchParams.set(k, String(v));
const headers: Record<string, string> = { Accept: 'application/json' };
if (this.authHeader) headers.Authorization = this.authHeader;
if (body !== undefined) headers['Content-Type'] = 'application/json';
let res;
try {
res = await undiciFetch(url, {
method,
headers,
body: body === undefined ? undefined : JSON.stringify(body),
dispatcher: this.agent,
signal: AbortSignal.timeout(timeoutMs),
});
} catch (err) {
const cause = (err as { cause?: { message?: string; code?: string } }).cause;
const detail = cause ? ` (${cause.code ?? ''} ${cause.message ?? ''})`.replace(/\(\s+/, '(').trim() : '';
throw new Error(`${method} ${path}: ${(err as Error).message}${detail}`);
}
const text = await res.text();
let json: { success?: boolean; data?: T; error?: string; errorCode?: string } & Record<string, unknown> = {};
try {
json = text ? JSON.parse(text) : {};
} catch {
throw new Error(`${method} ${path}: non-JSON ${res.status} response: ${text.slice(0, 200)}`);
}
if (!res.ok || json.success === false) {
throw new Error(
`${method} ${path}: ${res.status} ${json.errorCode ?? ''} ${json.error ?? text.slice(0, 200)}`.trim()
);
}
// Most routes use the {success, data} envelope; a few legacy GETs return the raw shape.
return (json.success === true && json.data !== undefined ? json.data : json) as T;
}
async status(): Promise<{ version?: string }> {
return this.request<{ version?: string }>('GET', '/api/status');
}
async listSessions(): Promise<SessionRecord[]> {
const data = await this.request<SessionRecord[] | { sessions: SessionRecord[] }>('GET', '/api/sessions');
return Array.isArray(data) ? data : (data.sessions ?? []);
}
async getSession(id: string): Promise<SessionRecord> {
return this.request<SessionRecord>('GET', `/api/sessions/${id}`);
}
/** Create + start. Creation alone leaves pid null and no pane, so the two are one step here. */
async createInteractiveSession(opts: CreateSessionOptions): Promise<string> {
const created = await this.request<{ session: { id: string } }>('POST', '/api/sessions', {
workingDir: opts.workingDir,
mode: 'claude',
name: opts.name,
modelOverride: opts.modelOverride,
effort: opts.effort,
resumeSessionId: opts.resumeSessionId,
});
const id = created.session?.id;
if (!id) throw new Error('POST /api/sessions returned no session id');
await this.request('POST', `/api/sessions/${id}/interactive`, {});
return id;
}
async deleteSession(id: string): Promise<void> {
if (!id || id.length < 8) throw new Error(`refusing to delete session "${id}"`);
await this.request('DELETE', `/api/sessions/${id}`);
}
async waitOutput(id: string, match: string, from: 'now' | 'buffer', timeoutMs: number): Promise<boolean> {
const data = await this.request<{ wait?: { matched?: boolean } }>(
'GET',
`/api/sessions/${id}/wait-output`,
undefined,
{ match, from, timeout: timeoutMs },
timeoutMs + 15_000
);
return Boolean(data.wait?.matched);
}
async waitSignal(id: string, until: string, timeoutMs: number): Promise<WaitResult> {
const data = await this.request<{ wait?: WaitResult }>(
'GET',
`/api/sessions/${id}/wait`,
undefined,
{ until, timeout: timeoutMs },
timeoutMs + 15_000
);
return data.wait ?? { ended: false, timedOut: true };
}
async terminalText(id: string): Promise<string> {
const data = await this.request<{ terminalBuffer?: string }>('GET', `/api/sessions/${id}/terminal`, undefined, {
full: '1',
});
return data.terminalBuffer ?? '';
}
async sendKeys(id: string, input: string, clientId: string, seq: number): Promise<void> {
await this.request('POST', `/api/sessions/${id}/input`, { input, useMux: true, clientId, seq });
}
async lastResponse(id: string): Promise<string> {
const data = await this.request<{ text?: string }>('GET', `/api/sessions/${id}/last-response`);
return data.text ?? '';
}
/** Composer wait, trust-dialog fallback, composer wait again. Throws when the pane never gets there. */
async ensureReady(id: string, log: (m: string) => void): Promise<void> {
if (await this.waitOutput(id, 'shift+tab', 'buffer', 5000)) return;
for (let i = 1; i <= 6; i++) {
const key = trustDialogKey(await this.terminalText(id));
if (!key) break;
log(`trust dialog on screen: ${key === 'confirm' ? 'Enter' : 'arrow down'}`);
await this.sendKeys(id, key === 'confirm' ? '\r' : '\x1b[B', `prbot-trust-${id}`, i);
if (key === 'confirm') break;
await sleep(1000);
}
if (await this.waitOutput(id, 'shift+tab', 'buffer', 45_000)) return;
throw new Error('the session never drew its composer (no `shift+tab` in the pane after 50s)');
}
/**
* Send ONE prompt and block until the turn ends, the session blocks on a question,
* the pane exits, or `deadlineMs` passes. `isDone` lets the caller finish early on
* an out-of-band signal (the report file appearing), which also covers a stop edge
* that fired between two waits.
*/
async runTurn(
id: string,
prompt: string,
opts: { deadlineMs: number; isDone?: () => boolean; log: (m: string) => void }
): Promise<TurnOutcome> {
if (prompt.includes('\n'))
throw new Error('runTurn prompts must be single-line (embedded newlines are stripped by tmux)');
const clientId = `prbot-${id}`;
const seq = Math.floor(Date.now() / 1000);
const frame = { input: prompt + '\r', useMux: true, clientId, seq, wait: 'stop,blocked,exit', waitTimeout: 20_000 };
const started = Date.now();
const post = (body: unknown, timeout: number) =>
this.request<{ delivered?: boolean; wait?: WaitResult }>(
'POST',
`/api/sessions/${id}/input`,
body,
undefined,
timeout + 15_000
);
let r = await post(frame, 20_000);
if (!r.delivered) throw new Error('the prompt was not delivered (pane dead?)');
let wait = r.wait;
let nudged = false;
while (true) {
if (wait && !wait.timedOut) return toOutcome(wait);
if (opts.isDone?.()) return { kind: 'stop' };
const remaining = opts.deadlineMs - (Date.now() - started);
if (remaining <= 0) return { kind: 'timeout' };
if (!nudged) {
// An Ink repaint occasionally eats the Enter: a bare \r is the missing key when
// the prompt is stranded and a no-op when the turn is genuinely running.
nudged = true;
await this.sendKeys(id, '\r', clientId, seq + 1);
}
const slice = Math.min(remaining, 580_000);
opts.log(`still working (${Math.round((Date.now() - started) / 60_000)} min)`);
r = await post({ ...frame, waitTimeout: slice }, slice);
wait = r.wait;
}
}
}
function toOutcome(wait: WaitResult): TurnOutcome {
const signal = wait.signal ?? '';
if (signal === 'blocked') return { kind: 'blocked' };
if (signal === 'exit') return { kind: 'exit' };
return { kind: 'stop' };
}
+194
View File
@@ -0,0 +1,194 @@
/**
* @fileoverview PR bot configuration.
*
* Read from `~/.codeman/pr-bot.env` (KEY=VALUE lines, mode 0600, the same shape as
* the data dir's `.env`) with the process environment layered on top, then validated
* into a typed config. `parseEnvFile` and `buildConfig` are pure so the validation
* rules are unit-testable without touching the filesystem.
*
* Nothing here reads Codeman's own settings: the bot is maintainer tooling that
* drives a running Codeman over HTTP, it is not part of the server.
*/
import { existsSync, readFileSync } from 'fs';
import { homedir } from 'os';
import { dirname, join, resolve } from 'path';
import { fileURLToPath } from 'url';
export interface PrBotConfig {
/** Telegram bot token from BotFather. */
telegramBotToken: string;
/** The ONE chat the bot talks to and accepts commands from. Everything else is ignored. */
telegramChatId: string;
/** `owner/name` of the repository whose PRs are reviewed. */
githubRepo: string;
/** Codeman server the review sessions are spawned on. */
codemanApiUrl: string;
codemanUsername?: string;
codemanPassword?: string;
/** How often open PRs are listed. */
pollIntervalMs: number;
/** The maintainer's checkout; worktrees are added from its git dir. Never checked out by the bot. */
mainCheckout: string;
/** State, reports and worktrees live under here. */
dataDir: string;
worktreesDir: string;
/** Optional model / effort for the review sessions (Codeman `modelOverride` / `effort`). */
model?: string;
effort?: string;
/** Hard ceiling for one review turn. */
reviewTimeoutMs: number;
/** Hard ceiling for one follow-up turn. */
followupTimeoutMs: number;
/** When false, PRs are only reviewed on an explicit `/review N`. */
autoReview: boolean;
/** Draft PRs are skipped unless this is on. */
reviewDrafts: boolean;
}
export const CONFIG_FILE_NAME = 'pr-bot.env';
/**
* The maintainer's existing Telegram notifier bot (a separate, send-only process)
* keeps its token and chat id here. The PR bot shares that bot identity by default,
* so it reads those two keys from the same file rather than making anyone copy a
* secret around. Override with `PR_BOT_TELEGRAM_ENV_FILE`.
*/
export const DEFAULT_TELEGRAM_ENV_FILE = join('codeman-cases', 'telegram', '.env');
const SHARED_TELEGRAM_KEYS = ['TELEGRAM_BOT_TOKEN', 'TELEGRAM_CHAT_ID'] as const;
/** The keys the env file understands, for `check` and the docs. */
export const CONFIG_KEYS = [
'TELEGRAM_BOT_TOKEN',
'TELEGRAM_CHAT_ID',
'GITHUB_REPO',
'CODEMAN_API_URL',
'CODEMAN_USERNAME',
'CODEMAN_PASSWORD',
'PR_BOT_POLL_INTERVAL',
'PR_BOT_MAIN_CHECKOUT',
'PR_BOT_DATA_DIR',
'PR_BOT_MODEL',
'PR_BOT_EFFORT',
'PR_BOT_REVIEW_TIMEOUT',
'PR_BOT_FOLLOWUP_TIMEOUT',
'PR_BOT_AUTO_REVIEW',
'PR_BOT_REVIEW_DRAFTS',
'PR_BOT_TELEGRAM_ENV_FILE',
] as const;
/** Parse `KEY=VALUE` lines. Comments, blanks, `export ` prefixes and matching quotes are handled. */
export function parseEnvFile(text: string): Record<string, string> {
const out: Record<string, string> = {};
for (const rawLine of text.split(/\r?\n/)) {
const line = rawLine.trim();
if (!line || line.startsWith('#')) continue;
const eq = line.indexOf('=');
if (eq <= 0) continue;
const key = line
.slice(0, eq)
.trim()
.replace(/^export\s+/, '');
let value = line.slice(eq + 1).trim();
if (value.length >= 2) {
const first = value[0];
const last = value[value.length - 1];
if ((first === '"' && last === '"') || (first === "'" && last === "'")) value = value.slice(1, -1);
}
if (/^[A-Z_][A-Z0-9_]*$/.test(key)) out[key] = value;
}
return out;
}
function intFrom(raw: string | undefined, fallback: number, min: number): number {
const n = parseInt(raw ?? '', 10);
if (!Number.isFinite(n) || n <= 0) return fallback;
return Math.max(min, n);
}
function flagFrom(raw: string | undefined, fallback: boolean): boolean {
if (raw === undefined || raw === '') return fallback;
return !['0', 'false', 'no', 'off'].includes(raw.trim().toLowerCase());
}
/** Build the typed config from an env map. Throws with every missing key named at once. */
export function buildConfig(
env: Record<string, string | undefined>,
defaults: { home: string; repoRoot: string }
): PrBotConfig {
const missing: string[] = [];
const telegramBotToken = env.TELEGRAM_BOT_TOKEN?.trim() ?? '';
const telegramChatId = env.TELEGRAM_CHAT_ID?.trim() ?? '';
if (!telegramBotToken) missing.push('TELEGRAM_BOT_TOKEN');
if (!telegramChatId) missing.push('TELEGRAM_CHAT_ID');
if (missing.length) throw new Error(`pr-bot config is missing: ${missing.join(', ')}`);
const githubRepo = env.GITHUB_REPO?.trim() || 'Ark0N/Codeman';
if (!/^[\w.-]+\/[\w.-]+$/.test(githubRepo)) throw new Error(`GITHUB_REPO must be owner/name, got "${githubRepo}"`);
const codemanApiUrl = (env.CODEMAN_API_URL?.trim() || 'https://127.0.0.1:3000').replace(/\/+$/, '');
if (!/^https?:\/\//.test(codemanApiUrl))
throw new Error(`CODEMAN_API_URL must be http(s)://..., got "${codemanApiUrl}"`);
const dataDir = resolve(env.PR_BOT_DATA_DIR?.trim() || join(defaults.home, '.codeman', 'pr-bot'));
const mainCheckout = resolve(env.PR_BOT_MAIN_CHECKOUT?.trim() || defaults.repoRoot);
return {
telegramBotToken,
telegramChatId,
githubRepo,
codemanApiUrl,
codemanUsername: env.CODEMAN_USERNAME?.trim() || undefined,
codemanPassword: env.CODEMAN_PASSWORD || undefined,
pollIntervalMs: intFrom(env.PR_BOT_POLL_INTERVAL, 600, 60) * 1000,
mainCheckout,
dataDir,
worktreesDir: join(dataDir, 'worktrees'),
model: env.PR_BOT_MODEL?.trim() || undefined,
effort: env.PR_BOT_EFFORT?.trim() || undefined,
reviewTimeoutMs: intFrom(env.PR_BOT_REVIEW_TIMEOUT, 40, 5) * 60_000,
followupTimeoutMs: intFrom(env.PR_BOT_FOLLOWUP_TIMEOUT, 20, 2) * 60_000,
autoReview: flagFrom(env.PR_BOT_AUTO_REVIEW, true),
reviewDrafts: flagFrom(env.PR_BOT_REVIEW_DRAFTS, false),
};
}
/** The repository this script lives in (scripts/pr-bot/ -> repo root). */
export function scriptRepoRoot(): string {
return resolve(dirname(fileURLToPath(import.meta.url)), '..', '..');
}
export function configFilePath(): string {
return join(process.env.CODEMAN_DATA_DIR || join(homedir(), '.codeman'), CONFIG_FILE_NAME);
}
export function telegramEnvFilePath(fromFile: Record<string, string>): string {
return resolve(
process.env.PR_BOT_TELEGRAM_ENV_FILE ||
fromFile.PR_BOT_TELEGRAM_ENV_FILE ||
join(homedir(), DEFAULT_TELEGRAM_ENV_FILE)
);
}
/**
* Layers, lowest first: the shared Telegram notifier's `.env` (token + chat id only),
* then `~/.codeman/pr-bot.env`, then the process environment, so a one-off
* `PR_BOT_MODEL=... npx tsx ...` wins over everything.
*/
export function loadConfig(): PrBotConfig {
const file = configFilePath();
const fromFile = existsSync(file) ? parseEnvFile(readFileSync(file, 'utf8')) : {};
const sharedFile = telegramEnvFilePath(fromFile);
const shared = existsSync(sharedFile) ? parseEnvFile(readFileSync(sharedFile, 'utf8')) : {};
const merged: Record<string, string | undefined> = {};
for (const key of SHARED_TELEGRAM_KEYS) if (shared[key]) merged[key] = shared[key];
Object.assign(merged, fromFile);
for (const key of CONFIG_KEYS) {
const v = process.env[key];
if (v !== undefined && v !== '') merged[key] = v;
}
try {
return buildConfig(merged, { home: homedir(), repoRoot: scriptRepoRoot() });
} catch (err) {
throw new Error(`${(err as Error).message} (config file: ${file}; shared Telegram env: ${sharedFile})`);
}
}
+230
View File
@@ -0,0 +1,230 @@
/**
* @fileoverview GitHub access for the PR bot, entirely through the `gh` CLI.
*
* `gh` carries the maintainer's own login, so the bot needs no token of its own and
* every write (merge, close, comment, CI approval) lands under that account. That is
* why every write here is only ever reached from an explicit, confirmed Telegram
* command (see bot.ts); nothing in this file is called on a timer.
*
* `classifyCi` and `latestRunPerWorkflow` are pure and unit-tested.
*/
import { execFile } from 'child_process';
import { promisify } from 'util';
const execFileAsync = promisify(execFile);
export interface PrSummary {
number: number;
title: string;
author: string;
headSha: string;
baseRef: string;
headRef: string;
isDraft: boolean;
mergeable: 'MERGEABLE' | 'CONFLICTING' | 'UNKNOWN';
mergeState: string;
additions: number;
deletions: number;
changedFiles: number;
updatedAt: string;
url: string;
isCrossRepository: boolean;
labels: string[];
}
export interface PrFile {
path: string;
additions: number;
deletions: number;
}
export interface PrDetail extends PrSummary {
body: string;
files: PrFile[];
authorAssociation: string;
linkedIssues: { number: number; title: string }[];
commitCount: number;
commentCount: number;
reviewDecision: string;
headRepo: string;
}
export interface WorkflowRun {
id: number;
name: string;
status: string;
conclusion: string | null;
}
export type CiState = 'passed' | 'failed' | 'pending' | 'awaiting-approval' | 'none';
export interface CiStatus {
state: CiState;
runs: WorkflowRun[];
}
const PR_LIST_FIELDS =
'number,title,author,headRefOid,baseRefName,headRefName,isDraft,mergeable,mergeStateStatus,additions,deletions,changedFiles,updatedAt,url,isCrossRepository,labels';
export async function gh(args: string[], opts: { timeoutMs?: number; input?: string } = {}): Promise<string> {
const child = execFileAsync('gh', args, {
maxBuffer: 32 * 1024 * 1024,
timeout: opts.timeoutMs ?? 60_000,
env: { ...process.env, GH_PROMPT_DISABLED: '1', GH_NO_UPDATE_NOTIFIER: '1' },
});
if (opts.input !== undefined && child.child.stdin) {
child.child.stdin.end(opts.input);
}
const { stdout } = await child;
return stdout;
}
interface RawPr {
number: number;
title: string;
author?: { login?: string };
headRefOid: string;
baseRefName: string;
headRefName: string;
isDraft: boolean;
mergeable: string;
mergeStateStatus: string;
additions: number;
deletions: number;
changedFiles: number;
updatedAt: string;
url: string;
isCrossRepository: boolean;
labels?: { name: string }[];
}
function toSummary(raw: RawPr): PrSummary {
const mergeable = raw.mergeable === 'MERGEABLE' || raw.mergeable === 'CONFLICTING' ? raw.mergeable : 'UNKNOWN';
return {
number: raw.number,
title: raw.title ?? '',
author: raw.author?.login ?? 'unknown',
headSha: raw.headRefOid,
baseRef: raw.baseRefName,
headRef: raw.headRefName,
isDraft: Boolean(raw.isDraft),
mergeable,
mergeState: raw.mergeStateStatus ?? 'UNKNOWN',
additions: raw.additions ?? 0,
deletions: raw.deletions ?? 0,
changedFiles: raw.changedFiles ?? 0,
updatedAt: raw.updatedAt ?? '',
url: raw.url,
isCrossRepository: Boolean(raw.isCrossRepository),
labels: (raw.labels ?? []).map((l) => l.name),
};
}
export async function listOpenPrs(repo: string): Promise<PrSummary[]> {
const out = await gh(['pr', 'list', '--repo', repo, '--state', 'open', '--limit', '100', '--json', PR_LIST_FIELDS]);
const raw = JSON.parse(out) as RawPr[];
return raw.map(toSummary);
}
export async function getPrDetail(repo: string, number: number): Promise<PrDetail> {
const fields = `${PR_LIST_FIELDS},body,files,commits,comments,reviewDecision,closingIssuesReferences,headRepository,headRepositoryOwner`;
const out = await gh(['pr', 'view', String(number), '--repo', repo, '--json', fields]);
const raw = JSON.parse(out) as RawPr & {
body?: string;
files?: { path: string; additions: number; deletions: number }[];
commits?: unknown[];
comments?: unknown[];
reviewDecision?: string;
closingIssuesReferences?: { number: number; title: string }[];
headRepository?: { name?: string };
headRepositoryOwner?: { login?: string };
};
let authorAssociation = 'NONE';
try {
const assoc = await gh(['api', `repos/${repo}/pulls/${number}`, '--jq', '.author_association']);
authorAssociation = assoc.trim() || 'NONE';
} catch {
// Metadata only; a failed lookup must not fail the review.
}
const owner = raw.headRepositoryOwner?.login;
const name = raw.headRepository?.name;
return {
...toSummary(raw),
body: raw.body ?? '',
files: (raw.files ?? []).map((f) => ({ path: f.path, additions: f.additions ?? 0, deletions: f.deletions ?? 0 })),
authorAssociation,
linkedIssues: (raw.closingIssuesReferences ?? []).map((i) => ({ number: i.number, title: i.title })),
commitCount: raw.commits?.length ?? 0,
commentCount: raw.comments?.length ?? 0,
reviewDecision: raw.reviewDecision ?? '',
headRepo: owner && name ? `${owner}/${name}` : '',
};
}
/** The API returns newest first; keep only the newest run of each workflow. */
export function latestRunPerWorkflow(runs: WorkflowRun[]): WorkflowRun[] {
const seen = new Set<string>();
const out: WorkflowRun[] = [];
for (const run of runs) {
if (seen.has(run.name)) continue;
seen.add(run.name);
out.push(run);
}
return out;
}
/**
* Collapse workflow runs into one word the report can show. `action_required` is
* the fork-PR case where GitHub waits for a maintainer to approve the run: the PR
* looks unchecked and stays that way until someone clicks, so it gets its own state.
*/
export function classifyCi(runs: WorkflowRun[]): CiState {
const latest = latestRunPerWorkflow(runs);
if (latest.length === 0) return 'none';
if (latest.some((r) => r.conclusion === 'action_required')) return 'awaiting-approval';
if (latest.some((r) => ['queued', 'in_progress', 'waiting', 'pending', 'requested'].includes(r.status)))
return 'pending';
if (latest.some((r) => ['failure', 'timed_out', 'cancelled', 'startup_failure'].includes(r.conclusion ?? '')))
return 'failed';
if (latest.every((r) => ['success', 'skipped', 'neutral'].includes(r.conclusion ?? ''))) return 'passed';
return 'pending';
}
export async function getCiStatus(repo: string, headSha: string): Promise<CiStatus> {
const out = await gh([
'api',
`repos/${repo}/actions/runs?head_sha=${headSha}&event=pull_request&per_page=30`,
'--jq',
'[.workflow_runs[] | {id, name, status, conclusion}]',
]);
const runs = JSON.parse(out) as WorkflowRun[];
return { state: classifyCi(runs), runs: latestRunPerWorkflow(runs) };
}
export async function approveWorkflowRun(repo: string, runId: number): Promise<void> {
await gh(['api', '-X', 'POST', `repos/${repo}/actions/runs/${runId}/approve`]);
}
/** Merge commits, matching the repository's history (`Merge pull request #N from ...`). */
export async function mergePr(repo: string, number: number): Promise<string> {
return gh(['pr', 'merge', String(number), '--repo', repo, '--merge'], { timeoutMs: 120_000 });
}
export async function closePr(repo: string, number: number, comment: string): Promise<string> {
const args = ['pr', 'close', String(number), '--repo', repo];
if (comment.trim()) args.push('--comment', comment);
return gh(args);
}
export async function commentPr(repo: string, number: number, body: string): Promise<string> {
return gh(['pr', 'comment', String(number), '--repo', repo, '--body-file', '-'], { input: body });
}
export async function ghAuthOk(): Promise<boolean> {
try {
await gh(['auth', 'status']);
return true;
} catch {
return false;
}
}
+281
View File
@@ -0,0 +1,281 @@
#!/usr/bin/env -S npx tsx
/**
* @fileoverview CLI entry for the PR bot.
*
* npx tsx scripts/pr-bot/main.ts run # the daemon (what the service runs)
* npx tsx scripts/pr-bot/main.ts check # config, gh, Codeman, Telegram, git
* npx tsx scripts/pr-bot/main.ts scan # list open PRs and what would be queued
* npx tsx scripts/pr-bot/main.ts review N [--no-telegram] # one review, now
* npx tsx scripts/pr-bot/main.ts status # what the state file knows
* npx tsx scripts/pr-bot/main.ts notify N # resend PR N's review message to Telegram
* npx tsx scripts/pr-bot/main.ts install-service # systemd user unit, enabled + started
* npx tsx scripts/pr-bot/main.ts uninstall-service
*
* User guide: docs/pr-bot.md
*/
import { execFileSync } from 'child_process';
import { existsSync, mkdirSync, writeFileSync } from 'fs';
import { homedir } from 'os';
import { join } from 'path';
import { PrBot, type TelegramLike } from './bot.js';
import { CodemanClient } from './codeman-client.js';
import { configFilePath, loadConfig, type PrBotConfig } from './config.js';
import { ghAuthOk, listOpenPrs } from './github.js';
import { orderBacklog } from './report.js';
import { StateStore } from './state.js';
import { TelegramClient } from './telegram.js';
const SERVICE_NAME = 'codeman-pr-bot';
function log(msg: string): void {
console.log(`${new Date().toISOString()} ${msg}`);
}
/** Prints what the bot would have sent; used by `review --no-telegram`. */
class ConsoleTelegram implements TelegramLike {
private nextId = 1;
isOurChat(): boolean {
return true;
}
async sendMessage(text: string): Promise<number> {
console.log(`\n--- telegram (html) ---\n${text}\n---`);
return this.nextId++;
}
async sendPlain(text: string): Promise<number> {
console.log(`\n--- telegram (plain) ---\n${text}\n---`);
return this.nextId++;
}
async editReplyMarkup(): Promise<void> {}
async deleteMessage(): Promise<void> {}
async answerCallback(): Promise<void> {}
async sendDocument(filename: string, content: string): Promise<void> {
console.log(`\n--- telegram document ${filename} (${content.length} chars) ---`);
}
async getUpdates(): Promise<[]> {
return [];
}
async setMyCommands(): Promise<void> {}
}
function makeCodeman(cfg: PrBotConfig): CodemanClient {
return new CodemanClient({ apiUrl: cfg.codemanApiUrl, username: cfg.codemanUsername, password: cfg.codemanPassword });
}
export function logFilePath(cfg: PrBotConfig): string {
return join(cfg.dataDir, 'bot.log');
}
function unitFile(cfg: PrBotConfig): string {
const tsx = join(cfg.mainCheckout, 'node_modules', '.bin', 'tsx');
// A user service gets a minimal PATH, which is where `gh` (and an nvm/Homebrew
// node) are not: the first run failed its scan with `spawn gh ENOENT`. Bake the
// installing shell's PATH in, as `codeman service install` does.
const seen = new Set<string>();
const path = (process.env.PATH || '/usr/local/bin:/usr/bin:/bin')
.split(':')
.filter((p) => p && !p.endsWith('/node_modules/.bin') && !seen.has(p) && seen.add(p))
.join(':');
return `[Unit]
Description=Codeman PR review bot (Telegram)
After=network-online.target
Wants=network-online.target
StartLimitIntervalSec=300
StartLimitBurst=5
[Service]
Type=simple
WorkingDirectory=${cfg.mainCheckout}
ExecStart=${tsx} scripts/pr-bot/main.ts run
Restart=always
RestartSec=15
Environment=HOME=${homedir()}
Environment=NODE_ENV=production
Environment=PATH=${path}
# A file rather than the journal: on some boxes \`journalctl --user\` cannot read
# the user journal at all, and a review bot whose logs cannot be found is not
# debuggable from a phone.
StandardOutput=append:${logFilePath(cfg)}
StandardError=append:${logFilePath(cfg)}
SyslogIdentifier=${SERVICE_NAME}
[Install]
WantedBy=default.target
`;
}
async function cmdCheck(): Promise<void> {
const cfg = loadConfig();
console.log(
`config file: ${configFilePath()}${existsSync(configFilePath()) ? '' : ' (absent, defaults + shared Telegram env)'}`
);
console.log(`repo: ${cfg.githubRepo}`);
console.log(`codeman: ${cfg.codemanApiUrl}`);
console.log(`main checkout: ${cfg.mainCheckout}`);
console.log(`data dir: ${cfg.dataDir}`);
console.log(`model: ${cfg.model ?? '(session default)'}, effort: ${cfg.effort ?? '(default)'}`);
console.log(
`poll: every ${cfg.pollIntervalMs / 60_000} min; review timeout ${cfg.reviewTimeoutMs / 60_000} min; auto-review ${cfg.autoReview}`
);
let ok = true;
const step = async (name: string, fn: () => Promise<string>) => {
try {
console.log(`✔ ${name}: ${await fn()}`);
} catch (err) {
ok = false;
console.log(`✘ ${name}: ${(err as Error).message}`);
}
};
await step('gh auth', async () =>
(await ghAuthOk()) ? 'logged in' : Promise.reject(new Error('run `gh auth login`'))
);
await step('git', async () =>
execFileSync('git', ['-C', cfg.mainCheckout, 'rev-parse', '--git-dir'], { encoding: 'utf8' }).trim()
);
await step('codeman', async () => {
const s = await makeCodeman(cfg).status();
return `up (version ${s.version ?? 'unknown'})`;
});
await step('telegram', async () => {
const me = await new TelegramClient(cfg.telegramBotToken, cfg.telegramChatId).getMe();
return `@${me.username ?? '?'} for chat ${cfg.telegramChatId}`;
});
await step('open PRs', async () => `${(await listOpenPrs(cfg.githubRepo)).length}`);
if (!ok) process.exit(1);
}
async function cmdScan(): Promise<void> {
const cfg = loadConfig();
const store = new StateStore(join(cfg.dataDir, 'state.json'));
const open = await listOpenPrs(cfg.githubRepo);
const rows = orderBacklog(open).map((pr) => {
const rec = store.pr(pr.number);
const state =
rec?.reviewedSha === pr.headSha ? `reviewed (${rec?.verdict ?? '?'})` : rec?.reviewedSha ? 'updated' : 'new';
const flags = [pr.isDraft ? 'draft' : '', pr.mergeable === 'CONFLICTING' ? 'conflicts' : '']
.filter(Boolean)
.join(', ');
return `#${pr.number}\t${state}\t+${pr.additions}/-${pr.deletions}\t${pr.author}\t${pr.title}${flags ? ` [${flags}]` : ''}`;
});
console.log(`${open.length} open PRs in review order:\n${rows.join('\n')}`);
}
async function cmdStatus(): Promise<void> {
const cfg = loadConfig();
const store = new StateStore(join(cfg.dataDir, 'state.json'));
console.log(`paused: ${store.state.paused}; telegram offset: ${store.state.telegramOffset}`);
for (const rec of Object.values(store.state.prs).sort((a, b) => b.number - a.number)) {
console.log(
`#${rec.number}\t${rec.status}\t${rec.verdict ?? '-'}\t${rec.reviewedSha?.slice(0, 8) ?? '-'}\t${rec.author}\t${rec.title}${
rec.lastError ? `\n\t${rec.lastError.split('\n')[0]}` : ''
}`
);
}
}
async function cmdReview(args: string[]): Promise<void> {
const number = parseInt(args.find((a) => /^\d+$/.test(a)) ?? '', 10);
if (!Number.isFinite(number)) throw new Error('usage: review <pr-number> [--no-telegram]');
const cfg = loadConfig();
const telegram = args.includes('--no-telegram')
? new ConsoleTelegram()
: new TelegramClient(cfg.telegramBotToken, cfg.telegramChatId);
const bot = new PrBot(cfg, { telegram, codeman: makeCodeman(cfg), log });
const rec = await bot.reviewPr(number);
console.log(
`\n#${number}: ${rec.status}${rec.verdict ? ` (${rec.verdict})` : ''}${rec.lastError ? `\n${rec.lastError}` : ''}`
);
if (rec.reportMdPath) console.log(`report: ${rec.reportMdPath}`);
process.exit(rec.status === 'reviewed' ? 0 : 1);
}
async function cmdNotify(args: string[]): Promise<void> {
const number = parseInt(args[0] ?? '', 10);
if (!Number.isFinite(number)) throw new Error('usage: notify <pr-number>');
const cfg = loadConfig();
const bot = new PrBot(cfg, {
telegram: new TelegramClient(cfg.telegramBotToken, cfg.telegramChatId),
codeman: makeCodeman(cfg),
log,
});
const rec = bot.store.pr(number);
if (!rec?.report) throw new Error(`no review of #${number} in ${cfg.dataDir}`);
await bot.sendSummary(rec);
console.log(`sent the review message for #${number}`);
}
async function cmdRun(): Promise<void> {
const cfg = loadConfig();
const bot = new PrBot(cfg, {
telegram: new TelegramClient(cfg.telegramBotToken, cfg.telegramChatId),
codeman: makeCodeman(cfg),
log,
});
let stopping = false;
const shutdown = (signal: string) => {
if (stopping) return;
stopping = true;
log(`${signal}: stopping`);
bot
.stop()
.catch((err) => log(`stop: ${(err as Error).message}`))
.finally(() => process.exit(0));
};
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));
log(`starting: repo ${cfg.githubRepo}, codeman ${cfg.codemanApiUrl}, data ${cfg.dataDir}`);
await bot.start();
}
function cmdInstallService(): void {
const cfg = loadConfig();
const dir = join(homedir(), '.config', 'systemd', 'user');
mkdirSync(dir, { recursive: true });
const path = join(dir, `${SERVICE_NAME}.service`);
mkdirSync(cfg.dataDir, { recursive: true });
writeFileSync(path, unitFile(cfg));
execFileSync('systemctl', ['--user', 'daemon-reload'], { stdio: 'inherit' });
execFileSync('systemctl', ['--user', 'enable', SERVICE_NAME], { stdio: 'inherit' });
// `restart` rather than `enable --now`: a re-install must pick up the new unit.
execFileSync('systemctl', ['--user', 'restart', SERVICE_NAME], { stdio: 'inherit' });
console.log(`installed ${path}\nlogs: tail -f ${logFilePath(cfg)}`);
}
function cmdUninstallService(): void {
const path = join(homedir(), '.config', 'systemd', 'user', `${SERVICE_NAME}.service`);
execFileSync('systemctl', ['--user', 'disable', '--now', SERVICE_NAME], { stdio: 'inherit' });
if (existsSync(path)) execFileSync('rm', ['-f', path]);
execFileSync('systemctl', ['--user', 'daemon-reload'], { stdio: 'inherit' });
console.log(`removed ${SERVICE_NAME}`);
}
async function main(): Promise<void> {
const [cmd = 'run', ...rest] = process.argv.slice(2);
switch (cmd) {
case 'run':
return cmdRun();
case 'check':
return cmdCheck();
case 'scan':
return cmdScan();
case 'status':
return cmdStatus();
case 'review':
return cmdReview(rest);
case 'notify':
return cmdNotify(rest);
case 'install-service':
return cmdInstallService();
case 'uninstall-service':
return cmdUninstallService();
default:
console.error(
'usage: main.ts run | check | scan | status | review <N> [--no-telegram] | install-service | uninstall-service'
);
process.exit(2);
}
}
main().catch((err) => {
console.error((err as Error).stack ?? String(err));
process.exit(1);
});
+368
View File
@@ -0,0 +1,368 @@
/**
* @fileoverview Pure report handling: parse the reviewer's JSON (leniently, it is
* model output), render the Telegram summary (HTML, under the 4096-char cap), the
* status list, the inline keyboard, and the backlog order. Unit-tested.
*/
import type { CiState, PrSummary } from './github.js';
import { VERDICTS, type Verdict } from './review-task.js';
export type Severity = 'blocker' | 'major' | 'minor' | 'nit';
export interface Finding {
severity: Severity;
title: string;
file?: string;
line?: number;
detail: string;
invariant?: string;
}
export interface CheckResult {
name: string;
command?: string;
result: 'pass' | 'fail' | 'skipped';
notes?: string;
}
export interface ReviewReport {
verdict: Verdict;
confidence: 'high' | 'medium' | 'low';
summary: string;
changes: string[];
findings: Finding[];
checks: CheckResult[];
scope: 'focused' | 'mixed';
risk: string;
recommendation: string;
draftComment: string;
assumptions: string[];
}
export const TELEGRAM_MAX = 4096;
/** Leave room for HTML tags the counter cannot see and for the keyboard-less fallback. */
const SUMMARY_BUDGET = 3600;
const SEVERITY_ORDER: Severity[] = ['blocker', 'major', 'minor', 'nit'];
const SEVERITY_ICON: Record<Severity, string> = { blocker: '🔴', major: '🟠', minor: '🟡', nit: '⚪' };
const VERDICT_LABEL: Record<Verdict, string> = {
merge: '✅ MERGE',
'merge-with-fixes': '🟢 MERGE WITH FIXES',
'request-changes': '🟠 REQUEST CHANGES',
close: '❌ CLOSE',
'needs-discussion': '💬 NEEDS DISCUSSION',
};
const CI_LABEL: Record<CiState, string> = {
passed: 'CI ✅',
failed: 'CI ❌',
pending: 'CI ⏳',
'awaiting-approval': 'CI ⏸ needs your approval',
none: 'CI none',
};
export function escapeHtml(s: string): string {
return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
function str(v: unknown, fallback = ''): string {
return typeof v === 'string' ? v : fallback;
}
function strList(v: unknown): string[] {
if (!Array.isArray(v)) return [];
return v.filter((x): x is string => typeof x === 'string' && x.trim().length > 0);
}
/** Extract the first JSON object from text that may carry fences or prose around it. */
export function extractJsonObject(text: string): unknown {
const trimmed = text.trim();
try {
return JSON.parse(trimmed);
} catch {
// fall through
}
const fence = trimmed.match(/```(?:json)?\s*([\s\S]*?)```/);
if (fence) {
try {
return JSON.parse(fence[1]);
} catch {
// fall through
}
}
const start = trimmed.indexOf('{');
const end = trimmed.lastIndexOf('}');
if (start >= 0 && end > start) {
try {
return JSON.parse(trimmed.slice(start, end + 1));
} catch {
return null;
}
}
return null;
}
/** Normalize model output into a ReviewReport. Returns null only when there is no verdict at all. */
export function parseReport(raw: unknown): ReviewReport | null {
if (!raw || typeof raw !== 'object') return null;
const o = raw as Record<string, unknown>;
const verdictRaw = str(o.verdict).trim().toLowerCase().replace(/[_ ]/g, '-');
const verdict = (VERDICTS as readonly string[]).includes(verdictRaw) ? (verdictRaw as Verdict) : null;
if (!verdict) return null;
const confidenceRaw = str(o.confidence).trim().toLowerCase();
const confidence = confidenceRaw === 'high' || confidenceRaw === 'low' ? confidenceRaw : 'medium';
const findings: Finding[] = [];
if (Array.isArray(o.findings)) {
for (const f of o.findings) {
if (!f || typeof f !== 'object') continue;
const fo = f as Record<string, unknown>;
const sevRaw = str(fo.severity).trim().toLowerCase();
const severity = (SEVERITY_ORDER as string[]).includes(sevRaw) ? (sevRaw as Severity) : 'minor';
const title = str(fo.title).trim();
if (!title) continue;
const line = typeof fo.line === 'number' && Number.isFinite(fo.line) ? Math.trunc(fo.line) : undefined;
findings.push({
severity,
title,
file: str(fo.file).trim() || undefined,
line,
detail: str(fo.detail).trim(),
invariant: str(fo.invariant).trim() || undefined,
});
}
}
findings.sort((a, b) => SEVERITY_ORDER.indexOf(a.severity) - SEVERITY_ORDER.indexOf(b.severity));
const checks: CheckResult[] = [];
if (Array.isArray(o.checks)) {
for (const c of o.checks) {
if (!c || typeof c !== 'object') continue;
const co = c as Record<string, unknown>;
const name = str(co.name).trim();
if (!name) continue;
const resRaw = str(co.result).trim().toLowerCase();
const result = resRaw === 'pass' || resRaw === 'fail' ? resRaw : 'skipped';
checks.push({
name,
command: str(co.command).trim() || undefined,
result,
notes: str(co.notes).trim() || undefined,
});
}
}
return {
verdict,
confidence,
summary: str(o.summary).trim(),
changes: strList(o.changes),
findings,
checks,
scope: str(o.scope).trim().toLowerCase() === 'mixed' ? 'mixed' : 'focused',
risk: str(o.risk).trim(),
recommendation: str(o.recommendation).trim(),
draftComment: str(o.draftComment).trim(),
assumptions: strList(o.assumptions),
};
}
export function countBySeverity(findings: Finding[]): Record<Severity, number> {
const out: Record<Severity, number> = { blocker: 0, major: 0, minor: 0, nit: 0 };
for (const f of findings) out[f.severity]++;
return out;
}
function findingLine(f: Finding): string {
const where = f.file ? ` <code>${escapeHtml(f.file)}${f.line ? `:${f.line}` : ''}</code>` : '';
return `${SEVERITY_ICON[f.severity]} ${escapeHtml(f.title)}${where}`;
}
function checksLine(checks: CheckResult[]): string {
if (!checks.length) return '';
const parts = checks.map((c) => {
const icon = c.result === 'pass' ? '✅' : c.result === 'fail' ? '❌' : '⏭';
return `${escapeHtml(c.name)} ${icon}`;
});
return `<b>Checks:</b> ${parts.join(' · ')}`;
}
function truncate(text: string, max: number): string {
if (text.length <= max) return text;
return text.slice(0, Math.max(0, max - 1)).trimEnd() + '…';
}
export interface SummaryMeta {
ci: CiState;
/** Time the review took, for the footer. */
durationMin?: number;
}
/** The message the maintainer reads on the phone. HTML parse mode. */
export function formatTelegramSummary(pr: PrSummary, report: ReviewReport, meta: SummaryMeta): string {
const header =
`🔍 <b>PR #${pr.number}</b> · ${escapeHtml(truncate(pr.title, 120))}\n` +
`<i>by ${escapeHtml(pr.author)} · +${pr.additions}/−${pr.deletions} · ${pr.changedFiles} files · ${CI_LABEL[meta.ci]} · ${
pr.mergeable === 'CONFLICTING'
? 'conflicts ⚠️'
: pr.mergeable === 'MERGEABLE'
? 'mergeable'
: 'mergeability unknown'
}${pr.isDraft ? ' · draft' : ''}</i>\n` +
`<a href="${escapeHtml(pr.url)}">${escapeHtml(pr.url)}</a>\n`;
const verdict = `\n<b>${VERDICT_LABEL[report.verdict]}</b> <i>(confidence ${report.confidence}${report.scope === 'mixed' ? ', mixed scope' : ''})</i>\n`;
const summary = report.summary ? `\n${escapeHtml(report.summary)}\n` : '';
const counts = countBySeverity(report.findings);
const countStr = SEVERITY_ORDER.filter((s) => counts[s] > 0)
.map((s) => `${counts[s]} ${s}${counts[s] === 1 ? '' : 's'}`)
.join(', ');
const findingsHeader = report.findings.length ? `\n<b>Findings</b> (${countStr}):\n` : '\n<b>Findings:</b> none\n';
const checks = checksLine(report.checks);
const recommendation = report.recommendation ? `\n<b>Recommendation:</b> ${escapeHtml(report.recommendation)}\n` : '';
const footer = meta.durationMin !== undefined ? `\n<i>review took ${meta.durationMin} min</i>` : '';
const fixed = header + verdict + summary + findingsHeader;
const tail = (checks ? `\n${checks}\n` : '') + recommendation + footer;
let budget = SUMMARY_BUDGET - fixed.length - tail.length;
const lines: string[] = [];
let shown = 0;
for (const f of report.findings) {
const line = findingLine(f) + '\n';
if (line.length > budget) break;
lines.push(line);
budget -= line.length;
shown++;
}
const hidden = report.findings.length - shown;
const more = hidden > 0 ? `<i>… ${hidden} more in the full report</i>\n` : '';
return fixed + lines.join('') + more + tail;
}
export function formatReviewFailure(
pr: Pick<PrSummary, 'number' | 'title' | 'author' | 'url'>,
reason: string
): string {
return (
`⚠️ <b>PR #${pr.number}</b> · ${escapeHtml(truncate(pr.title, 120))}\n` +
`<i>by ${escapeHtml(pr.author)}</i>\n<a href="${escapeHtml(pr.url)}">${escapeHtml(pr.url)}</a>\n\n` +
`The review did not complete: ${escapeHtml(truncate(reason, 1500))}\n\n` +
`Use /review ${pr.number} to try again.`
);
}
/** Split on line boundaries so no chunk exceeds Telegram's cap. */
export function splitTelegramMessage(text: string, max = TELEGRAM_MAX): string[] {
if (text.length <= max) return [text];
const chunks: string[] = [];
let current = '';
for (const line of text.split('\n')) {
let piece = line;
while (piece.length > max) {
if (current) {
chunks.push(current);
current = '';
}
chunks.push(piece.slice(0, max));
piece = piece.slice(max);
}
const candidate = current ? `${current}\n${piece}` : piece;
if (candidate.length > max) {
chunks.push(current);
current = piece;
} else {
current = candidate;
}
}
if (current) chunks.push(current);
return chunks;
}
export interface InlineButton {
text: string;
callback_data: string;
}
/** Callback data is capped at 64 bytes by Telegram; these stay far under it. */
export function buildReportKeyboard(prNumber: number, opts: { ci: CiState; hasDraft: boolean }): InlineButton[][] {
const rows: InlineButton[][] = [
[
{ text: '📄 Full report', callback_data: `report:${prNumber}` },
...(opts.hasDraft ? [{ text: '💬 Draft comment', callback_data: `draft:${prNumber}` }] : []),
{ text: '🔁 Re-review', callback_data: `review:${prNumber}` },
],
[
{ text: '✅ Merge', callback_data: `merge:${prNumber}` },
...(opts.hasDraft ? [{ text: '📮 Post comment', callback_data: `post:${prNumber}` }] : []),
{ text: '🗑 Close', callback_data: `close:${prNumber}` },
],
];
if (opts.ci === 'awaiting-approval')
rows.push([{ text: '▶️ Approve CI run', callback_data: `approveci:${prNumber}` }]);
return rows;
}
export function confirmKeyboard(action: string, prNumber: number, nonce: string): InlineButton[][] {
return [
[
{ text: `Yes, ${action} #${prNumber}`, callback_data: `confirm:${action}:${prNumber}:${nonce}` },
{ text: 'Cancel', callback_data: `cancel:${action}:${prNumber}:${nonce}` },
],
];
}
export interface StatusRow {
number: number;
title: string;
author: string;
verdict?: Verdict;
status: string;
ci?: CiState;
mergeable: PrSummary['mergeable'];
isDraft: boolean;
}
export function formatStatusList(rows: StatusRow[], paused: boolean): string {
if (!rows.length) return 'No open pull requests.';
const lines = rows.map((r) => {
const v = r.verdict
? VERDICT_LABEL[r.verdict].split(' ')[0]
: r.status === 'reviewing'
? '⏳'
: r.status === 'queued'
? '🕓'
: '·';
const flags = [
r.ci ? CI_LABEL[r.ci].replace('CI ', '') : '',
r.mergeable === 'CONFLICTING' ? 'conflicts' : '',
r.isDraft ? 'draft' : '',
]
.filter(Boolean)
.join(', ');
return `${v} <b>#${r.number}</b> ${escapeHtml(truncate(r.title, 60))} <i>(${escapeHtml(r.author)}${flags ? `; ${flags}` : ''})</i>`;
});
return `${paused ? '⏸ auto-review paused\n' : ''}<b>Open PRs (${rows.length})</b>\n${lines.join('\n')}`;
}
/**
* Backlog order for a fresh sweep: the ones you can act on first (mergeable, small),
* conflicting and huge ones last. Ties keep the newer PR first.
*/
export function orderBacklog<T extends Pick<PrSummary, 'number' | 'mergeable' | 'additions' | 'deletions'>>(
prs: T[]
): T[] {
const size = (p: T) => p.additions + p.deletions;
return [...prs].sort((a, b) => {
const ca = a.mergeable === 'CONFLICTING' ? 1 : 0;
const cb = b.mergeable === 'CONFLICTING' ? 1 : 0;
if (ca !== cb) return ca - cb;
const sa = size(a);
const sb = size(b);
if (sa !== sb) return sa - sb;
return b.number - a.number;
});
}
export function verdictLabel(v: Verdict): string {
return VERDICT_LABEL[v];
}
+241
View File
@@ -0,0 +1,241 @@
/**
* @fileoverview The review brief handed to each reviewer session, and the follow-up
* brief. Pure: the bot writes the result to a file and sends the session one short
* line pointing at it (prompts are single-line over tmux, and a brief this size
* belongs on disk anyway).
*
* The brief is opinionated on purpose. It names the repository's own rules (CLAUDE.md,
* CONTRIBUTING.md), the checks to run, the verdict vocabulary, and the exact JSON the
* bot parses. Everything the maintainer would say out loud before delegating a
* review lives here.
*/
import type { CiStatus, PrDetail } from './github.js';
export const VERDICTS = ['merge', 'merge-with-fixes', 'request-changes', 'close', 'needs-discussion'] as const;
export type Verdict = (typeof VERDICTS)[number];
export interface ReviewBriefInput {
pr: PrDetail;
ci: CiStatus;
mergeBase: string;
worktreeDir: string;
mainCheckout: string;
reportJsonPath: string;
reportMdPath: string;
}
function ciLine(ci: CiStatus): string {
const detail = ci.runs.map((r) => `${r.name}: ${r.conclusion ?? r.status}`).join(', ');
switch (ci.state) {
case 'passed':
return `passed (${detail})`;
case 'failed':
return `FAILED (${detail}); read the failing job's log with \`gh run view <id> --log-failed\` before you trust or dismiss it`;
case 'pending':
return `still running (${detail})`;
case 'awaiting-approval':
return 'never ran: the workflow is waiting for a maintainer to approve it (first-time contributor), so run the checks yourself';
default:
return 'no workflow runs found for this head (a conflicting PR gets no CI at all); run the checks yourself';
}
}
export function buildReviewBrief(input: ReviewBriefInput): string {
const { pr, ci, mergeBase, worktreeDir, mainCheckout, reportJsonPath, reportMdPath } = input;
const files = pr.files.map((f) => `- \`${f.path}\` (+${f.additions}/-${f.deletions})`).join('\n');
const linked = pr.linkedIssues.length
? pr.linkedIssues.map((i) => `- #${i.number} ${i.title}`).join('\n')
: '- none linked';
const mergeability =
pr.mergeable === 'CONFLICTING'
? 'CONFLICTING with master. It cannot be merged as-is and GitHub runs no CI for it. Review the PR head as it stands, and say in the report whether the conflicts look mechanical or structural (`git merge-tree` against origin/master helps).'
: pr.mergeable === 'MERGEABLE'
? 'mergeable'
: 'unknown (GitHub has not computed it yet)';
return `# Review brief: PR #${pr.number} ${pr.title}
You are reviewing a pull request against Codeman on behalf of the maintainer. You are
in a private clone at \`${worktreeDir}\`, checked out (detached) at the PR head. The
maintainer reads your report on a phone and decides what happens next, so write for
someone who has not seen the diff.
## Ground rules (read twice)
- Nothing you do here reaches GitHub. Do NOT push, comment, merge, close, label, or
create anything with \`gh\`; \`gh\` is for READING only (\`gh pr view\`, \`gh run view\`,
\`gh api\` GETs).
- Do NOT run \`npm install\`, \`npm ci\`, \`npm update\` or \`npm run build\`: \`node_modules\`
may be a symlink into the maintainer's live checkout. Everything else in package.json
scripts is fine (\`npm run typecheck\`, \`npm run lint\`, \`npm test -- <file>\`, ...).
- Do NOT restart, stop or install any service, and never bind port 3000: the
maintainer's production Codeman runs there. Test ports are 3150 and up.
- \`${mainCheckout}\` is the maintainer's shared checkout. You may READ it for comparison;
never run a git command there that changes anything (no checkout, reset, stash, clean).
- Stay inside this clone for writes. Do not create files elsewhere except the two
report files named below.
- Do not ask questions. Nobody is watching this session. Where something is ambiguous,
decide, and list the assumption in the report.
## The pull request
- **#${pr.number}** ${pr.title}
- Author: ${pr.author} (${pr.authorAssociation.toLowerCase().replace(/_/g, ' ')})${pr.headRepo ? `, from \`${pr.headRepo}\`` : ''}
- URL: ${pr.url}
- Base: \`${pr.baseRef}\` at merge base \`${mergeBase.slice(0, 12)}\`; head: \`${pr.headSha.slice(0, 12)}\` (${pr.commitCount} commits)
- Size: +${pr.additions} / -${pr.deletions} across ${pr.changedFiles} files
- Mergeability: ${mergeability}
- CI: ${ciLine(ci)}
- Draft: ${pr.isDraft ? 'yes' : 'no'}; existing comments: ${pr.commentCount}${pr.labels.length ? `; labels: ${pr.labels.join(', ')}` : ''}
### Linked issues
${linked}
### Files changed
${files || '- (none reported)'}
### PR description, verbatim
\`\`\`text
${pr.body.trim() || '(empty)'}
\`\`\`
## How to review
1. Read \`CLAUDE.md\` at the root and \`.github/CONTRIBUTING.md\`. Most review feedback on
this repository traces back to a rule already written there, and a change that
contradicts one of those rules is a finding even when the code works. Open the
\`docs/architecture-invariants.md\` sections the change touches.
2. Understand the change: \`git log --oneline ${mergeBase.slice(0, 12)}..HEAD\` and
\`git diff ${mergeBase.slice(0, 12)}..HEAD\`. Read the surrounding code, not only the
hunks: the file's \`@fileoverview\` first, then the call sites of anything changed.
3. Look for, in this order: correctness bugs (wrong logic, races, missed error paths,
lost state across restart); security (auth and ownership checks, path confinement,
the env-prefix allowlist, shell/command injection, SSRF, secrets on the command
line or in state files); violations of CLAUDE.md rules (cite the rule); behaviour
changes without tests; contract changes (\`/api/v1\` paths, response envelope,
\`errorCode\` values, SSE event names are public and stable, see
\`docs/versioning-policy.md\`); scope (one change per PR: flag unrelated changes
bundled in); docs and registries that must move with the code (CLAUDE.md and
architecture-invariants when a rule changes, \`sse-events.ts\` and \`constants.js\`
parity, \`docs/api-reference.md\`); housekeeping that does not belong in a PR
(version bumps, CHANGELOG edits, files pulled back into Prettier's scope, committed
vendor bundles, changeset files are fine).
4. Run the checks and record what you ran and what came back:
\`npm run typecheck\`, \`npm run lint\`, \`npm run check:frontend-syntax\`,
\`npm run format:check\`, then the tests covering the touched areas
(\`npm test -- test/<file>.test.ts\`, several files at once is fine). Run the full
\`npm test\` when the change is broad or touches shared infrastructure (session,
tmux, routes, state); it takes minutes, which is acceptable. A red check that is
also red on origin/master is not the PR's fault: say so rather than blaming it.
Other test suites may be running on this machine at the same time and they share
the 3150+ port range, so re-run a failed file on its own (\`npm test -- <file>\`)
before you read an EADDRINUSE or a timeout as the PR's regression.
5. Verify before you report. A finding that could be a misread must be confirmed by
reading the full code path, by a tiny test, or by running it. Every finding names a
file and line. Rank: **blocker** (must be fixed before merge: data loss, security,
breaks a documented invariant, breaks the build or tests), **major** (should be
fixed: a real bug in an edge the PR introduces, a missing test for new behaviour),
**minor**, **nit**.
6. Judge the PR, not the author. Contributors here are volunteers and the maintainer
thanks them by name in every release; be exact and be kind.
## Verdict vocabulary
- \`merge\`: no blockers or majors, checks green; merge as-is.
- \`merge-with-fixes\`: mergeable, but with small things the maintainer would rather fix
at merge time than round-trip (list them so they can be applied on top).
- \`request-changes\`: blockers or majors the author should fix.
- \`close\`: wrong direction, superseded, or not wanted; say what should happen instead.
- \`needs-discussion\`: a design question the maintainer must answer before anyone
spends more time (name the question).
## Output, mandatory
Write BOTH files, then reply with exactly one line: \`REVIEW COMPLETE\`.
1. \`${reportJsonPath}\`: a single JSON object, no markdown fences, this shape:
\`\`\`json
{
"verdict": "merge | merge-with-fixes | request-changes | close | needs-discussion",
"confidence": "high | medium | low",
"summary": "Two or three sentences: what the PR does, and the review's bottom line.",
"changes": ["one bullet per thing the PR actually changes"],
"findings": [
{
"severity": "blocker | major | minor | nit",
"title": "one line",
"file": "path/from/repo/root.ts",
"line": 123,
"detail": "what is wrong, why it matters, what to do instead",
"invariant": "the CLAUDE.md / CONTRIBUTING rule it breaks, or omit"
}
],
"checks": [
{ "name": "typecheck", "command": "npm run typecheck", "result": "pass | fail | skipped", "notes": "" }
],
"_checks_note": "result is from the PR's point of view: a regression test you deliberately ran against master to prove it fails is a pass (say so in notes), a red run caused by another suite on the machine is skipped with the reason, only a genuine problem with the PR is fail",
"scope": "focused | mixed",
"risk": "One or two sentences naming the judgment calls a second reviewer should look at.",
"recommendation": "Two to four sentences for the maintainer: what to do next and why.",
"draftComment": "A comment to the contributor, in markdown, ready to post (rules below).",
"assumptions": ["anything you had to decide alone"]
}
\`\`\`
2. \`${reportMdPath}\`: the full report in markdown for the maintainer, in this order:
what the PR does; the verdict with the reasoning; findings in severity order with
file:line and the fix; checks run with results; CLAUDE.md rules touched; scope and
risk; recommendation; assumptions. Include the diff stat. No length limit, but no
padding either.
### Draft comment rules
The draft is written AS the maintainer TO the contributor and must stand alone: the
reader has not seen this brief. Open by thanking them and saying in one sentence what
the PR does. Then the findings that need action, each with file:line and the concrete
ask, blockers first. Close with what happens next (merge after fixes, will fix at merge
time, and so on). When the verdict is \`merge\`, the whole comment is a short thank-you
naming anything you would touch at merge time. Plain markdown. No em-dashes (use
commas, colons or parentheses). No emojis. No "Generated with Claude Code" or similar
attribution line. No hedging words. The maintainer reads it before it is posted and may
edit it.
`;
}
/** Sent as ONE line; the brief above is on disk. */
export function reviewKickoffLine(briefPath: string): string {
return `Read ${briefPath} and carry out the review it describes. Do not ask questions. Finish by writing both report files it names, then reply with exactly: REVIEW COMPLETE`;
}
export function followupKickoffLine(followupPath: string): string {
return `Read ${followupPath}: it holds a follow-up from the maintainer about the pull request you reviewed. Do what it asks within the ground rules of the original brief (no pushing, no gh writes, no npm install, no builds, no services), then answer in plain text. Do not ask questions.`;
}
export function buildFollowupBrief(input: {
prNumber: number;
title: string;
instruction: string;
worktreeDir: string;
reportMdPath: string;
briefPath: string;
}): string {
return `# Follow-up on PR #${input.prNumber} ${input.title}
The maintainer read your review report (\`${input.reportMdPath}\`; the original brief is
\`${input.briefPath}\`, and its ground rules still apply: nothing reaches GitHub, no
installs, no builds, no services, writes stay inside \`${input.worktreeDir}\`).
Their message:
\`\`\`text
${input.instruction.trim()}
\`\`\`
Answer concisely and concretely, for a phone screen: lead with the answer, then the
evidence (commands run, file:line). If the message asks you to change code, make the
change in this clone, run the relevant checks, and describe the diff (\`git diff
--stat\` plus the essential hunks). Keep the changes uncommitted unless asked to commit;
never push. If it asks for something outside the ground rules, say so and stop.
`;
}
+166
View File
@@ -0,0 +1,166 @@
/**
* @fileoverview The bot's persisted state: one record per PR (what was reviewed at
* which head, the parsed report, the Claude session to resume for follow-ups, the
* Telegram messages that belong to it), the Telegram update offset, pending
* confirmations, and the pause flag. One JSON file, written atomically (tmp + rename)
* with mode 0600, since reports quote code and draft comments.
*/
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'fs';
import { dirname, join } from 'path';
import type { CiState, PrSummary } from './github.js';
import type { ReviewReport } from './report.js';
import type { Verdict } from './review-task.js';
export type PrStatus = 'new' | 'queued' | 'reviewing' | 'reviewed' | 'failed' | 'skipped' | 'closed';
export interface PrRecord {
number: number;
title: string;
author: string;
url: string;
headSha: string;
isDraft: boolean;
mergeable: PrSummary['mergeable'];
additions?: number;
deletions?: number;
changedFiles?: number;
status: PrStatus;
ci?: CiState;
reviewedSha?: string;
reviewedAt?: string;
reviewDurationMin?: number;
verdict?: Verdict;
report?: ReviewReport;
briefPath?: string;
reportJsonPath?: string;
reportMdPath?: string;
/** The Claude conversation to resume for follow-ups. */
claudeSessionId?: string;
/** The live Codeman session while a turn is running; cleared afterwards. */
activeSessionId?: string;
worktreeDir?: string;
telegramMessageId?: number;
lastError?: string;
/** Consecutive failed attempts at `failedSha`; the scan stops auto-retrying at MAX_AUTO_RETRIES. */
failedAttempts?: number;
failedSha?: string;
closedAs?: 'merged' | 'closed';
updatedAt: string;
}
export interface PendingConfirm {
action: 'merge' | 'close' | 'post';
prNumber: number;
createdAt: string;
messageId?: number;
/** Closing comment for `close`. */
reason?: string;
}
export interface BotState {
version: 1;
paused: boolean;
telegramOffset: number;
prs: Record<string, PrRecord>;
pending: Record<string, PendingConfirm>;
/** Telegram message id -> PR number, so a reply to any of the bot's messages finds its PR. */
messages: Record<string, number>;
/** Telegram message id -> PR number for "reply with the closing reason" prompts. */
reasonPrompts: Record<string, number>;
}
export function emptyState(): BotState {
return { version: 1, paused: false, telegramOffset: 0, prs: {}, pending: {}, messages: {}, reasonPrompts: {} };
}
const MAX_MESSAGE_MAP = 2000;
export class StateStore {
state: BotState;
constructor(private readonly path: string) {
this.state = emptyState();
if (existsSync(path)) {
try {
const parsed = JSON.parse(readFileSync(path, 'utf8')) as Partial<BotState>;
this.state = { ...emptyState(), ...parsed, version: 1 };
} catch (err) {
throw new Error(`state file ${path} is unreadable: ${(err as Error).message}`);
}
}
}
save(): void {
mkdirSync(dirname(this.path), { recursive: true });
this.pruneMessageMap();
const tmp = join(dirname(this.path), `.state.${process.pid}.${Date.now()}.tmp`);
writeFileSync(tmp, JSON.stringify(this.state, null, 2), { mode: 0o600 });
renameSync(tmp, this.path);
}
pr(number: number): PrRecord | undefined {
return this.state.prs[String(number)];
}
/**
* Refresh a PR's metadata, keeping its review. Mutates the EXISTING record in place:
* a review in flight holds a reference to it, and a scan that replaced the object
* with a copy made that review write its verdict into an orphan (first daemon run:
* PR 363 reported to Telegram, state still said `reviewing`).
*/
upsertPr(summary: PrSummary): PrRecord {
const key = String(summary.number);
const existing = this.state.prs[key];
const record: PrRecord = existing ?? {
number: summary.number,
title: summary.title,
author: summary.author,
url: summary.url,
headSha: summary.headSha,
isDraft: summary.isDraft,
mergeable: summary.mergeable,
status: 'new',
updatedAt: new Date().toISOString(),
};
record.title = summary.title;
record.author = summary.author;
record.url = summary.url;
record.headSha = summary.headSha;
record.isDraft = summary.isDraft;
record.mergeable = summary.mergeable;
record.additions = summary.additions;
record.deletions = summary.deletions;
record.changedFiles = summary.changedFiles;
if (record.status === 'closed') {
// Reopened.
record.status = record.reviewedSha ? 'reviewed' : 'new';
record.closedAs = undefined;
}
record.updatedAt = new Date().toISOString();
this.state.prs[key] = record;
return record;
}
openPrs(): PrRecord[] {
return Object.values(this.state.prs)
.filter((r) => r.status !== 'closed')
.sort((a, b) => b.number - a.number);
}
rememberMessage(messageId: number, prNumber: number): void {
this.state.messages[String(messageId)] = prNumber;
}
prForMessage(messageId: number | undefined): number | undefined {
if (messageId === undefined) return undefined;
return this.state.messages[String(messageId)];
}
private pruneMessageMap(): void {
const keys = Object.keys(this.state.messages);
if (keys.length <= MAX_MESSAGE_MAP) return;
// Message ids grow monotonically per chat; drop the oldest.
keys.sort((a, b) => Number(a) - Number(b));
for (const key of keys.slice(0, keys.length - MAX_MESSAGE_MAP)) delete this.state.messages[key];
}
}
+188
View File
@@ -0,0 +1,188 @@
/**
* @fileoverview Minimal Telegram Bot API client (long polling, no webhook: the box sits
* behind Tailscale) plus the pure command / callback parsers.
*
* Only updates from the configured chat are ever acted on; everything else is dropped
* without an answer, so a stranger who finds the bot gets silence, not a menu.
*/
export interface TelegramMessage {
message_id: number;
chat: { id: number | string };
from?: { id: number; username?: string };
text?: string;
reply_to_message?: { message_id: number; text?: string };
}
export interface TelegramCallbackQuery {
id: string;
from: { id: number; username?: string };
message?: TelegramMessage;
data?: string;
}
export interface TelegramUpdate {
update_id: number;
message?: TelegramMessage;
callback_query?: TelegramCallbackQuery;
}
export interface SendOptions {
replyMarkup?: unknown;
replyToMessageId?: number;
disablePreview?: boolean;
}
export class TelegramClient {
private readonly base: string;
constructor(
token: string,
private readonly chatId: string
) {
this.base = `https://api.telegram.org/bot${token}`;
}
private async call<T>(method: string, body?: Record<string, unknown>, timeoutMs = 30_000): Promise<T> {
const res = await fetch(`${this.base}/${method}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body ?? {}),
signal: AbortSignal.timeout(timeoutMs),
});
const json = (await res.json()) as { ok: boolean; result?: T; description?: string };
if (!json.ok) throw new Error(`telegram ${method}: ${json.description ?? res.status}`);
return json.result as T;
}
isOurChat(chatId: number | string | undefined): boolean {
return chatId !== undefined && String(chatId) === this.chatId;
}
async getMe(): Promise<{ username?: string }> {
return this.call<{ username?: string }>('getMe');
}
async sendMessage(text: string, opts: SendOptions = {}): Promise<number> {
const result = await this.call<{ message_id: number }>('sendMessage', {
chat_id: this.chatId,
text,
parse_mode: 'HTML',
disable_web_page_preview: opts.disablePreview ?? true,
reply_markup: opts.replyMarkup,
reply_to_message_id: opts.replyToMessageId,
});
return result.message_id;
}
/** Plain text, no parse mode: for content the bot did not write (reviewer answers, drafts). */
async sendPlain(text: string, opts: SendOptions = {}): Promise<number> {
const result = await this.call<{ message_id: number }>('sendMessage', {
chat_id: this.chatId,
text,
disable_web_page_preview: opts.disablePreview ?? true,
reply_markup: opts.replyMarkup,
reply_to_message_id: opts.replyToMessageId,
});
return result.message_id;
}
async editReplyMarkup(messageId: number, replyMarkup: unknown): Promise<void> {
try {
await this.call('editMessageReplyMarkup', {
chat_id: this.chatId,
message_id: messageId,
reply_markup: replyMarkup,
});
} catch (err) {
// "message is not modified" is Telegram's way of saying the keyboard already looks like that.
if (!String(err).includes('not modified')) throw err;
}
}
async deleteMessage(messageId: number): Promise<void> {
try {
await this.call('deleteMessage', { chat_id: this.chatId, message_id: messageId });
} catch {
// Already gone, or older than Telegram allows a bot to delete; the message was informational.
}
}
async answerCallback(callbackId: string, text?: string): Promise<void> {
await this.call('answerCallbackQuery', { callback_query_id: callbackId, text });
}
async sendDocument(filename: string, content: string, caption?: string): Promise<void> {
const form = new FormData();
form.set('chat_id', this.chatId);
if (caption) form.set('caption', caption);
form.set('document', new Blob([content], { type: 'text/markdown' }), filename);
const res = await fetch(`${this.base}/sendDocument`, {
method: 'POST',
body: form,
signal: AbortSignal.timeout(60_000),
});
const json = (await res.json()) as { ok: boolean; description?: string };
if (!json.ok) throw new Error(`telegram sendDocument: ${json.description ?? res.status}`);
}
async getUpdates(offset: number, timeoutSec: number): Promise<TelegramUpdate[]> {
return this.call<TelegramUpdate[]>(
'getUpdates',
{ offset, timeout: timeoutSec, allowed_updates: ['message', 'callback_query'] },
(timeoutSec + 15) * 1000
);
}
async setMyCommands(commands: { command: string; description: string }[]): Promise<void> {
await this.call('setMyCommands', { commands });
}
}
export interface ParsedCommand {
command: string;
prNumber?: number;
rest: string;
}
/** `/merge 381 force` -> {command:'merge', prNumber:381, rest:'force'}; `/help@botname` is handled. */
export function parseCommand(text: string | undefined): ParsedCommand | null {
if (!text) return null;
const m = text.trim().match(/^\/([a-zA-Z_]+)(?:@\w+)?(?:\s+([\s\S]*))?$/);
if (!m) return null;
const command = m[1].toLowerCase();
const argText = (m[2] ?? '').trim();
const numMatch = argText.match(/^#?(\d+)\b\s*([\s\S]*)$/);
if (numMatch) return { command, prNumber: parseInt(numMatch[1], 10), rest: numMatch[2].trim() };
return { command, rest: argText };
}
export interface ParsedCallback {
action: string;
prNumber: number;
nonce?: string;
/** For confirm/cancel: the action being confirmed. */
target?: string;
}
export function parseCallback(data: string | undefined): ParsedCallback | null {
if (!data) return null;
const parts = data.split(':');
if (parts[0] === 'confirm' || parts[0] === 'cancel') {
if (parts.length !== 4) return null;
const prNumber = parseInt(parts[2], 10);
if (!Number.isFinite(prNumber)) return null;
return { action: parts[0], target: parts[1], prNumber, nonce: parts[3] };
}
if (parts.length !== 2) return null;
const prNumber = parseInt(parts[1], 10);
if (!Number.isFinite(prNumber)) return null;
return { action: parts[0], prNumber };
}
/** Find the PR number a report message is about, from its first line (`🔍 PR #381 · ...`). */
export function prNumberFromMessageText(text: string | undefined): number | null {
if (!text) return null;
const m = text.match(/PR #(\d+)/);
return m ? parseInt(m[1], 10) : null;
}
+253
View File
@@ -0,0 +1,253 @@
/**
* @fileoverview Per-PR checkouts for the review sessions.
*
* The maintainer's checkout is SHARED with other agent sessions (CLAUDE.md, Session
* Safety), so the bot never runs `git checkout` there. It fetches the PR head into a
* private ref (`refs/pr-bot/<n>`) of the main repository, which anchors the objects,
* and checks the PR out in a private clone under the bot's own data dir; every
* in-tree git command runs with `-C <clone>`.
*
* Why a `git clone --shared` and not a linked worktree: Claude Code resolves a linked
* worktree's project settings through the git common dir, i.e. the MAIN checkout's
* `.claude/settings.local.json`, whose model pin then silently overrides anything
* written into the worktree (measured 2026-09-05: a worktree pinned to
* `claude-fable-5-1` reported `claude-opus-5[1m]`). A shared clone has its own
* project root, so Codeman's `modelOverride` and hooks land where the CLI reads them,
* while `objects/info/alternates` keeps the object store shared (no duplication).
*
* Dependencies: a clone has no `node_modules`. When the PR leaves the lockfile
* untouched, `node_modules` is a SYMLINK to the main checkout's tree (read-only use:
* tsc, vitest, eslint). When the PR changes dependencies, the symlink is unlinked
* first and `npm ci` installs a real tree, so npm can never write through the link
* into the live server's modules. `src/web/public/vendor` is COPIED per file, never
* linked: postinstall regenerates it in place, and a link would let a PR's bundle
* overwrite the bundle the production server is serving.
*/
import { execFile } from 'child_process';
import {
cpSync,
existsSync,
lstatSync,
mkdirSync,
readdirSync,
rmSync,
statSync,
symlinkSync,
unlinkSync,
writeFileSync,
} from 'fs';
import { join } from 'path';
import { promisify } from 'util';
const execFileAsync = promisify(execFile);
export interface WorktreeInfo {
dir: string;
headSha: string;
mergeBase: string;
deps: 'linked' | 'installed' | 'kept';
}
export type Logger = (msg: string) => void;
async function git(args: string[], cwd: string, timeoutMs = 120_000): Promise<string> {
const { stdout } = await execFileAsync('git', args, { cwd, maxBuffer: 64 * 1024 * 1024, timeout: timeoutMs });
return stdout;
}
export function prRef(prNumber: number): string {
return `refs/pr-bot/${prNumber}`;
}
/** The upstream master, as fetched into the main repository, mirrored into the clone. */
const MASTER_REF = 'refs/remotes/origin/master';
export function worktreeDirFor(worktreesDir: string, prNumber: number): string {
return join(worktreesDir, `pr-${prNumber}`);
}
const DEP_FILES = [
'package.json',
'package-lock.json',
'packages/xterm-zerolag-input/package.json',
'packages/gesture-control/package.json',
];
async function originUrl(mainCheckout: string): Promise<string> {
return (await git(['remote', 'get-url', 'origin'], mainCheckout)).trim();
}
/** A linked worktree from the first version of this file: `.git` is a FILE there. */
function isLegacyWorktree(dir: string): boolean {
const dotGit = join(dir, '.git');
try {
return statSync(dotGit).isFile();
} catch {
return false;
}
}
function isOwnClone(dir: string): boolean {
try {
return statSync(join(dir, '.git')).isDirectory();
} catch {
return false;
}
}
/** Fetch the PR head, (re)create the clone at it, and make node_modules usable. */
export async function preparePrWorktree(opts: {
mainCheckout: string;
worktreesDir: string;
prNumber: number;
/** Reset a reused clone to the fetched head (drops edits a follow-up may have made). */
reset: boolean;
log: Logger;
}): Promise<WorktreeInfo> {
const { mainCheckout, worktreesDir, prNumber, log } = opts;
const ref = prRef(prNumber);
const dir = worktreeDirFor(worktreesDir, prNumber);
mkdirSync(worktreesDir, { recursive: true });
log(`fetching origin master + pull/${prNumber}/head`);
await git(
['fetch', '--quiet', 'origin', `+refs/heads/master:${MASTER_REF}`, `+refs/pull/${prNumber}/head:${ref}`],
mainCheckout,
300_000
);
const headSha = (await git(['rev-parse', ref], mainCheckout)).trim();
if (existsSync(dir) && isLegacyWorktree(dir)) {
log(`replacing the linked worktree at ${dir} with a clone`);
await git(['worktree', 'remove', '--force', dir], mainCheckout).catch(() =>
rmSync(dir, { recursive: true, force: true })
);
await git(['worktree', 'prune'], mainCheckout);
}
if (existsSync(dir) && !isOwnClone(dir)) {
log(`removing stale directory ${dir}`);
rmSync(dir, { recursive: true, force: true });
}
if (!existsSync(dir)) {
log(`cloning (shared objects) into ${dir}`);
await git(['clone', '--quiet', '--shared', '--no-checkout', mainCheckout, dir], mainCheckout, 300_000);
// `origin` of the clone should mean GitHub, like everywhere else, not the main
// checkout's path; the refs below are fetched from the main checkout by path.
await git(['remote', 'set-url', 'origin', await originUrl(mainCheckout)], dir);
}
// Mirror the two refs from the main repository (objects are already reachable via
// alternates, so this only moves refs). `+` because both can move backwards.
await git(['fetch', '--quiet', mainCheckout, `+${MASTER_REF}:${MASTER_REF}`, `+${ref}:${ref}`], dir);
const current = (await git(['rev-parse', '--verify', '--quiet', 'HEAD'], dir).catch(() => '')).trim();
if (current !== headSha) {
log(`checking out ${headSha.slice(0, 8)}${current ? ` (was ${current.slice(0, 8)})` : ''}`);
await git(['checkout', '--quiet', '--detach', ref], dir);
}
if (opts.reset) {
await git(['reset', '--hard', '--quiet', ref], dir);
}
const mergeBase = (await git(['merge-base', MASTER_REF, 'HEAD'], dir)).trim();
const deps = await ensureDependencies({ mainCheckout, dir, ref, mergeBase, log });
ensureVendorCopy(mainCheckout, dir, log);
return { dir, headSha, mergeBase, deps };
}
/** Written into a clone's own node_modules once `npm ci` has finished; its absence means a half install. */
const INSTALL_MARKER = '.pr-bot-installed';
async function ensureDependencies(opts: {
mainCheckout: string;
dir: string;
ref: string;
mergeBase: string;
log: Logger;
}): Promise<WorktreeInfo['deps']> {
const { mainCheckout, dir, ref, mergeBase, log } = opts;
const target = join(dir, 'node_modules');
// Against the MERGE BASE, not master: master's own version bumps since the PR
// branched would otherwise make every older PR look like a dependency change and
// cost a full npm ci each. Only what the PR itself did to the dependency files counts.
let depsChanged = false;
try {
await git(['diff', '--quiet', mergeBase, ref, '--', ...DEP_FILES], mainCheckout);
} catch {
depsChanged = true;
}
let existing = existsSync(target) || isSymlink(target) ? lstatSync(target) : null;
if (existing?.isDirectory() && !existsSync(join(target, INSTALL_MARKER))) {
// A real tree without the marker is an install that was interrupted (service
// restart mid `npm ci`); never trust it.
log('discarding an incomplete node_modules install');
rmSync(target, { recursive: true, force: true });
existing = null;
}
if (!depsChanged) {
if (existing?.isSymbolicLink()) return 'linked';
if (existing?.isDirectory()) return 'kept';
symlinkSync(join(mainCheckout, 'node_modules'), target, 'dir');
log('node_modules linked to the main checkout (dependencies unchanged by the PR)');
return 'linked';
}
// The PR changes dependencies: a real install, and NEVER through the symlink.
if (existing?.isSymbolicLink()) unlinkSync(target);
if (existing?.isDirectory()) return 'kept';
log('the PR changes dependencies: running npm ci in the clone (this can take minutes)');
await execFileAsync('npm', ['ci', '--no-audit', '--no-fund', '--loglevel=error'], {
cwd: dir,
timeout: 20 * 60_000,
maxBuffer: 64 * 1024 * 1024,
});
writeFileSync(join(target, INSTALL_MARKER), new Date().toISOString());
return 'installed';
}
function isSymlink(path: string): boolean {
try {
return lstatSync(path).isSymbolicLink();
} catch {
return false;
}
}
function ensureVendorCopy(mainCheckout: string, dir: string, log: Logger): void {
const rel = join('src', 'web', 'public', 'vendor');
const src = join(mainCheckout, rel);
const dst = join(dir, rel);
if (!existsSync(src)) return;
// Two of the vendor files are tracked in git, so the directory already exists in a
// fresh checkout; copy whatever is MISSING (the postinstall-built xterm bundles).
mkdirSync(dst, { recursive: true });
let copied = 0;
for (const entry of readdirSync(src)) {
const target = join(dst, entry);
if (existsSync(target)) continue;
cpSync(join(src, entry), target, { recursive: true });
copied++;
}
if (copied) log(`${copied} vendor bundle(s) copied from the main checkout`);
}
export async function removePrWorktree(opts: {
mainCheckout: string;
worktreesDir: string;
prNumber: number;
log: Logger;
}): Promise<void> {
const dir = worktreeDirFor(opts.worktreesDir, opts.prNumber);
if (existsSync(dir)) {
opts.log(`removing ${dir}`);
if (isLegacyWorktree(dir)) {
await git(['worktree', 'remove', '--force', dir], opts.mainCheckout).catch(() => undefined);
await git(['worktree', 'prune'], opts.mainCheckout).catch(() => undefined);
}
rmSync(dir, { recursive: true, force: true });
}
try {
await git(['update-ref', '-d', prRef(opts.prNumber)], opts.mainCheckout);
} catch {
// The ref may never have been created; nothing to delete.
}
}
+1
View File
@@ -283,6 +283,7 @@ than into an existing checkout.
| create a session in an arbitrary directory (no case, **no PTY**, id at `.data.session.id`) | `POST /api/v1/sessions`, then `POST /api/v1/sessions/:id/interactive` or `.../shell` to start it, see [Starting a worker](#starting-a-worker) |
| send input | `POST /api/v1/sessions/:id/input` |
| **read a worker's answer** (claude/codex/deepseek) | `GET /api/v1/sessions/:id/last-response` → `.data.{text,timestamp}`, clean transcript text, no TUI noise. ⚠️ **Poll it**, see [symptom 7](#7-last-response-returns-an-empty-string-right-after-stop) |
| read the whole conversation | `GET /api/v1/sessions/:id/last-response?context=full` → `.data.messages[]`. ⚠️ **Only `{role,text}` is present for every mode.** `kind`/`label` come from claude (`prompt`/`response`), deepseek and the pane parser (which also emit `status`/`tool`) but NOT from codex; `timestamp` from claude and codex but not deepseek/pane; `turn` and `queued:true` (a prompt typed while the agent was working) from claude only. `.data.text` is unchanged by `context=full` — it stays the last assistant message, never `messages[-1]` |
| read terminal (tail is in **BYTES**, raw ANSI) | `GET /api/v1/sessions/:id/terminal?tail=3000` → `.data.terminalBuffer`, for *diagnosis* (unsubmitted prompt?), not for reading answers |
| full tmux scrollback (context bomb; post-mortems only) | `GET /api/v1/sessions/:id/terminal?full=1` |
| background agents, one session | `GET /api/v1/sessions/:id/subagents` |
+11 -1
View File
@@ -407,7 +407,17 @@ done
printf '%s\n' "$TXT"
```
`.data` is `{text, timestamp}`. ⚠️ **On a hook-less workspace this reads the PREVIOUS
`.data` is `{text, timestamp}`. Add `?context=full` for the whole conversation in
`.data.messages[]`. ⚠️ **The four readers do not emit the same fields — only `{role, text}`
is guaranteed.** `kind`/`label` come from claude (`prompt`/`response`), deepseek and the pane
parser (the last two also emit `status`/`tool`), but **not** from codex; `timestamp` comes
from claude and codex but not from deepseek or the pane parser. A claude worker additionally
carries `turn` (a run of same-speaker messages inside one `turn` is one utterance split into
segments, not separate exchanges) and `queued: true` on a prompt the user typed while the
agent was still working. Filter on `role`, not on `kind`, unless you know the mode.
`.data.text` does not change under `context=full`: it stays the
last **assistant** message, so never read it as `messages[-1]`, which can be a prompt.
⚠️ **On a hook-less workspace this reads the PREVIOUS
turn.** `last-response` returns whatever the transcript last flushed, so it is only as
correct as your end-of-turn signal: pair it with a `stop` signal or a marker, never
with a bare `idle` ([§5.1](#51-where-to-spawn)). ⚠️ **Poll it, do not read it once.** `text` is written
+24 -2
View File
@@ -16,6 +16,7 @@ import { isAbsolute, join } from 'node:path';
import { homedir } from 'node:os';
import { dataPath } from './config/instance.js';
import { casePath } from './config/cases-dir.js';
import { assertValidBasePath } from './config/base-path.js';
import { installAgentSkillInto, removeAgentSkillFrom, type AgentSkillApplyResult } from './hooks-config.js';
import { getSessionManager } from './session-manager.js';
import { getTaskQueue } from './task-queue.js';
@@ -843,6 +844,11 @@ function addWebLaunchOptions(cmd: Command): Command {
.option('-H, --host <host>', 'Host to bind to', process.env.CODEMAN_HOST || '127.0.0.1')
.option('-p, --port <port>', 'Port to listen on (env: CODEMAN_PORT)', process.env.CODEMAN_PORT || '3000')
.option('--https', 'Enable HTTPS with self-signed certificate (only needed for remote access, not localhost)')
.option(
'--base-url <path>',
'Sub-path Codeman is mounted under behind a reverse proxy, e.g. /codeman (env: CODEMAN_BASE_URL)',
process.env.CODEMAN_BASE_URL || '/'
)
.option('--title-hostname <hostname>', 'Override the hostname shown in the browser title')
.option(
'--allow-unauthenticated-network',
@@ -859,6 +865,7 @@ function toWebLaunchOptions(options: {
host: string;
port: string;
https?: boolean;
baseUrl?: string;
titleHostname?: string;
allowUnauthenticatedNetwork?: boolean;
multiuser?: boolean;
@@ -868,10 +875,18 @@ function toWebLaunchOptions(options: {
console.error(palette.err(`✗ Invalid port: ${options.port}`));
process.exit(1);
}
let basePath: string;
try {
basePath = assertValidBasePath(options.baseUrl);
} catch (err) {
console.error(palette.err(`✗ ${err instanceof Error ? err.message : String(err)}`));
process.exit(1);
}
return {
host: options.host,
port,
https: !!options.https,
basePath,
titleHostname: options.titleHostname,
allowUnauthenticatedNetwork: !!options.allowUnauthenticatedNetwork,
multiuser: !!options.multiuser,
@@ -961,14 +976,21 @@ webCmd.action(async (options) => {
const https = launch.https;
const titleHostname = options.titleHostname;
const allowUnauthenticatedNetwork = launch.allowUnauthenticatedNetwork ?? false;
const basePath = launch.basePath ?? '';
// Single source of truth for subsystems that read it directly (e.g. renderers).
if (basePath) process.env.CODEMAN_BASE_URL = basePath;
const displayHost = host === '0.0.0.0' ? 'localhost' : host;
console.log(palette.info(`Starting Codeman web interface on ${displayHost}:${port}${https ? ' (HTTPS)' : ''}...`));
console.log(
palette.info(
`Starting Codeman web interface on ${displayHost}:${port}${basePath ? basePath + '/' : ''}${https ? ' (HTTPS)' : ''}...`
)
);
try {
// The server prints its own "running at" line (it also covers the daemon and
// service launch paths), so this one used to be a duplicate of it.
const server = await startWebServer(port, https, false, host, titleHostname, allowUnauthenticatedNetwork);
const server = await startWebServer(port, https, false, host, titleHostname, allowUnauthenticatedNetwork, basePath);
if (https) {
console.log(palette.warn(' Note: Accept the self-signed certificate in your browser on first visit'));
}
+101
View File
@@ -0,0 +1,101 @@
/**
* @fileoverview Reverse-proxy base-path support — the single source of truth for
* the URL prefix Codeman is mounted under.
*
* When Codeman runs behind a reverse proxy at a sub-path (e.g. `/codeman/`), the
* proxy forwards the FULL request path INCLUDING that prefix (it does not strip
* it). Every URL the server emits to the browser (the HTML shell, redirects,
* the manifest/service-worker) and every URL the browser builds (fetch/SSE/WS)
* must therefore carry the prefix too.
*
* This module normalizes the operator-supplied value (`--base-url` / the
* `CODEMAN_BASE_URL` env var) into ONE canonical form used everywhere:
* - `''` — mounted at the origin root (the default, `/`)
* - `/foo` — mounted at a sub-path (leading slash, NO trailing slash)
*
* Keeping the normalized form free of a trailing slash means `basePath + '/api/x'`
* and `basePath + '/'` both compose cleanly, and `''` degrades to the historical
* root behavior with no special-casing at the call sites.
*
* @module config/base-path
*/
/**
* A normalized base path is either empty (root) or one-or-more `/segment`
* groups, where a segment is a conservative, proxy-safe subset of path
* characters. This deliberately excludes anything that could change routing
* meaning (`?`, `#`, `:`, whitespace, `%`) so the prefix is a plain path.
*/
const VALID_BASE_PATH = /^(?:\/[A-Za-z0-9._~-]+)+$/;
/**
* Normalize an operator-supplied base path into the canonical form.
*
* Accepts loose input (`codeman`, `/codeman`, `/codeman/`, `//codeman//`) and
* returns `''` for root or `/codeman` otherwise. Does NOT validate the character
* set — call {@link assertValidBasePath} (or {@link isValidBasePath}) for that.
*/
export function normalizeBasePath(input: string | undefined | null): string {
if (input === undefined || input === null) return '';
let p = String(input).trim();
if (p === '' || p === '/') return '';
if (!p.startsWith('/')) p = '/' + p;
p = p.replace(/\/{2,}/g, '/'); // collapse duplicate slashes
p = p.replace(/\/+$/, ''); // drop trailing slash(es)
return p;
}
/** True if `normalized` is a legal canonical base path (`''` or `/seg[/seg...]`). */
export function isValidBasePath(normalized: string): boolean {
return normalized === '' || VALID_BASE_PATH.test(normalized);
}
/**
* Normalize AND validate, throwing a human-readable error on bad input. Used by
* the CLI so a typo (`--base-url /a b`, `--base-url ?x`) fails loudly at startup
* instead of silently producing broken URLs.
*/
export function assertValidBasePath(input: string | undefined | null): string {
const normalized = normalizeBasePath(input);
if (!isValidBasePath(normalized)) {
throw new Error(
`Invalid --base-url ${JSON.stringify(input)}: use a plain path like "/codeman" ` +
`(letters, digits, and ._~- in each segment).`
);
}
return normalized;
}
/**
* Join the base path onto a root-absolute application path (`/api/x` → `/base/api/x`).
*
* Leaves alone anything that is not a root-absolute app path: empty strings,
* protocol-relative (`//host`) and absolute URLs (`http://`, `ws://`, `data:`),
* fragments/queries, and paths already carrying the prefix. This is the one
* function the whole codebase routes URL construction through.
*/
export function joinBasePath(basePath: string, path: string): string {
if (!basePath) return path;
if (typeof path !== 'string' || path.length === 0) return path;
if (!path.startsWith('/')) return path; // relative / fragment / query — resolved against <base>
if (path.startsWith('//')) return path; // protocol-relative
if (path === basePath || path.startsWith(basePath + '/') || path.startsWith(basePath + '?')) {
return path; // already prefixed
}
return basePath + path;
}
/**
* Strip the base path off an INCOMING request URL so internal routing stays
* prefix-agnostic. Requests that arrive WITHOUT the prefix (health checks,
* hooks, the docker bridge — all of which hit the raw port, bypassing the proxy)
* are returned unchanged, so the server answers at both `/api/x` and
* `/base/api/x`.
*/
export function stripBasePath(basePath: string, url: string): string {
if (!basePath) return url;
if (url === basePath) return '/';
if (url.startsWith(basePath + '/')) return url.slice(basePath.length);
if (url.startsWith(basePath + '?')) return '/' + url.slice(basePath.length);
return url;
}
+1 -1
View File
@@ -322,7 +322,7 @@ const commandLine = z
);
const overlayTargetSchema = z.union([
z.object({ command: commandLine.optional() }).strict(),
z.object({ command: commandLine.optional(), rootCommand: commandLine.optional() }).strict(),
z.object({ disabled: z.literal(true) }).strict(),
]);
+4 -1
View File
@@ -210,7 +210,10 @@ const CLAUDE: CliEntry = {
// (no trust-folder/permission prompt that nothing on that side can answer). A per-host
// `commands.claude` override, or the docker multi-user clamp, stays the escape hatch.
remote: { command: 'claude --dangerously-skip-permissions' },
docker: { command: 'claude --dangerously-skip-permissions' },
// ⚠️ As root the flag is not merely unnecessary, it is REFUSED ("cannot be used with
// root/sudo privileges"), and only inside the container — so an adopted root container
// would just show a dead pane. Drop it there and let claude ask.
docker: { command: 'claude --dangerously-skip-permissions', rootCommand: 'claude' },
// Claude's docker/remote credential handling has its own dedicated code path
// (claudeDockerPaneCommand, artifacts at docker-hosts.ts:537-575) — no generic credStore.
},
+9 -1
View File
@@ -442,7 +442,15 @@ export interface CliOverlays {
* all (docker for `shell`) — distinct from "no override", which still gets a default.
*/
remote?: { command?: string } | { disabled: true };
docker?: { command?: string } | { disabled: true };
/**
* `rootCommand` is the same invocation for a container whose exec user is uid 0. Only
* declare it when the normal `command` would be REFUSED as root: claude's carries
* `--dangerously-skip-permissions`, which Claude Code rejects outright under root, and
* the rejection is visible only inside the container, so the pane dies with no clue on
* the outside. Codeman's own base image runs a non-root user and never selects this; an
* ADOPTED container belongs to its owner and is frequently root. Absent = use `command`.
*/
docker?: { command?: string; rootCommand?: string } | { disabled: true };
/**
* ⚠️ DECLARED-FOR-LATER, unlike `remote`/`docker` above, which are live.
*
+3
View File
@@ -45,6 +45,8 @@ export interface WebLaunchOptions {
host: string;
port: number;
https: boolean;
/** Reverse-proxy sub-path prefix (normalized: '' for root, or '/foo'). */
basePath?: string;
titleHostname?: string;
allowUnauthenticatedNetwork?: boolean;
multiuser?: boolean;
@@ -87,6 +89,7 @@ export interface DaemonStatus {
export function buildWebArgs(options: WebLaunchOptions): string[] {
const args = ['web', '--host', options.host, '--port', String(options.port)];
if (options.https) args.push('--https');
if (options.basePath) args.push('--base-url', options.basePath);
if (options.titleHostname) args.push('--title-hostname', options.titleHostname);
if (options.allowUnauthenticatedNetwork) args.push('--allow-unauthenticated-network');
if (options.multiuser) args.push('--multiuser');
+8 -1
View File
@@ -30,6 +30,7 @@ import { spawn } from 'node:child_process';
import { pipeline } from 'node:stream/promises';
import type { DockerEngine, SessionDocker } from './types.js';
import { runWithConversionLimit } from './document-conversion-limiter.js';
import { isAdoptedContainer } from './docker-hosts.js';
const IS_TEST_MODE = !!process.env.VITEST;
@@ -287,7 +288,13 @@ export async function exportDockerCase(params: {
const bundlePath = join(exportsDir, exportBundleName(caseName, timestamp, mode));
const stageDir = join(exportsDir, `.stage-${caseName}-${timestamp}`);
mkdirSync(stageDir, { recursive: true });
const wasRunning = await isContainerRunning(argv, docker.containerName);
// ⚠️ NEVER pause an ADOPTED container. The freeze exists only to make the committed
// image and the workspace tar mutually consistent, and it is a lifecycle mutation on a
// container that belongs to the user — it stops their processes for however long the
// tar takes. A workspace-only export of an adopted case therefore accepts a live
// filesystem, the same guarantee `tar` gives on any running host directory. Full-image
// export is refused for an adopted case at the route, before reaching here.
const wasRunning = !isAdoptedContainer(docker) && (await isContainerRunning(argv, docker.containerName));
let commitTag: string | undefined;
try {
+323 -6
View File
@@ -24,7 +24,7 @@
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import fs from 'node:fs/promises';
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
import { getCli } from './config/cli-registry/registry.js';
import { enabledCliIds, getCli } from './config/cli-registry/registry.js';
import { fileURLToPath } from 'node:url';
import { homedir } from 'node:os';
import { createHash } from 'node:crypto';
@@ -55,6 +55,30 @@ export const DEFAULT_AGENT_IMAGE = 'codeman/agent:base';
/** HOME inside the base image (the `agent` user). Cred mounts + hook-secret land under it. */
export const CONTAINER_HOME = '/home/agent';
/**
* Modes the adoption preflight probes for inside an existing container, derived from the
* CLI registry so a newly-enabled CLI is probed without a second list to remember.
*
* No arm for `shell` here: it declares no binary, so `probeAdoptableContainer` drops it
* from the `command -v` list and reports it available unconditionally, which is the same
* answer a special case would have produced.
*/
export function dockerAdoptProbeModes(): SessionMode[] {
return enabledCliIds() as SessionMode[];
}
/**
* The BINARY a mode looks for inside a container. ⚠️ NOT always the mode name:
* `antigravity` ships as `agy` and `deepseek` as `dsh`, so probing by mode name
* would report those two as missing on a container that has them. Same source
* `probeDockerCliVersion` reads, and the same one `defaultDockerCommandForMode`
* launches from — a local table here duplicated the registry with nothing
* keeping the two in step.
*/
function containerBinaryFor(mode: SessionMode): string | undefined {
return getCli(mode)?.discovery.binaries[0];
}
/** Per-case container name prefix. The `case` letters deliberately do NOT matter to
* tmux; this is a DOCKER name (`^[a-zA-Z0-9][a-zA-Z0-9_.-]+$`), and case names are
* already validated `^[a-zA-Z0-9_-]+$`, so `codeman-case-<name>` is always valid. */
@@ -142,14 +166,21 @@ export function dockerContainerName(caseName: string): string {
* nothing keeping the two in step. `shell` is the one arm still written here, because it is
* the entry that declares `docker: { disabled: true }` — a container has no per-user login
* shell to resolve, so it gets a plain `bash -l` rather than a CLI invocation.
*
* ⚠️ `runsAsRoot` selects the overlay's `rootCommand` when it declares one. Claude Code
* REFUSES `--dangerously-skip-permissions` under uid 0 ("cannot be used with root/sudo
* privileges", still true in 2.1.261), and the refusal is only visible INSIDE the
* container, so the pane just dies. Our own base image runs a non-root user and never hits
* it; an ADOPTED container's user belongs to its owner and is frequently root. Which flag
* to drop is a per-CLI fact, so it lives in the registry rather than in a branch here.
*/
export function defaultDockerCommandForMode(mode: SessionMode): string {
export function defaultDockerCommandForMode(mode: SessionMode, runsAsRoot = false): string {
const entry = getCli(mode);
const overlay = entry?.overlays.docker;
if (!entry || (overlay && 'disabled' in overlay)) return 'exec bash -l';
// Mirrors the LOCAL default for each CLI; claude's carries
// `--dangerously-skip-permissions` so the in-container agent runs non-interactively.
const cli = overlay?.command ?? entry.discovery.binaries[0];
const cli = (runsAsRoot ? overlay?.rootCommand : undefined) ?? overlay?.command ?? entry.discovery.binaries[0];
return cli ? `exec ${cli}` : 'exec bash -l';
}
@@ -253,7 +284,22 @@ export function toSessionDocker(host: DockerHost, dockerCase: DockerCase): Sessi
extraCreateArgs: host.extraCreateArgs,
extraExecArgs: host.extraExecArgs,
};
return { ...base, configHash: dockerConfigHash(base) };
// `owned` is deliberately applied AFTER the hash: dockerConfigHash() picks an
// explicit field list, so ownership can never shift an existing case's hash and
// mass-trip the drift gate.
const session: SessionDocker = { ...base, configHash: dockerConfigHash(base) };
if (dockerCase.owned === false) session.owned = false;
return session;
}
/**
* An ADOPTED container is one the user built and runs themselves. Codeman may
* only exec into it; it must never create, start, stop, restart or remove it.
* Every lifecycle branch routes through this one predicate so a new call site
* cannot silently opt out.
*/
export function isAdoptedContainer(docker: Pick<SessionDocker, 'owned'>): boolean {
return docker.owned === false;
}
// ========== Shell escaping ==========
@@ -754,9 +800,15 @@ export interface DockerDriftStatus {
* daemon down) means there is nothing to drift. No-op under VITEST.
*/
export async function checkDockerConfigDrift(
docker: Pick<SessionDocker, 'engine' | 'context' | 'daemonHost' | 'containerName' | 'configHash'>
docker: Pick<SessionDocker, 'engine' | 'context' | 'daemonHost' | 'containerName' | 'configHash' | 'owned'>
): Promise<DockerDriftStatus> {
if (IS_TEST_MODE) return { exists: false, running: false, drifted: false };
// An ADOPTED container carries no `codeman.confighash` label — it was never
// created from our config — so every comparison would report drift and the
// launch gate would demand a recreate we are not allowed to perform. Ownership
// of its configuration belongs to the user; report "no drift" and never offer
// to rebuild it.
if (isAdoptedContainer(docker)) return { exists: true, running: false, drifted: false };
const argv = dockerEngineArgv(docker);
try {
const { stdout } = await execFileAsync(
@@ -784,8 +836,15 @@ export async function checkDockerConfigDrift(
* case's lastClaudeSessionId. No-op under VITEST.
*/
export async function removeDockerContainer(
docker: Pick<SessionDocker, 'engine' | 'context' | 'daemonHost' | 'containerName'>
docker: Pick<SessionDocker, 'engine' | 'context' | 'daemonHost' | 'containerName' | 'owned'>
): Promise<void> {
// Fail CLOSED at the lowest layer: an adopted container is the user's, and no
// caller — recreate-on-drift, case delete, a future teardown — may remove it.
if (isAdoptedContainer(docker)) {
throw new Error(
`Refusing to remove adopted container "${docker.containerName}": Codeman does not own its lifecycle.`
);
}
if (IS_TEST_MODE) return;
const argv = dockerEngineArgv(docker);
await execFileAsync(argv[0], [...argv.slice(1), 'rm', '-f', docker.containerName], { timeout: 30_000 });
@@ -1031,6 +1090,255 @@ export async function checkDockerTmuxAvailable(
}
}
/** Preflight facts about an ALREADY-RUNNING container the user wants to adopt. */
export interface AdoptedContainerProbe {
ok: boolean;
exists: boolean;
running: boolean;
/** The container's own image ref (informational — we never enforce ours on it). */
image?: string;
/** `command -v tmux` inside the container; required for durable sessions. */
tmuxPath?: string;
/** Modes whose CLI resolved inside the container (`command -v <mode>`). */
availableModes?: SessionMode[];
/** Whether the requested working directory exists INSIDE the container. */
workdirExists?: boolean;
/** Whether the container's exec user is root (uid 0). */
runsAsRoot?: boolean;
error?: string;
}
/** One container on the engine, as offered to the adoption picker. */
export interface DockerContainerInfo {
name: string;
image: string;
running: boolean;
/** Engine's own status string, e.g. "Up 3 hours" / "Exited (0) 2 days ago". */
status: string;
}
/**
* List the engine's containers for the adoption picker (mirror of
* `listRemoteCodemanSessions`). Read-only and NEVER throws: an unreachable
* daemon, a missing engine or zero containers all return `[]`, because this
* feeds a convenience picker whose input the user can always type by hand.
*
* Stopped containers ARE included, sorted after running ones and carrying their
* status: adoption requires a running container, but hiding a stopped one turns
* "my container is not in the list" into a dead end with no explanation, while
* showing `my-box (Exited (0) 2 days ago)` says exactly what to fix.
*/
export async function listDockerContainers(
docker: Pick<SessionDocker, 'engine' | 'context' | 'daemonHost'>
): Promise<DockerContainerInfo[]> {
if (IS_TEST_MODE) return [];
const argv = dockerEngineArgv(docker);
try {
const { stdout } = await execFileAsync(
argv[0],
[...argv.slice(1), 'ps', '-a', '--format', '{{.Names}}\t{{.Image}}\t{{.State}}\t{{.Status}}'],
{ timeout: DOCKER_PROBE_TIMEOUT_MS }
);
const rows = stdout
.split('\n')
.map((line) => line.split('\t'))
.filter((parts) => parts.length >= 4 && parts[0])
.map(([name, image, state, status]) => ({
name,
image: image || '',
running: state === 'running',
status: status || '',
}));
// Running first, then by name, so the containers a user can actually adopt
// are the ones at the top of the list.
return rows.sort((a, b) => Number(b.running) - Number(a.running) || a.name.localeCompare(b.name));
} catch {
return [];
}
}
/**
* Preflight an EXISTING container for adoption. Read-only by construction: it
* runs `inspect` plus one `exec` of `command -v`, and never creates, starts or
* modifies anything. Refusing here is what keeps the failure at link time — a
* clear message — instead of at session launch, where the only alternatives
* would be a dead pane or starting a container we do not own.
*
* `--pull=never` is irrelevant here: adoption never touches images. The image
* ref is reported only so the UI can show what the user is attaching to.
*/
export async function probeAdoptableContainer(
docker: Pick<SessionDocker, 'engine' | 'context' | 'daemonHost' | 'containerName'>,
modes: SessionMode[] = [],
containerWorkdir?: string
): Promise<AdoptedContainerProbe> {
if (IS_TEST_MODE) {
return {
ok: true,
exists: true,
running: true,
tmuxPath: '/usr/bin/tmux',
availableModes: modes,
workdirExists: true,
};
}
const argv = dockerEngineArgv(docker);
let running = false;
let image: string | undefined;
try {
const { stdout } = await execFileAsync(
argv[0],
[...argv.slice(1), 'inspect', '-f', '{{.State.Running}}\t{{.Config.Image}}', docker.containerName],
{ timeout: DOCKER_PROBE_TIMEOUT_MS }
);
const [state = '', img = ''] = stdout.trim().split('\t');
running = state === 'true';
image = img || undefined;
} catch {
return {
ok: false,
exists: false,
running: false,
error: `container "${docker.containerName}" not found (adoption never creates a container — start it yourself first)`,
};
}
if (!running) {
return {
ok: false,
exists: true,
running: false,
image,
error: `container "${docker.containerName}" exists but is not running (Codeman never starts a container it does not own — start it yourself, then retry)`,
};
}
// One exec resolves tmux plus every requested CLI, so adoption costs a single
// round trip. Binaries are fixed mode names, never user input.
// A mode with no binary of its own (`shell`) is dropped: there is nothing to look up,
// and `command -v ''` would make the whole probe meaningless.
const wanted = modes.filter((m) => !!containerBinaryFor(m));
const probes = ['tmux', ...wanted.map((m) => containerBinaryFor(m) as string)];
// `; exit 0` is load-bearing: the script's status is its LAST command's, so a
// missing final CLI made the whole `sh -lc` exit 1 and the probe reported
// "could not exec into the container" for a container that was perfectly fine.
// Absence of a CLI is data here, not failure — only a real exec error is.
const steps = probes.map((bin) => `command -v ${bin} >/dev/null 2>&1 && echo ${bin}`);
// The workdir is checked INSIDE the container, and that is a fact independent
// of hostWorkspacePath: an owned container gets the host dir bind-mounted at the
// same absolute path at create time, but adoption mounts nothing, so the two
// paths only coincide if the user mounted it there themselves. `docker exec
// --workdir <missing>` fails with an OCI chdir error the pane surfaces as a bare
// "execvp failed", so it is resolved here into an actionable message.
if (containerWorkdir) steps.push(`[ -d ${shellescape(containerWorkdir)} ] && echo __workdir__`);
// Claude Code REFUSES --dangerously-skip-permissions as root. Our own base
// image runs a non-root user so an owned container never hits it; an adopted
// container's user belongs to its owner and is frequently root.
steps.push(`[ "$(id -u)" = 0 ] && echo __root__`);
const script = `${steps.join('; ')}; exit 0`;
try {
const { stdout } = await execFileAsync(
argv[0],
[...argv.slice(1), 'exec', docker.containerName, 'sh', '-lc', script],
{ timeout: DOCKER_PROBE_TIMEOUT_MS }
);
const found = new Set(
stdout
.split('\n')
.map((line) => line.trim())
.filter(Boolean)
);
if (!found.has('tmux')) {
return {
ok: false,
exists: true,
running: true,
image,
error: `container "${docker.containerName}" has no tmux (required for durable sessions; install it inside the container)`,
};
}
const workdirExists = containerWorkdir ? found.has('__workdir__') : undefined;
if (containerWorkdir && !workdirExists) {
return {
ok: false,
exists: true,
running: true,
image,
workdirExists: false,
error: `"${containerWorkdir}" does not exist inside container "${docker.containerName}". Adoption mounts nothing, so the container workdir must already exist there — set it to a path inside the container (it need not match the host workspace path).`,
};
}
return {
ok: true,
exists: true,
running: true,
image,
tmuxPath: 'tmux',
availableModes: modes.filter((m) => {
const bin = containerBinaryFor(m);
return bin ? found.has(bin) : true; // `shell` needs no binary
}),
workdirExists,
runsAsRoot: found.has('__root__'),
};
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
return { ok: false, exists: true, running: true, image, error: `could not exec into the container: ${msg}` };
}
}
/** One directory listing from INSIDE a container, shaped like the host picker's. */
export interface DockerBrowseResult {
path: string;
parent: string | null;
entries: Array<{ name: string; path: string; type: 'directory' | 'file' }>;
error?: string;
}
/**
* List a directory INSIDE a container, for the adoption form's container-workdir
* picker. The host filesystem picker cannot serve this: the path lives in the
* container, and for an adopted container nothing is mounted at a matching host
* location, so the user would otherwise be typing a path blind.
*
* Read-only: one `ls` through `docker exec`, no writes, no lifecycle. The path
* is shell-escaped like every other value this module interpolates, and output
* is parsed as NUL-free lines with a leading type marker so a filename with
* spaces survives.
*/
export async function browseInContainer(
docker: Pick<SessionDocker, 'engine' | 'context' | 'daemonHost' | 'containerName'>,
path: string
): Promise<DockerBrowseResult> {
const target = path && path.startsWith('/') ? path : '/';
const parent = target === '/' ? null : target.replace(/\/+$/, '').split('/').slice(0, -1).join('/') || '/';
if (IS_TEST_MODE) return { path: target, parent, entries: [] };
const argv = dockerEngineArgv(docker);
// `-p` marks directories with a trailing slash; `-A` shows dotfiles but not
// the . and .. entries the picker navigates with its own Up control.
const script = `cd ${shellescape(target)} 2>/dev/null && ls -Ap 2>/dev/null || echo __ERR__`;
try {
const { stdout } = await execFileAsync(
argv[0],
[...argv.slice(1), 'exec', docker.containerName, 'sh', '-lc', script],
{ timeout: DOCKER_PROBE_TIMEOUT_MS, maxBuffer: 4 * 1024 * 1024 }
);
if (stdout.includes('__ERR__')) return { path: target, parent, entries: [], error: 'Not a readable directory' };
const base = target.endsWith('/') ? target : `${target}/`;
const entries = stdout
.split('\n')
.map((line) => line.trim())
.filter(Boolean)
.map((name) => {
const isDir = name.endsWith('/');
const clean = isDir ? name.slice(0, -1) : name;
return { name: clean, path: `${base}${clean}`, type: (isDir ? 'directory' : 'file') as 'directory' | 'file' };
})
.sort((a, b) => Number(b.type === 'directory') - Number(a.type === 'directory') || a.name.localeCompare(b.name));
return { path: target, parent, entries };
} catch (err) {
return { path: target, parent, entries: [], error: err instanceof Error ? err.message : String(err) };
}
}
/**
* Resolve the host's IP on the default docker bridge (the address a container
* reaches as `host.docker.internal`), so the server can bind a hooks-only listener
@@ -1093,9 +1401,18 @@ export async function reapOrphanedDockerContainers(
}
const cases = await readDockerCases(configDir);
const expected = new Set(cases.map((c) => c.container ?? dockerContainerName(c.name)));
// ADOPTED containers are never reapable, and this guard is deliberately
// independent of the two conditions that already cover them (we never applied
// the `codeman.managed=1` label filtered on above, and they are referenced by a
// live case so they are in `expected`). An adopted container is the user's
// property; it must survive even if a future edit narrows either condition.
const adopted = new Set(
cases.filter((item) => item.owned === false).map((item) => item.container ?? dockerContainerName(item.name))
);
const reaped: string[] = [];
for (const { name, inst } of rows) {
if (inst !== instance) continue; // only THIS instance's containers
if (adopted.has(name)) continue; // never reap a container we do not own
if (expected.has(name)) continue; // still referenced by a live case
try {
await execFileAsync(bin, ['rm', '-f', name], { timeout: DOCKER_PROBE_TIMEOUT_MS });
+40 -3
View File
@@ -366,19 +366,33 @@ export function generateHooksConfig(): { hooks: Record<string, unknown[]> } {
// never lands in this config and rotation needs no respawn. If the var/file is
// missing the header is empty — the middleware then allows the request only on
// the plain loopback bypass (tunnel down), same as pre-secret behavior.
const curlCmd = (event: HookEventType) =>
const curlCmd = (event: HookEventType, options: { discardStdout?: boolean } = {}) =>
`HOOK_DATA=$(cat 2>/dev/null || echo '{}'); ` +
`printf '{"event":"${event}","sessionId":"%s","data":%s}' "$CODEMAN_SESSION_ID" "$HOOK_DATA" | ` +
// `-k`, same as the statusline exporter: CODEMAN_API_URL is loopback HTTPS with
// a self-signed cert on --https/tailscale installs. Without it curl exits 60,
// the `|| true` swallows it, and ALL SIX hook events die silently: respawn loses
// its definitive idle signals and the wait endpoints lose stop/blocked.
`curl -sk -X POST "$CODEMAN_API_URL/api/hook-event" ` +
`curl -sk ${options.discardStdout ? '-o /dev/null ' : ''}-X POST "$CODEMAN_API_URL/api/hook-event" ` +
`-H 'Content-Type: application/json' ` +
`-H "X-Codeman-Hook-Secret: $(cat "$CODEMAN_HOOK_SECRET_FILE" 2>/dev/null)" ` +
`--data @- ` +
`2>/dev/null || true`;
// The same POST with stdout DISCARDED, via curl's own `-o`. UserPromptSubmit is
// one of the hook events whose stdout Claude Code injects into the model's
// context (the CLI's own hook reference: "Exit code 0 - stdout shown to
// Claude"), so an undiscarded curl pastes Codeman's `{"success":true,…}`
// envelope into the user's prompt on every single turn.
// ⚠️ It MUST be curl's flag, not a trailing redirect. `curlCmd` already ends
// `… 2>/dev/null || true`, and in `pipeline || true >/dev/null` the shell binds
// the redirection to `true` — which never runs on the success path — so the
// envelope still reaches stdout. Verified in dash and bash.
// ⚠️ The flag is opt-in so the other events' command text stays byte-identical:
// their stdout feeds the SSE stream harmlessly, and changing it would rewrite
// every workspace's settings file for no gain.
const curlCmdSilent = (event: HookEventType) => curlCmd(event, { discardStdout: true });
return {
hooks: {
Notification: [
@@ -410,6 +424,16 @@ export function generateHooksConfig(): { hooks: Record<string, unknown[]> } {
hooks: [{ type: 'command', command: curlCmd('stop'), timeout: HOOK_TIMEOUT_SECONDS }],
},
],
// The pane's LIVE conversation id, reported by the CLI process itself.
// Without it the response viewer has to guess which `<uuid>.jsonl` a pane
// is on after a `/clear`, and the only anchor it can guess from is an
// Enter that went THROUGH Codeman — so a user who attaches to tmux
// directly never gets one and stays pinned to the launch conversation.
UserPromptSubmit: [
{
hooks: [{ type: 'command', command: curlCmdSilent('prompt_submitted'), timeout: HOOK_TIMEOUT_SECONDS }],
},
],
SubagentStop: [
{
hooks: [
@@ -735,9 +759,22 @@ export async function refreshStaleCodemanHooks(casePath: string): Promise<void>
// Approvals Inbox needs the elicitation_complete/elicitation_response
// matchers; their absence marks a pre-inbox hooks block.
const hasElicitationComplete = hooksJson.includes('elicitation_complete');
// The UserPromptSubmit event is what gives a tmux-driven pane a first-hand
// conversation id; its absence marks a pre-prompt_submitted hooks block.
// ⚠️ No surrounding quotes: `hooksJson` is JSON.stringify'd, so the marker
// inside the command reads \"prompt_submitted\" and a quoted needle never
// matches — which would make this gate permanently false and rewrite every
// workspace's settings file on every Claude spawn. The sibling markers are
// quote-free for the same reason.
const hasPromptSubmit = hooksJson.includes('prompt_submitted');
if (
!isOurs ||
(hasSecret && hasBackgroundWake && hasSubagentStopGuard && hasElicitationComplete && !hasTlsFlaglessCurl)
(hasSecret &&
hasBackgroundWake &&
hasSubagentStopGuard &&
hasElicitationComplete &&
hasPromptSubmit &&
!hasTlsFlaglessCurl)
)
return;
const generated = generateHooksConfig();
+110 -4
View File
@@ -156,6 +156,11 @@ const WIRE_ACTIVITY_SETTLE_MS = 15_000;
/** Graceful shutdown delay when stopping session (100ms) */
const GRACEFUL_SHUTDOWN_DELAY_MS = 100;
// Conversations kept in a pane's chain. A pane that /clears repeatedly would
// otherwise grow state.json without bound; 32 covers any real session's history
// and the oldest entries are the ones whose transcripts Claude Code has pruned.
const MAX_CLAUDE_SESSION_CHAIN = 32;
// Filter out terminal focus escape sequences (focus in/out reports)
// ^[[I (focus in), ^[[O (focus out), and the enable/disable sequences
// eslint-disable-next-line no-control-regex
@@ -438,6 +443,17 @@ export class Session extends EventEmitter {
private _wireActivityAt: number;
private _wireActivitySettleUntil: number;
private _claudeSessionId: string | null = null;
// Set only when the id came from the CLI's own UserPromptSubmit/Stop hook
// payload, keyed on this pane's $CODEMAN_SESSION_ID. That binding is a fact,
// not a correlation: it never consults cwd, so a sibling pane on the same
// folder cannot steal it. Runtime-only — a restart must re-earn it from the
// next hook rather than trust a persisted claim.
private _claudeSessionIdIsFirstHand = false;
// Conversations this pane has been on, oldest first, current last. Grows only
// through a first-hand adoption, so it can never splice in a foreign
// conversation. Persisted, because `/clear` is otherwise unrecoverable: the
// predecessor id exists nowhere else once the pane moves on.
private _claudeSessionChain: string[] = [];
private _totalCost: number = 0;
private _messages: ClaudeMessage[] = [];
private _lineBuffer: string = '';
@@ -660,6 +676,8 @@ export class Session extends EventEmitter {
attachmentHistory?: SessionAttachmentHistoryItem[];
/** Restored wall-clock ms of the pane's last Enter (see `lastSubmitAt`). */
lastSubmitAt?: number;
/** Restored conversation chain, oldest first (see `claudeSessionChain`). */
claudeSessionChain?: string[];
/** Restored wall-clock ms of the pane's last output (recovery only; see `_wireActivityAt`). */
lastActivityAt?: number;
/** Remote execution metadata for sessions launched through SSH inside local tmux. */
@@ -723,6 +741,13 @@ export class Session extends EventEmitter {
// response viewer re-derive the live conversation without waiting for the
// user to type again.
this._lastSubmitAt = config.lastSubmitAt ?? 0;
// Restored chain: its tail is the conversation the CLI was actually on when
// the server stopped, which outranks the launch id seeded just above. The
// FIRST-HAND flag is deliberately NOT restored — a persisted claim is not a
// fact, so the pane re-earns the guess-free path from its next hook.
this._claudeSessionChain = Array.isArray(config.claudeSessionChain) ? [...config.claudeSessionChain] : [];
const restoredConversation = this._claudeSessionChain[this._claudeSessionChain.length - 1];
if (restoredConversation) this._claudeSessionId = restoredConversation;
this._mux = config.mux || null;
this._useMux = config.useMux ?? (this._mux !== null && this._mux.isAvailable());
this._muxSession = config.muxSession || null;
@@ -921,6 +946,20 @@ export class Session extends EventEmitter {
return this._claudeSessionId;
}
/**
* True when `claudeSessionId` came from the CLI's own hook payload rather than
* from the launch config or a history correlation. The response viewer uses it
* to skip guessing entirely — see resolveActiveClaudeSessionIdFromHistory().
*/
get claudeSessionIdIsFirstHand(): boolean {
return this._claudeSessionIdIsFirstHand;
}
/** Conversations this pane has been on, oldest first, current last. */
get claudeSessionChain(): readonly string[] {
return this._claudeSessionChain;
}
/** Docker execution metadata when this session runs inside a container, else undefined. */
get docker(): SessionDocker | undefined {
return this._docker;
@@ -978,11 +1017,38 @@ export class Session extends EventEmitter {
// payload). In interactive PTY mode Claude CLI emits no JSON to stdout, so
// `_handleJsonMessage` never sees `session_id`; hooks are the only signal
// that conveys a post-/clear conversation switch.
adoptClaudeSessionId(newId: string): void {
if (!newId || newId === this._claudeSessionId) return;
//
// `firstHand` marks an id that came from the CLI process itself — a hook
// payload whose delivery was keyed on this pane's $CODEMAN_SESSION_ID. Only
// those extend the chain: a history-correlated guess must never be able to
// write a foreign conversation into this pane's permanent record.
adoptClaudeSessionId(newId: string, options: { firstHand?: boolean } = {}): void {
if (!newId) return;
if (options.firstHand) {
this._claudeSessionIdIsFirstHand = true;
this._recordClaudeSessionInChain(newId);
}
if (newId === this._claudeSessionId) return;
this._claudeSessionId = newId;
}
/**
* Append to the conversation chain, oldest first. A repeat of the current tail
* is a no-op (every prompt in a conversation reports the same id), and an id
* already in the chain moves to the tail rather than duplicating, which is
* what a `/resume` back to an earlier conversation does.
*/
private _recordClaudeSessionInChain(id: string): void {
if (this._claudeSessionChain[this._claudeSessionChain.length - 1] === id) return;
const existing = this._claudeSessionChain.indexOf(id);
if (existing !== -1) this._claudeSessionChain.splice(existing, 1);
this._claudeSessionChain.push(id);
// A pane that /clears in a loop must not grow this without bound.
if (this._claudeSessionChain.length > MAX_CLAUDE_SESSION_CHAIN) {
this._claudeSessionChain.splice(0, this._claudeSessionChain.length - MAX_CLAUDE_SESSION_CHAIN);
}
}
/** The tmux session name, if the session is running inside a mux */
get muxName(): string | null {
return this._muxSession?.muxName ?? null;
@@ -1416,6 +1482,12 @@ export class Session extends EventEmitter {
respawnBlocked: this._respawnBlocked || undefined,
attachmentHistory: this.attachmentHistory.length > 0 ? this.attachmentHistory : undefined,
lastSubmitAt: this._lastSubmitAt || undefined,
// Only a chain the CLI's own hooks vouched for is persisted, and only when
// the pane actually moved conversation. Its LAST entry is the live one, so
// it is also what restores `claudeSessionId` across a restart — `start()`
// resets that field to the launch id at three separate points, which is
// why a recovered pane otherwise shows its pre-/clear transcript forever.
claudeSessionChain: this._claudeSessionChain.length > 0 ? [...this._claudeSessionChain] : undefined,
// envOverrides intentionally NOT on the public SessionState type — they must not
// leak into SSE / GET /api/sessions broadcasts (schema allows OPENCODE_*, which
// can carry secrets). For disk persistence, session-manager calls
@@ -1955,6 +2027,11 @@ export class Session extends EventEmitter {
}, REMOTE_CLI_VERSION_PROBE_DELAY_MS);
}
// ⚠️ Hoisted, because the "third reset point" below runs unconditionally
// AFTER the mux branch and would otherwise stomp the restored conversation
// straight back to the launch id.
let restoredConversation: string | undefined;
// If mux wrapping is enabled, create or attach to a mux session
if (this._useMux && this._mux) {
try {
@@ -1999,8 +2076,19 @@ export class Session extends EventEmitter {
// reason: its thread id lives in `_codexConfig`, so without it every
// respawn drops a resumed codex session's alias and its Past-Sessions
// row springs back as a duplicate that still resumes.
// ⚠️ A RESTORED mux session is the one case where the launch id is a
// lie: the CLI never stopped, so a `/clear` before the Codeman restart
// already moved it to a conversation `this.id` knows nothing about. The
// persisted chain's tail is that conversation, reported first-hand by
// the CLI's own hook, so it outranks every fallback here. A NEW pane has
// an empty chain and falls through to the resume/alias fallbacks.
restoredConversation = isRestored ? this._claudeSessionChain[this._claudeSessionChain.length - 1] : undefined;
this._claudeSessionId =
this._resumeSessionId || this._ompConfig?.resumeSessionId || this._codexConfig?.resumeSessionId || this.id;
restoredConversation ||
this._resumeSessionId ||
this._ompConfig?.resumeSessionId ||
this._codexConfig?.resumeSessionId ||
this.id;
// 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
@@ -2104,8 +2192,16 @@ export class Session extends EventEmitter {
// the ompConfig and codexConfig fallbacks or it stomps the mux branch's
// correctly-resolved OMP/codex alias back to this.id on every mux/plain-
// reattach boot recovery (the "third reset point" — see DECISIONS.md).
// For the same reason it needs `restoredConversation`: on a RESTORED mux
// attach the CLI never stopped and may have `/clear`ed before the restart,
// so the launch id is a lie and the chain's tail is the live conversation.
// It is empty on every other path, so those paths keep the alias chain.
this._claudeSessionId =
this._resumeSessionId || this._ompConfig?.resumeSessionId || this._codexConfig?.resumeSessionId || this.id;
restoredConversation ||
this._resumeSessionId ||
this._ompConfig?.resumeSessionId ||
this._codexConfig?.resumeSessionId ||
this.id;
this._pid = this.ptyProcess.pid;
console.log('[Session] Interactive PTY spawned with PID:', this._pid);
@@ -3232,6 +3328,16 @@ export class Session extends EventEmitter {
}
}
/**
* A prompt was submitted, reported by the CLI's own UserPromptSubmit hook.
* `_trackSubmit` only sees input that flows through Codeman's write path, so
* a pane the user drives by attaching to tmux directly never stamped this and
* `lastSubmitAt` stayed 0 for its whole life.
*/
markPromptSubmitted(): void {
this._lastSubmitAt = Date.now();
}
/**
* Per-client highest-applied input sequence, for exactly-once input delivery.
* Keyed by the web client's stable `clientId`. Bounded so many devices over a
+63 -8
View File
@@ -951,14 +951,23 @@ export interface DockerLaunchOptions {
export function buildDockerLaunchCommand(opts: DockerLaunchOptions): string {
const { mode, docker, sessionId, resumeSessionId, createContext, execEnv, execEnvNames, seedCopies } = opts;
const base = buildDockerBaseArgs(docker).join(' ');
const createArgs = buildDockerCreateArgs(createContext).join(' ');
// ADOPTED container (docker.owned === false): the user built it and runs it, so
// this chain may only LOOK and then exec. No image check (the image is theirs),
// no create, and above all no `start` — starting a container we do not own is
// exactly the lifecycle mutation adoption promises never to perform. A missing
// or stopped container fails closed with an actionable message instead.
const adopted = docker.owned === false;
// Built lazily: an adopted case has no meaningful create-config, so computing
// create args for it would demand a context the adopt path never assembles.
const createArgs = adopted ? '' : buildDockerCreateArgs(createContext).join(' ');
const name = shellescape(docker.containerName);
const workdir = shellescape(docker.containerWorkdir);
const image = shellescape(docker.image);
const dkrName = dockerTmuxSessionName(sessionId);
const sid = sessionId.slice(0, 8);
let modeCommand = docker.commands?.[mode as DockerCommandMode] || defaultDockerCommandForMode(mode);
let modeCommand =
docker.commands?.[mode as DockerCommandMode] || defaultDockerCommandForMode(mode, !!docker.runsAsRoot);
if (mode === 'claude') {
modeCommand = claudeDockerPaneCommand(modeCommand, sessionId, resumeSessionId);
} else if (resumeSessionId) {
@@ -994,7 +1003,16 @@ export function buildDockerLaunchCommand(opts: DockerLaunchOptions): string {
);
const startFailMsg = shellescape(`Codeman: container ${docker.containerName} failed to start (docker daemon down?)`);
const imageCheck = `${base} image inspect ${image} >/dev/null 2>&1 || { echo ${imageMissingMsg}; exit 1; }`;
const notFoundMsg = shellescape(
`Codeman: container ${docker.containerName} not found. Adopted containers are never created by Codeman - start it yourself, then reopen this session.`
);
const notRunningMsg = shellescape(
`Codeman: container ${docker.containerName} is not running. Codeman never starts a container it does not own - start it yourself, then reopen this session.`
);
const imageCheck = adopted
? ''
: `${base} image inspect ${image} >/dev/null 2>&1 || { echo ${imageMissingMsg}; exit 1; }`;
// create-if-missing (idempotent): reconnect / boot recovery re-runs this exact
// chain. A daemon without swap accounting warns whenever --memory is present,
// even when --memory-swap is omitted. In compatibility mode, retain the memory
@@ -1011,14 +1029,27 @@ export function buildDockerLaunchCommand(opts: DockerLaunchOptions): string {
`elif ${base} inspect ${name} >/dev/null 2>&1; then ${removeCreateOutput}; ` +
`else ${filteredCreateOutput} >&2; ${removeCreateOutput}; false; fi; }`
: `${base} ${createArgs}`;
const ensure = `${base} inspect ${name} >/dev/null 2>&1 || ${createCommand}`;
const start = `${base} start ${name} >/dev/null 2>&1 || { echo ${startFailMsg}; exit 1; }`;
const ensure = adopted
? `${base} inspect ${name} >/dev/null 2>&1 || { echo ${notFoundMsg}; exit 1; }`
: `${base} inspect ${name} >/dev/null 2>&1 || ${createCommand}`;
// ⚠️ No double quotes and no `$(…)` in the ADOPTED arms. This whole chain is
// embedded in an outer `bash -c "…"`, so an unescaped `"` closes that string early,
// the rest is re-tokenized, and tmux fails to exec with a bare `execvp(3) failed`.
// A `grep -qx` pipeline reads the same answer using only the single-quoted form
// every other line in this builder already uses.
const start = adopted
? `${base} inspect -f ${shellescape('{{.State.Running}}')} ${name} 2>/dev/null | grep -qx true || { echo ${notRunningMsg}; exit 1; }`
: `${base} start ${name} >/dev/null 2>&1 || { echo ${startFailMsg}; exit 1; }`;
// Seed writable credential config from read-only host mounts ONCE per container
// (guarded by [ -e ] so reconnects never clobber in-container config; `cp -a` for
// whole-dir credential seeds). mkdir -p the parent so a file seed works even when
// no sibling share-mount pre-created the dir. Paths are fixed CONTAINER_HOME
// constants (no shell metachars), so the whole inner command is shell-quoted once.
const seedSteps = (seedCopies ?? []).map((s) => {
// An ADOPTED container gets NO seed copies: those read from create-time
// read-only mounts that do not exist here, and writing host credentials into a
// container the user owns is a mutation adoption does not permit. Its CLIs must
// already be authenticated inside it.
const seedSteps = (adopted ? [] : (seedCopies ?? [])).map((s) => {
const cp = s.recursive ? 'cp -a' : 'cp';
const parent = s.to.slice(0, s.to.lastIndexOf('/'));
return `mkdir -p ${parent} 2>/dev/null; [ -e ${s.to} ] || ${cp} ${s.from} ${s.to} 2>/dev/null || true`;
@@ -1026,7 +1057,7 @@ export function buildDockerLaunchCommand(opts: DockerLaunchOptions): string {
const innerCmd = seedSteps.length ? `${seedSteps.join(' ; ')} ; ${tmuxInvocation}` : tmuxInvocation;
const execCmd = `exec ${base} exec -it --workdir ${workdir} ${execEnvFlags.join(' ')} ${name} sh -lc ${shellescape(innerCmd)}`;
return [imageCheck, ensure, start, execCmd].join(' ; ');
return [imageCheck, ensure, start, execCmd].filter(Boolean).join(' ; ');
}
/**
@@ -1042,13 +1073,29 @@ export function buildDockerKillCommand(options: { docker: SessionDocker; session
return `${base} exec ${shellescape(docker.containerName)} tmux -L ${DOCKER_TMUX_SOCKET} kill-session -t ${shellescape(dkrName)}`;
}
/**
* Guard for the two builders that mutate CONTAINER lifecycle. They are pure
* string builders, so refusing here means an adopted container cannot even have
* a stop/remove command constructed for it — there is no shape of caller bug
* that turns into a `docker stop`/`rm` on something we do not own.
*/
function assertOwnedContainer(docker: SessionDocker, action: string): void {
if (docker.owned === false) {
throw new Error(
`Refusing to ${action} adopted container "${docker.containerName}": Codeman does not own its lifecycle.`
);
}
}
/** Explicit container stop (frees RAM/CPU; conversation resumes on next launch via --resume). */
export function buildDockerStopCommand(docker: SessionDocker): string {
assertOwnedContainer(docker, 'stop');
return `${buildDockerBaseArgs(docker).join(' ')} stop -t 10 ${shellescape(docker.containerName)}`;
}
/** Explicit container removal (case-delete). Destroys in-image state; bind mounts survive. */
export function buildDockerRemoveCommand(docker: SessionDocker): string {
assertOwnedContainer(docker, 'remove');
return `${buildDockerBaseArgs(docker).join(' ')} rm -f ${shellescape(docker.containerName)}`;
}
@@ -1725,7 +1772,15 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
// `missingCliMessage()` returns null for a mode with no binary to find (`shell`), and
// carries bounded PATH/login-shell/search-dir diagnostics so the error says where we
// actually looked.
if (!cliDir) {
//
// ⚠️ Skipped entirely for a DOCKER session: the CLI runs INSIDE the container, so the
// host does not need it at all. Demanding it here threw for a host without the binary,
// the catch fell back to a direct PTY, and that PTY tried to exec the CLI on the HOST —
// surfacing as a bare `execvp(3) failed: No such file or directory` with nothing
// pointing at the real cause. The container's own CLIs are verified by the adoption
// preflight / image gate before launch instead.
const cliRunsInContainer = !!docker;
if (!cliRunsInContainer && !cliDir) {
const message = missingCliMessage(mode);
if (message) throw new Error(message);
}
+22
View File
@@ -110,6 +110,10 @@ export type HookEventType =
| 'stop'
| 'teammate_idle'
| 'task_completed'
// Claude Code's UserPromptSubmit. The payload's `session_id` is the pane's
// LIVE conversation id, reported by the CLI process itself, so it survives a
// `/clear` without any cwd/timestamp correlation.
| 'prompt_submitted'
// No Claude Code hook behind this one: it is the DeepSeek status bridge's
// "a turn STARTED" report (see deepseek-status-shim.ts). Keep in step with
// HookEventSchema in web/schemas.ts.
@@ -167,6 +171,24 @@ export interface CaseInfo {
image?: string;
path: string;
network?: string;
/**
* CLIs available INSIDE the container. A container case runs its agents in
* the container, so HOST CLI availability says nothing about what it can
* run. Absent = unknown (an owned container runs our base image, which ships
* every CLI), which the UI reads as "do not gate".
*/
availableModes?: string[];
/**
* `false` for an ADOPTED container (mirror of `DockerCase.owned`); absent = owned.
*
* ⚠️ The UI needs this to read a FAILED container probe correctly. For an adopted
* case a missing container is a real fault worth reporting, because the user is the
* only one who can start it. For an owned case it is the NORMAL state before the
* first session: the container is created on demand by the launch chain, so treating
* "not found" as a fault there hid every agent mode behind an error telling the user
* to start a container Codeman was about to create itself.
*/
owned?: boolean;
};
}
+49
View File
@@ -244,6 +244,33 @@ export interface DockerCase {
containerWorkdir?: string;
/** Container name (default codeman-case-<slug>). */
container?: string;
/**
* Whether THIS Codeman created the container (mirror of `SessionRemote.owned`).
*
* - `true` (default for cases Codeman linked/quick-created): we own the
* container; drift may recreate it, case-delete may `docker rm -f` it, and
* the launch chain may create + start it.
* - `false` (ADOPTED: an already-running container the user built and runs
* themselves): Codeman must never create, start, stop, restart or remove it.
* The launch chain fails closed when the container is missing or not running
* instead of touching its lifecycle, drift is not evaluated (there is no
* `codeman.confighash` label to compare), and no credential seed is copied
* into its HOME. Only the in-container tmux session is ever created or
* killed — exactly the `owned:false` remote-SSH contract.
*
* Absent is treated as owned (cases persisted before this field existed were
* all created by us).
*/
owned?: boolean;
/**
* CLIs found INSIDE the container by the adoption preflight. A container case
* runs its agents in the container, so host CLI availability says nothing about
* what this case can run — the base image ships every CLI, and an adopted
* container ships whatever its owner installed. Absent = unknown (owned cases,
* or a case linked before this field existed), which callers read as "do not
* gate".
*/
availableModes?: SessionMode[];
/** Last captured Claude conversation id, replayed via --resume on a fresh launch. */
lastClaudeSessionId?: string;
}
@@ -276,6 +303,19 @@ export interface SessionDocker {
extraExecArgs?: string[];
/** Stable hash of the drift-relevant create args (recreate-on-drift detection). */
configHash?: string;
/**
* Whether the container's exec user is root. Claude Code REFUSES
* `--dangerously-skip-permissions` as root, and an adopted container's user
* belongs to its owner, so the flag is omitted rather than letting the pane
* die with a message only visible inside the container.
*/
runsAsRoot?: boolean;
/**
* Mirror of `DockerCase.owned`, flattened onto the live session so every
* lifecycle decision (launch chain, drift, stop, remove) can see it without
* re-reading docker-cases.json. Absent = owned. See `DockerCase.owned`.
*/
owned?: boolean;
}
/**
@@ -648,6 +688,15 @@ export interface SessionState {
* again until the pane's own Enter is known.
*/
lastSubmitAt?: number;
/**
* Claude conversations this pane has been on, oldest first, current last.
* Written ONLY from a first-hand `UserPromptSubmit`/`Stop` hook payload —
* never from the history correlation — so it cannot record a sibling pane's
* conversation. Persisted because `/clear` is otherwise unrecoverable: once
* the pane moves on, the predecessor id exists nowhere else, and the last
* entry is what re-pins `claudeSessionId` past `start()`'s three resets.
*/
claudeSessionChain?: string[];
/**
* PTY-exit circuit breaker tripped — respawn blocked until an explicit restart
* (COD-118). Runtime-only: never restored on boot (fresh server = fresh breaker).
+17 -11
View File
@@ -142,7 +142,9 @@ function isPasswordChangeExempt(req: FastifyRequest): boolean {
* match the prefix at all. The Host allowlist is NOT bypassed, so DNS-rebinding
* protection still applies to these requests.
*/
function hasValidWebviewCapability(req: FastifyRequest): boolean {
function hasValidWebviewCapability(req: FastifyRequest, basePath = ''): boolean {
// req.url is already base-stripped by the server's rewriteUrl, so the path form
// needs no base; the Referer form below is browser-supplied and does.
const url = (req.url ?? '').split('?')[0];
const fromPath = capabilityFromProxyPath(url);
@@ -167,7 +169,10 @@ function hasValidWebviewCapability(req: FastifyRequest): boolean {
// class the 404 relay could never rescue. See matchesRegisteredRoute.
if (matchesRegisteredRoute(req, url)) return false;
const fromReferer = capabilityFromReferer(typeof req.headers.referer === 'string' ? req.headers.referer : undefined);
const fromReferer = capabilityFromReferer(
typeof req.headers.referer === 'string' ? req.headers.referer : undefined,
basePath
);
return !!fromReferer && webviewCapabilities.resolve(fromReferer) !== undefined;
}
@@ -210,7 +215,7 @@ function matchesRegisteredRoute(req: FastifyRequest, url: string): boolean {
*
* @returns AuthState for lifecycle management (dispose on server stop)
*/
export function registerAuthMiddleware(app: FastifyInstance, https: boolean): AuthState {
export function registerAuthMiddleware(app: FastifyInstance, https: boolean, basePath = ''): AuthState {
const state: AuthState = {
authSessions: null,
authFailures: null,
@@ -270,7 +275,7 @@ export function registerAuthMiddleware(app: FastifyInstance, https: boolean): Au
ttlMs: AUTH_FAILURE_WINDOW_MS,
refreshOnGet: false,
});
registerMultiUserAuthHook(app, https, authSessions, authFailures, hookSecretFailures, state.userFailures);
registerMultiUserAuthHook(app, https, authSessions, authFailures, hookSecretFailures, state.userFailures, basePath);
return state;
}
@@ -293,7 +298,7 @@ export function registerAuthMiddleware(app: FastifyInstance, https: boolean): Au
}
// Web-tab proxy, authenticated by the capability in the path, not the cookie.
if (hasValidWebviewCapability(req)) {
if (hasValidWebviewCapability(req, basePath)) {
done();
return;
}
@@ -381,7 +386,8 @@ function registerMultiUserAuthHook(
authSessions: StaleExpirationMap<string, AuthSessionRecord>,
authFailures: StaleExpirationMap<string, number>,
hookSecretFailures: StaleExpirationMap<string, number>,
userFailures: StaleExpirationMap<string, number>
userFailures: StaleExpirationMap<string, number>,
basePath = ''
): void {
const setSessionCookie = (reply: FastifyReply, token: string) =>
reply.setCookie(AUTH_COOKIE_NAME, token, {
@@ -432,7 +438,7 @@ function registerMultiUserAuthHook(
// `req.authUser` stays undefined here on purpose: the proxy handler enforces
// ownership against the identity BOUND TO THE CAPABILITY, which is stricter
// than re-deriving it from a request that carries no credentials.
if (hasValidWebviewCapability(req)) return;
if (hasValidWebviewCapability(req, basePath)) return;
const clientIp = req.ip;
@@ -552,7 +558,7 @@ const SAFE_HTTP_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
*
* WebSocket upgrades are validated separately in the ws route handler.
*/
export function registerHostGuard(app: FastifyInstance, getPolicy: () => HostPolicy): void {
export function registerHostGuard(app: FastifyInstance, getPolicy: () => HostPolicy, basePath = ''): void {
app.addHook('onRequest', (req, reply, done) => {
const policy = getPolicy();
if (!isAllowedRequestHost(req.headers.host, policy)) {
@@ -568,7 +574,7 @@ export function registerHostGuard(app: FastifyInstance, getPolicy: () => HostPol
if (
!SAFE_HTTP_METHODS.has(req.method) &&
!isAllowedRequestOrigin(req.headers.origin, policy) &&
!hasValidWebviewCapability(req)
!hasValidWebviewCapability(req, basePath)
) {
reply.code(403).send('Forbidden: cross-site request blocked');
return;
@@ -580,7 +586,7 @@ export function registerHostGuard(app: FastifyInstance, getPolicy: () => HostPol
/**
* Register security headers and CORS middleware on every response.
*/
export function registerSecurityHeaders(app: FastifyInstance, https: boolean): void {
export function registerSecurityHeaders(app: FastifyInstance, https: boolean, basePath = ''): void {
// Gesture-control overlay (opt-in via CODEMAN_GESTURE=1) runs MediaPipe, which
// needs WebAssembly eval (script-src) and blob workers (worker-src). Its wasm
// runtime + model are self-hosted under /gesture/ (same-origin, covered by
@@ -634,7 +640,7 @@ export function registerSecurityHeaders(app: FastifyInstance, https: boolean): v
// net::ERR_FAILED while the page itself renders fine (script/css/img loads
// are not CORS-checked). Falling through lets the proxy route reply with the
// right headers.
if (req.method === 'OPTIONS' && !hasValidWebviewCapability(req)) {
if (req.method === 'OPTIONS' && !hasValidWebviewCapability(req, basePath)) {
reply.code(204).send();
done();
return;
+55 -10
View File
@@ -80,7 +80,7 @@ try {
const prev = localStorage.getItem('codeman-crash-diag');
if (prev) {
console.log('[CRASH-DIAG] Previous session breadcrumbs:\n' + prev);
navigator.sendBeacon('/api/crash-diag', JSON.stringify({ data: prev, id: _crashDiag._pageId + '-prev' }));
navigator.sendBeacon(CodemanBase.url('/api/crash-diag'), JSON.stringify({ data: prev, id: _crashDiag._pageId + '-prev' }));
}
} catch {}
_crashDiag.log('PAGE LOAD');
@@ -89,7 +89,7 @@ _crashDiag.log('PAGE LOAD');
function _crashDiagBeacon() {
try {
if (_crashDiag._entries.length > 0) {
navigator.sendBeacon('/api/crash-diag', JSON.stringify({ data: _crashDiag._entries.join('\n'), id: _crashDiag._pageId }));
navigator.sendBeacon(CodemanBase.url('/api/crash-diag'), JSON.stringify({ data: _crashDiag._entries.join('\n'), id: _crashDiag._pageId }));
}
} catch {}
}
@@ -1268,7 +1268,11 @@ class CodemanApp {
if (typeof window !== 'undefined' && typeof window.__CODEMAN_SOLO__ === 'string' && window.__CODEMAN_SOLO__) {
return window.__CODEMAN_SOLO__;
}
const m = location.pathname.match(/^\/session\/([^/]+)\/?$/);
// Strip the reverse-proxy base so the match works under a sub-path mount.
const base = window.CodemanBase?.base || '';
let path = location.pathname;
if (base && path.startsWith(base)) path = path.slice(base.length) || '/';
const m = path.match(/^\/session\/([^/]+)\/?$/);
return m ? decodeURIComponent(m[1]) : null;
} catch { return null; }
}
@@ -1293,7 +1297,7 @@ class CodemanApp {
if (this.detachedSessions.has(id) && this._raiseDetached(id)) return;
const features = 'width=960,height=680,menubar=no,toolbar=no,location=no,status=no';
let win = null;
try { win = window.open('/session/' + encodeURIComponent(id), 'codeman-session-' + id, features); } catch {}
try { win = window.open(CodemanBase.url('/session/' + encodeURIComponent(id)), 'codeman-session-' + id, features); } catch {}
if (!win) {
this.showToast?.('Pop-out blocked — allow popups for this site to detach a session', 'error');
return;
@@ -1545,7 +1549,7 @@ class CodemanApp {
// regardless of filter (server side).
const _sseParams = new URLSearchParams({ clientId: this._clientId });
if (this.activeSessionId) _sseParams.set('sessions', this.activeSessionId);
this.eventSource = new EventSource(`/api/events?${_sseParams.toString()}`);
this.eventSource = new EventSource(CodemanBase.url(`/api/events?${_sseParams.toString()}`));
// Store all event listeners for cleanup on reconnect.
//
@@ -2183,15 +2187,26 @@ class CodemanApp {
}
/** Build one response-viewer message so the brief and full views share markup and CSS. */
_buildResponseViewerMessage(text, role, agentLabel) {
_buildResponseViewerMessage(text, role, agentLabel, meta) {
const div = document.createElement('div');
const isUser = role === 'user';
div.className = 'rv-message ' + (isUser ? 'rv-msg-user' : 'rv-msg-assistant');
// Consecutive messages from one speaker inside one turn are segments of a
// single utterance: one badge, a hairline seam. Claude emits a median of 3
// messages per turn (p90 11, max 51), so a badge per message would be the
// card spam the old concatenation was introduced to avoid. `meta` is
// optional so the brief view's 3-argument call keeps its exact shape.
const continuation = !!(meta && meta.continuation);
if (continuation) div.classList.add('rv-msg-cont');
if (meta && meta.kind) div.dataset.kind = meta.kind;
if (meta && meta.queued) div.dataset.queued = '1';
if (!continuation) {
const roleBadge = document.createElement('div');
roleBadge.className = 'rv-role ' + (isUser ? 'rv-role-user' : 'rv-role-assistant');
roleBadge.textContent = isUser ? 'You' : agentLabel;
div.appendChild(roleBadge);
}
const renderedText = document.createElement('div');
renderedText.className = 'rv-text';
@@ -2351,19 +2366,49 @@ class CodemanApp {
if (!body) return;
if (messages.length === 0) {
body.textContent = 'No conversation history available';
// Never destroy what the eye button already rendered: the brief view has
// a terminal-buffer fallback (see toggleResponseViewer) that this
// endpoint does not, so an empty full-context result must not wipe a
// real answer the user is reading.
// ⚠️ Idempotent, because More deliberately stays live here: the branch
// returns before the button is hidden so a transcript that appears a
// moment later can still be loaded, and appending would then stack a
// second identical notice on every retry.
// `:scope >` keeps the lookup off model-rendered markdown inside .rv-text.
let notice = body.querySelector(':scope > .rv-notice');
if (!notice) {
notice = document.createElement('div');
notice.className = 'rv-notice';
body.appendChild(notice);
}
const emptyText = 'No full conversation history available for this session';
notice.textContent = window.codemanT?.(emptyText) || emptyText;
return;
}
// Render conversation thread
const agentLabel = this._getResponseViewerAgentLabel();
body.innerHTML = '';
let previous = null;
for (const msg of messages) {
body.appendChild(this._buildResponseViewerMessage(msg.text, msg.role, agentLabel));
// ⚠️ A numeric `turn` is REQUIRED, never same-role adjacency alone.
// Only the Claude reader emits turns; Codex and the external-CLI pane
// parser emit adjacent assistant/response blocks with no turn at all, and
// an older server emits none either — all three must keep rendering one
// badged card per message exactly as they do today.
const continuation =
!!previous && previous.role === msg.role && typeof msg.turn === 'number' && previous.turn === msg.turn;
body.appendChild(this._buildResponseViewerMessage(msg.text, msg.role, agentLabel, { ...msg, continuation }));
previous = msg;
}
this._bindResponseViewerInteractions(body);
if (title) title.textContent = `Conversation (${messages.length} messages)`;
const turns = new Set(messages.filter((msg) => typeof msg.turn === 'number').map((msg) => msg.turn)).size;
if (title) {
title.textContent = turns
? `Conversation (${messages.length} messages, ${turns} turns)`
: `Conversation (${messages.length} messages)`;
}
if (moreBtn) moreBtn.style.display = 'none';
// Scroll to bottom (latest message)
body.scrollTop = body.scrollHeight;
@@ -2753,7 +2798,7 @@ class CodemanApp {
// up to the limit).
const cid = this._clientId ? `${this._clientId}:${this._wsTabNonce}` : '';
const cidQuery = cid ? `?cid=${encodeURIComponent(cid)}` : '';
const url = `${proto}//${location.host}/ws/sessions/${sessionId}/terminal${cidQuery}`;
const url = `${proto}//${location.host}${CodemanBase.base}/ws/sessions/${sessionId}/terminal${cidQuery}`;
const ws = new WebSocket(url);
this._ws = ws;
this._wsSessionId = sessionId;
+58
View File
@@ -22,6 +22,63 @@
// Codeman — Shared constants and utility functions for frontend modules
// ═══════════════════════════════════════════════════════════════
// Reverse-proxy base path
// ═══════════════════════════════════════════════════════════════
// When Codeman is served behind a reverse proxy under a sub-path (e.g. /codeman/),
// the server injects `window.__CODEMAN_BASE__` (normalized: '' for root, or '/foo').
// The `<base href>` tag in index.html already rewrites the RELATIVE asset refs, but
// every URL the frontend builds at RUNTIME is root-absolute (`/api/...`, `/ws/...`)
// and root-absolute URLs ignore `<base>` — so those must be prefixed here instead.
// Rather than touch ~190 call sites, all runtime URL construction routes through this
// ONE choke point: `CodemanBase.url()` is the route builder, and a thin wrapper over
// `fetch` applies it transparently. The handful of EventSource/WebSocket sites call
// `CodemanBase.url()` / `CodemanBase.base` explicitly. No-op when mounted at root.
const CodemanBase = (function () {
// `window` is absent in some unit-test vm contexts that load this module in
// isolation; guard so the module still evaluates (base degrades to root).
const _win = typeof window !== 'undefined' ? window : undefined;
const base = String((_win && _win.__CODEMAN_BASE__) || '').replace(/\/+$/, '');
/**
* Prefix a root-absolute application path with the mount base. Leaves untouched:
* relative paths and fragments/queries (resolved against `<base>`), protocol-relative
* (`//host`) and absolute URLs, and paths already carrying the prefix.
*/
function url(path) {
if (!base) return path;
if (typeof path !== 'string' || path.length === 0) return path;
if (path[0] !== '/') return path; // relative / fragment / query
if (path[1] === '/') return path; // protocol-relative
if (path === base || path.startsWith(base + '/') || path.startsWith(base + '?')) return path;
return base + path;
}
return { base, url };
})();
if (typeof window !== 'undefined') window.CodemanBase = CodemanBase;
// Transparently prefix root-absolute app paths on every fetch, so the many
// `/api/...` string literals across the frontend need no per-call edit.
if (typeof window !== 'undefined' && CodemanBase.base && typeof window.fetch === 'function') {
const _origFetch = window.fetch.bind(window);
window.fetch = function (input, init) {
if (typeof input === 'string') return _origFetch(CodemanBase.url(input), init);
if (typeof Request !== 'undefined' && input instanceof Request) {
try {
const u = new URL(input.url);
if (u.origin === location.origin) {
const prefixed = CodemanBase.url(u.pathname);
if (prefixed !== u.pathname) {
return _origFetch(new Request(u.origin + prefixed + u.search + u.hash, input), init);
}
}
} catch (_e) {
/* not a parseable URL — fall through */
}
}
return _origFetch(input, init);
};
}
// ═══════════════════════════════════════════════════════════════
// Web Push Utilities
// ═══════════════════════════════════════════════════════════════
@@ -958,6 +1015,7 @@ const SSE_EVENTS = {
HOOK_AGENT_WORKING: 'hook:agent_working',
HOOK_TEAMMATE_IDLE: 'hook:teammate_idle',
HOOK_TASK_COMPLETED: 'hook:task_completed',
HOOK_PROMPT_SUBMITTED: 'hook:prompt_submitted',
// Approvals Inbox
APPROVAL_PENDING: 'approval:pending',
+14
View File
@@ -86,6 +86,7 @@
'Instance count': '实例数量',
'No response yet': '暂无回复',
'No response yet — send a message in this session first.': '暂无回复,请先在此会话中发送一条消息。',
'No full conversation history available for this session': '此会话没有可显示的完整对话历史',
'Last Response': '最近一次回复',
More: '更多',
'Codeman version': '{name}版本',
@@ -713,6 +714,19 @@
'Runs this case in a hardened, isolated container. The base image is built automatically on first use. Docker/Podman must be installed.':
'在加固的隔离容器中运行此案例。首次使用时会自动构建基础镜像;必须安装 Docker/Podman。',
'Run in an isolated Docker container': '在隔离的 Docker 容器中运行',
'Attach to an existing container': '接入已在运行的容器',
'On: Codeman only runs docker exec into a container you already built and run — it never creates, starts, stops or removes it. The CLIs must already be installed and logged in inside it.':
'开启后,{name}只会 docker exec 进入你自己构建并运行的容器,绝不创建、启动、停止或删除它;容器内必须已安装并登录好相应 CLI。',
'Container Name': '容器名称',
'Pick from the running containers or type a name.': '从正在运行的容器中选择,或直接输入名称。',
'Check container': '检查容器',
'Container Workdir': '容器内工作目录',
'A path that already exists inside the container. Adoption mounts nothing, so this need not match the host workspace path.':
'容器内已存在的路径。接入不挂载任何目录,因此它不必与主机工作区路径相同。',
'Already have a container running?': '已经有正在运行的容器?',
'Attach to it instead': '改为接入该容器',
'Codeman only runs docker exec into it and never touches its lifecycle.':
'{name}只会 docker exec 进入它,绝不触碰其生命周期。',
'Absolute HOST directory, bind-mounted into the container. Codeman scaffolds CLAUDE.md + hooks into it.':
'绑定挂载到容器中的主机绝对目录;{name}会在其中生成 CLAUDE.md 和 hooks。',
'A reusable docker host profile. Reuse the same ID across cases to share settings.':
+32 -3
View File
@@ -2589,8 +2589,15 @@
<div class="modal-content modal-lg set-shell">
<div class="modal-header set-shell-head">
<h3>Add Case</h3>
<!-- mobile.css hides this modal's .set-foot, so on a phone the footer's
Create/Link button is unreachable and the modal cannot be submitted
at all. Mirrors the Settings modal's header Save: close first in the
DOM so the focus trap still lands on it, row-reverse puts this to
its left. Both buttons are driven together by switchCaseModalTab()
and submitCaseModal(). -->
<div class="set-head-actions">
<button class="modal-close" onclick="app.closeCreateCaseModal()" aria-label="Close create case">&times;</button>
<button class="set-head-save" id="caseModalSubmitMobile" onclick="app.submitCaseModal()">Create</button>
</div>
</div>
<div class="set-body">
@@ -2644,6 +2651,7 @@
<div class="form-row docker-quick-row">
<label class="checkbox-row"><input type="checkbox" id="newCaseDocker"> 🐳 Run in an isolated Docker container</label>
<span class="form-hint">Runs this case in a hardened, isolated container. The base image is built automatically on first use. Docker/Podman must be installed.</span>
<span class="form-hint">Already have a container running? <button type="button" class="btn-inline-check" id="dockerAdoptJumpBtn">Attach to it instead</button> Codeman only runs docker exec into it and never touches its lifecycle.</span>
</div>
<details class="advanced-options docker-quick-settings" id="dockerQuickSettings">
<summary><svg class="set-adv-chev" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 9l6 6 6-6"/></svg><span>Container settings (optional, sensible defaults)</span></summary>
@@ -2847,6 +2855,24 @@
<h2>Docker</h2>
</div>
<p class="set-section-blurb">Run the case inside a container: one per case, shared by all its sessions.</p>
<div class="form-row">
<label class="checkbox-row"><input type="checkbox" id="dockerAdoptExisting"> Attach to an existing container</label>
<span class="form-hint">On: Codeman only runs docker exec into a container you already built and run — it never creates, starts, stops or removes it. The CLIs must already be installed and logged in inside it.</span>
</div>
<div class="form-row docker-adopt-only">
<label>Container Name</label>
<input type="text" id="dockerContainerName" list="dockerContainerList" placeholder="my-dev-box" pattern="[a-zA-Z0-9][a-zA-Z0-9_.-]+" autocomplete="off" autocapitalize="off" spellcheck="false">
<datalist id="dockerContainerList"></datalist>
<span class="form-hint">Pick from the running containers or type a name. <button type="button" class="btn-inline-check" id="dockerAdoptCheckBtn">Check container</button></span>
</div>
<div class="form-row docker-adopt-only">
<label>Container Workdir</label>
<div class="path-input-group">
<input type="text" id="dockerAdoptWorkdir" placeholder="/workspace" autocomplete="off" autocapitalize="off" autocorrect="off" spellcheck="false">
<button type="button" class="btn path-input-browse" onclick="app.openDockerWorkdirPicker()">Browse&hellip;</button>
</div>
<span class="form-hint">A path that already exists inside the container. Adoption mounts nothing, so this need not match the host workspace path.</span>
</div>
<div class="form-row">
<label>Case Name</label>
<input type="text" id="dockerCaseName" placeholder="sandbox" pattern="[a-zA-Z0-9_-]+" autocomplete="off" autocapitalize="off" spellcheck="false">
@@ -2854,7 +2880,10 @@
</div>
<div class="form-row">
<label>Workspace Path</label>
<div class="path-input-group">
<input type="text" id="dockerWorkspacePath" placeholder="/home/user/projects/sandbox" autocomplete="off" autocapitalize="off" autocorrect="off" spellcheck="false">
<button type="button" class="btn path-input-browse" onclick="app.openDockerWorkspacePathPicker()">Browse&hellip;</button>
</div>
<span class="form-hint">Absolute HOST directory, bind-mounted into the container. Codeman scaffolds CLAUDE.md + hooks into it.</span>
</div>
<div class="form-row">
@@ -2862,12 +2891,12 @@
<input type="text" id="dockerHostId" placeholder="local" pattern="[a-zA-Z0-9_-]+" autocomplete="off" autocapitalize="off" spellcheck="false">
<span class="form-hint">A reusable docker host profile. Reuse the same ID across cases to share settings.</span>
</div>
<div class="form-row">
<div class="form-row docker-create-only">
<label>Image</label>
<input type="text" id="dockerImage" placeholder="codeman/agent:base" autocomplete="off" autocapitalize="off" spellcheck="false">
<span class="form-hint">Build it once with <code>node scripts/build-agent-image.mjs</code>. Contains node + claude/codex/gemini/opencode/agy/pi/grok/dsh + tmux.</span>
</div>
<div class="form-row">
<div class="form-row docker-create-only">
<label>Network</label>
<select id="dockerNetwork">
<option value="bridge">bridge (internet on, default)</option>
@@ -2875,7 +2904,7 @@
<option value="custom">custom bridge</option>
</select>
</div>
<details class="advanced-options">
<details class="advanced-options docker-create-only">
<summary><svg class="set-adv-chev" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 9l6 6 6-6"/></svg><span>Advanced container settings</span></summary>
<div class="advanced-options-content">
<div class="form-row">
+8 -4
View File
@@ -185,9 +185,13 @@ const PathPicker = {
if (this._options.sessionId) params.set('sessionId', this._options.sessionId);
if (this._showHidden) params.set('showHidden', 'true');
try {
const response = await fetch(`/api/filesystem/browse?${params.toString()}`);
const result = await response.json();
if (!response.ok || !result.success) throw new Error(result.error || 'Failed to browse this folder');
// A caller may supply its own source (the container-workdir picker browses
// INSIDE a container, which the host filesystem endpoint cannot answer).
// It returns the same shape, so everything below is unchanged.
const result = this._options.fetchListing
? await this._options.fetchListing(path)
: await (await fetch(`/api/filesystem/browse?${params.toString()}`)).json();
if (!result?.success) throw new Error(result?.error || 'Failed to browse this folder');
if (!this.overlay || loadSequence !== this._loadSequence) return;
this.render(result.data);
} catch (error) {
@@ -304,7 +308,7 @@ const PathPicker = {
// A hidden file is only reachable while the toggle is on, and the preview
// endpoint re-resolves the path independently, so it needs the flag too.
if (this._showHidden) params.set('showHidden', 'true');
const previewUrl = `/api/filesystem/preview?${params.toString()}`;
const previewUrl = (window.CodemanBase?.url || ((p) => p))(`/api/filesystem/preview?${params.toString()}`);
const overlay = document.createElement('div');
overlay.className = 'path-preview-overlay';
+2 -1
View File
@@ -2,7 +2,8 @@
"name": "Codeman",
"short_name": "Codeman",
"description": "Claude Code session manager",
"start_url": "/",
"start_url": "./",
"scope": "./",
"display": "standalone",
"orientation": "any",
"background_color": "#0a0a0a",
+13 -2
View File
@@ -3333,8 +3333,10 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat
recessed tray and matching pill geometry instead of reading as a fat
accent pill parked beside a stray × glyph. Tray colors come from skin
tokens, never a hardcoded black alpha, or the light skins get a grey slab.
`:has()` keeps the tray off the two sheets that carry a lone × (Session
Options and Add Case save from inside their own forms). */
`:has()` keeps the tray off Session Options, the one sheet left carrying a
lone × because it saves from inside its own per-section forms. Add Case
now has a header save of its own (its footer is hidden below 860px, so
that button is the only way to submit it there), and picks up the tray. */
:is(#appSettingsModal, #sessionOptionsModal, #createCaseModal) .set-head-actions:has(.set-head-save) {
padding: 3px;
border: 1px solid var(--border);
@@ -3353,6 +3355,15 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat
font-size: 0.86rem;
}
/* Add Case's pending state has to show on the header button: below 860px it is
the only submit control (the footer is hidden), and the #caseModalSubmit
.loading rule in the phone block dims a button nobody can see. Measured at
390px before this: header opacity 1 for the whole clone, hidden footer 0.6. */
#createCaseModal .set-head-save.loading {
opacity: 0.6;
pointer-events: none;
}
:is(#appSettingsModal, #sessionOptionsModal, #createCaseModal) .set-head-actions .modal-close {
width: 36px;
height: 36px;
+1 -1
View File
@@ -390,7 +390,7 @@ class NotificationManager {
const notif = new Notification(`${this.originalTitle}: ${localizedTitle}`, {
body: localizedBody,
tag, // Groups same-tag notifications
icon: '/favicon.ico',
icon: (window.CodemanBase?.url || ((p) => p))('/favicon.ico'),
silent: true, // We handle audio ourselves
});
+31 -24
View File
@@ -3430,7 +3430,7 @@ Object.assign(CodemanApp.prototype, {
const nameClass = isDir ? 'file-tree-name directory' : 'file-tree-name';
const downloadBtn = !isDir
? `<a class="file-tree-download" href="${escapeHtml(`/api/sessions/${encodeURIComponent(owner)}/file-raw?path=${encodeURIComponent(node.path)}&download=true`)}" title="Download" onclick="event.stopPropagation()">&#x2B07;</a>`
? `<a class="file-tree-download" href="${escapeHtml(CodemanBase.url(`/api/sessions/${encodeURIComponent(owner)}/file-raw?path=${encodeURIComponent(node.path)}&download=true`))}" title="Download" onclick="event.stopPropagation()">&#x2B07;</a>`
: '';
html.push(`
@@ -3605,7 +3605,7 @@ Object.assign(CodemanApp.prototype, {
: '';
const nameClass = isDir ? 'file-tree-name directory' : 'file-tree-name';
const downloadBtn = !isDir
? `<a class="file-tree-download" href="${escapeHtml(`/api/sessions/${ownerPath}/file-raw?path=${encodeURIComponent(match.path)}&download=true`)}" title="Download" onclick="event.stopPropagation()">&#x2B07;</a>`
? `<a class="file-tree-download" href="${escapeHtml(CodemanBase.url(`/api/sessions/${ownerPath}/file-raw?path=${encodeURIComponent(match.path)}&download=true`))}" title="Download" onclick="event.stopPropagation()">&#x2B07;</a>`
: '';
return `
<div class="file-tree-item" data-path="${escapeHtml(match.path)}" data-type="${escapeHtml(match.type)}" data-owner="${escapeHtml(ownerSessionId)}">
@@ -4004,18 +4004,20 @@ Object.assign(CodemanApp.prototype, {
// (html/htm arrive as a download there by design — file-raw serves them
// attachment-only so widening READ never widens RUN.)
const officeDoc = ext === 'docx' || ext === 'pptx';
this.filePreviewDetachUrl = attachmentId
this.filePreviewDetachUrl = CodemanBase.url(
attachmentId
? `/api/sessions/${sessionId}/attachments/${encodeURIComponent(attachmentId)}/${officeDoc ? 'preview' : 'raw'}`
: officeDoc
? `/api/sessions/${sessionId}/file-preview?path=${encodeURIComponent(filePath)}`
: `/api/sessions/${sessionId}/file-raw?path=${encodeURIComponent(filePath)}`;
: `/api/sessions/${sessionId}/file-raw?path=${encodeURIComponent(filePath)}`
);
if (detachBtn) detachBtn.hidden = false;
// Registered attachment: render straight from its by-id routes — images and
// PDFs inline, Office docs via the server-converted PDF preview, text fetched
// raw. (Workspace-path previews fall through to the file-content endpoint.)
if (attachmentId) {
const base = `/api/sessions/${sessionId}/attachments/${encodeURIComponent(attachmentId)}`;
const base = CodemanBase.url(`/api/sessions/${sessionId}/attachments/${encodeURIComponent(attachmentId)}`);
const IMAGE_EXTS = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg']);
// VIDEO/AUDIO mirror VIDEO_ATTACHMENT_EXTENSIONS/AUDIO_ATTACHMENT_EXTENSIONS
// (src/attachment-registry.ts, the single source); the frontend cannot import
@@ -4073,13 +4075,13 @@ Object.assign(CodemanApp.prototype, {
// to file-content below, which would dump the binary bytes as mojibake.
if (ext === 'docx' || ext === 'pptx') {
footerEl.textContent = ext.toUpperCase();
const previewSrc = `/api/sessions/${sessionId}/file-preview?path=${encodeURIComponent(filePath)}`;
const previewSrc = CodemanBase.url(`/api/sessions/${sessionId}/file-preview?path=${encodeURIComponent(filePath)}`);
bodyEl.innerHTML = `<iframe src="${escapeHtml(previewSrc)}" title="${escapeHtml(filePath)}"></iframe>`;
return;
}
if (ext === 'pdf') {
footerEl.textContent = 'PDF';
const rawSrc = `/api/sessions/${sessionId}/file-raw?path=${encodeURIComponent(filePath)}`;
const rawSrc = CodemanBase.url(`/api/sessions/${sessionId}/file-raw?path=${encodeURIComponent(filePath)}`);
bodyEl.innerHTML = `<iframe src="${escapeHtml(rawSrc)}" title="${escapeHtml(filePath)}"></iframe>`;
return;
}
@@ -4113,19 +4115,19 @@ Object.assign(CodemanApp.prototype, {
const data = result.data;
if (data.type === 'image') {
bodyEl.innerHTML = `<img src="${data.url}" alt="${escapeHtml(filePath)}">`;
bodyEl.innerHTML = `<img src="${escapeHtml(CodemanBase.url(data.url))}" alt="${escapeHtml(filePath)}">`;
footerEl.textContent = `${this.formatFileSize(data.size)} \u2022 ${data.extension}`;
} else if (data.type === 'video') {
// playsinline: iOS otherwise hijacks playback into its fullscreen
// player, which leaves the overlay behind it and its own close button
// as the only way back.
bodyEl.innerHTML = `<video src="${escapeHtml(data.url)}" controls autoplay playsinline preload="metadata"></video>`;
bodyEl.innerHTML = `<video src="${escapeHtml(CodemanBase.url(data.url))}" controls autoplay playsinline preload="metadata"></video>`;
footerEl.textContent = `${this.formatFileSize(data.size)} \u2022 ${data.extension}`;
} else if (data.type === 'audio') {
bodyEl.innerHTML = `<audio src="${escapeHtml(data.url)}" controls autoplay preload="metadata"></audio>`;
bodyEl.innerHTML = `<audio src="${escapeHtml(CodemanBase.url(data.url))}" controls autoplay preload="metadata"></audio>`;
footerEl.textContent = `${this.formatFileSize(data.size)} \u2022 ${data.extension}`;
} else if (data.type === 'binary') {
const downloadHref = `/api/sessions/${sessionId}/file-raw?path=${encodeURIComponent(filePath)}&download=true`;
const downloadHref = CodemanBase.url(`/api/sessions/${sessionId}/file-raw?path=${encodeURIComponent(filePath)}&download=true`);
bodyEl.innerHTML = `<div class="binary-message">Binary file (${this.formatFileSize(data.size)})<br>Cannot preview<br><a href="${escapeHtml(downloadHref)}" download>Download</a></div>`;
footerEl.textContent = data.extension || 'binary';
} else {
@@ -4422,9 +4424,11 @@ Object.assign(CodemanApp.prototype, {
},
openAttachmentInNewTab(sessionId, filePath, attachmentId = null) {
const url = attachmentId
const url = CodemanBase.url(
attachmentId
? `/api/sessions/${sessionId}/attachments/${encodeURIComponent(attachmentId)}/raw`
: `/api/sessions/${sessionId}/file-raw?path=${encodeURIComponent(filePath)}`;
: `/api/sessions/${sessionId}/file-raw?path=${encodeURIComponent(filePath)}`
);
window.open(url, '_blank');
},
@@ -4460,19 +4464,22 @@ Object.assign(CodemanApp.prototype, {
const stack = this.ensureAttachmentCardStack();
const session = this.sessions.get(sessionId);
const sessionName = session?.name || sessionId.substring(0, 8);
const attachmentRawUrl =
const attachmentRawUrl = CodemanBase.url(
rawUrl ||
(attachmentId
? `/api/sessions/${sessionId}/attachments/${encodeURIComponent(attachmentId)}/raw`
: `/api/sessions/${sessionId}/file-raw?path=${encodeURIComponent(filePath)}`);
const attachmentPreviewUrl =
: `/api/sessions/${sessionId}/file-raw?path=${encodeURIComponent(filePath)}`)
);
const attachmentPreviewUrl = CodemanBase.url(
previewUrl ||
(attachmentId ? `/api/sessions/${sessionId}/attachments/${encodeURIComponent(attachmentId)}/preview` : null);
const attachmentThumbnailUrl =
(attachmentId ? `/api/sessions/${sessionId}/attachments/${encodeURIComponent(attachmentId)}/preview` : null)
);
const attachmentThumbnailUrl = CodemanBase.url(
thumbnailUrl ||
(attachmentId
? `/api/sessions/${sessionId}/attachments/${encodeURIComponent(attachmentId)}/thumbnail`
: `/api/sessions/${sessionId}/file-thumbnail?path=${encodeURIComponent(filePath)}`);
: `/api/sessions/${sessionId}/file-thumbnail?path=${encodeURIComponent(filePath)}`)
);
const downloadUrl = attachmentId ? `${attachmentRawUrl}?download=true` : `${attachmentRawUrl}&download=true`;
const typeLabel = (extension || attachmentType || 'file').toUpperCase();
@@ -4736,7 +4743,7 @@ Object.assign(CodemanApp.prototype, {
.join(' • ');
const thumb =
item.thumbnailUrl && !item.missing
? `<img class="attachment-history-thumb-img" src="${escapeHtml(item.thumbnailUrl)}" alt="">`
? `<img class="attachment-history-thumb-img" src="${escapeHtml(CodemanBase.url(item.thumbnailUrl))}" alt="">`
: '';
const disabled = item.missing ? 'disabled aria-disabled="true"' : '';
return `
@@ -4776,7 +4783,7 @@ Object.assign(CodemanApp.prototype, {
const item = this.getAttachmentHistoryItem(itemId);
if (!item || item.missing) return;
if (item.rawUrl || item.url) {
window.open(item.rawUrl || item.url, '_blank');
window.open(CodemanBase.url(item.rawUrl || item.url), '_blank');
return;
}
this.openAttachmentInNewTab(item.sessionId, item.relativePath || item.fileName, item.attachmentId || null);
@@ -4785,7 +4792,7 @@ Object.assign(CodemanApp.prototype, {
downloadAttachmentHistoryItem(itemId) {
const item = this.getAttachmentHistoryItem(itemId);
if (!item || item.missing || !item.downloadUrl) return;
window.open(item.downloadUrl, '_blank');
window.open(CodemanBase.url(item.downloadUrl), '_blank');
},
reshowAttachmentCard(itemId) {
@@ -4931,7 +4938,7 @@ Object.assign(CodemanApp.prototype, {
// Connect to SSE stream
const eventSource = new EventSource(
`/api/sessions/${sessionId}/tail-file?path=${encodeURIComponent(filePath)}&lines=50`
CodemanBase.url(`/api/sessions/${sessionId}/tail-file?path=${encodeURIComponent(filePath)}&lines=50`)
);
eventSource.onmessage = (e) => {
@@ -5073,7 +5080,7 @@ Object.assign(CodemanApp.prototype, {
// Build image URL using the existing file-raw endpoint
// Use relativePath (path from working dir) instead of fileName (basename) for subdirectory images
const imageUrl = `/api/sessions/${sessionId}/file-raw?path=${encodeURIComponent(relativePath || fileName)}`;
const imageUrl = CodemanBase.url(`/api/sessions/${sessionId}/file-raw?path=${encodeURIComponent(relativePath || fileName)}`);
// Create window element
const win = document.createElement('div');
+334 -16
View File
@@ -187,6 +187,13 @@ Object.assign(CodemanApp.prototype, {
this.closeCasePicker();
this.updateDirDisplayForCase(select.value);
this.updateMobileCaseLabel(select.value);
// Warm the container's CLI list HERE rather than when the run menu opens.
// The probe is a `docker exec` round trip, so gating it on the menu meant the
// menu painted every mode first and only narrowed a moment later — which
// reads as "it shows all of them" and lets a mode be picked that the
// container does not have.
const picked = (this.cases || []).find((c) => c.name === select.value);
if (picked?.location === 'docker') void this._probeDockerCaseModes(picked, null);
if (save) {
this.saveLastUsedCase(select.value);
}
@@ -477,10 +484,40 @@ Object.assign(CodemanApp.prototype, {
* run modes like the rest, and neither `agy` nor `pi` is likely to be installed.
*/
_refreshRunModeAvailability(menu) {
// A DOCKER case runs its agents INSIDE the container, so host CLI
// availability answers the wrong question: the host may have no claude at
// all while the container ships one, and gating on the host hides a mode
// that would have worked. Adoption records what the container really has
// (`availableModes`); an owned container runs our base image, which ships
// every CLI, so an absent list means "do not gate" rather than "nothing".
// Same source every run* path reads the selected case from.
const caseName = document.getElementById('quickStartCase')?.value;
const activeCase = caseName ? (this.cases || []).find((c) => c.name === caseName) : null;
const isDocker = activeCase?.location === 'docker';
// Prefer a LIVE probe over the value stored at attach time: a container's
// CLIs can be installed or removed long after the case was linked, and a
// case linked before that field existed has none at all.
const containerModes = isDocker
? this._dockerCaseModes?.[caseName] || activeCase.docker?.availableModes || null
: null;
if (isDocker && !this._dockerCaseModes?.[caseName]) void this._probeDockerCaseModes(activeCase, menu);
// An unreachable container hides every agent mode and explains why, instead
// of silently offering modes that cannot start.
//
// ⚠️ ADOPTED cases only. For an OWNED case a missing container is the normal
// state before the first session — the launch chain creates and starts it — so
// reporting it as a fault hid every agent mode on a freshly linked Docker case
// behind "start it yourself first", for a container Codeman was about to create.
const probeError = isDocker ? this._dockerCaseProbeError?.[caseName] : null;
for (const mode of ['claude', 'opencode', 'codex', 'gemini', 'antigravity', 'pi', 'grok', 'deepseek', 'omp']) {
const btn = menu.querySelector(`.run-mode-option[data-mode="${mode}"]`);
if (btn) btn.style.display = this.isCliAvailable(mode) ? 'flex' : 'none';
if (!btn) continue;
let available;
if (isDocker) available = probeError ? false : containerModes ? containerModes.includes(mode) : true;
else available = this.isCliAvailable(mode);
btn.style.display = available ? 'flex' : 'none';
}
this._renderRunModeNotice(menu, probeError);
// DeepSeek is the one mode whose availability has two halves: `dsh` can be
// perfectly installed while no pane-capable profile exists, because DeepSeek
// ships no terminal front door. In that state the honest offer is "add one",
@@ -622,6 +659,81 @@ Object.assign(CodemanApp.prototype, {
}
},
/**
* One-line explanation at the top of the run menu. Only a container that could
* not be read produces one; everything else removes it, so a stale reason can
* never outlive the condition that caused it.
*/
_renderRunModeNotice(menu, message) {
if (!menu) return;
let el = menu.querySelector('.run-mode-notice');
if (!message) {
el?.remove();
return;
}
if (!el) {
el = document.createElement('div');
el.className = 'run-mode-notice';
menu.prepend(el);
}
// Server-supplied text: set it, never parse it as markup.
el.textContent = message;
},
/**
* Ask the container which CLIs it actually has, and re-gate the menu once the
* answer lands. Cached per case for the page's lifetime: the menu re-opens
* often and the probe is a `docker exec` round trip.
*
* Best-effort by design — an unreachable daemon or a stopped container leaves
* the cache empty, which the caller reads as "unknown" and therefore does not
* gate. Hiding every mode because a probe failed would be worse than showing
* one that turns out to be missing, which the launch path already refuses with
* a specific message.
*/
async _probeDockerCaseModes(activeCase, menu) {
const name = activeCase?.name;
const container = activeCase?.docker?.container;
const hostId = activeCase?.docker?.hostId;
if (!name || !container || !hostId) return;
this._dockerCaseModes = this._dockerCaseModes || {};
if (this._dockerModeProbeInFlight?.[name]) return;
this._dockerModeProbeInFlight = this._dockerModeProbeInFlight || {};
this._dockerModeProbeInFlight[name] = true;
try {
// ⚠️ _api serializes `body` and sets Content-Type itself. Passing an
// already-stringified body double-encodes it and the server rejects a
// JSON string where it expects an object (400 INVALID_INPUT).
const probe = await this._apiJson('/api/docker-cases/adopt-preflight', {
method: 'POST',
body: { hostId, container },
});
if (probe?.ok && Array.isArray(probe.availableModes)) {
this._dockerCaseModes[name] = probe.availableModes;
delete this._dockerCaseProbeError?.[name];
} else {
// An ADOPTED container that cannot be probed — recreated, stopped, engine
// down — must NOT fall through to "show everything". Offering claude on a
// container that is not running is a click that can only fail, with the
// reason visible nowhere. Record the reason and say it in the menu.
//
// ⚠️ An OWNED container gets no error: it does not exist until the first
// session launches it, so "not found" is the expected answer for every
// newly linked Docker case, and gating on it made those cases unusable.
// Leaving the cache empty reads as "unknown", which does not gate.
if (activeCase?.docker?.owned === false) {
this._dockerCaseProbeError = this._dockerCaseProbeError || {};
this._dockerCaseProbeError[name] = probe?.error || `Could not read container "${container}".`;
}
delete this._dockerCaseModes[name];
}
// Only repaint while the menu the user opened is still on screen.
if (menu?.classList.contains('active')) this._refreshRunModeAvailability(menu);
} finally {
delete this._dockerModeProbeInFlight[name];
}
},
async _loadRunModeHistory() {
const container = document.getElementById('runModeHistory');
if (!container) return;
@@ -2387,6 +2499,28 @@ Object.assign(CodemanApp.prototype, {
modal.querySelectorAll('.set-rail-item').forEach(btn => {
btn.onclick = () => this.switchCaseModalTab(btn.dataset.tab);
});
// Adopt-an-existing-container toggle + its read-only preflight. Assigned (not
// addEventListener) so reopening the modal cannot stack duplicate handlers,
// matching the rail wiring right above.
const adoptToggle = document.getElementById('dockerAdoptExisting');
if (adoptToggle) adoptToggle.onchange = () => this._syncDockerAdoptMode();
const adoptCheck = document.getElementById('dockerAdoptCheckBtn');
if (adoptCheck) adoptCheck.onclick = () => this._dockerAdoptPreflight();
const adoptJump = document.getElementById('dockerAdoptJumpBtn');
if (adoptJump) adoptJump.onclick = () => this.jumpToDockerAdopt();
// Containers come from the host profile, so switching Host ID invalidates the
// suggestions. Dropping the marker (rather than refetching here) keeps the
// fetch lazy — it happens when adopt mode is actually on.
const hostIdInput = document.getElementById('dockerHostId');
if (hostIdInput) {
hostIdInput.onchange = () => {
delete document.getElementById('dockerContainerList')?.dataset.loadedFor;
if (document.getElementById('dockerAdoptExisting')?.checked) void this._loadDockerContainerOptions();
};
}
// A fresh open re-reads the engine: containers start and stop between visits.
delete document.getElementById('dockerContainerList')?.dataset.loadedFor;
this._syncDockerAdoptMode();
// Scroll-into-view on focus for mobile keyboard visibility
modal.querySelectorAll('input[type="text"]').forEach(input => {
if (!input._mobileScrollWired) {
@@ -2416,15 +2550,19 @@ Object.assign(CodemanApp.prototype, {
// A switched-to panel starts at its own top.
const doc = document.getElementById('createCaseDoc');
if (doc) doc.scrollTop = 0;
// Update submit button (hide for manage tab)
const submitBtn = document.getElementById('caseModalSubmit');
// Update submit buttons (hide for manage tab). Two of them: mobile.css hides
// this modal's .set-foot, so phones submit through the header button instead.
const submitBtns = ['caseModalSubmit', 'caseModalSubmitMobile']
.map((id) => document.getElementById(id))
.filter(Boolean);
if (tabName === 'case-manage') {
submitBtn.style.display = 'none';
submitBtns.forEach((btn) => {
btn.style.display = 'none';
});
this.renderCaseManageList();
this.refreshDockerExports();
} else {
submitBtn.style.display = '';
submitBtn.textContent =
const label =
tabName === 'case-create'
? 'Create'
: tabName === 'case-clone'
@@ -2434,6 +2572,10 @@ Object.assign(CodemanApp.prototype, {
: tabName === 'case-docker'
? 'Link Docker'
: 'Link';
submitBtns.forEach((btn) => {
btn.style.display = '';
btn.textContent = label;
});
}
// Focus appropriate input
if (tabName === 'case-create') {
@@ -2454,14 +2596,19 @@ Object.assign(CodemanApp.prototype, {
},
async submitCaseModal() {
const btn = document.getElementById('caseModalSubmit');
const originalText = btn.textContent;
btn.classList.add('loading');
btn.textContent =
// Both submit buttons move together: whichever one the user pressed, the
// other must show the same pending state and be equally unclickable.
const btns = ['caseModalSubmit', 'caseModalSubmitMobile'].map((id) => document.getElementById(id)).filter(Boolean);
const originalText = btns.map((btn) => btn.textContent);
const pendingText =
this.caseModalTab === 'case-create' ? 'Creating...' : this.caseModalTab === 'case-clone' ? 'Cloning...' : 'Linking...';
// A clone holds this request open for minutes; without disabling the button a
// second click fires a second clone (the loser then fails on ALREADY_EXISTS).
btns.forEach((btn) => {
btn.classList.add('loading');
btn.textContent = pendingText;
btn.disabled = true;
});
try {
if (this.caseModalTab === 'case-create') {
await this.createCase();
@@ -2475,9 +2622,11 @@ Object.assign(CodemanApp.prototype, {
await this.linkCase();
}
} finally {
btns.forEach((btn, index) => {
btn.classList.remove('loading');
btn.disabled = false;
btn.textContent = originalText;
btn.textContent = originalText[index];
});
}
},
@@ -2862,6 +3011,61 @@ Object.assign(CodemanApp.prototype, {
});
},
/** HOST workspace directory — the same picker Link Existing uses. */
openDockerWorkspacePathPicker() {
const pathInput = document.getElementById('dockerWorkspacePath');
PathPicker.open({
title: 'Select Host Workspace Folder',
initialPath: pathInput.value.trim(),
directoriesOnly: true,
onSelect: (path) => {
pathInput.value = path;
const nameInput = document.getElementById('dockerCaseName');
if (nameInput && !nameInput.value.trim()) {
const folder = path.split('/').filter(Boolean).pop() || '';
if (/^[a-zA-Z0-9_-]+$/.test(folder)) nameInput.value = folder;
}
},
});
},
/**
* Container workdir. Browses INSIDE the container, because for an adopted
* container nothing is mounted at a matching host path — the host picker would
* be listing a different filesystem, and typing this field blind is exactly
* what makes the launch fail with an OCI chdir error.
*/
openDockerWorkdirPicker() {
const pathInput = document.getElementById('dockerAdoptWorkdir');
const container = document.getElementById('dockerContainerName')?.value.trim();
const hostId = document.getElementById('dockerHostId')?.value.trim() || 'local';
if (!container) {
this.showToast('Enter the container name first', 'error');
return;
}
PathPicker.open({
title: `Select Folder Inside ${container}`,
initialPath: pathInput.value.trim() || '/',
directoriesOnly: true,
fetchListing: async (path) => {
const data = await this._apiJson('/api/docker-cases/browse', {
method: 'POST',
body: { hostId, container, path: path || '/' },
});
if (!data) return { success: false, error: `Could not read ${container}. Is it running?` };
if (data.error) return { success: false, error: data.error };
// Shape it like the host endpoint: one root, so Up/Location behave.
return {
success: true,
data: { ...data, root: '/', roots: [{ label: container, path: '/' }], truncated: false },
};
},
onSelect: (path) => {
pathInput.value = path;
},
});
},
async linkRemoteCase() {
const name = document.getElementById('remoteCaseName').value.trim();
const remotePath = document.getElementById('remoteCasePath').value.trim();
@@ -2943,10 +3147,107 @@ Object.assign(CodemanApp.prototype, {
}
},
/**
* Reflect the "attach to an existing container" checkbox onto the modal so CSS
* can swap which half of the Docker panel applies. An attribute rather than
* per-row inline styles: the panel is rebuilt by nothing, but the create-time
* rows are a SET (image, network, advanced block) and one attribute keeps them
* in lockstep with the container-name row.
*/
_syncDockerAdoptMode() {
const modal = document.getElementById('createCaseModal');
if (!modal) return;
const adopting = document.getElementById('dockerAdoptExisting')?.checked;
if (adopting) modal.setAttribute('data-docker-adopt', '1');
else modal.removeAttribute('data-docker-adopt');
if (adopting) void this._loadDockerContainerOptions();
},
/**
* Fill the container-name `<datalist>`. A native datalist is deliberate: the
* field must accept a free-typed name (the engine may be remote, or the
* container may not exist yet when the form is filled), and datalist gives
* type-to-filter over the suggestions without a custom dropdown.
*
* Best-effort by design — the endpoint returns [] for an unreachable daemon,
* and an empty list simply leaves the field as plain text input.
*/
async _loadDockerContainerOptions() {
const list = document.getElementById('dockerContainerList');
if (!list) return;
const hostId = document.getElementById('dockerHostId')?.value.trim() || 'local';
if (list.dataset.loadedFor === hostId) return; // one fetch per host per open
const data = await this._apiJson(`/api/docker-hosts/${encodeURIComponent(hostId)}/containers`);
const containers = data?.containers || [];
list.textContent = '';
for (const c of containers) {
const option = document.createElement('option');
option.value = c.name;
// Engine-supplied strings: set as text, never as markup.
option.textContent = c.running ? `${c.image} · ${c.status}` : `${c.image} · ${c.status} (not running)`;
list.appendChild(option);
}
list.dataset.loadedFor = hostId;
},
/**
* Cross-link from the Create New tab's "Run in an isolated Docker container"
* row. Adoption lives on the Docker tab, but the place users actually look for
* anything container-shaped is that checkbox, so this jumps them there with the
* toggle already on rather than leaving the feature undiscoverable.
*/
jumpToDockerAdopt() {
this.switchCaseModalTab('case-docker');
const toggle = document.getElementById('dockerAdoptExisting');
if (toggle) toggle.checked = true;
this._syncDockerAdoptMode();
document.getElementById('dockerContainerName')?.focus();
},
/**
* Read-only preflight against an existing container. It links nothing, so the
* user can find out "not running" / "no tmux" / "codex present, claude missing"
* before committing to a case name — the same reason the server refuses at link
* time rather than at session launch.
*/
async _dockerAdoptPreflight() {
const statusEl = document.getElementById('dockerLinkStatus');
const container = document.getElementById('dockerContainerName')?.value.trim();
const containerWorkdir = document.getElementById('dockerAdoptWorkdir')?.value.trim();
const hostId = document.getElementById('dockerHostId').value.trim() || 'local';
if (!container) {
if (statusEl) statusEl.textContent = 'Enter a container name first.';
return;
}
if (statusEl) statusEl.textContent = 'Inspecting container...';
// _apiJson folds every failure to null, and a preflight's whole value is the
// reason it failed, so the envelope is unwrapped by hand here.
const probe = await this._apiJson('/api/docker-cases/adopt-preflight', {
method: 'POST',
body: { hostId, container, ...(containerWorkdir ? { containerWorkdir } : {}) },
});
if (!statusEl) return;
if (!probe) {
statusEl.textContent = 'Could not reach the docker host profile. Save a Host ID first.';
return;
}
if (!probe.ok) {
statusEl.textContent = probe.error || 'Container is not adoptable.';
return;
}
const modes = (probe.availableModes || []).filter((m) => m !== 'shell');
statusEl.textContent = modes.length
? `Running (${probe.image || 'unknown image'}). Available: ${modes.join(', ')}.`
: `Running (${probe.image || 'unknown image'}), but no agent CLI found inside — only Shell will work.`;
},
async linkDockerCase() {
const name = document.getElementById('dockerCaseName').value.trim();
const hostWorkspacePath = document.getElementById('dockerWorkspacePath').value.trim();
const hostId = document.getElementById('dockerHostId').value.trim() || 'local';
const adopting = !!document.getElementById('dockerAdoptExisting')?.checked;
const container = document.getElementById('dockerContainerName')?.value.trim() || '';
const adoptWorkdir = document.getElementById('dockerAdoptWorkdir')?.value.trim() || '';
const image = document.getElementById('dockerImage').value.trim() || 'codeman/agent:base';
const network = document.getElementById('dockerNetwork').value;
const memory = document.getElementById('dockerMemory').value.trim();
@@ -2967,9 +3268,15 @@ Object.assign(CodemanApp.prototype, {
this.showToast('Workspace path must be absolute', 'error');
return;
}
if (adopting && !container) {
this.showToast('Enter the name of the running container to attach to', 'error');
return;
}
try {
if (statusEl) statusEl.textContent = 'Checking docker daemon + base image...';
if (statusEl) {
statusEl.textContent = adopting ? 'Inspecting the existing container...' : 'Checking docker daemon + base image...';
}
// omitted optionals sent as UNDEFINED (never null — Zod .optional() rejects null)
const resources = {};
if (memory) resources.memory = memory;
@@ -3000,16 +3307,27 @@ Object.assign(CodemanApp.prototype, {
}
if (!hostData.success) throw new Error(hostData.error || 'Failed to save docker host');
const caseRes = await fetch('/api/cases/docker-link', {
// Adoption reuses this whole flow and differs only in the final call: a
// different endpoint (which never creates a container) plus the container
// name. The host upsert above still applies — it is what resolves the
// engine/context/daemon for the `docker exec`; its create-time fields are
// simply never read for an adopted case.
const caseRes = await fetch(adopting ? '/api/cases/docker-adopt' : '/api/cases/docker-link', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name, hostId, hostWorkspacePath }),
body: JSON.stringify(
adopting
? { name, hostId, hostWorkspacePath, container, ...(adoptWorkdir ? { containerWorkdir: adoptWorkdir } : {}) }
: { name, hostId, hostWorkspacePath }
),
});
const caseData = await caseRes.json();
if (caseData.success) {
this.closeCreateCaseModal();
const caps = caseData.data?.capsEnforced === false ? ' (resource caps are advisory on this engine)' : '';
this.showToast(`Docker case "${name}" linked${caps}`, 'success');
const modes = (caseData.data?.availableModes || []).filter((m) => m !== 'shell');
const found = adopting && modes.length ? ` — found ${modes.join(', ')}` : '';
this.showToast(`Docker case "${name}" ${adopting ? 'attached' : 'linked'}${caps}${found}`, 'success');
await this.loadQuickStartCases(name);
await this.saveLastUsedCase(name);
} else {
@@ -3046,7 +3364,7 @@ Object.assign(CodemanApp.prototype, {
return `<div class="case-manage-item" style="display:flex; align-items:center; gap:8px; justify-content:space-between;">
<span style="overflow:hidden; text-overflow:ellipsis; white-space:nowrap;" title="${nm}">${nm} <span class="form-hint">(${mb} MB)</span></span>
<span style="flex-shrink:0;">
<a class="btn-toolbar" href="/api/docker-exports/${encodeURIComponent(e.name)}" download>Download</a>
<a class="btn-toolbar" href="${CodemanBase.url(`/api/docker-exports/${encodeURIComponent(e.name)}`)}" download>Download</a>
<button class="btn-toolbar" onclick="app.importDockerBundle('${nm.replace(/'/g, "\\'")}')">Import</button>
<button class="btn-toolbar" onclick="app.deleteDockerExport('${nm.replace(/'/g, "\\'")}')">Delete</button>
</span>
+4 -1
View File
@@ -187,7 +187,10 @@ Object.assign(CodemanApp.prototype, {
registerServiceWorker() {
if (!('serviceWorker' in navigator)) return;
navigator.serviceWorker.register('/sw.js').then((reg) => {
// Behind a sub-path mount the worker is served at <base>/sw.js and controls
// <base>/ (Service-Worker-Allowed is '/', so this narrower scope is permitted).
const _swBase = window.CodemanBase?.base || '';
navigator.serviceWorker.register(_swBase + '/sw.js', { scope: _swBase + '/' }).then((reg) => {
this._swRegistration = reg;
// Listen for messages from service worker (notification clicks)
navigator.serviceWorker.addEventListener('message', (event) => {
+75
View File
@@ -12607,6 +12607,43 @@ kbd {
background: color-mix(in srgb, var(--green) 12%, transparent);
}
/* Consecutive messages from one speaker inside one turn are segments of a
single utterance, not separate cards: no repeated badge, a hairline seam.
The role accent survives because the colour rules above match on BOTH
:has(.rv-role-*) and .rv-msg-* — a badge-less continuation still hits the
class arm. Do not drop either arm. */
.rv-message.rv-msg-cont {
margin-top: -18px;
border-top: 0;
border-top-left-radius: 0;
border-top-right-radius: 0;
padding-top: 0;
}
.rv-message.rv-msg-cont > .rv-text {
border-top: 1px solid var(--border);
padding-top: 12px;
}
.rv-message:has(+ .rv-msg-cont) {
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
padding-bottom: 0;
}
/* A prompt the user typed while the agent was working (absorbed mid-turn).
A pseudo-element, not a text node, so the i18n MutationObserver cannot
rewrite it. */
.rv-message[data-queued='1'] .rv-role::after {
content: ' ⏱';
}
.rv-notice {
opacity: 0.7;
font-style: italic;
margin-top: 12px;
}
/* Markdown rendered content inside response viewer.
Prose uses a proportional font for readability; code keeps monospace. */
.rv-text,
@@ -16645,6 +16682,44 @@ html[data-tab-orientation='vertical'] .home-sessions {
label as a row label, its `.form-hint` as a row description. Scoped to the
document, so `.form-row` everywhere else is untouched.
─────────────────────────────────────────────────────────────────────────── */
/* Adopt-an-existing-container mode swaps which half of the Docker panel applies:
the create-time fields (image, network, resources, credential mounts) describe
a `docker create` that adoption never runs, and the container name is the one
field only adoption needs. `.docker-adopt-only` is hidden by default so the
panel stays exactly as it was until the checkbox is ticked. Rules carry
`!important` because the adapter block above paints `.form-row` as a row card
and `details.advanced-options` has its own display. */
/* Run-menu notice: why a container case is offering no agent modes. Lives at the
top of the menu so the reason is where the missing entries would have been. */
.run-mode-notice {
padding: 8px 12px;
margin: 0 0 4px;
font-size: 12px;
line-height: 1.45;
color: var(--text-muted, #9aa0a6);
border-bottom: 1px solid var(--border, #333);
white-space: normal;
}
#createCaseModal .docker-adopt-only {
display: none !important;
}
#createCaseModal[data-docker-adopt='1'] .docker-adopt-only {
display: block !important;
}
#createCaseModal[data-docker-adopt='1'] .docker-create-only {
display: none !important;
}
#createCaseModal .btn-inline-check {
background: none;
border: none;
padding: 0;
font: inherit;
color: var(--accent, #4a9eff);
cursor: pointer;
text-decoration: underline;
}
#createCaseModal .set-doc .form-row {
margin: 0 0 3px;
padding: 7px 10px;
+13 -6
View File
@@ -20,6 +20,13 @@
const CACHE_NAME = 'codeman-v1';
// Reverse-proxy base path: the worker is served at `<base>/sw.js`, so its own
// location tells us the mount prefix ('' at root, or '/codeman'). Every URL below
// is prefixed through B() so the cached shell, icons and API calls resolve under
// the mount instead of escaping to the origin root.
const SW_BASE = self.location.pathname.replace(/\/sw\.js$/, '');
const B = (p) => (p && p[0] === '/' ? SW_BASE + p : p);
// Core app shell -- cached on install for instant startup
const APP_SHELL = [
'/',
@@ -45,7 +52,7 @@ const APP_SHELL = [
'/icon-192.png',
'/icon-512.png',
'/manifest.json',
];
].map(B);
// --- Install: precache app shell ---
@@ -116,9 +123,9 @@ self.addEventListener('push', (event) => {
const options = {
body: body || '',
tag: tag || 'codeman-default',
icon: '/icon-192.png',
badge: '/icon-192.png',
data: { sessionId, approvalId, url: sessionId ? `/?session=${sessionId}` : '/' },
icon: B('/icon-192.png'),
badge: B('/icon-192.png'),
data: { sessionId, approvalId, url: sessionId ? B(`/?session=${sessionId}`) : B('/') },
renotify: true,
requireInteraction: urgency === 'critical',
};
@@ -143,7 +150,7 @@ self.addEventListener('notificationclick', (event) => {
event.notification.close();
const { sessionId, approvalId, url } = event.notification.data || {};
const targetUrl = url || '/';
const targetUrl = url || B('/');
const action = event.action || null;
// Approve/Deny action buttons answer the Approvals Inbox item directly from
@@ -152,7 +159,7 @@ self.addEventListener('notificationclick', (event) => {
// because a service worker fetch carries the worker's own (same) origin.
if ((action === 'approve' || action === 'deny') && approvalId) {
event.waitUntil(
fetch(`/api/approvals/${encodeURIComponent(approvalId)}/answer`, {
fetch(B(`/api/approvals/${encodeURIComponent(approvalId)}/answer`), {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
+1 -1
View File
@@ -322,7 +322,7 @@ const ClaudeVoiceProvider = {
if (opts.keyterms?.length) params.set('keyterms', opts.keyterms.join(','));
const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
try {
this._ws = new WebSocket(`${proto}//${location.host}/ws/voice/stream?${params}`);
this._ws = new WebSocket(`${proto}//${location.host}${window.CodemanBase?.base || ''}/ws/voice/stream?${params}`);
} catch (err) {
this._onError?.('Failed to open voice stream: ' + err.message);
this._cleanup();
+3 -1
View File
@@ -182,7 +182,9 @@ Object.assign(CodemanApp.prototype, {
if (webview.trusted) sandbox.push('allow-same-origin');
frame.setAttribute('sandbox', sandbox.join(' '));
frame.setAttribute('referrerpolicy', 'no-referrer-when-downgrade');
frame.src = src;
// Proxied dashboards carry a root-absolute `/webview/<cap>/` embedUrl that must
// ride the mount prefix; external (trusted) URLs are absolute and pass through.
frame.src = CodemanBase.url(src);
const failure = document.createElement('div');
failure.className = 'webview-failure';
+5
View File
@@ -424,6 +424,11 @@ export function sanitizeHookData(data: Record<string, unknown> | null | undefine
'stop_hook_active',
'transcript_path',
'message',
// UserPromptSubmit identity fields. `prompt` is deliberately NOT here: the
// prompt text would land in the SSE broadcast, and Read My Mind already
// captures intent through transcript-watcher.
'prompt_id',
'source',
];
for (const key of allowedKeys) {
+229 -3
View File
@@ -13,7 +13,7 @@ import fs from 'node:fs/promises';
import { join, resolve, basename } from 'node:path';
import { fileURLToPath } from 'node:url';
import { homedir } from 'node:os';
import type { ApiResponse, CaseInfo, DockerHost, RemoteSessionInfo, SessionDocker } from '../../types.js';
import type { ApiResponse, CaseInfo, DockerHost, RemoteSessionInfo, SessionDocker, SessionMode } from '../../types.js';
import { ApiErrorCode, createErrorResponse, getErrorMessage } from '../../types.js';
import {
CreateCaseSchema,
@@ -24,6 +24,9 @@ import {
RemoteCaseLinkSchema,
RemoteHostSchema,
DockerCaseLinkSchema,
DockerCaseAdoptSchema,
DockerAdoptPreflightSchema,
DockerBrowseSchema,
DockerHostSchema,
DockerExportSchema,
DockerImportSchema,
@@ -66,6 +69,10 @@ import {
DEFAULT_AGENT_IMAGE,
dockerContainerName,
dockerDisplayPath,
probeAdoptableContainer,
listDockerContainers,
browseInContainer,
dockerAdoptProbeModes,
readDockerCases,
readDockerHosts,
removeDockerContainer,
@@ -73,6 +80,7 @@ import {
writeDockerCases,
writeDockerHosts,
} from '../../docker-hosts.js';
import type { AdoptedContainerProbe, DockerBrowseResult, DockerContainerInfo } from '../../docker-hosts.js';
import { buildDockerRemoveCommand } from '../../tmux-manager.js';
import {
checkRemoteTmuxAvailable,
@@ -291,6 +299,8 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
image: host.image,
path: dockerCase.hostWorkspacePath,
network: host.network ?? 'bridge',
...(dockerCase.availableModes ? { availableModes: dockerCase.availableModes } : {}),
...(dockerCase.owned === false ? { owned: false } : {}),
},
};
const existingIndex = cases.findIndex((item) => item.name === dockerCase.name);
@@ -771,6 +781,191 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
}
);
/**
* ADOPT an already-running container (`owned: false`). The mirror of the
* remote-SSH attach path: Codeman execs into a container the user built and
* runs, and never creates, starts, stops, restarts or removes it.
*
* Everything here is read-only toward the container. The preflight refuses at
* LINK time — missing, stopped, or no tmux inside — because the alternative is
* failing at session launch, where the only ways out would be a dead pane or
* starting a container we do not own. There is no image gate and no
* `ensureCaseImage`: adoption never runs `docker create`, so the container's
* image is the user's business.
*/
app.post(
'/api/cases/docker-adopt',
async (req, reply): Promise<ApiResponse<{ case: unknown; image?: string; availableModes?: SessionMode[] }>> => {
// ⚠️ Admin-only in multi-user mode, unlike `docker-link` right above. Linking
// creates OUR container, whose only bind mount is a workspace `isWorkingDirAllowed`
// has already confined. Adoption names a container someone else built, and its
// mounts are whatever its owner gave it — a container mounting `/` hands the
// adopter a shell over the whole host, which is exactly the workspace scoping this
// mode exists to enforce. Same machine-level reasoning as the docker HOST routes.
const denied = adminOnly(req, reply);
if (denied) return denied;
const dockerCase = {
...parseBody(DockerCaseAdoptSchema, req.body),
type: 'docker' as const,
owner: ownerFor(req),
owned: false as const,
};
const host = (await readDockerHosts(CODEMAN_CONFIG_DIR)).find((item) => item.id === dockerCase.hostId);
if (!host) return createErrorResponse(ApiErrorCode.NOT_FOUND, 'Docker host not found');
const linkedCases = await readLinkedCases();
const dockerCases = await readDockerCases(CODEMAN_CONFIG_DIR);
if (
dockerCases.some((item) => item.name === dockerCase.name) ||
linkedCases[dockerCase.name] ||
existsSync(join(resolveCasesDir(getAuthUser(req)), dockerCase.name))
) {
return createErrorResponse(ApiErrorCode.ALREADY_EXISTS, 'Case already exists');
}
// Two cases must never share one adopted container: session close kills the
// in-container tmux by session id, but a shared adoption would let one case's
// teardown and another's launch race over the same tmux server.
const container = dockerCase.container;
if (dockerCases.some((item) => (item.container ?? dockerContainerName(item.name)) === container)) {
return createErrorResponse(ApiErrorCode.ALREADY_EXISTS, `Container "${container}" is already linked to a case`);
}
if (!isWorkingDirAllowed(getAuthUser(req), dockerCase.hostWorkspacePath)) {
return createErrorResponse(ApiErrorCode.FORBIDDEN, 'hostWorkspacePath is outside your workspace');
}
// The workspace must ALREADY exist: it mirrors a path inside a container we
// did not create, so silently mkdir-ing it would invent a host directory that
// does not correspond to whatever is actually mounted there.
if (!existsSync(dockerCase.hostWorkspacePath)) {
return createErrorResponse(
ApiErrorCode.INVALID_INPUT,
'hostWorkspacePath does not exist. Adoption mirrors an existing container, so point this at the real host directory already mounted into it.'
);
}
const availability = await checkDockerAvailable(host.engine);
if (!availability.ok) {
return createErrorResponse(
ApiErrorCode.OPERATION_FAILED,
availability.error || 'docker daemon is not available'
);
}
// The container workdir is validated INSIDE the container. It defaults to
// hostWorkspacePath only because that is what an owned container's bind
// mount guarantees; adoption mounts nothing, so the probe has to prove it.
const adoptDocker = toSessionDocker(host, dockerCase);
const probe = await probeAdoptableContainer(adoptDocker, dockerAdoptProbeModes(), adoptDocker.containerWorkdir);
if (!probe.ok) {
return createErrorResponse(ApiErrorCode.OPERATION_FAILED, probe.error || 'container is not adoptable');
}
// Persist what the container actually has: the run-mode picker gates on
// HOST CLIs, which is the wrong question for a case whose agents run inside
// a container the host knows nothing about.
const adoptedCase = { ...dockerCase, availableModes: probe.availableModes };
await writeDockerCases(CODEMAN_CONFIG_DIR, [...dockerCases, adoptedCase]);
ctx.broadcast(SseEvent.CaseLinked, {
name: adoptedCase.name,
path: adoptedCase.hostWorkspacePath,
type: 'docker',
});
return {
success: true,
data: { case: adoptedCase, image: probe.image, availableModes: probe.availableModes },
};
}
);
/**
* Preflight an existing container WITHOUT linking anything, so the UI can tell
* the user "not running" / "no tmux" / "codex present, claude missing" before
* they commit to a case name. Read-only; never touches container lifecycle.
*/
/**
* Containers on the host's engine, for the adoption picker. Read-only and
* best-effort (mirror of the remote `:hostId/sessions` discovery route): an
* unreachable daemon yields an empty list rather than an error, because the
* container name is a free-text field the user can always type by hand.
*/
app.get(
'/api/docker-hosts/:hostId/containers',
async (req, reply): Promise<ApiResponse<{ containers: DockerContainerInfo[] }>> => {
// Enumerating every container on the engine is machine-level information (names,
// images, uptime), so it follows the docker-host policy rather than the case one.
const denied = adminOnly(req, reply);
if (denied) return denied;
const { hostId } = req.params as { hostId: string };
const host = (await readDockerHosts(CODEMAN_CONFIG_DIR)).find((item) => item.id === hostId);
if (!host) return createErrorResponse(ApiErrorCode.NOT_FOUND, 'Docker host not found');
const containers = await listDockerContainers({
engine: host.engine ?? 'docker',
context: host.context,
daemonHost: host.daemonHost,
});
return { success: true, data: { containers } };
}
);
/**
* Browse a directory INSIDE a container, for the adoption form's
* container-workdir picker. The host picker cannot answer this: for an adopted
* container nothing is mounted at a matching host path, so the field would
* otherwise be typed blind. Read-only — one `ls` through `docker exec`.
*/
app.post('/api/docker-cases/browse', async (req, reply): Promise<ApiResponse<DockerBrowseResult>> => {
// Reads a directory listing inside an ARBITRARY named container, so it is gated with
// the adopt flow it serves rather than with the (owner-scoped) case file routes.
const denied = adminOnly(req, reply);
if (denied) return denied;
const body = parseBody(DockerBrowseSchema, req.body);
const host = (await readDockerHosts(CODEMAN_CONFIG_DIR)).find((item) => item.id === body.hostId);
if (!host) return createErrorResponse(ApiErrorCode.NOT_FOUND, 'Docker host not found');
const result = await browseInContainer(
{
engine: host.engine ?? 'docker',
context: host.context,
daemonHost: host.daemonHost,
containerName: body.container,
},
body.path || '/'
);
return { success: true, data: result };
});
app.post('/api/docker-cases/adopt-preflight', async (req, reply): Promise<ApiResponse<AdoptedContainerProbe>> => {
const body = parseBody(DockerAdoptPreflightSchema, req.body);
const dockerCases = await readDockerCases(CODEMAN_CONFIG_DIR);
// ⚠️ NOT plain `adminOnly`, unlike the two routes above: the run menu probes this for
// every docker case to learn which CLIs the CONTAINER has, so an admin-only gate would
// hide every agent mode from a non-admin's own docker case. A non-admin may therefore
// probe a container ALREADY linked to a case they can access — never an arbitrary one,
// which is the adopt-time question and stays admin-only with the rest of that flow.
if (!isAdmin(req)) {
const owns = dockerCases.some(
(item) =>
(item.container ?? dockerContainerName(item.name)) === body.container &&
canAccessOwned(getAuthUser(req), item.owner)
);
if (!owns) {
reply.code(403);
return createErrorResponse(ApiErrorCode.FORBIDDEN, 'Admin only in multi-user mode');
}
}
const host = (await readDockerHosts(CODEMAN_CONFIG_DIR)).find((item) => item.id === body.hostId);
if (!host) return createErrorResponse(ApiErrorCode.NOT_FOUND, 'Docker host not found');
const probe = await probeAdoptableContainer(
{
engine: host.engine ?? 'docker',
context: host.context,
daemonHost: host.daemonHost,
containerName: body.container,
},
dockerAdoptProbeModes(),
body.containerWorkdir
);
return { success: true, data: probe };
});
// One-click "Run in Docker": create a NORMAL case (folder in CASES_DIR, scaffolded)
// AND link it to a hardened container with default settings, auto-provisioning a
// shared `default` docker host so the user never touches host/image/network fields.
@@ -899,6 +1094,17 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
if (!host) return createErrorResponse(ApiErrorCode.NOT_FOUND, 'Docker host not found');
const sessionDocker = toSessionDocker(host, dockerCase);
// A full export `docker commit`s the container into an image. For an ADOPTED
// container that means packaging someone else's container — with whatever
// credentials its owner logged in with — into a bundle Codeman then hands out,
// and it is the one export step that touches the container at all. The
// workspace-only export is a plain host-directory tar and stays available.
if (mode === 'full' && dockerCase.owned === false) {
return createErrorResponse(
ApiErrorCode.FORBIDDEN,
`Case "${name}" adopted an existing container. Codeman does not own it and will not commit it to an image — use a workspace-only export, or build the image yourself.`
);
}
if (mode === 'full' && !sessionDocker.mountCredentials) {
return createErrorResponse(
ApiErrorCode.INVALID_INPUT,
@@ -1042,8 +1248,22 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
'/api/docker-cases/:name/recreate',
async (req): Promise<ApiResponse<{ name: string; container: string }>> => {
const { name } = req.params as { name: string };
const dockerCase = (await readDockerCases(CODEMAN_CONFIG_DIR)).find((item) => item.name === name);
// Ownership gate: recreate DESTROYS a container, so it must be scoped like
// delete is (`canAccessOwned`). Without it any user could rebuild another
// user's container by name.
const dockerCase = (await readDockerCases(CODEMAN_CONFIG_DIR)).find(
(item) => item.name === name && canAccessOwned(getAuthUser(req), item.owner)
);
if (!dockerCase) return createErrorResponse(ApiErrorCode.NOT_FOUND, 'Docker case not found');
// An ADOPTED container is the user's own: there is nothing to recreate it
// from (no create-config, no image gate) and destroying it is exactly what
// adoption promises never to do.
if (dockerCase.owned === false) {
return createErrorResponse(
ApiErrorCode.FORBIDDEN,
`Case "${name}" adopted an existing container. Codeman does not own its lifecycle and will not recreate it — rebuild it yourself, or unlink the case.`
);
}
const host = (await readDockerHosts(CODEMAN_CONFIG_DIR)).find((item) => item.id === dockerCase.hostId);
if (!host) return createErrorResponse(ApiErrorCode.NOT_FOUND, 'Docker host not found');
const sessionDocker = toSessionDocker(host, dockerCase);
@@ -1154,7 +1374,13 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
);
// Best-effort `docker rm -f` the per-case container (case-delete is the
// explicit teardown that removes it; the bind-mounted workspace survives).
const host = (await readDockerHosts(CODEMAN_CONFIG_DIR)).find((item) => item.id === dockerCase.hostId);
// An ADOPTED container is skipped entirely: unlinking the case must leave
// the user's own container running and untouched. The seed file is skipped
// with it — adoption never wrote one.
const host =
dockerCase.owned === false
? undefined
: (await readDockerHosts(CODEMAN_CONFIG_DIR)).find((item) => item.id === dockerCase.hostId);
if (host) {
const sessionDocker = toSessionDocker(host, dockerCase);
try {
+64 -4
View File
@@ -38,7 +38,7 @@ import {
import { generateFirstPageThumbnail } from '../../document-thumbnailer.js';
import { getOfficePreviewPdfPath, getPreviewPdfDownloadName } from '../../document-preview-cache.js';
import { sanitizeAttachmentHistoryItem } from '../../session-attachment-history.js';
import { isBlockedAttachmentPath, loadAttachmentGuardConfig } from '../../config/attachment-guard.js';
import { isBlockedAttachmentPath, isUnderTree, loadAttachmentGuardConfig } from '../../config/attachment-guard.js';
import { isMultiUserMode, userSpacePath } from '../../config/multiuser.js';
import {
CASES_DIR,
@@ -425,6 +425,40 @@ function getFilesystemPreviewKind(fileName: string): FilesystemPreviewKind | und
return undefined;
}
/**
* Blocked trees, minus any tree that would swallow a configured picker root
* whole.
*
* `/root` is a default blocked tree, and Codeman running as root (containers,
* plenty of servers) makes `homedir()` exactly `/root` — so the picker's own
* allowlisted Home root was blocked by the attachment guard, every other
* candidate lives under it or does not exist, and the endpoint answered 403
* "No filesystem browse roots are available" with no root the user could reach.
*
* Dropping the tree does NOT expose secrets: `isSensitivePath` independently
* matches `.ssh/`, `.env`, `credentials*` and friends at any depth, and it is
* what the directory probe below asks about. Trees with no configured root
* beneath them (`/etc`) are untouched.
*/
function pickerBlockedTrees(blockedTrees: readonly string[], roots: readonly string[]): readonly string[] {
if (roots.length === 0) return blockedTrees;
return blockedTrees.filter((tree) => !roots.some((root) => isUnderTree(root, tree)));
}
/** Resolve candidate roots to realpaths, dropping the ones that do not exist. */
function resolveCandidateRootPaths(candidates: ReadonlyArray<{ path: string }>): string[] {
const out: string[] = [];
for (const candidate of candidates) {
if (!isAbsolute(candidate.path)) continue;
try {
out.push(realpathSync(candidate.path));
} catch {
// Optional roots (for example /mnt/d on non-WSL hosts) are omitted.
}
}
return out;
}
function isBlockedPickerPath(path: string, blockedTrees: readonly string[], directory = false): boolean {
if (isBlockedAttachmentPath(path, blockedTrees)) return true;
// The shared sensitive-path matcher describes file locations such as
@@ -491,13 +525,14 @@ async function resolveFilesystemPickerRoots(
}
const guard = await loadAttachmentGuardConfig();
const trees = pickerBlockedTrees(guard.blockedTrees, resolveCandidateRootPaths(candidates));
const roots: FilesystemBrowseRoot[] = [];
const seen = new Set<string>();
for (const candidate of candidates) {
if (!isAbsolute(candidate.path)) continue;
try {
const resolved = realpathSync(candidate.path);
if (seen.has(resolved) || isBlockedPickerPath(resolved, guard.blockedTrees, true)) continue;
if (seen.has(resolved) || isBlockedPickerPath(resolved, trees, true)) continue;
const stat = await fs.stat(resolved);
if (!stat.isDirectory()) continue;
seen.add(resolved);
@@ -536,8 +571,21 @@ async function resolveFilesystemPickerPath(
throwFilesystemPickerError(403, ApiErrorCode.INVALID_INPUT, 'No filesystem browse roots are available');
}
// With no explicit path (the "Link Existing" case picker, which passes no
// sessionId and an empty initialPath until the user has typed something),
// land on the shared cases root rather than falling through to whichever
// root happens to be first. `Codeman Cases` sits inside `Home` only on the
// native default (~/codeman-cases); a Docker deployment binds them at
// unrelated host paths (CODEMAN_APPDATA_PATH vs CODEMAN_CASES_PATH), so a
// Home-first fallback opened the picker somewhere with no cases in sight —
// and, worse, made an OLD case folder left behind by a since-changed
// CODEMAN_CASES_PATH look like a normal thing to stumble across while
// browsing for one to link.
const fallbackRoot =
roots.find((root) => root.label === 'Current Folder') ?? roots.find((root) => root.path === '/mnt/d') ?? roots[0];
roots.find((root) => root.label === 'Current Folder') ??
roots.find((root) => root.label === 'Codeman Cases') ??
roots.find((root) => root.path === '/mnt/d') ??
roots[0];
const candidatePath = resolve(requestedPath ?? fallbackRoot.path);
let resolvedPath: string;
@@ -556,7 +604,19 @@ async function resolveFilesystemPickerPath(
}
const guard = await loadAttachmentGuardConfig();
return { candidatePath, resolvedPath, roots, matchingRoot, blockedTrees: guard.blockedTrees };
// Navigation must use the SAME narrowed list the roots were selected with.
// Handing the raw trees down here would admit a root and then refuse every
// path inside it, which reads as a picker that opens and then does nothing.
return {
candidatePath,
resolvedPath,
roots,
matchingRoot,
blockedTrees: pickerBlockedTrees(
guard.blockedTrees,
roots.map((root) => root.path)
),
};
}
function appendDownloadFlag(url: string): string {
+31 -3
View File
@@ -126,10 +126,34 @@ export function registerHookEventRoutes(
// Sync Claude's current conversation id. Interactive PTY mode never emits
// `session_id` on stdout, so hooks are the only reliable way to learn that
// the user ran `/clear` (which spins up a new conversation jsonl).
let conversationChanged = false;
if (data && typeof data.session_id === 'string' && data.session_id) {
const session = ctx.sessions.get(sessionId);
const prevClaudeSessionId = session?.claudeSessionId;
session?.adoptClaudeSessionId(data.session_id);
const prevChainLength = session?.claudeSessionChain.length ?? 0;
// FIRST-HAND: this payload came from the CLI process itself and reached us
// because the pane's own $CODEMAN_SESSION_ID addressed it. No cwd, no
// timestamp, nothing a sibling pane on the same folder could win — so the
// response viewer can stop guessing entirely (see
// resolveActiveClaudeSessionIdFromHistory).
session?.adoptClaudeSessionId(data.session_id, { firstHand: true });
if (event === 'prompt_submitted') {
// Repairs `lastSubmitAt` for a pane driven straight from tmux: it was
// bumped only by input that flowed through Codeman's own write path, so
// it read 0 forever for those panes and every consumer of "when did this
// pane last submit" silently degraded.
session?.markPromptSubmitted();
}
// Persist when the conversation actually moved: `/clear` emits no
// completion event, so without this the successor id is lost on restart
// and recovery falls back to the launch conversation.
if (
session &&
(session.claudeSessionId !== prevClaudeSessionId || session.claudeSessionChain.length !== prevChainLength)
) {
conversationChanged = true;
ctx.persistSessionState(session);
}
// Docker sessions: keep the case's resume seed following the LIVE
// conversation (post-/clear id switches), so a container stop/reboot
// relaunch resumes the right transcript.
@@ -207,9 +231,13 @@ export function registerHookEventRoutes(
...(approvalId && session?.mode !== 'deepseek' && { approvalId }),
});
// Track in run summary
// Track in run summary. `prompt_submitted` fires on EVERY prompt of every
// Claude pane; only the ones where the conversation actually moved (a /clear
// successor) carry information, and recording the rest would push a row into
// the Summary timeline and /api/search per turn and evict useful rows from
// the 1000-event FIFO (#367 merge-time fix).
const summaryTracker = ctx.runSummaryTrackers.get(sessionId);
if (summaryTracker) {
if (summaryTracker && (event !== 'prompt_submitted' || conversationChanged)) {
summaryTracker.recordHookEvent(event, safeData);
}
+106 -30
View File
@@ -134,6 +134,7 @@ import {
import {
checkDockerAvailable,
checkDockerConfigDrift,
probeAdoptableContainer,
checkDockerTmuxAvailable,
ensureAgentBaseImage,
DEFAULT_AGENT_IMAGE,
@@ -1840,8 +1841,17 @@ export function registerSessionRoutes(
session: Session,
projectsDir: string
): Promise<string | null> {
// A pane whose conversation id came from its OWN hook needs no correlation:
// $CODEMAN_SESSION_ID (the pane's env) -> data.session_id (the CLI's own
// stdin JSON) is a first-hand binding that never looks at cwd, so it cannot
// be stolen by a sibling pane, a closed tab, or a bare `claude` in a
// terminal. Guessing can only be worse than the fact. This is also what
// closes the hole below for a pane driven straight from tmux: it never
// reaches `if (!submitAt)`.
if (session.claudeSessionIdIsFirstHand) return null;
const submitAt = session.lastSubmitAt;
if (!submitAt) return null; // never typed through Codeman — nothing to credit
if (!submitAt) return null; // no anchor at all — nothing to credit
const cached = claudeHistoryPinCache.get(session.id);
if (cached && cached.submitAt === submitAt) return cached.claudeSessionId;
@@ -1906,9 +1916,13 @@ export function registerSessionRoutes(
}
interface ClaudeResponseMessage {
kind: 'prompt' | 'response';
label: 'Prompt' | 'Response';
role: 'user' | 'assistant';
text: string;
timestamp?: string;
turn: number;
queued?: boolean;
}
interface ClaudeTranscriptEntry {
@@ -1918,6 +1932,19 @@ export function registerSessionRoutes(
isSidechain?: boolean;
isCompactSummary?: boolean;
message?: { content?: unknown };
// A prompt typed while Claude is working is absorbed mid-turn and recorded
// ONLY here — the CLI never re-emits it as a `user` row. Every field stays
// optional and unvalidated: `queued_command` is not a documented CLI
// contract, so a missing/renamed field must mean "skip", which is also what
// the CLI's own non-human queue entries (commandMode 'task-notification',
// no `origin` key) require. Shape observed on Claude Code 2.1.220-2.1.251.
attachment?: {
type?: string;
prompt?: string;
commandMode?: string;
timestamp?: string;
origin?: { kind?: string };
};
}
function extractClaudeText(content: unknown, separator: string): string {
@@ -1943,10 +1970,17 @@ export function registerSessionRoutes(
}
/**
* Claude writes one logical turn as many JSONL rows: text, thinking and tool
* blocks share message ids, while tool results are represented as user rows.
* Build viewer cards from real user boundaries instead of treating every row
* as a separate chat message.
* Claude writes an append-only event log: tool results arrive as user rows,
* thinking/tool_use rows carry no text, and a prompt typed while the agent is
* working is only ever recorded as an `attachment/queued_command` row. But one
* assistant row IS one whole model message: measured across ~/.claude/projects
* (CLI 2.1.220-2.1.251) no assistant row carries more than one content block
* and no message id carries more than one text block, so there is nothing to
* reassemble. Emit one card per row and group them with `turn` instead of
* concatenating a human turn's replies into a single card (#169), which fused
* up to 74 distinct model messages into one card. Splitting is safe for
* markdown: no adjacent pair of assistant text rows in the corpus continues a
* table, a list, or an open code fence.
*/
function parseClaudeResponseTranscript(
content: string,
@@ -1955,8 +1989,23 @@ export function registerSessionRoutes(
let lastText = '';
let lastTimestamp = '';
const messages: ClaudeResponseMessage[] = [];
let currentUserFragments = new Set<string>();
let currentAssistantFragments = new Set<string>();
// #169's replay guards, kept: they now SKIP a duplicated row instead of
// concatenating it into the previous card.
const currentUserFragments = new Set<string>();
const currentAssistantFragments = new Set<string>();
// Turn 0 is reserved for anything emitted before the first human prompt.
let turn = 0;
const pushUserMessage = (text: string, timestamp: string | undefined, queued: boolean): void => {
// A run of consecutive human inputs (a mid-turn queued burst) is ONE turn,
// so the viewer renders it under one badge instead of one badge per line.
if (messages.at(-1)?.role !== 'user') turn += 1;
const message: ClaudeResponseMessage = { kind: 'prompt', label: 'Prompt', role: 'user', text, timestamp, turn };
if (queued) message.queued = true;
messages.push(message);
currentUserFragments.add(text);
currentAssistantFragments.clear();
};
for (const line of content.split('\n')) {
if (!line) continue;
@@ -1970,25 +2019,37 @@ export function registerSessionRoutes(
// rows include repeated image dimensions and other UI-generated context.
if (entry.isSidechain) continue;
// A prompt typed while Claude is working is absorbed mid-turn and lives
// ONLY in an attachment row, so it was lost outright. `origin.kind` and
// `commandMode` separate the human's queue entries from the CLI's own:
// measured over 57 real transcripts on 2026-09-01, 322 queued_command rows
// split 163 `prompt`/`human` and 159 `task-notification`, and not one of
// those 159 carries an `origin` key. The 163 human rows become 162 user
// cards here — one is a verbatim repeat inside a still-unanswered user run
// and is collapsed by the dedup guard below — out of 353 user cards total.
if (entry.type === 'attachment') {
if (!full) continue;
const queued = entry.attachment;
if (!queued || queued.type !== 'queued_command') continue;
if (queued.origin?.kind !== 'human' || queued.commandMode !== 'prompt') continue;
const text = typeof queued.prompt === 'string' ? queued.prompt.trim() : '';
if (!text || isClaudeSyntheticUserMessage(entry, text)) continue;
if (currentUserFragments.has(text)) continue;
pushUserMessage(text, queued.timestamp || entry.timestamp, true);
continue;
}
if (entry.type === 'user') {
const text = extractClaudeText(entry.message?.content, '\n').trim();
// A tool_result block has no text block and naturally drops out here.
if (!text || isClaudeSyntheticUserMessage(entry, text)) continue;
if (!full) continue;
const previous = messages.at(-1);
if (previous?.role === 'user') {
// Claude can replay the initial user row while restoring a transcript.
// Only collapse duplicates within the same unanswered user turn; the
// same prompt after an assistant response remains a legitimate turn.
// Claude replays the initial user row while restoring a transcript, and
// a CLI that also wrote an absorbed prompt as a user row would double it.
// Both collapse here. The same prompt sent again AFTER a reply is a
// legitimate second turn, because that reply cleared the set.
if (currentUserFragments.has(text)) continue;
previous.text += `\n\n${text}`;
currentUserFragments.add(text);
} else {
messages.push({ role: 'user', text, timestamp: entry.timestamp });
currentUserFragments = new Set([text]);
}
currentAssistantFragments.clear();
pushUserMessage(text, entry.timestamp, false);
continue;
}
@@ -1999,18 +2060,10 @@ export function registerSessionRoutes(
lastTimestamp = entry.timestamp || '';
if (!full) continue;
const previous = messages.at(-1);
if (previous?.role === 'assistant') {
// Replayed snapshots sometimes repeat an identical text block. Distinct
// progress/final blocks are kept, but remain inside one Claude card.
// Replayed snapshots repeat an identical text block inside one turn.
if (currentAssistantFragments.has(text)) continue;
previous.text += `\n\n${text}`;
previous.timestamp = entry.timestamp || previous.timestamp;
messages.push({ kind: 'response', label: 'Response', role: 'assistant', text, timestamp: entry.timestamp, turn });
currentAssistantFragments.add(text);
} else {
messages.push({ role: 'assistant', text, timestamp: entry.timestamp });
currentAssistantFragments = new Set([text]);
}
currentUserFragments.clear();
}
@@ -3020,6 +3073,28 @@ export function registerSessionRoutes(
);
}
const sessionDocker = toSessionDocker(host, dockerCase);
// An ADOPTED container skips every image-side gate: we never run `docker
// create`, so the image is the user's business, and `ensureAgentBaseImage`
// would build/require an image that has nothing to do with their container.
// The prerequisite that DOES still hold is tmux inside it, so probe the live
// container (not the image) and refuse before launch rather than dead-paning.
if (sessionDocker.owned === false) {
const probe = await probeAdoptableContainer(sessionDocker, [mode]);
if (!probe.ok) {
return createErrorResponse(ApiErrorCode.OPERATION_FAILED, probe.error || 'container is not usable');
}
// The probe already exec'd into the container; carry its facts onto the
// live session so the launch chain does not have to re-ask.
sessionDocker.runsAsRoot = probe.runsAsRoot;
// No `mode !== 'shell'` arm: a mode with no binary of its own is reported
// available by the probe unconditionally, so this reads the same answer for it.
if (!probe.availableModes?.includes(mode)) {
return createErrorResponse(
ApiErrorCode.OPERATION_FAILED,
`"${mode}" is not installed in container "${sessionDocker.containerName}". Adoption never modifies the container — install it inside, or pick another mode.`
);
}
} else {
// Ensure the base image exists, auto-building the default image on first use so
// it is never a blocker. Dedup'd with any build kicked off at case-create, so
// this awaits the SAME in-flight build rather than starting a second one.
@@ -3041,6 +3116,7 @@ export function registerSessionRoutes(
return createErrorResponse(ApiErrorCode.OPERATION_FAILED, tmuxCheck.error || 'base image is missing tmux');
}
}
}
// Config drift (docs/docker-cases-plan.md §4): the desired create-config no
// longer matches the existing container's codeman.confighash label. Refuse to
+37 -21
View File
@@ -102,14 +102,14 @@ function withWebviews<T>(fn: (list: Webview[]) => Promise<T> | T): Promise<T> {
return next;
}
export function registerWebviewRoutes(app: FastifyInstance, ctx: EventPort & TabLayoutPort): void {
registerCrudRoutes(app, ctx);
registerProxyRoutes(app);
export function registerWebviewRoutes(app: FastifyInstance, ctx: EventPort & TabLayoutPort, basePath = ''): void {
registerCrudRoutes(app, ctx, basePath);
registerProxyRoutes(app, basePath);
}
// ───────────────────────────── CRUD ─────────────────────────────
function registerCrudRoutes(app: FastifyInstance, ctx: EventPort & TabLayoutPort): void {
function registerCrudRoutes(app: FastifyInstance, ctx: EventPort & TabLayoutPort, basePath: string): void {
app.get('/api/webviews', async (req) => {
const user = getAuthUser(req);
const all = await readWebviews(configDir());
@@ -279,7 +279,7 @@ function registerCrudRoutes(app: FastifyInstance, ctx: EventPort & TabLayoutPort
}
const capability = webviewCapabilities.mint(webview.id, webview.owner);
const data: WebviewOpenData = { webview, embedUrl: proxyPrefixFor(capability) };
const data: WebviewOpenData = { webview, embedUrl: proxyPrefixFor(capability, basePath) };
return { success: true, data };
});
}
@@ -347,7 +347,7 @@ async function probeUrl(url: string): Promise<WebviewProbe> {
// ───────────────────────────── Proxy ─────────────────────────────
function registerProxyRoutes(app: FastifyInstance): void {
function registerProxyRoutes(app: FastifyInstance, basePath: string): void {
app.register(async (scope) => {
// Encapsulated to this plugin only. The proxy must relay request bodies
// BYTE-FOR-BYTE, so every parser is replaced with a pass-through that hands
@@ -358,11 +358,11 @@ function registerProxyRoutes(app: FastifyInstance): void {
// A single GET route serving both roles: `handler` for normal requests,
// `wsHandler` for upgrades. Registering them as two routes on one URL would
// collide.
// collide. (The WS leg produces no browser-facing URLs, so it needs no base.)
scope.route<{ Params: ProxyParams }>({
method: 'GET',
url: `${WEBVIEW_PROXY_PREFIX}/:cap/*`,
handler: proxyHttp,
handler: (req, reply) => proxyHttp(req, reply, basePath),
wsHandler: proxyWebSocket,
});
@@ -371,14 +371,14 @@ function registerProxyRoutes(app: FastifyInstance): void {
scope.route<{ Params: ProxyParams }>({
method: ['POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
url: `${WEBVIEW_PROXY_PREFIX}/:cap/*`,
handler: proxyHttp,
handler: (req, reply) => proxyHttp(req, reply, basePath),
});
// `/webview/<cap>` with no trailing slash: redirect rather than serve, so the
// browser's notion of the base path ends in `/` and relative URLs in the
// dashboard's HTML resolve inside the prefix instead of one level above it.
scope.get<{ Params: { cap: string } }>(`${WEBVIEW_PROXY_PREFIX}/:cap`, (req, reply) => {
return reply.redirect(proxyPrefixFor(req.params.cap), 302);
return reply.redirect(proxyPrefixFor(req.params.cap, basePath), 302);
});
});
}
@@ -406,8 +406,12 @@ async function lookupCapability(capability: string): Promise<Webview | null> {
* streamed asset comes back zero-length. Returning the reply is what tells Fastify
* the response is already owned by this handler.
*/
function proxyHttp(req: FastifyRequest<{ Params: ProxyParams }>, reply: FastifyReply): Promise<FastifyReply> {
return proxyRequest(req, reply, req.params.cap, req.params['*'] ?? '');
function proxyHttp(
req: FastifyRequest<{ Params: ProxyParams }>,
reply: FastifyReply,
basePath: string
): Promise<FastifyReply> {
return proxyRequest(req, reply, req.params.cap, req.params['*'] ?? '', basePath);
}
/**
@@ -419,7 +423,8 @@ async function proxyRequest(
req: FastifyRequest,
reply: FastifyReply,
cap: string,
wildcard: string
wildcard: string,
basePath = ''
): Promise<FastifyReply> {
const webview = await lookupCapability(cap);
if (!webview) {
@@ -454,7 +459,8 @@ async function proxyRequest(
const headers = buildUpstreamRequestHeaders(req.headers, upstream, {
forwardCookies: webview.trusted,
sessionCookieName: AUTH_COOKIE_NAME,
refererPath: typeof req.headers.referer === 'string' ? stripProxyPrefix(req.headers.referer, cap) : undefined,
refererPath:
typeof req.headers.referer === 'string' ? stripProxyPrefix(req.headers.referer, cap, basePath) : undefined,
});
// #237: the timeout bounds TIME-TO-HEADERS only. A plain AbortSignal.timeout on
@@ -546,7 +552,8 @@ async function proxyRequest(
response.headers.getSetCookie(),
cap,
upstream,
secureContext
secureContext,
basePath
);
reply.code(response.status);
@@ -575,7 +582,7 @@ async function proxyRequest(
// Buffer only HTML, only under the cap: `<base>` injection needs the whole
// document, and buffering an unbounded upstream body is a memory hazard.
const html = await response.text();
return reply.send(html.length <= MAX_WEBVIEW_HTML_REWRITE_BYTES ? rewriteHtml(html, cap) : html);
return reply.send(html.length <= MAX_WEBVIEW_HTML_REWRITE_BYTES ? rewriteHtml(html, cap, basePath) : html);
}
return reply.send(Readable.fromWeb(response.body as Parameters<typeof Readable.fromWeb>[0]));
@@ -596,25 +603,34 @@ async function proxyRequest(
*
* @returns true when the request was handled (caller must not also reply).
*/
export async function tryWebviewRefererFallback(req: FastifyRequest, reply: FastifyReply): Promise<boolean> {
export async function tryWebviewRefererFallback(
req: FastifyRequest,
reply: FastifyReply,
basePath = ''
): Promise<boolean> {
// Safe methods only. A write arriving here has already lost its raw body to the
// root instance's JSON parser, so it could not be relayed faithfully anyway.
if (req.method !== 'GET' && req.method !== 'HEAD') return false;
const capability = capabilityFromReferer(typeof req.headers.referer === 'string' ? req.headers.referer : undefined);
const capability = capabilityFromReferer(
typeof req.headers.referer === 'string' ? req.headers.referer : undefined,
basePath
);
if (!capability) return false;
if (!webviewCapabilities.resolve(capability)) return false;
// req.url is already base-stripped by the server's rewriteUrl, so this is the
// internal path the upstream resolver expects.
const path = req.url.split('?')[0].replace(/^\//, '');
await proxyRequest(req, reply, capability, path);
await proxyRequest(req, reply, capability, path, basePath);
return true;
}
/** Turn a proxy-side Referer back into the upstream path it corresponds to. */
function stripProxyPrefix(referer: string, capability: string): string | undefined {
function stripProxyPrefix(referer: string, capability: string, basePath = ''): string | undefined {
try {
const url = new URL(referer);
const prefix = proxyPrefixFor(capability);
const prefix = proxyPrefixFor(capability, basePath);
if (!url.pathname.startsWith(prefix)) return undefined;
return `/${url.pathname.slice(prefix.length)}${url.search}`;
} catch {
+71
View File
@@ -868,6 +868,74 @@ export const DockerCaseLinkSchema = z.object({
.optional(),
});
/**
* ADOPT an already-running container the user built and runs themselves. The
* container name is REQUIRED (there is nothing to derive it from — we are not
* creating it), and `hostWorkspacePath` still points at real host bytes so the
* file routes, watchers and transcript correlation keep working exactly as they
* do for an owned case. Everything that only makes sense at container-create
* time (image, network, resources, gpus, credential mounts) is deliberately
* absent: adoption never runs `docker create`.
*/
export const DockerCaseAdoptSchema = z.object({
name: z.string().regex(/^[a-zA-Z0-9_-]+$/, 'Invalid case name format'),
hostId: z.string().regex(/^[a-zA-Z0-9_-]+$/, 'Invalid docker host id'),
container: z
.string()
.min(2)
.max(128)
.regex(/^[a-zA-Z0-9][a-zA-Z0-9_.-]+$/, 'Invalid container name'),
hostWorkspacePath: z
.string()
.min(1)
.max(2000)
.regex(/^\//, 'Workspace path must be absolute')
.regex(/^[^,]*$/, 'Workspace path must not contain commas (docker --mount is comma-delimited)')
.regex(NO_SHELL_META, 'Invalid characters in workspace path'),
containerWorkdir: z
.string()
.min(1)
.max(2000)
.regex(/^\//, 'Container workdir must be absolute')
.regex(/^[^,]*$/, 'Container workdir must not contain commas (docker --mount is comma-delimited)')
.regex(NO_SHELL_META, 'Invalid characters in container workdir')
.optional(),
});
/** Read-only adoption preflight: report on an existing container, link nothing. */
export const DockerAdoptPreflightSchema = z.object({
hostId: z.string().regex(/^[a-zA-Z0-9_-]+$/, 'Invalid docker host id'),
container: z
.string()
.min(2)
.max(128)
.regex(/^[a-zA-Z0-9][a-zA-Z0-9_.-]+$/, 'Invalid container name'),
/** Optional: also verify this path exists INSIDE the container. */
containerWorkdir: z
.string()
.min(1)
.max(2000)
.regex(/^\//, 'Container workdir must be absolute')
.regex(NO_SHELL_META, 'Invalid characters in container workdir')
.optional(),
});
/** Read-only directory listing inside a container (adoption workdir picker). */
export const DockerBrowseSchema = z.object({
hostId: z.string().regex(/^[a-zA-Z0-9_-]+$/, 'Invalid docker host id'),
container: z
.string()
.min(2)
.max(128)
.regex(/^[a-zA-Z0-9][a-zA-Z0-9_.-]+$/, 'Invalid container name'),
path: z
.string()
.max(2000)
.regex(/^\//, 'Path must be absolute')
.regex(NO_SHELL_META, 'Invalid characters in path')
.optional(),
});
export const DockerExportSchema = z.object({
mode: z.enum(['full', 'workspace']).optional(),
});
@@ -975,6 +1043,9 @@ export const HookEventSchema = z.object({
'stop',
'teammate_idle',
'task_completed',
// Claude Code's UserPromptSubmit: a first-hand report of the pane's live
// conversation id. Keep in step with HookEventType in types/api.ts.
'prompt_submitted',
// A turn STARTED. Unlike the others this one has no Claude Code hook behind
// it: it is reported by the DeepSeek Harness status shim, and exists so a
// dialog answered in the terminal resolves its Approvals Inbox item at once
+69 -14
View File
@@ -41,6 +41,7 @@ import fs from 'node:fs/promises';
import { execSync } from 'node:child_process';
import { hostname as getHostname } from 'node:os';
import { dataPath, getDataDir, CODEMAN_INSTANCE } from '../config/instance.js';
import { normalizeBasePath, stripBasePath, joinBasePath } from '../config/base-path.js';
import { GLYPH, palette } from '../cli-style.js';
import { getHookSecret } from '../config/hook-secret.js';
import { EventEmitter } from 'node:events';
@@ -260,6 +261,8 @@ export class WebServer extends EventEmitter {
private port: number;
private host: string;
private https: boolean;
/** Reverse-proxy sub-path prefix (normalized: '' for root, or '/foo'). */
private basePath: string;
private testMode: boolean;
private mux: TerminalMultiplexer;
// Centralized cleanup for standalone timers (intervals + resettable timeouts)
@@ -330,13 +333,16 @@ export class WebServer extends EventEmitter {
testMode: boolean = false,
host: string = '127.0.0.1',
titleHostname?: string,
allowUnauthenticatedNetwork: boolean = false
allowUnauthenticatedNetwork: boolean = false,
basePath: string = ''
) {
super();
this.setMaxListeners(0);
this.host = host;
this.port = port;
this.https = https;
// Normalize so callers may pass raw operator input; '' == mounted at root.
this.basePath = normalizeBasePath(basePath || process.env.CODEMAN_BASE_URL);
this.testMode = testMode;
this.allowUnauthenticatedNetwork =
allowUnauthenticatedNetwork || isExplicitlyEnabled(process.env.CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK);
@@ -344,7 +350,12 @@ export class WebServer extends EventEmitter {
this.windowTitle = `codeman:${this.titleHostname}`;
this.indexHtmlTemplate = readFileSync(join(__dirname, 'public', 'index.html'), 'utf-8');
const rewriteUrl = (req: { url?: string }): string => rewriteApiV1Url(req.url || '');
// Ingress: strip the reverse-proxy prefix so all internal routing stays
// prefix-agnostic (routes are still declared at `/api/...`, `/`, `/ws/...`).
// Requests that arrive WITHOUT the prefix (hooks, health checks, the docker
// bridge — all hitting the raw port) pass through unchanged. Then apply the
// existing /api/v1 alias rewrite.
const rewriteUrl = (req: { url?: string }): string => rewriteApiV1Url(stripBasePath(this.basePath, req.url || ''));
if (https) {
const { key, cert } = getOrCreateSelfSignedCert();
this.app = Fastify({ logger: false, https: { key, cert }, rewriteUrl });
@@ -725,6 +736,21 @@ export class WebServer extends EventEmitter {
// Cookie plugin (needed for auth session tokens)
await this.app.register(fastifyCookie);
// Egress: when mounted under a reverse-proxy sub-path, any root-absolute
// `Location` we emit (redirects in system/webview/file routes, `/`, `/api/...`)
// must carry the prefix or the browser resolves it against the origin root and
// escapes the mount. One hook covers every current and future redirect, mirroring
// the ingress strip in `rewriteUrl`. No-op when mounted at root (basePath === '').
if (this.basePath) {
this.app.addHook('onSend', (_req, reply, payload, done) => {
const loc = reply.getHeader('location');
if (typeof loc === 'string') {
reply.header('location', joinBasePath(this.basePath, loc));
}
done(null, payload);
});
}
// Uniform response envelope (stable HTTP contract — docs/api-reference.md):
// wrap bare JSON payloads as { success:true, data } and map { success:false }
// error envelopes to a conventional HTTP status (instead of 200). Skips
@@ -749,10 +775,10 @@ export class WebServer extends EventEmitter {
// Anti-DNS-rebinding Host allowlist + cross-site (CSRF) Origin guard. Registered
// before auth so forged cross-site / rebound requests are rejected up front, even
// on the default no-password install. See docs/reports/security-review-2026-06-09.md.
registerHostGuard(this.app, () => this.getHostPolicy());
registerHostGuard(this.app, () => this.getHostPolicy(), this.basePath);
// Auth middleware (Basic Auth + session cookies + rate limiting)
const authState = registerAuthMiddleware(this.app, this.https);
const authState = registerAuthMiddleware(this.app, this.https, this.basePath);
if (authState) {
this.authSessions = authState.authSessions;
this.authFailures = authState.authFailures;
@@ -777,7 +803,7 @@ export class WebServer extends EventEmitter {
});
// Security headers + CORS
registerSecurityHeaders(this.app, this.https);
registerSecurityHeaders(this.app, this.https, this.basePath);
this.app.get('/', async (_req, reply) => {
return reply
.header('Cache-Control', 'no-cache')
@@ -949,7 +975,7 @@ export class WebServer extends EventEmitter {
// rescue. Reaching this handler at all already proves no Codeman route matched,
// and the relay declines unless the Referer carries a live capability, so
// genuinely unknown `/api` paths still get the envelope below.
if (await tryWebviewRefererFallback(req, reply)) return reply;
if (await tryWebviewRefererFallback(req, reply, this.basePath)) return reply;
if (req.url.startsWith('/api')) {
return reply.code(404).send(createErrorResponse(ApiErrorCode.NOT_FOUND, notFound));
}
@@ -1023,7 +1049,7 @@ export class WebServer extends EventEmitter {
registerMeRoutes(this.app, ctx);
registerAdminRoutes(this.app, ctx);
registerOrchestratorRoutes(this.app, ctx);
registerWebviewRoutes(this.app, ctx);
registerWebviewRoutes(this.app, ctx, this.basePath);
registerTabLayoutRoutes(this.app, ctx);
// Cron: build the service from the same context, recompute
@@ -1383,6 +1409,20 @@ export class WebServer extends EventEmitter {
'<title>Codeman</title>',
`<title>${escapeHtmlText(this.windowTitle)}</title>`
);
// Reverse-proxy sub-path support. The template ships `<base href="/">` and all
// static asset refs are RELATIVE, so pointing the base at the mount prefix
// rewrites every asset URL for free. `window.__CODEMAN_BASE__` gives the
// frontend the same prefix for the root-absolute URLs it builds at runtime
// (fetch/SSE/WS), which `<base>` cannot touch. Injected right after `<base>`
// so it is set before any (deferred) script runs. ONLY when a base is set —
// at root ('') the template is left byte-identical to the historical output
// (the frontend reads a missing `__CODEMAN_BASE__` as root anyway).
if (this.basePath) {
html = html.replace(
'<base href="/">',
`<base href="${escapeHtmlText(this.basePath + '/')}">\n <script>window.__CODEMAN_BASE__=${JSON.stringify(this.basePath)};</script>`
);
}
// Cache-bust same-origin module scripts + stylesheets so a normal reload
// always serves the latest (static assets carry a 1-year immutable cache).
html = this.cacheBustAssets(html);
@@ -1492,10 +1532,9 @@ export class WebServer extends EventEmitter {
html = html.replace('</head>', `<script>window.__codemanGestureAvailable=true;</script>\n</head>`);
if (settings.gestureControlEnabled === true) {
const v = this.gestureBundleVersion();
html = html.replace(
'</head>',
`<script type="module" src="/gesture/gesture-codeman.js${v}"></script>\n</head>`
);
// Relative src so the injected `<base href>` resolves it under the mount
// prefix (a root-absolute `/gesture/...` would escape a sub-path mount).
html = html.replace('</head>', `<script type="module" src="gesture/gesture-codeman.js${v}"></script>\n</head>`);
}
}
return html;
@@ -2490,7 +2529,18 @@ export class WebServer extends EventEmitter {
const displayHost = this.host === '0.0.0.0' ? 'localhost' : this.host;
// The only startup banner: `codeman web` used to print its own copy of this
// line, but the daemon and service launch paths never go through the CLI.
console.log(palette.ok(`${GLYPH.ok} Codeman web interface running at ${protocol}://${displayHost}:${this.port}`));
console.log(
palette.ok(
`${GLYPH.ok} Codeman web interface running at ${protocol}://${displayHost}:${this.port}${this.basePath}${this.basePath ? '/' : ''}`
)
);
if (this.basePath) {
console.log(
palette.muted(
` Mounted under base path ${this.basePath} (front it with a reverse proxy that forwards ${this.basePath}/ unchanged).`
)
);
}
// Opt-in: also serve the HOOK endpoints on the docker bridge gateway so
// in-container hooks (permission/idle/stop callbacks) can reach a loopback-bound
@@ -2794,6 +2844,10 @@ export class WebServer extends EventEmitter {
// the launch conversation until the user types again, even though
// the re-attached CLI is on a post-`/clear` one.
lastSubmitAt: savedState?.lastSubmitAt,
// Conversations this pane provably owned, oldest first. Its tail is
// the conversation the CLI was on when the server stopped, which is
// what a re-attach must point the viewer at instead of the launch id.
claudeSessionChain: savedState?.claudeSessionChain,
// The pane's last output, previous run's value. Without it every
// restart restamped all sessions "now" (constructor + the attach
// repaint within the same second), flattening the home screens'
@@ -3335,9 +3389,10 @@ export async function startWebServer(
testMode: boolean = false,
host: string = '127.0.0.1',
titleHostname?: string,
allowUnauthenticatedNetwork: boolean = false
allowUnauthenticatedNetwork: boolean = false,
basePath: string = ''
): Promise<WebServer> {
const server = new WebServer(port, https, testMode, host, titleHostname, allowUnauthenticatedNetwork);
const server = new WebServer(port, https, testMode, host, titleHostname, allowUnauthenticatedNetwork, basePath);
await server.start();
return server;
}
+4 -2
View File
@@ -5,7 +5,7 @@
* and referenced by the frontend (`SSE_EVENTS` in `constants.js`).
* Both files MUST be kept in sync.
*
* 157 event constants organized by category:
* 158 event constants organized by category:
* - **Core** (1): init
* - **Transport** (1): sse:heartbeat
* - **Session lifecycle** (23): created, updated, deleted, terminal, idle, working, ...
@@ -25,7 +25,7 @@
* - **Plan orchestration** (5): started, progress, subagent, completed, cancelled
* - **Tunnel** (7): started, stopped, progress, error, qrRotated, qrRegenerated, qrAuthUsed
* - **Image / attachments** (2): image:detected, attachment:detected
* - **Hooks** (9): idle_prompt, permission_prompt, elicitation_dialog, elicitation_complete, elicitation_response, stop, agent_working, teammate_idle, task_completed
* - **Hooks** (10): idle_prompt, permission_prompt, elicitation_dialog, elicitation_complete, elicitation_response, stop, agent_working, teammate_idle, task_completed, prompt_submitted
* (agent_working is the odd one out: reported by the DeepSeek Harness status bridge, not by a Claude Code hook)
* - **Approvals** (3): pending, updated, resolved (cross-session Approvals Inbox)
* - **Orchestrator** (12): stateChanged, planProgress, planReady, phase*, verification, task*, completed, error
@@ -372,6 +372,8 @@ export const HookAgentWorking = 'hook:agent_working' as const;
export const HookTeammateIdle = 'hook:teammate_idle' as const;
/** Claude Code hook: teammate task completed. */
export const HookTaskCompleted = 'hook:task_completed' as const;
/** UserPromptSubmit fired in a Claude pane (#367): the pane learned its live conversation id first-hand. */
export const HookPromptSubmitted = 'hook:prompt_submitted' as const;
// ─── Approvals Inbox ─────────────────────────────────────────────────────────
+29 -15
View File
@@ -39,6 +39,7 @@
*/
import { WEBVIEW_PROXY_PREFIX } from '../config/webview-limits.js';
import { stripBasePath } from '../config/base-path.js';
/** Headers that are per-connection and must never be relayed in either direction. */
const HOP_BY_HOP = new Set([
@@ -99,9 +100,18 @@ const DROP_RESPONSE_HEADERS = new Set([
'referrer-policy',
]);
/** The same-origin path prefix an iframe loads for a given capability. */
export function proxyPrefixFor(capability: string): string {
return `${WEBVIEW_PROXY_PREFIX}/${capability}/`;
/**
* The same-origin path prefix an iframe loads for a given capability.
*
* `basePath` is the reverse-proxy mount prefix (`''` at root, or `/foo`). It is
* INCLUDED here because this value is browser-facing — the iframe src, the
* `<base href>`, the runtime shim's rewrite target, Location/Set-Cookie rebasing —
* and all of those must ride the mount or they escape it. Requests coming the other
* way are base-stripped before routing, so the parsers (`capabilityFromProxyPath`,
* `resolveUpstreamUrl`) deliberately do NOT take a base.
*/
export function proxyPrefixFor(capability: string, basePath = ''): string {
return `${basePath}${WEBVIEW_PROXY_PREFIX}/${capability}/`;
}
/**
@@ -178,10 +188,13 @@ export function capabilityFromProxyPath(pathname: string): string | null {
* Extract the capability a `Referer` belongs to. Backs the 404 fallback that
* catches root-absolute asset requests (`/static/app.js`) which `<base>` cannot fix.
*/
export function capabilityFromReferer(referer: string | undefined): string | null {
export function capabilityFromReferer(referer: string | undefined, basePath = ''): string | null {
if (!referer) return null;
try {
return capabilityFromProxyPath(new URL(referer).pathname);
// The Referer is browser-supplied, so under a sub-path mount it carries the
// prefix (`/foo/webview/<cap>/...`); strip it back to the internal path the
// capability parser expects.
return capabilityFromProxyPath(stripBasePath(basePath, new URL(referer).pathname));
} catch {
return null;
}
@@ -232,7 +245,7 @@ export function isFramableCrossOrigin(xFrameOptions: string | undefined, csp: st
* proxied: relaying them would turn this into an open proxy for any host the
* upstream chooses to name.
*/
export function rewriteLocation(location: string, requestUrl: URL, capability: string): string {
export function rewriteLocation(location: string, requestUrl: URL, capability: string, basePath = ''): string {
let resolved: URL;
try {
resolved = new URL(location, requestUrl);
@@ -241,7 +254,7 @@ export function rewriteLocation(location: string, requestUrl: URL, capability: s
}
if (resolved.origin !== requestUrl.origin) return location;
const suffix = resolved.pathname.replace(/^\//, '');
return `${proxyPrefixFor(capability)}${suffix}${resolved.search}${resolved.hash}`;
return `${proxyPrefixFor(capability, basePath)}${suffix}${resolved.search}${resolved.hash}`;
}
/**
@@ -252,7 +265,7 @@ export function rewriteLocation(location: string, requestUrl: URL, capability: s
* cookie name, and `Secure` is dropped when Codeman itself is serving plain HTTP
* in dev, where a Secure cookie would simply be discarded.
*/
export function rewriteSetCookie(cookie: string, capability: string, secureContext: boolean): string {
export function rewriteSetCookie(cookie: string, capability: string, secureContext: boolean, basePath = ''): string {
const parts = cookie.split(';');
const out: string[] = [parts[0]];
let sawPath = false;
@@ -266,13 +279,13 @@ export function rewriteSetCookie(cookie: string, capability: string, secureConte
sawPath = true;
const value = attr.slice('path='.length);
const suffix = value.replace(/^\//, '');
out.push(`Path=${proxyPrefixFor(capability)}${suffix}`);
out.push(`Path=${proxyPrefixFor(capability, basePath)}${suffix}`);
continue;
}
out.push(attr);
}
if (!sawPath) out.push(`Path=${proxyPrefixFor(capability)}`);
if (!sawPath) out.push(`Path=${proxyPrefixFor(capability, basePath)}`);
return out.join('; ');
}
@@ -336,7 +349,8 @@ export function buildDownstreamResponseHeaders(
setCookies: string[],
capability: string,
requestUrl: URL,
secureContext: boolean
secureContext: boolean,
basePath = ''
): { headers: Record<string, string>; setCookie: string[]; csp: string | null } {
const headers: Record<string, string> = {};
let csp: string | null = null;
@@ -349,7 +363,7 @@ export function buildDownstreamResponseHeaders(
continue;
}
if (lower === 'location') {
headers['location'] = rewriteLocation(value, requestUrl, capability);
headers['location'] = rewriteLocation(value, requestUrl, capability, basePath);
continue;
}
if (DROP_RESPONSE_HEADERS.has(lower)) continue;
@@ -365,7 +379,7 @@ export function buildDownstreamResponseHeaders(
// override this; that is the dashboard author's own decision about their page.
headers['referrer-policy'] = 'same-origin';
const setCookie = setCookies.map((cookie) => rewriteSetCookie(cookie, capability, secureContext));
const setCookie = setCookies.map((cookie) => rewriteSetCookie(cookie, capability, secureContext, basePath));
return { headers, setCookie, csp };
}
@@ -593,8 +607,8 @@ try{
* relative URLs, attribute rewriting for root-absolute markup, and the shim for
* URLs built at runtime.
*/
export function rewriteHtml(html: string, capability: string): string {
const prefix = proxyPrefixFor(capability);
export function rewriteHtml(html: string, capability: string, basePath = ''): string {
const prefix = proxyPrefixFor(capability, basePath);
// Fresh regexes per call: module-level /g patterns carry `lastIndex` between calls.
const rebased = html
+78
View File
@@ -0,0 +1,78 @@
/**
* @fileoverview Server wiring for the reverse-proxy base path (#381): prefixed and
* unprefixed forms both route, the shell gets the base injected, root-absolute
* redirects are rebased without double-prefixing, and a WebSocket upgrade under the
* prefix reaches the terminal route. The pure helpers are covered by
* test/base-path.test.ts; this boots a real WebServer in test mode.
*/
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { WebServer } from '../src/web/server.js';
const PORT = 3197;
describe('reverse-proxy base path: server wiring', () => {
let server: WebServer;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let app: any;
beforeAll(async () => {
server = new WebServer(PORT, false, true, '127.0.0.1', undefined, false, '/codeman');
await server.start();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
app = (server as any).app;
});
afterAll(async () => {
await server.stop();
});
it('routes prefixed, unprefixed and /api/v1 forms', async () => {
for (const url of ['/codeman/api/status', '/api/status', '/codeman/api/v1/status']) {
const r = await app.inject({ method: 'GET', url });
expect(r.statusCode, url).toBe(200);
expect(JSON.parse(r.body).success).toBe(true);
}
});
it('serves the shell with the base injected at /codeman, /codeman/ and /codeman/session/:id', async () => {
for (const url of ['/codeman', '/codeman/', '/codeman/session/abc']) {
const r = await app.inject({ method: 'GET', url });
expect(r.statusCode, url).toBe(200);
expect(r.body).toContain('<base href="/codeman/">');
expect(r.body).toContain('window.__CODEMAN_BASE__="/codeman"');
}
});
it('serves sw.js under the prefix', async () => {
const r = await app.inject({ method: 'GET', url: '/codeman/sw.js' });
expect(r.statusCode).toBe(200);
expect(r.headers['content-type']).toContain('javascript');
});
it('rebases root-absolute redirects and never double-prefixes', async () => {
const qr = await app.inject({ method: 'GET', url: '/codeman/q/abcdef' });
expect(qr.statusCode).toBe(302);
expect(qr.headers.location).toBe('/codeman/');
const wv = await app.inject({ method: 'GET', url: '/codeman/webview/somecap' });
expect(wv.statusCode).toBe(302);
expect(wv.headers.location).toBe('/codeman/webview/somecap/');
});
it('unknown prefixed API path still gets the 404 envelope', async () => {
const r = await app.inject({ method: 'GET', url: '/codeman/api/nope' });
expect(r.statusCode).toBe(404);
expect(JSON.parse(r.body).success).toBe(false);
});
it('routes a prefixed WebSocket upgrade to the terminal route', async () => {
const { WebSocket } = await import('ws');
const close = (path: string) =>
new Promise<{ code: number; reason: string }>((resolve) => {
const ws = new WebSocket(`ws://127.0.0.1:${PORT}${path}`, { headers: { origin: `http://127.0.0.1:${PORT}` } });
ws.on('close', (code, reason) => resolve({ code, reason: reason.toString() }));
ws.on('error', (e) => resolve({ code: -1, reason: String(e) }));
});
const prefixed = await close('/codeman/ws/sessions/nosuch/terminal');
const bare = await close('/ws/sessions/nosuch/terminal');
expect(prefixed).toEqual({ code: 4004, reason: 'Session not found' });
expect(prefixed).toEqual(bare);
});
});
+119
View File
@@ -0,0 +1,119 @@
/**
* @fileoverview Unit tests for the pure reverse-proxy base-path helpers
* (src/config/base-path.ts). These back the server ingress strip (rewriteUrl),
* the egress Location rewrite (onSend), and the frontend route builder, so their
* correctness is what makes a sub-path mount work end to end.
*/
import { describe, it, expect } from 'vitest';
import {
normalizeBasePath,
isValidBasePath,
assertValidBasePath,
joinBasePath,
stripBasePath,
} from '../src/config/base-path.js';
describe('normalizeBasePath', () => {
it('treats root / and empty as no prefix', () => {
expect(normalizeBasePath('/')).toBe('');
expect(normalizeBasePath('')).toBe('');
expect(normalizeBasePath(undefined)).toBe('');
expect(normalizeBasePath(null)).toBe('');
expect(normalizeBasePath(' ')).toBe('');
});
it('adds a leading slash and drops trailing slashes', () => {
expect(normalizeBasePath('codeman')).toBe('/codeman');
expect(normalizeBasePath('/codeman')).toBe('/codeman');
expect(normalizeBasePath('/codeman/')).toBe('/codeman');
expect(normalizeBasePath('codeman///')).toBe('/codeman');
});
it('collapses duplicate slashes and keeps nested segments', () => {
expect(normalizeBasePath('//a//b//')).toBe('/a/b');
expect(normalizeBasePath('/tools/codeman')).toBe('/tools/codeman');
});
});
describe('isValidBasePath / assertValidBasePath', () => {
it('accepts root and well-formed segments', () => {
expect(isValidBasePath('')).toBe(true);
expect(isValidBasePath('/codeman')).toBe(true);
expect(isValidBasePath('/tools/codeman-2')).toBe(true);
expect(isValidBasePath('/a_b.c~d')).toBe(true);
});
it('rejects segments with unsafe characters', () => {
expect(isValidBasePath('/a b')).toBe(false);
expect(isValidBasePath('/a?b')).toBe(false);
expect(isValidBasePath('/a#b')).toBe(false);
expect(isValidBasePath('/a%2f')).toBe(false);
});
it('assertValidBasePath normalizes valid input and throws on bad', () => {
expect(assertValidBasePath('/codeman/')).toBe('/codeman');
expect(assertValidBasePath('/')).toBe('');
expect(() => assertValidBasePath('/a b')).toThrow(/Invalid --base-url/);
expect(() => assertValidBasePath('?x')).toThrow(/Invalid --base-url/);
});
});
describe('joinBasePath (frontend/egress route builder)', () => {
it('is a no-op at root', () => {
expect(joinBasePath('', '/api/x')).toBe('/api/x');
expect(joinBasePath('', '/')).toBe('/');
});
it('prefixes root-absolute app paths', () => {
expect(joinBasePath('/codeman', '/api/x')).toBe('/codeman/api/x');
expect(joinBasePath('/codeman', '/')).toBe('/codeman/');
expect(joinBasePath('/codeman', '/ws/sessions/1/terminal')).toBe('/codeman/ws/sessions/1/terminal');
});
it('leaves absolute, protocol-relative, and relative URLs alone', () => {
expect(joinBasePath('/codeman', 'https://x/y')).toBe('https://x/y');
expect(joinBasePath('/codeman', 'ws://x/y')).toBe('ws://x/y');
expect(joinBasePath('/codeman', '//host/y')).toBe('//host/y');
expect(joinBasePath('/codeman', 'app.js')).toBe('app.js');
expect(joinBasePath('/codeman', '#frag')).toBe('#frag');
expect(joinBasePath('/codeman', 'data:image/png;base64,AAAA')).toBe('data:image/png;base64,AAAA');
});
it('is idempotent — never double-prefixes', () => {
expect(joinBasePath('/codeman', '/codeman/api/x')).toBe('/codeman/api/x');
expect(joinBasePath('/codeman', '/codeman')).toBe('/codeman');
expect(joinBasePath('/codeman', '/codeman?y=1')).toBe('/codeman?y=1');
});
it('does not treat a same-named sibling path as already-prefixed', () => {
// /codeman-docs must NOT be mistaken for the /codeman mount.
expect(joinBasePath('/codeman', '/codeman-docs/x')).toBe('/codeman/codeman-docs/x');
});
});
describe('stripBasePath (server ingress)', () => {
it('is a no-op at root', () => {
expect(stripBasePath('', '/api/x')).toBe('/api/x');
});
it('strips the prefix from proxied requests', () => {
expect(stripBasePath('/codeman', '/codeman/api/x')).toBe('/api/x');
expect(stripBasePath('/codeman', '/codeman')).toBe('/');
expect(stripBasePath('/codeman', '/codeman/')).toBe('/');
expect(stripBasePath('/codeman', '/codeman?y=1')).toBe('/?y=1');
});
it('leaves un-prefixed requests unchanged (direct-to-port: hooks, health, docker bridge)', () => {
expect(stripBasePath('/codeman', '/api/x')).toBe('/api/x');
expect(stripBasePath('/codeman', '/api/hook-event')).toBe('/api/hook-event');
// A same-named sibling is not the mount.
expect(stripBasePath('/codeman', '/codeman-docs/x')).toBe('/codeman-docs/x');
});
it('round-trips with joinBasePath', () => {
const base = '/tools/codeman';
for (const p of ['/', '/api/x', '/ws/y', '/session/abc']) {
expect(stripBasePath(base, joinBasePath(base, p))).toBe(p);
}
});
});
+59
View File
@@ -0,0 +1,59 @@
/**
* @fileoverview Static guard for the Add Case modal's submit controls (#368).
*
* Below 860px the shared set-* surface hides the modal footer, and for eight
* releases that footer held the only Create/Clone/Link button, so no case could
* be added from a phone and nothing failed. This pins the contract that fixed it:
* a header submit button exists after the close button, and the two JS paths
* that toggle submit state drive BOTH buttons.
*/
import { describe, it, expect } from 'vitest';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
const publicDir = resolve(import.meta.dirname, '../src/web/public');
const html = readFileSync(resolve(publicDir, 'index.html'), 'utf8');
const sessionUi = readFileSync(resolve(publicDir, 'session-ui.js'), 'utf8');
const mobileCss = readFileSync(resolve(publicDir, 'mobile.css'), 'utf8');
function caseModal(): string {
const start = html.indexOf('<div class="modal" id="createCaseModal">');
expect(start).toBeGreaterThan(-1);
const next = html.indexOf('<div class="modal"', start + 1);
return html.slice(start, next === -1 ? html.length : next);
}
function methodBody(signature: string): string {
const start = sessionUi.indexOf(`\n ${signature} {`);
expect(start, `${signature} not found in session-ui.js`).toBeGreaterThan(-1);
return sessionUi.slice(start, sessionUi.indexOf('\n },', start));
}
describe('Add Case modal submit controls', () => {
it('hides the footer on phones, so the header must carry a submit button', () => {
expect(mobileCss).toMatch(
/:is\(#appSettingsModal, #sessionOptionsModal, #createCaseModal\) \.set-foot \{\s*display: none;/
);
const modal = caseModal();
const head = modal.slice(0, modal.indexOf('<div class="set-body">'));
const closeIdx = head.indexOf('class="modal-close"');
const saveIdx = head.indexOf('class="set-head-save" id="caseModalSubmitMobile" onclick="app.submitCaseModal()"');
expect(closeIdx).toBeGreaterThan(-1);
expect(saveIdx).toBeGreaterThan(-1);
// Close stays first in the DOM; row-reverse paints Save to its left.
expect(closeIdx).toBeLessThan(saveIdx);
expect(modal).toContain('id="caseModalSubmit" onclick="app.submitCaseModal()"');
});
it('drives the footer and header submit buttons together', () => {
for (const sig of ['switchCaseModalTab(tabName)', 'async submitCaseModal()']) {
const body = methodBody(sig);
expect(body, sig).toContain("'caseModalSubmit'");
expect(body, sig).toContain("'caseModalSubmitMobile'");
}
});
it('dims the header button while a submit is pending, where it is the only one visible', () => {
expect(mobileCss).toMatch(/#createCaseModal \.set-head-save\.loading \{\s*opacity: 0\.6;\s*pointer-events: none;/);
});
});
+10
View File
@@ -52,6 +52,16 @@ describe('buildWebArgs', () => {
]);
});
it('forwards --base-url so a detached/service relaunch keeps the mount prefix', () => {
const args = buildWebArgs({ host: '127.0.0.1', port: 3000, https: false, basePath: '/codeman' });
expect(args).toContain('--base-url');
expect(args[args.indexOf('--base-url') + 1]).toBe('/codeman');
});
it('omits --base-url at root (empty basePath)', () => {
expect(buildWebArgs({ host: '127.0.0.1', port: 3000, https: false, basePath: '' })).not.toContain('--base-url');
});
it('never re-emits the daemon flags themselves (the child must not re-fork)', () => {
const args = buildWebArgs({ host: '127.0.0.1', port: 3000, https: false });
expect(args).not.toContain('--daemon');
+453
View File
@@ -0,0 +1,453 @@
/**
* @fileoverview Adopting an ALREADY-RUNNING container (`DockerCase.owned === false`).
*
* The whole point of adoption is a negative guarantee: Codeman execs into a
* container the user built and runs, and never creates, starts, stops, restarts
* or removes it. A negative guarantee cannot be observed by using the feature —
* only by asserting that the mutating verbs are absent — so these tests read the
* generated command strings and assert on what is NOT in them.
*
* Mirror of the `owned:false` remote-SSH contract (COD-105).
*/
import { describe, it, expect } from 'vitest';
import { readFileSync } from 'node:fs';
import {
defaultDockerCommandForMode,
toSessionDocker,
isAdoptedContainer,
removeDockerContainer,
checkDockerConfigDrift,
dockerConfigHash,
dockerAdoptProbeModes,
} from '../src/docker-hosts.js';
import { enabledCliIds, getCli } from '../src/config/cli-registry/index.js';
import {
buildDockerLaunchCommand,
buildDockerStopCommand,
buildDockerRemoveCommand,
buildDockerKillCommand,
} from '../src/tmux-manager.js';
import type { DockerCase, DockerHost, SessionDocker } from '../src/types.js';
const HOST: DockerHost = { id: 'h1', label: 'local', engine: 'docker', image: 'codeman/agent:base' };
function caseFor(owned: boolean | undefined): DockerCase {
return {
name: 'adopted',
type: 'docker',
hostId: 'h1',
hostWorkspacePath: '/srv/work',
container: 'my-own-container',
...(owned === undefined ? {} : { owned }),
};
}
function launchFor(docker: SessionDocker): string {
return buildDockerLaunchCommand({
mode: 'codex',
docker,
sessionId: '11111111-2222-3333-4444-555555555555',
createContext: {
docker,
sessionId: '11111111-2222-3333-4444-555555555555',
instance: 'default',
userArgs: ['--user', '1000:0'],
credentialMounts: [],
extraMounts: [],
envCreate: { HOME: '/home/agent' },
addHostGateway: true,
gatewayAlias: 'host.docker.internal',
},
execEnv: { TERM: 'xterm-256color' },
execEnvNames: [],
seedCopies: [{ from: '/seed/creds.json', to: '/home/agent/.claude/.credentials.json' }],
});
}
describe('adopted container: ownership plumbing', () => {
it('carries owned:false from the case onto the live session metadata', () => {
expect(toSessionDocker(HOST, caseFor(false)).owned).toBe(false);
expect(isAdoptedContainer(toSessionDocker(HOST, caseFor(false)))).toBe(true);
});
it('treats an absent flag as owned, so existing cases are unchanged', () => {
const docker = toSessionDocker(HOST, caseFor(undefined));
expect(docker.owned).toBeUndefined();
expect(isAdoptedContainer(docker)).toBe(false);
});
it('keeps ownership OUT of the config hash so adoption cannot mass-trip drift', () => {
// A drift-hash that moved with `owned` would flag every pre-existing case the
// moment this field shipped, and the remedy the UI offers is "recreate".
const owned = toSessionDocker(HOST, caseFor(undefined));
const adopted = toSessionDocker(HOST, caseFor(false));
expect(adopted.configHash).toBe(owned.configHash);
expect(dockerConfigHash({ ...owned, owned: false } as never)).toBe(owned.configHash);
});
});
describe('adopted container: the launch chain never mutates lifecycle', () => {
const adopted = launchFor(toSessionDocker(HOST, caseFor(false)));
const owned = launchFor(toSessionDocker(HOST, caseFor(undefined)));
it('never creates the container', () => {
expect(owned).toContain('docker create');
expect(adopted).not.toContain('docker create');
});
it('never starts the container', () => {
expect(owned).toContain('docker start');
expect(adopted).not.toContain('docker start');
});
it('never stops or removes the container', () => {
for (const verb of ['docker stop', 'docker rm', 'docker restart', 'docker kill']) {
expect(adopted).not.toContain(verb);
}
});
it('fails closed when the container is missing instead of creating it', () => {
expect(adopted).toContain('docker inspect');
expect(adopted).toMatch(/not found.*start it yourself/i);
});
it('fails closed when the container is stopped instead of starting it', () => {
expect(adopted).toMatch(/\{\{\.State\.Running\}\}/);
expect(adopted).toMatch(/not running.*never starts a container it does not own/i);
});
it('uses no double quote and no command substitution in the launch chain', () => {
// The whole chain is embedded in an outer `bash -c "…"`. An unescaped `"`
// closes that string early, the remainder is re-tokenized, and tmux fails to
// exec with a bare `execvp(3) failed: No such file or directory` — no hint
// that the command was ever malformed. `$(…)` is banned with it because it
// is then evaluated by the wrong shell at the wrong time.
expect(adopted).not.toContain('"');
expect(adopted).not.toContain('$(');
// Every other line already quotes with the single-quote helper.
expect(adopted).toContain('grep -qx true');
});
it('skips the base-image gate, which describes an image adoption never uses', () => {
expect(owned).toContain('image inspect');
expect(adopted).not.toContain('image inspect');
});
it('never seeds host credentials into a container it does not own', () => {
expect(owned).toContain('.credentials.json');
expect(adopted).not.toContain('.credentials.json');
});
it('still execs into the in-container tmux, which is the whole point', () => {
expect(adopted).toContain('docker exec -it');
expect(adopted).toContain('new-session -A');
});
});
describe('adopted container: the probe request must reach the server', () => {
const ui = readFileSync(new URL('../src/web/public/session-ui.js', import.meta.url), 'utf8');
const api = readFileSync(new URL('../src/web/public/api-client.js', import.meta.url), 'utf8');
it('never hands _apiJson an already-stringified body', () => {
// _api serializes `body` and sets Content-Type itself. Passing a string
// double-encodes it, the server sees a JSON string where it expects an
// object, and answers 400 INVALID_INPUT — which the caller reads as "the
// container could not be probed", so the menu silently showed every mode.
expect(api).toContain('fetchOpts.body = JSON.stringify(body)');
const calls = [...ui.matchAll(/_apiJson\([^)]*\{[\s\S]{0,400}?\}\s*\)/g)].map((m) => m[0]);
expect(calls.length).toBeGreaterThan(0);
for (const call of calls) expect(call).not.toContain('body: JSON.stringify');
});
it('hides every agent mode and says why when the container cannot be read', () => {
// Offering claude on a container that is not running is a click that can
// only fail, with the reason visible nowhere.
// Brace-matched, not a character window: slicing between two call sites
// silently yields '' when the second one appears ABOVE the first, and the
// assertion then passes over nothing. That has bitten this file twice.
const start = ui.indexOf('async _probeDockerCaseModes(activeCase, menu) {');
expect(start).toBeGreaterThan(-1);
const open = ui.indexOf('{', start);
let depth = 0;
let fn = '';
for (let i = open; i < ui.length; i++) {
if (ui[i] === '{') depth++;
else if (ui[i] === '}' && --depth === 0) {
fn = ui.slice(start, i + 1);
break;
}
}
expect(fn).toContain('_dockerCaseProbeError');
expect(ui).toContain('_renderRunModeNotice');
});
});
describe('adopted container: claude as root', () => {
it('drops --dangerously-skip-permissions when the container runs as root', () => {
// Claude Code refuses the flag as root ("cannot be used with root/sudo
// privileges"), so keeping it kills the pane with a message only visible
// inside the container. Our base image runs a non-root user, which is why an
// owned container never hit this.
expect(defaultDockerCommandForMode('claude', true)).toBe('exec claude');
expect(defaultDockerCommandForMode('claude', false)).toContain('--dangerously-skip-permissions');
expect(defaultDockerCommandForMode('claude')).toContain('--dangerously-skip-permissions');
});
it('leaves every other mode unchanged as root', () => {
for (const mode of ['codex', 'shell', 'pi'] as const) {
expect(defaultDockerCommandForMode(mode, true)).toBe(defaultDockerCommandForMode(mode, false));
}
});
});
describe('adopted container: the host is not required to have the CLI', () => {
const src = readFileSync(new URL('../src/tmux-manager.ts', import.meta.url), 'utf8');
it('skips the host CLI requirement for a docker session', () => {
// A docker session runs its CLI inside the container. Demanding it on the
// host threw, the catch fell back to a direct PTY, and that PTY tried to
// exec the CLI on the HOST — surfacing as a bare `execvp(3) failed` with
// nothing naming the real cause.
//
// The CLI registry collapsed the old per-mode `mode === 'claude' && !cliDir` chain
// into ONE `missingCliMessage(mode)` gate, so the guarantee is now that the single
// gate carries the docker exemption and that no per-mode arm has grown back.
expect(src).toContain('if (!cliRunsInContainer && !cliDir) {');
expect(src.match(/if \(mode === '[a-z]+' && !cliDir\)/g)).toBeNull();
});
it('derives the flag from the docker metadata the session already carries', () => {
expect(src).toContain('const cliRunsInContainer = !!docker;');
});
});
describe('adopted container: mutating verbs fail closed at the builder', () => {
const docker = toSessionDocker(HOST, caseFor(false));
it('refuses to build a stop command', () => {
expect(() => buildDockerStopCommand(docker)).toThrow(/does not own its lifecycle/);
});
it('refuses to build a remove command', () => {
expect(() => buildDockerRemoveCommand(docker)).toThrow(/does not own its lifecycle/);
});
it('refuses to remove the container', async () => {
await expect(removeDockerContainer(docker)).rejects.toThrow(/does not own its lifecycle/);
});
it('still allows killing THIS session in-container tmux, never the container', () => {
const kill = buildDockerKillCommand({ docker, sessionId: 'abcdef12-0000-0000-0000-000000000000' });
expect(kill).toContain('tmux');
expect(kill).toContain('kill-session');
expect(kill).not.toContain('docker stop');
expect(kill).not.toContain('docker rm');
});
it('still permits every verb for an owned container', () => {
const ownedDocker = toSessionDocker(HOST, caseFor(undefined));
expect(buildDockerStopCommand(ownedDocker)).toContain('stop -t 10');
expect(buildDockerRemoveCommand(ownedDocker)).toContain('rm -f');
});
});
describe('adopted container: the Add Case panel id contract', () => {
// The modal's load/save contract is getElementById by fixed id, so a renamed or
// dropped id stops the control working with no error anywhere. Static guard in
// the style of app-settings-structure / session-options-structure.
const html = readFileSync(new URL('../src/web/public/index.html', import.meta.url), 'utf8');
const ui = readFileSync(new URL('../src/web/public/session-ui.js', import.meta.url), 'utf8');
const css = readFileSync(new URL('../src/web/public/styles.css', import.meta.url), 'utf8');
it('ships every id session-ui.js reads back', () => {
for (const id of ['dockerAdoptExisting', 'dockerContainerName', 'dockerAdoptCheckBtn']) {
expect(html).toContain(`id="${id}"`);
expect(ui).toContain(`'${id}'`);
}
});
it('routes adoption to the endpoint that never creates a container', () => {
expect(ui).toContain('/api/cases/docker-adopt');
expect(ui).toContain('/api/docker-cases/adopt-preflight');
// The create path must survive untouched beside it.
expect(ui).toContain('/api/cases/docker-link');
});
it('hides the adopt-only row until the toggle is on, so the panel is unchanged by default', () => {
expect(css).toContain('#createCaseModal .docker-adopt-only');
expect(css).toMatch(/#createCaseModal \.docker-adopt-only \{\s*display: none/);
expect(css).toContain("#createCaseModal[data-docker-adopt='1'] .docker-adopt-only");
});
it('marks the create-time rows so adoption hides the fields it never uses', () => {
// image / network / advanced describe a `docker create` adoption never runs.
expect(html.match(/docker-create-only/g)?.length).toBeGreaterThanOrEqual(3);
expect(css).toContain("#createCaseModal[data-docker-adopt='1'] .docker-create-only");
});
});
describe('adopted container: run modes come from the CONTAINER, not the host', () => {
const ui = readFileSync(new URL('../src/web/public/session-ui.js', import.meta.url), 'utf8');
/** Slice the method BODY. Anchored on the definition, not a call site: the
* menu opener calls _loadRunModeHistory() ABOVE this definition, so slicing
* between call sites silently yields an empty string and passes nothing. */
/**
* The method BODY, delimited by brace depth rather than a character budget.
* A fixed window silently truncates the moment the method grows — which is
* exactly what happened twice: a comment added above the assertion pushed the
* asserted line past the cutoff and CI failed on a test that was still true.
*/
const refreshFn = (src) => {
const start = src.indexOf('_refreshRunModeAvailability(menu) {');
expect(start).toBeGreaterThan(-1);
const open = src.indexOf('{', start);
let depth = 0;
for (let i = open; i < src.length; i++) {
if (src[i] === '{') depth++;
else if (src[i] === '}' && --depth === 0) return src.slice(start, i + 1);
}
throw new Error('unbalanced braces in _refreshRunModeAvailability');
};
it('gates a docker case on availableModes instead of host CLI probes', () => {
// The sandbox host had codex but no claude while the adopted container had
// claude and no codex; gating on the host hid the only mode that worked.
const fn = refreshFn(ui);
expect(fn).toContain("location === 'docker'");
expect(fn).toContain('availableModes');
// Non-docker cases must keep the original host probe (#201).
expect(fn).toContain('this.isCliAvailable(mode)');
});
it('leaves an owned container ungated when nothing was probed', () => {
// Our base image ships every CLI, so an absent list means "unknown", and
// treating unknown as "nothing available" would empty the menu.
expect(refreshFn(ui)).toMatch(/containerModes \?[^:]*:\s*true/);
});
});
describe('adopted container: both path fields get a folder picker', () => {
const html = readFileSync(new URL('../src/web/public/index.html', import.meta.url), 'utf8');
const ui = readFileSync(new URL('../src/web/public/session-ui.js', import.meta.url), 'utf8');
const picker = readFileSync(new URL('../src/web/public/keyboard-accessory.js', import.meta.url), 'utf8');
it('wires a Browse button to each of the two paths', () => {
expect(html).toContain('app.openDockerWorkspacePathPicker()');
expect(html).toContain('app.openDockerWorkdirPicker()');
// Same markup Link Existing uses, so the two look and behave alike.
expect(html.match(/path-input-browse/g)?.length).toBeGreaterThanOrEqual(3);
});
it('browses the CONTAINER for the container workdir, not the host', () => {
// For an adopted container nothing is mounted at a matching host path, so a
// host listing would be a different filesystem — and typing this field blind
// is what makes the launch fail with an OCI chdir error.
const fn = ui.slice(ui.indexOf('openDockerWorkdirPicker()'), ui.indexOf('async linkRemoteCase()'));
expect(fn).toContain('/api/docker-cases/browse');
expect(fn).not.toContain('/api/filesystem/browse');
expect(fn).toContain('fetchListing');
});
it('keeps the host picker for the host workspace path', () => {
const fn = ui.slice(ui.indexOf('openDockerWorkspacePathPicker()'), ui.indexOf('openDockerWorkdirPicker()'));
expect(fn).toContain('PathPicker.open');
expect(fn).not.toContain('fetchListing');
});
it('reuses one PathPicker via an optional source rather than forking it', () => {
expect(picker).toContain('this._options.fetchListing');
expect(picker).toContain('/api/filesystem/browse');
});
});
describe('adopted container: drift is not evaluated', () => {
it('reports no drift rather than demanding a recreate we may not perform', async () => {
// An adopted container carries no codeman.confighash label, so a real
// comparison would always report drift and the launch gate would 409 forever.
const status = await checkDockerConfigDrift(toSessionDocker(HOST, caseFor(false)));
expect(status.drifted).toBe(false);
});
});
describe('adopted container: probe modes come from the CLI registry', () => {
it('probes every enabled CLI, so a newly-enabled one needs no second list', () => {
// A hand-written list here silently froze: `omp` shipped in 1.24.0 and was
// missing from it, which hid the omp run mode on EVERY docker case — owned
// ones included, since the run menu gates on this same probe.
const modes = dockerAdoptProbeModes();
expect(modes).toEqual(enabledCliIds());
expect(modes).toContain('omp');
expect(modes).toContain('shell');
});
it('resolves the real binary name, not the mode name', () => {
// `antigravity` ships as `agy` and `deepseek` as `dsh`, so a mode-name probe
// would report both as missing on a container that has them.
expect(getCli('antigravity')?.discovery.binaries[0]).toBe('agy');
expect(getCli('deepseek')?.discovery.binaries[0]).toBe('dsh');
expect(getCli('shell')?.discovery.binaries[0]).toBeUndefined();
});
});
describe('adopted container: export never touches the container', () => {
const routes = readFileSync(new URL('../src/web/routes/case-routes.ts', import.meta.url), 'utf8');
const exporter = readFileSync(new URL('../src/docker-export.ts', import.meta.url), 'utf8');
it('refuses a full-image export, which would commit a container we do not own', () => {
expect(routes).toContain("if (mode === 'full' && dockerCase.owned === false)");
});
it('never pauses an adopted container for the workspace tar', () => {
// `docker pause` freezes the owner's processes for as long as the tar takes.
// It is the one export step that touches the container at all.
expect(exporter).toContain('!isAdoptedContainer(docker) && (await isContainerRunning(');
});
});
describe('adopted container: naming a foreign container is machine-level', () => {
const routes = readFileSync(new URL('../src/web/routes/case-routes.ts', import.meta.url), 'utf8');
const routeFor = (marker: string) => routes.slice(routes.indexOf(marker), routes.indexOf(marker) + 1400);
it('admin-gates adoption in multi-user mode, unlike docker-link', () => {
// docker-link only ever creates OUR container, whose sole bind mount is a
// workspace isWorkingDirAllowed already confined. An adopted container's
// mounts belong to its owner — one mounting `/` hands the adopter the host.
expect(routeFor("'/api/cases/docker-adopt'")).toContain('adminOnly(req, reply)');
});
it('admin-gates enumerating and browsing containers', () => {
expect(routeFor("'/api/docker-hosts/:hostId/containers'")).toContain('adminOnly(req, reply)');
expect(routeFor("'/api/docker-cases/browse'")).toContain('adminOnly(req, reply)');
});
it('lets a non-admin preflight only a container linked to a case they own', () => {
// NOT plain adminOnly: the run menu probes this for every docker case to learn
// which CLIs the container has, so an admin-only gate would hide every agent
// mode from a non-admin's own docker case.
const route = routeFor("'/api/docker-cases/adopt-preflight'");
expect(route).toContain('if (!isAdmin(req))');
expect(route).toContain('canAccessOwned(getAuthUser(req), item.owner)');
expect(route).not.toContain('adminOnly(req, reply)');
});
});
describe('adopted container: a missing container means different things per ownership', () => {
const ui = readFileSync(new URL('../src/web/public/session-ui.js', import.meta.url), 'utf8');
const routes = readFileSync(new URL('../src/web/routes/case-routes.ts', import.meta.url), 'utf8');
it('records a probe failure only for an adopted case', () => {
// An OWNED container does not exist until the first session launches it, so
// "not found" is the expected answer for every freshly linked Docker case.
// Treating it as a fault hid every agent mode behind an error telling the user
// to start a container the launch chain was about to create itself.
const probe = ui.slice(ui.indexOf('async _probeDockerCaseModes('), ui.indexOf('async _loadRunModeHistory('));
expect(probe).toContain('if (activeCase?.docker?.owned === false) {');
expect(probe.indexOf('if (activeCase?.docker?.owned === false) {')).toBeLessThan(
probe.indexOf('this._dockerCaseProbeError[name] =')
);
});
it('ships the ownership flag the UI reads that decision from', () => {
expect(routes).toContain('...(dockerCase.owned === false ? { owned: false } : {}),');
});
});
+4
View File
@@ -161,6 +161,8 @@ function loadPanel(options: { sessionId?: string | null; showHidden?: boolean }
CodemanApp,
console,
escapeHtml,
// Reverse-proxy route builder from constants.js (not loaded here); identity at root.
CodemanBase: { base: '', url: (p: string) => p },
localStorage: { getItem: () => null, setItem: vi.fn() },
document: {
getElementById: (id: string) => elements[id] ?? null,
@@ -222,6 +224,8 @@ function loadRealSelectSessionHarness(options: { terminalFailure?: boolean } = {
},
HTMLCanvasElement: class HTMLCanvasElement {},
WebSocket: { OPEN: 1 },
// Reverse-proxy route builder from constants.js (not loaded here); identity at root.
CodemanBase: { base: '', url: (p: string) => p },
MobileDetection: { isTouchDevice: () => false },
localStorage: { length: 0, key: vi.fn(), getItem: vi.fn(), setItem: vi.fn(), removeItem: vi.fn() },
document: {
+53
View File
@@ -0,0 +1,53 @@
/**
* @fileoverview The picker must offer a root when Codeman runs as root.
*
* `/root` is a DEFAULT blocked tree in the attachment guard, and Codeman running
* as root — containers, plenty of servers — makes `homedir()` exactly `/root`.
* The picker's own allowlisted Home root was therefore blocked by the guard,
* every other candidate lives under it or does not exist, and the endpoint
* answered 403 "No filesystem browse roots are available" with nothing the user
* could open. The fix drops only the trees that would swallow a configured root
* whole; `isSensitivePath` still guards what is inside.
*/
import { describe, it, expect } from 'vitest';
import { readFileSync } from 'node:fs';
import { isBlockedAttachmentPath, isUnderTree } from '../src/config/attachment-guard.js';
const TREES = ['/root', '/etc'];
/** Mirror of pickerBlockedTrees in file-routes.ts. */
const narrow = (trees: readonly string[], roots: readonly string[]) =>
roots.length === 0 ? trees : trees.filter((t) => !roots.some((r) => isUnderTree(r, t)));
describe('file picker roots when the server runs as root', () => {
it('drops the tree that would swallow the configured Home root', () => {
expect(narrow(TREES, ['/root'])).toEqual(['/etc']);
});
it('keeps trees that hold no configured root', () => {
expect(narrow(TREES, ['/home/alice'])).toEqual(['/root', '/etc']);
expect(narrow(TREES, [])).toEqual(['/root', '/etc']);
});
it('also frees a root nested under the blocked tree', () => {
// ~/codeman-cases is /root/codeman-cases when running as root.
expect(narrow(TREES, ['/root/codeman-cases'])).toEqual(['/etc']);
});
it('still refuses secrets inside the freed tree', () => {
const trees = narrow(TREES, ['/root']);
for (const p of ['/root/.ssh/id_rsa', '/root/.aws/credentials', '/root/app/.env']) {
expect(isBlockedAttachmentPath(p, trees)).toBe(true);
}
// …while ordinary files under it become reachable, which is the point.
expect(isBlockedAttachmentPath('/root/projects/readme.md', trees)).toBe(false);
});
it('navigation reuses the same narrowed list the roots were chosen with', () => {
// Handing the raw trees to navigation would admit a root and then refuse
// every path inside it — a picker that opens and then does nothing.
const src = readFileSync(new URL('../src/web/routes/file-routes.ts', import.meta.url), 'utf8');
expect(src.match(/pickerBlockedTrees\(/g)?.length).toBeGreaterThanOrEqual(3);
expect(src).not.toMatch(/blockedTrees:\s*guard\.blockedTrees/);
});
});
+2
View File
@@ -38,6 +38,8 @@ function loadApp() {
console: { ...console, warn: vi.fn(), error: vi.fn() },
localStorage: { getItem: () => null, setItem: () => {}, removeItem: () => {} },
escapeHtml: (s: string) => String(s),
// Reverse-proxy route builder from constants.js (not loaded here); identity at root.
CodemanBase: { base: '', url: (p: string) => p },
document: { getElementById: () => null, addEventListener: vi.fn() },
window: windowStub,
setTimeout,
+2
View File
@@ -64,6 +64,8 @@ function loadApp(media: FakeMedia[]) {
console: { ...console, warn: vi.fn() },
localStorage: { getItem: () => null, setItem: () => {}, removeItem: () => {} },
escapeHtml: (s: string) => String(s),
// Reverse-proxy route builder from constants.js (not loaded here); identity at root.
CodemanBase: { base: '', url: (p: string) => p },
document: { getElementById: () => null, addEventListener: vi.fn() },
window: { addEventListener: vi.fn() },
setTimeout,
+9 -1
View File
@@ -24,7 +24,15 @@ describe('frontend public asset tooling', () => {
const appJs = readFileSync(resolve(repoRoot, 'src/web/public/app.js'), 'utf8');
expect(appJs).toContain("body.appendChild(this._buildResponseViewerMessage(lastResponse, 'assistant'");
expect(appJs).toContain('body.appendChild(this._buildResponseViewerMessage(msg.text, msg.role, agentLabel));');
expect(appJs).toContain(
'body.appendChild(this._buildResponseViewerMessage(msg.text, msg.role, agentLabel, { ...msg, continuation }));'
);
// ⚠️ A numeric `turn` gates continuation rendering. Only the Claude reader
// emits turns; Codex, the external-CLI pane parser and an older server emit
// adjacent same-role messages with none, and must keep one badge per card.
expect(appJs).toContain(
"!!previous && previous.role === msg.role && typeof msg.turn === 'number' && previous.turn === msg.turn"
);
expect(appJs).toContain("div.className = 'rv-message ' + (isUser ? 'rv-msg-user' : 'rv-msg-assistant');");
expect(appJs).toContain("renderedText.className = 'rv-text';");
});
+61
View File
@@ -42,6 +42,34 @@ describe('generateHooksConfig', () => {
expect(config.hooks.Stop).toHaveLength(1);
});
it('reports the live conversation id on every prompt, with stdout discarded', () => {
const config = generateHooksConfig();
expect(config.hooks.UserPromptSubmit).toBeInstanceOf(Array);
expect(config.hooks.UserPromptSubmit).toHaveLength(1);
const command = (config.hooks.UserPromptSubmit as Array<{ hooks: Array<{ command: string }> }>)[0].hooks[0].command;
expect(command).toContain('"event":"prompt_submitted"');
expect(command).toContain('$CODEMAN_SESSION_ID');
// ⚠️ Claude Code injects a UserPromptSubmit hook's stdout into the model's
// context ("Exit code 0 - stdout shown to Claude"), so without this the API
// envelope is pasted into the user's own prompt on every turn. Every other
// event's stdout is harmless (it feeds SSE).
// ⚠️ Assert curl's OWN flag, not a trailing redirect: the command already
// ends `… 2>/dev/null || true`, and in `pipeline || true >/dev/null` the
// shell binds the redirect to `true`, which never runs on the success path.
// A `endsWith('>/dev/null')` assertion passes on exactly that broken form.
expect(command).toContain('curl -sk -o /dev/null -X POST');
expect(command.trimEnd().endsWith('>/dev/null')).toBe(false);
});
it("leaves every other hook event's command text byte-identical", () => {
// The opt-in discard exists so the five SSE-fed events do not change shape:
// rewriting their command churns every workspace's settings.local.json.
const config = generateHooksConfig();
const stop = (config.hooks.Stop as Array<{ hooks: Array<{ command: string }> }>)[0].hooks[0].command;
expect(stop).toContain('curl -sk -X POST');
expect(stop).not.toContain('-o /dev/null');
});
it('should guard subagent stops while their background work is active', () => {
const config = generateHooksConfig();
const subagentHooks = config.hooks.SubagentStop as Array<{
@@ -324,6 +352,39 @@ describe('writeHooksConfig', () => {
expect(serialized).not.toContain('CODEMAN_BACKGROUND_REWAKE_V1');
});
it('heals a hooks block written before UserPromptSubmit existed', async () => {
const claudeDir = join(testDir, '.claude');
const settingsPath = join(claudeDir, 'settings.local.json');
mkdirSync(claudeDir, { recursive: true });
// An otherwise-current block from the previous release: the pane would keep
// guessing its conversation from ~/.claude/history.jsonl forever.
const hooks = generateHooksConfig().hooks;
delete hooks.UserPromptSubmit;
writeFileSync(settingsPath, JSON.stringify({ hooks }, null, 2));
await refreshStaleCodemanHooks(testDir);
const parsed = JSON.parse(readFileSync(settingsPath, 'utf-8'));
expect(JSON.stringify(parsed.hooks.UserPromptSubmit)).toContain('prompt_submitted');
});
it('leaves an already-current hooks block untouched', async () => {
// ⚠️ The staleness gate reads a JSON.stringify'd blob, so a marker written
// with surrounding quotes never matches and the gate is permanently false —
// which rewrites every workspace's settings.local.json on every Claude
// spawn instead of never. This asserts the no-op, which is the property a
// quoted needle silently breaks.
const claudeDir = join(testDir, '.claude');
const settingsPath = join(claudeDir, 'settings.local.json');
mkdirSync(claudeDir, { recursive: true });
writeFileSync(settingsPath, JSON.stringify({ hooks: generateHooksConfig().hooks }, null, 2));
const before = readFileSync(settingsPath, 'utf-8');
await refreshStaleCodemanHooks(testDir);
expect(readFileSync(settingsPath, 'utf-8')).toBe(before);
});
it('replaces the V2 background hook without duplicating it', async () => {
const claudeDir = join(testDir, '.claude');
const settingsPath = join(claudeDir, 'settings.local.json');
+26
View File
@@ -29,6 +29,32 @@ export class MockSession extends EventEmitter {
terminalBuffer: string = '';
/** Mirrors Session.lastSubmitAt — the response viewer credits history entries by it. */
lastSubmitAt: number = 0;
/** Mirrors Session.claudeSessionId — the conversation the viewer reads. */
claudeSessionId: string | null = null;
/** Mirrors Session.claudeSessionIdIsFirstHand — set only by a hook adoption. */
claudeSessionIdIsFirstHand: boolean = false;
/** Mirrors Session.claudeSessionChain — oldest first, current last. */
claudeSessionChain: string[] = [];
/** Mirrors Session.adoptClaudeSessionId, including the first-hand chain rule. */
adoptClaudeSessionId(newId: string, options: { firstHand?: boolean } = {}): void {
if (!newId) return;
if (options.firstHand) {
this.claudeSessionIdIsFirstHand = true;
if (this.claudeSessionChain[this.claudeSessionChain.length - 1] !== newId) {
const existing = this.claudeSessionChain.indexOf(newId);
if (existing !== -1) this.claudeSessionChain.splice(existing, 1);
this.claudeSessionChain.push(newId);
}
}
if (newId === this.claudeSessionId) return;
this.claudeSessionId = newId;
}
/** Mirrors Session.markPromptSubmitted. */
markPromptSubmitted(): void {
this.lastSubmitAt = Date.now();
}
private _muxName: string | null = null;
+249
View File
@@ -0,0 +1,249 @@
/**
* @fileoverview The PR bot's Telegram command and button handling, driven through
* `PrBot.handleUpdate` with a recording Telegram stub and a mocked `gh` layer. Pins
* the one property that matters most: a GitHub write (merge, close, post) happens only
* after the confirmation tap, exactly once, and never for a foreign chat or a stale
* nonce.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { mkdtempSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
const gh = vi.hoisted(() => ({
listOpenPrs: vi.fn(async () => []),
getPrDetail: vi.fn(),
getCiStatus: vi.fn(async () => ({ state: 'passed', runs: [] })),
mergePr: vi.fn(async () => 'merged'),
closePr: vi.fn(async () => 'closed'),
commentPr: vi.fn(async () => 'commented'),
approveWorkflowRun: vi.fn(async () => undefined),
gh: vi.fn(async () => 'MERGED\n'),
}));
vi.mock('../scripts/pr-bot/github.js', () => gh);
vi.mock('../scripts/pr-bot/worktree.js', () => ({
preparePrWorktree: vi.fn(),
removePrWorktree: vi.fn(async () => undefined),
}));
import { PrBot, type TelegramLike } from '../scripts/pr-bot/bot.js';
import { buildConfig } from '../scripts/pr-bot/config.js';
import type { CodemanClient } from '../scripts/pr-bot/codeman-client.js';
import type { PrDetail } from '../scripts/pr-bot/github.js';
import type { ReviewReport } from '../scripts/pr-bot/report.js';
class FakeTelegram implements TelegramLike {
sent: { text: string; markup?: unknown; plain: boolean }[] = [];
edits: number[] = [];
private nextId = 100;
isOurChat(chatId: number | string | undefined): boolean {
return String(chatId) === '1';
}
async sendMessage(text: string, opts: { replyMarkup?: unknown } = {}): Promise<number> {
this.sent.push({ text, markup: opts.replyMarkup, plain: false });
return this.nextId++;
}
async sendPlain(text: string): Promise<number> {
this.sent.push({ text, plain: true });
return this.nextId++;
}
async editReplyMarkup(messageId: number): Promise<void> {
this.edits.push(messageId);
}
async deleteMessage(): Promise<void> {}
async answerCallback(): Promise<void> {}
async sendDocument(): Promise<void> {}
async getUpdates(): Promise<[]> {
return [];
}
async setMyCommands(): Promise<void> {}
last(): string {
return this.sent[this.sent.length - 1]?.text ?? '';
}
/** The confirm callback_data of the last message's keyboard. */
confirmData(): string {
const markup = this.sent[this.sent.length - 1]?.markup as { inline_keyboard: { callback_data: string }[][] };
return markup.inline_keyboard.flat().find((b) => b.callback_data.startsWith('confirm:'))!.callback_data;
}
}
function detail(over: Partial<PrDetail> = {}): PrDetail {
return {
number: 381,
title: 'feat(web): base URL',
author: 'mtiller',
headSha: 'abc123abc123',
baseRef: 'master',
headRef: 'feat',
isDraft: false,
mergeable: 'MERGEABLE',
mergeState: 'CLEAN',
additions: 10,
deletions: 2,
changedFiles: 3,
updatedAt: '',
url: 'https://github.com/Ark0N/Codeman/pull/381',
isCrossRepository: true,
labels: [],
body: '',
files: [],
authorAssociation: 'CONTRIBUTOR',
linkedIssues: [],
commitCount: 1,
commentCount: 0,
reviewDecision: '',
headRepo: 'mtiller/Codeman',
...over,
};
}
const report: ReviewReport = {
verdict: 'merge',
confidence: 'high',
summary: 's',
changes: [],
findings: [],
checks: [],
scope: 'focused',
risk: '',
recommendation: 'merge it',
draftComment: 'Thanks, merging.',
assumptions: [],
};
const msg = (text: string, chat = 1, replyTo?: { message_id: number; text?: string }) => ({
update_id: 1,
message: { message_id: 7, chat: { id: chat }, text, reply_to_message: replyTo },
});
const cb = (data: string, chat = 1) => ({
update_id: 2,
callback_query: { id: 'q', from: { id: 1 }, data, message: { message_id: 9, chat: { id: chat } } },
});
describe('PrBot commands', () => {
let bot: PrBot;
let tg: FakeTelegram;
beforeEach(() => {
vi.clearAllMocks();
gh.getPrDetail.mockImplementation(async () => detail());
const cfg = buildConfig(
{ TELEGRAM_BOT_TOKEN: 't', TELEGRAM_CHAT_ID: '1', PR_BOT_DATA_DIR: mkdtempSync(join(tmpdir(), 'prbot-cmd-')) },
{ home: '/h', repoRoot: '/r' }
);
tg = new FakeTelegram();
bot = new PrBot(cfg, { telegram: tg, codeman: {} as CodemanClient, log: () => undefined });
const rec = bot.store.upsertPr(detail());
Object.assign(rec, { status: 'reviewed', reviewedSha: 'abc123abc123', verdict: 'merge-with-fixes', report });
bot.store.save();
});
afterEach(async () => {
await bot.stop();
});
it('answers /help only for the configured chat', async () => {
await bot.handleUpdate(msg('/help', 2));
expect(tg.sent).toHaveLength(0);
await bot.handleUpdate(msg('/help'));
expect(tg.last()).toContain('/merge N');
});
it('shows the draft without posting it', async () => {
await bot.handleUpdate(msg('/draft 381'));
expect(tg.last()).toContain('Thanks, merging.');
expect(tg.last()).toContain('not posted');
expect(gh.commentPr).not.toHaveBeenCalled();
});
it('merges only after the confirmation tap, once, and rejects a reused nonce', async () => {
await bot.handleUpdate(msg('/merge 381'));
expect(gh.mergePr).not.toHaveBeenCalled();
expect(tg.last()).toContain('Merge <b>#381</b>');
expect(Object.keys(bot.store.state.pending)).toHaveLength(1);
const data = tg.confirmData();
expect(data).toMatch(/^confirm:merge:381:[0-9a-f]{8}$/);
await bot.handleUpdate(cb(data));
expect(gh.mergePr).toHaveBeenCalledTimes(1);
expect(gh.mergePr).toHaveBeenCalledWith('Ark0N/Codeman', 381);
expect(tg.last()).toContain('Merged <b>#381</b>');
expect(Object.keys(bot.store.state.pending)).toHaveLength(0);
expect(tg.edits).toContain(9); // the keyboard is removed from the confirmation message
await bot.handleUpdate(cb(data));
expect(gh.mergePr).toHaveBeenCalledTimes(1);
expect(tg.last()).toContain('no longer valid');
});
it('announces a bot-made merge once: the next scan retires the PR silently', async () => {
await bot.handleUpdate(msg('/merge 381'));
await bot.handleUpdate(cb(tg.confirmData()));
const merged = tg.sent.filter((s) => s.text.includes('Merged <b>#381</b>'));
expect(merged).toHaveLength(1);
expect(merged[0].text).toContain('fixes to apply at merge time'); // the verdict on the seeded record is merge-with-fixes below
const result = await bot.scanOnce('test'); // listOpenPrs is mocked to []: 381 is gone
expect(result.closed).toEqual([381]);
expect(bot.store.pr(381)?.closedAs).toBe('merged');
expect(tg.sent.filter((s) => s.text.includes('Merged <b>#381</b>'))).toHaveLength(1);
});
it('ignores a confirmation tap from a foreign chat', async () => {
await bot.handleUpdate(msg('/merge 381'));
await bot.handleUpdate(cb(tg.confirmData(), 2));
expect(gh.mergePr).not.toHaveBeenCalled();
});
it('refuses to offer a merge for a conflicting PR and warns about red CI', async () => {
gh.getPrDetail.mockImplementationOnce(async () => detail({ mergeable: 'CONFLICTING' }));
await bot.handleUpdate(msg('/merge 381'));
expect(tg.last()).toContain('needs a rebase');
expect(Object.keys(bot.store.state.pending)).toHaveLength(0);
gh.getCiStatus.mockImplementationOnce(async () => ({ state: 'failed', runs: [] }));
await bot.handleUpdate(msg('/merge 381'));
expect(tg.last()).toContain('CI is red');
expect(Object.keys(bot.store.state.pending)).toHaveLength(1);
});
it('cancel drops the pending confirmation', async () => {
await bot.handleUpdate(msg('/merge 381'));
const data = tg.confirmData().replace(/^confirm:/, 'cancel:');
await bot.handleUpdate(cb(data));
expect(Object.keys(bot.store.state.pending)).toHaveLength(0);
await bot.handleUpdate(cb(tg.sent[tg.sent.length - 1] ? data.replace(/^cancel:/, 'confirm:') : ''));
expect(gh.mergePr).not.toHaveBeenCalled();
});
it('closes with the given comment after confirmation, and asks for one when missing', async () => {
await bot.handleUpdate(msg('/close 381'));
expect(tg.last()).toContain('Reply to this message');
expect(gh.closePr).not.toHaveBeenCalled();
await bot.handleUpdate(msg('/close 381 superseded by #372'));
expect(tg.last()).toContain('superseded by #372');
await bot.handleUpdate(cb(tg.confirmData()));
expect(gh.closePr).toHaveBeenCalledWith('Ark0N/Codeman', 381, 'superseded by #372');
});
it('posts the draft only after confirmation', async () => {
await bot.handleUpdate(msg('/post 381'));
expect(gh.commentPr).not.toHaveBeenCalled();
expect(tg.sent.some((s) => s.plain && s.text === 'Thanks, merging.')).toBe(true);
await bot.handleUpdate(cb(tg.confirmData()));
expect(gh.commentPr).toHaveBeenCalledWith('Ark0N/Codeman', 381, 'Thanks, merging.');
});
it('a reply to a review message becomes a follow-up, refused when nothing was reviewed', async () => {
const rec = bot.store.upsertPr(detail({ number: 390, title: 'other' }));
bot.store.rememberMessage(55, 390);
expect(rec.reviewedSha).toBeUndefined();
await bot.handleUpdate(msg('does it handle X?', 1, { message_id: 55 }));
expect(tg.last()).toContain('No review of #390 yet');
});
it('reports status with verdict icons', async () => {
await bot.handleUpdate(msg('/status'));
expect(tg.last()).toContain('🟢 <b>#381</b>');
});
});
+370
View File
@@ -0,0 +1,370 @@
/**
* @fileoverview Unit tests for the PR bot's pure helpers: report parsing and
* Telegram formatting (report.ts), CI classification (github.ts), command and
* callback parsing (telegram.ts), the trust-dialog reader (codeman-client.ts) and
* config validation (config.ts). No network, no git, no Telegram.
*/
import { describe, it, expect } from 'vitest';
import {
buildReportKeyboard,
confirmKeyboard,
extractJsonObject,
formatReviewFailure,
formatStatusList,
formatTelegramSummary,
orderBacklog,
parseReport,
splitTelegramMessage,
TELEGRAM_MAX,
type ReviewReport,
} from '../scripts/pr-bot/report.js';
import { classifyCi, latestRunPerWorkflow, type PrSummary, type WorkflowRun } from '../scripts/pr-bot/github.js';
import { parseCallback, parseCommand, prNumberFromMessageText } from '../scripts/pr-bot/telegram.js';
import { trustDialogKey } from '../scripts/pr-bot/codeman-client.js';
import { buildConfig, parseEnvFile } from '../scripts/pr-bot/config.js';
import { buildReviewBrief } from '../scripts/pr-bot/review-task.js';
const pr: PrSummary = {
number: 381,
title: 'feat(web): support a reverse-proxy base URL',
author: 'mtiller',
headSha: '7e4914d991ea864d7dfbefe03f042380d02981c4',
baseRef: 'master',
headRef: 'feat/reverse-proxy-base-url',
isDraft: false,
mergeable: 'MERGEABLE',
mergeState: 'UNSTABLE',
additions: 664,
deletions: 112,
changedFiles: 28,
updatedAt: '2026-09-04T20:15:52Z',
url: 'https://github.com/Ark0N/Codeman/pull/381',
isCrossRepository: true,
labels: [],
};
const rawReport = {
verdict: 'request_changes',
confidence: 'HIGH',
summary: 'Adds a base path. Two real bugs.',
changes: ['base-path config', 'ingress rewrite'],
findings: [
{ severity: 'minor', title: 'nit first in input', file: 'a.ts', line: 1, detail: 'x' },
{ severity: 'blocker', title: 'SSE path not prefixed', file: 'src/web/server.ts', line: 210, detail: 'events 404' },
{ severity: 'bogus', title: 'unknown severity becomes minor', detail: '' },
{ title: '' },
],
checks: [
{ name: 'typecheck', command: 'npm run typecheck', result: 'PASS' },
{ name: 'tests', result: 'fail', notes: '2 failed' },
{ name: '', result: 'pass' },
],
scope: 'MIXED',
risk: 'r',
recommendation: 'Ask for the SSE fix, then merge.',
draftComment: 'Thanks!',
assumptions: ['none', 42],
};
describe('parseReport', () => {
it('normalizes case, separators and severities, and sorts findings by severity', () => {
const r = parseReport(rawReport)!;
expect(r.verdict).toBe('request-changes');
expect(r.confidence).toBe('high');
expect(r.scope).toBe('mixed');
expect(r.findings.map((f) => f.severity)).toEqual(['blocker', 'minor', 'minor']);
expect(r.findings[0].file).toBe('src/web/server.ts');
expect(r.findings[0].line).toBe(210);
expect(r.checks).toHaveLength(2);
expect(r.checks[0].result).toBe('pass');
expect(r.assumptions).toEqual(['none']);
});
it('returns null without a recognizable verdict', () => {
expect(parseReport({ summary: 'no verdict' })).toBeNull();
expect(parseReport(null)).toBeNull();
expect(parseReport('merge')).toBeNull();
});
it('defaults confidence to medium', () => {
expect(parseReport({ verdict: 'merge' })!.confidence).toBe('medium');
});
});
describe('extractJsonObject', () => {
it('reads bare JSON, fenced JSON and JSON inside prose', () => {
expect(extractJsonObject('{"verdict":"merge"}')).toEqual({ verdict: 'merge' });
expect(extractJsonObject('Here:\n```json\n{"verdict":"close"}\n```\nDone.')).toEqual({ verdict: 'close' });
expect(extractJsonObject('REVIEW COMPLETE {"verdict":"merge","x":1} trailing')).toEqual({ verdict: 'merge', x: 1 });
expect(extractJsonObject('nothing here')).toBeNull();
});
});
describe('formatTelegramSummary', () => {
const report = parseReport(rawReport)!;
it('carries the verdict, the top findings, checks and the recommendation, HTML-escaped', () => {
const text = formatTelegramSummary(pr, report, { ci: 'awaiting-approval', durationMin: 7 });
expect(text).toContain('PR #381');
expect(text).toContain('REQUEST CHANGES');
expect(text).toContain('needs your approval');
expect(text).toContain('🔴 SSE path not prefixed');
expect(text).toContain('src/web/server.ts:210');
expect(text).toContain('typecheck ✅');
expect(text).toContain('tests ❌');
expect(text).toContain('Ask for the SSE fix');
expect(text).toContain('review took 7 min');
expect(text.length).toBeLessThan(TELEGRAM_MAX);
});
it('escapes HTML in model output', () => {
const r: ReviewReport = { ...report, summary: 'uses <script> & friends', findings: [] };
const text = formatTelegramSummary(pr, r, { ci: 'passed' });
expect(text).toContain('uses &lt;script&gt; &amp; friends');
expect(text).not.toContain('<script>');
});
it('stays under the Telegram cap with many long findings and says how many are hidden', () => {
const findings = Array.from({ length: 60 }, (_, i) => ({
severity: 'major' as const,
title: `finding ${i} ${'x'.repeat(150)}`,
file: `src/file-${i}.ts`,
line: i,
detail: 'd',
}));
const text = formatTelegramSummary(pr, { ...report, findings }, { ci: 'failed' });
expect(text.length).toBeLessThanOrEqual(TELEGRAM_MAX);
expect(text).toMatch(/… \d+ more in the full report/);
});
});
describe('splitTelegramMessage', () => {
it('keeps short text whole and splits long text on line boundaries', () => {
expect(splitTelegramMessage('a\nb')).toEqual(['a\nb']);
const lines = Array.from({ length: 300 }, (_, i) => `line ${i} ${'y'.repeat(40)}`);
const chunks = splitTelegramMessage(lines.join('\n'));
expect(chunks.length).toBeGreaterThan(1);
for (const c of chunks) expect(c.length).toBeLessThanOrEqual(TELEGRAM_MAX);
expect(chunks.join('\n')).toBe(lines.join('\n'));
});
it('hard-splits a single line longer than the cap', () => {
const chunks = splitTelegramMessage('z'.repeat(9000), 4000);
expect(chunks.map((c) => c.length)).toEqual([4000, 4000, 1000]);
});
});
describe('keyboards', () => {
it("keeps every callback_data under Telegram's 64-byte cap and adds the approve button only when CI waits", () => {
const all = [
...buildReportKeyboard(38199, { ci: 'awaiting-approval', hasDraft: true }).flat(),
...buildReportKeyboard(1, { ci: 'passed', hasDraft: false }).flat(),
...confirmKeyboard('merge', 38199, 'deadbeef').flat(),
];
for (const b of all) expect(Buffer.byteLength(b.callback_data)).toBeLessThanOrEqual(64);
expect(
buildReportKeyboard(5, { ci: 'awaiting-approval', hasDraft: true })
.flat()
.some((b) => b.callback_data === 'approveci:5')
).toBe(true);
expect(
buildReportKeyboard(5, { ci: 'passed', hasDraft: true })
.flat()
.some((b) => b.callback_data.startsWith('approveci'))
).toBe(false);
expect(
buildReportKeyboard(5, { ci: 'passed', hasDraft: false })
.flat()
.some((b) => b.callback_data === 'post:5')
).toBe(false);
});
});
describe('orderBacklog', () => {
it('puts mergeable and small first, conflicting last, newer first on ties', () => {
const rows = [
{ number: 375, mergeable: 'CONFLICTING' as const, additions: 5000, deletions: 100 },
{ number: 383, mergeable: 'MERGEABLE' as const, additions: 29, deletions: 1 },
{ number: 380, mergeable: 'MERGEABLE' as const, additions: 1800, deletions: 400 },
{ number: 362, mergeable: 'CONFLICTING' as const, additions: 200, deletions: 10 },
{ number: 390, mergeable: 'UNKNOWN' as const, additions: 29, deletions: 1 },
];
expect(orderBacklog(rows).map((r) => r.number)).toEqual([390, 383, 380, 362, 375]);
});
});
describe('formatStatusList + formatReviewFailure', () => {
it('renders rows with verdict icons and flags', () => {
const text = formatStatusList(
[
{
number: 1,
title: 'a',
author: 'x',
verdict: 'merge',
status: 'reviewed',
ci: 'passed',
mergeable: 'MERGEABLE',
isDraft: false,
},
{ number: 2, title: 'b <c>', author: 'y', status: 'queued', mergeable: 'CONFLICTING', isDraft: true },
],
true
);
expect(text).toContain('⏸ auto-review paused');
expect(text).toContain('✅ <b>#1</b>');
expect(text).toContain('🕓 <b>#2</b> b &lt;c&gt;');
expect(text).toContain('conflicts, draft');
expect(formatStatusList([], false)).toBe('No open pull requests.');
});
it('failure notice names the retry command', () => {
expect(formatReviewFailure(pr, 'timed out')).toContain('/review 381');
});
});
describe('classifyCi', () => {
const run = (over: Partial<WorkflowRun>): WorkflowRun => ({
id: 1,
name: 'CI',
status: 'completed',
conclusion: 'success',
...over,
});
it('reads the newest run per workflow only', () => {
const runs = [
run({ id: 3, conclusion: 'success' }),
run({ id: 2, conclusion: 'failure' }),
run({ id: 1, name: 'Other', conclusion: 'failure' }),
];
expect(latestRunPerWorkflow(runs).map((r) => r.id)).toEqual([3, 1]);
expect(classifyCi(runs)).toBe('failed');
expect(classifyCi([run({ id: 3 }), run({ id: 2, conclusion: 'failure' })])).toBe('passed');
});
it('maps the fork-PR approval gate, pending and empty cases', () => {
expect(classifyCi([])).toBe('none');
expect(classifyCi([run({ conclusion: 'action_required' })])).toBe('awaiting-approval');
expect(classifyCi([run({ status: 'in_progress', conclusion: null })])).toBe('pending');
expect(classifyCi([run({ conclusion: 'skipped' })])).toBe('passed');
});
});
describe('telegram parsers', () => {
it('parses commands with and without a PR number, and bot-suffixed commands', () => {
expect(parseCommand('/merge 381')).toEqual({ command: 'merge', prNumber: 381, rest: '' });
expect(parseCommand('/close #381 superseded by #372')).toEqual({
command: 'close',
prNumber: 381,
rest: 'superseded by #372',
});
expect(parseCommand('/ask 12 does it handle\nmultiline?')).toEqual({
command: 'ask',
prNumber: 12,
rest: 'does it handle\nmultiline?',
});
expect(parseCommand('/status@arkon85_bot')).toEqual({ command: 'status', rest: '' });
expect(parseCommand('hello')).toBeNull();
expect(parseCommand(undefined)).toBeNull();
});
it('parses callbacks and rejects malformed data', () => {
expect(parseCallback('merge:381')).toEqual({ action: 'merge', prNumber: 381 });
expect(parseCallback('confirm:merge:381:ab12')).toEqual({
action: 'confirm',
target: 'merge',
prNumber: 381,
nonce: 'ab12',
});
expect(parseCallback('confirm:merge:381')).toBeNull();
expect(parseCallback('merge:x')).toBeNull();
expect(parseCallback(undefined)).toBeNull();
});
it('finds the PR number in a report message', () => {
expect(prNumberFromMessageText('🔍 PR #381 · title')).toBe(381);
expect(prNumberFromMessageText('no number')).toBeNull();
});
});
describe('trustDialogKey', () => {
it('reads the highlighted option off a tmux repaint that lost its spaces', () => {
const esc = '\x1b';
const screen = `Security guide\n${esc}[1m❯${esc}[CNo,${esc}[Cexit\n Yes, I trust this folder\nEnter to confirm`;
expect(trustDialogKey(screen)).toBe('move');
expect(trustDialogKey(' No, exit\n❯ Yes, I trust this folder\n')).toBe('confirm');
expect(trustDialogKey('❯ Try "fix the bug"\n shift+tab to cycle')).toBeNull();
});
it('lets the freshest marked row win', () => {
expect(trustDialogKey('❯ No, exit\n...\n❯ Yes, I trust this folder')).toBe('confirm');
});
});
describe('config', () => {
it('parses env files with quotes, comments and export prefixes', () => {
const env = parseEnvFile('# c\nexport A="x y"\nB=\'z\'\nC=plain\nbad line\n=nokey\n');
expect(env).toEqual({ A: 'x y', B: 'z', C: 'plain' });
});
it('validates required keys and derives paths and units', () => {
expect(() => buildConfig({}, { home: '/h', repoRoot: '/r' })).toThrow(/TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID/);
const cfg = buildConfig(
{
TELEGRAM_BOT_TOKEN: 't',
TELEGRAM_CHAT_ID: '1',
PR_BOT_POLL_INTERVAL: '30',
PR_BOT_REVIEW_TIMEOUT: '3',
PR_BOT_AUTO_REVIEW: 'off',
},
{ home: '/h', repoRoot: '/r' }
);
expect(cfg.githubRepo).toBe('Ark0N/Codeman');
expect(cfg.codemanApiUrl).toBe('https://127.0.0.1:3000');
expect(cfg.dataDir).toBe('/h/.codeman/pr-bot');
expect(cfg.worktreesDir).toBe('/h/.codeman/pr-bot/worktrees');
expect(cfg.mainCheckout).toBe('/r');
expect(cfg.pollIntervalMs).toBe(60_000); // floored at 60s
expect(cfg.reviewTimeoutMs).toBe(5 * 60_000); // floored at 5 min
expect(cfg.autoReview).toBe(false);
expect(cfg.reviewDrafts).toBe(false);
expect(() =>
buildConfig(
{ TELEGRAM_BOT_TOKEN: 't', TELEGRAM_CHAT_ID: '1', GITHUB_REPO: 'nope' },
{ home: '/h', repoRoot: '/r' }
)
).toThrow(/owner\/name/);
});
});
describe('buildReviewBrief', () => {
it('names the report paths, the ground rules and the CI situation', () => {
const brief = buildReviewBrief({
pr: {
...pr,
body: 'Body **md**',
files: [{ path: 'src/a.ts', additions: 1, deletions: 0 }],
authorAssociation: 'FIRST_TIME_CONTRIBUTOR',
linkedIssues: [],
commitCount: 2,
commentCount: 0,
reviewDecision: '',
headRepo: 'mtiller/Codeman',
},
ci: { state: 'awaiting-approval', runs: [] },
mergeBase: 'abcdef0123456789',
worktreeDir: '/wt/pr-381',
mainCheckout: '/main',
reportJsonPath: '/jobs/report.json',
reportMdPath: '/jobs/report.md',
});
expect(brief).toContain('/jobs/report.json');
expect(brief).toContain('/jobs/report.md');
expect(brief).toContain('REVIEW COMPLETE');
expect(brief).toContain('waiting for a maintainer to approve');
expect(brief).toContain('never bind port 3000');
expect(brief).toContain('first time contributor');
expect(brief).toContain('`src/a.ts` (+1/-0)');
});
});
+84
View File
@@ -0,0 +1,84 @@
/**
* @fileoverview StateStore semantics for the PR bot: upsert keeps review results
* across scans, a closed PR that reopens comes back as reviewed, saves are atomic
* and 0600, and the message map is bounded.
*/
import { describe, it, expect } from 'vitest';
import { mkdtempSync, readdirSync, statSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { StateStore } from '../scripts/pr-bot/state.js';
import type { PrSummary } from '../scripts/pr-bot/github.js';
function summary(over: Partial<PrSummary> = {}): PrSummary {
return {
number: 7,
title: 't',
author: 'a',
headSha: 'aaaa',
baseRef: 'master',
headRef: 'x',
isDraft: false,
mergeable: 'MERGEABLE',
mergeState: 'CLEAN',
additions: 1,
deletions: 1,
changedFiles: 1,
updatedAt: '',
url: 'https://example/7',
isCrossRepository: true,
labels: [],
...over,
};
}
describe('StateStore', () => {
it('starts empty, persists, and reloads', () => {
const dir = mkdtempSync(join(tmpdir(), 'prbot-state-'));
const path = join(dir, 'state.json');
const store = new StateStore(path);
const rec = store.upsertPr(summary());
expect(rec.status).toBe('new');
rec.status = 'reviewed';
rec.reviewedSha = 'aaaa';
rec.verdict = 'merge';
store.state.telegramOffset = 42;
store.save();
expect(statSync(path).mode & 0o777).toBe(0o600);
expect(readdirSync(dir)).toEqual(['state.json']); // no tmp file left behind
const again = new StateStore(path);
expect(again.pr(7)?.verdict).toBe('merge');
expect(again.state.telegramOffset).toBe(42);
});
it('upsert refreshes metadata but keeps the review; reopening a closed PR restores reviewed', () => {
const store = new StateStore(join(mkdtempSync(join(tmpdir(), 'prbot-state-')), 'state.json'));
const rec = store.upsertPr(summary());
rec.status = 'reviewed';
rec.reviewedSha = 'aaaa';
const moved = store.upsertPr(summary({ headSha: 'bbbb', title: 'renamed' }));
expect(moved).toBe(rec); // same object: a review in flight keeps writing into the stored record
expect(moved.status).toBe('reviewed');
expect(moved.reviewedSha).toBe('aaaa');
expect(moved.headSha).toBe('bbbb');
expect(moved.title).toBe('renamed');
moved.status = 'closed';
moved.closedAs = 'closed';
expect(store.openPrs()).toHaveLength(0);
const reopened = store.upsertPr(summary({ headSha: 'bbbb' }));
expect(reopened.status).toBe('reviewed');
expect(reopened.closedAs).toBeUndefined();
expect(store.openPrs()).toHaveLength(1);
});
it('bounds the message map on save', () => {
const store = new StateStore(join(mkdtempSync(join(tmpdir(), 'prbot-state-')), 'state.json'));
for (let i = 0; i < 2500; i++) store.rememberMessage(i, 1);
store.save();
const keys = Object.keys(store.state.messages).map(Number);
expect(keys).toHaveLength(2000);
expect(Math.min(...keys)).toBe(500);
expect(store.prForMessage(2499)).toBe(1);
expect(store.prForMessage(10)).toBeUndefined();
});
});
+39
View File
@@ -228,3 +228,42 @@ describe('WebServer.renderIndexHtml', () => {
expect(html).not.toContain('gesture-codeman.js');
});
});
describe('WebServer.renderIndexHtml reverse-proxy base path', () => {
const BASE_TEMPLATE = ['<head>', '<base href="/">', '<title>Codeman</title>', '</head>', '<body></body>'].join('\n');
function makeBaseServer(basePath: string) {
// constructor: (port, https, testMode, host, titleHostname, allowUnauth, basePath)
const server = new WebServer(0, false, true, '127.0.0.1', undefined, false, basePath);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(server as any).indexHtmlTemplate = BASE_TEMPLATE;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(server as any).readSettings = vi.fn(async () => ({}));
return server;
}
it('is inert at root — base tag unchanged and no base global injected', async () => {
const server = makeBaseServer('');
const html = await render(server);
expect(html).toContain('<base href="/">');
// At root the frontend reads a MISSING __CODEMAN_BASE__ as root, so nothing is
// injected and the historical output is byte-identical.
expect(html).not.toContain('__CODEMAN_BASE__');
});
it('points the base tag and the base global at a sub-path mount', async () => {
const server = makeBaseServer('/codeman');
const html = await render(server);
expect(html).toContain('<base href="/codeman/">');
expect(html).toContain('window.__CODEMAN_BASE__="/codeman"');
// The global rides right after <base>, before any (deferred) script.
expect(html.indexOf('window.__CODEMAN_BASE__')).toBeLessThan(html.indexOf('</head>'));
});
it('normalizes a raw operator prefix passed to the constructor', async () => {
const server = makeBaseServer('codeman/');
const html = await render(server);
expect(html).toContain('<base href="/codeman/">');
expect(html).toContain('window.__CODEMAN_BASE__="/codeman"');
});
});
+149
View File
@@ -0,0 +1,149 @@
/**
* @fileoverview Response-viewer turn segmentation (`CodemanApp._buildResponseViewerMessage`).
*
* The server now emits one message per model message instead of concatenating a
* human turn's replies into one card, so a long autonomous run arrives as tens
* of messages rather than one 12,000-character block. Rendered naively that is
* card spam — the measured distribution is p50 3 messages per turn, p90 11,
* max 51, with 58% of messages under 80 characters. So consecutive messages
* from one speaker inside one `turn` render as SEGMENTS of one card: no
* repeated role badge, a hairline seam.
*
* Pinned here because the badge suppression is the only thing standing between
* the server change and a wall of 51 "Claude" badges:
*
* 1. A continuation carries `rv-msg-cont` and has NO `.rv-role` child, while
* keeping its role class so the CSS accent survives (the colour rules match
* on both `:has(.rv-role-*)` and `.rv-msg-*` — only the class arm hits here).
* 2. A queued prompt is marked in the DOM, not in text, so the i18n
* MutationObserver cannot rewrite the marker.
* 3. The 4th argument is genuinely optional: the brief view's 3-argument call
* still renders a badge.
*
* Loaded via `vm` with a jsdom document injected (same technique as
* response-viewer-file-links.test.ts).
* Port: N/A
*/
import { readFileSync } from 'node:fs';
import { performance } from 'node:perf_hooks';
import { resolve } from 'node:path';
import vm from 'node:vm';
import { JSDOM } from 'jsdom';
import { describe, expect, it, vi } from 'vitest';
const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>');
const { document, NodeFilter } = dom.window;
interface MessageBuilder {
_buildResponseViewerMessage(text: string, role: string, agentLabel: string, meta?: unknown): HTMLElement;
loadFullContext(): Promise<void>;
activeSessionId?: string;
}
function loadCodemanAppClass() {
const constants = readFileSync(resolve(import.meta.dirname, '../src/web/public/constants.js'), 'utf8');
const source = readFileSync(resolve(import.meta.dirname, '../src/web/public/app.js'), 'utf8');
const context = vm.createContext({
console,
performance,
setInterval: vi.fn(),
clearInterval: vi.fn(),
setTimeout,
clearTimeout,
requestAnimationFrame: vi.fn(),
HTMLCanvasElement: class HTMLCanvasElement {},
fetch: vi.fn(),
document,
NodeFilter,
localStorage: { length: 0, key: vi.fn(), getItem: vi.fn(), setItem: vi.fn(), removeItem: vi.fn() },
window: { addEventListener: vi.fn(), removeEventListener: vi.fn() },
MobileDetection: {},
});
vm.runInContext(`${constants}\n${source}\nglobalThis.__CodemanApp = CodemanApp;`, context);
// The context is returned too: app.js closes over the context's own `fetch`, so a
// test that drives loadFullContext has to replace THAT binding, not globalThis'.
return { CodemanApp: (context as { __CodemanApp: { prototype: MessageBuilder } }).__CodemanApp, context };
}
const { CodemanApp, context: appContext } = loadCodemanAppClass();
function build(text: string, role: string, meta?: unknown): HTMLElement {
const app = Object.create(CodemanApp.prototype) as MessageBuilder;
return app._buildResponseViewerMessage(text, role, 'Claude', meta);
}
describe('response viewer turn segmentation', () => {
it('renders a continuation without a repeated role badge but keeps its role class', () => {
const div = build('second half of the same turn', 'assistant', { continuation: true, kind: 'response', turn: 3 });
expect(div.classList.contains('rv-msg-cont')).toBe(true);
expect(div.classList.contains('rv-msg-assistant')).toBe(true);
expect(div.querySelector('.rv-role')).toBeNull();
expect(div.querySelector('.rv-text')).not.toBeNull();
expect(div.dataset.kind).toBe('response');
});
it('marks a prompt the user queued mid-turn in the DOM, not in the text', () => {
const div = build('actually use PowerShell', 'user', {
continuation: false,
kind: 'prompt',
queued: true,
turn: 2,
});
expect(div.dataset.queued).toBe('1');
expect(div.dataset.kind).toBe('prompt');
const badge = div.querySelector('.rv-role');
expect(badge).not.toBeNull();
expect(badge!.classList.contains('rv-role-user')).toBe(true);
// The marker is a CSS pseudo-element, so the badge text stays translatable.
expect(badge!.textContent).toBe('You');
});
it('still renders a badge for the brief view, which passes no meta', () => {
const div = build('the last response', 'assistant');
expect(div.classList.contains('rv-msg-cont')).toBe(false);
expect(div.querySelector('.rv-role')!.textContent).toBe('Claude');
expect(div.dataset.kind).toBeUndefined();
expect(div.dataset.queued).toBeUndefined();
});
});
/**
* The empty-state branch deliberately does NOT wipe the body — the brief view has
* a terminal-buffer fallback this endpoint does not — and deliberately leaves the
* More button live so a transcript that appears a moment later can still be
* loaded. Both together mean the notice must be idempotent: without that, every
* retry stacks another identical line. Upstream got this for free because it
* assigned `body.textContent`.
*/
describe('response viewer empty full-context state', () => {
it('reuses one notice across repeated More clicks and keeps the brief card', async () => {
const body = document.createElement('div');
body.id = 'responseViewerBody';
const title = document.createElement('div');
title.id = 'responseViewerTitle';
const more = document.createElement('button');
more.id = 'responseViewerMore';
document.body.append(body, title, more);
body.textContent = 'No response yet — send a message in this session first.';
const app = Object.create(CodemanApp.prototype) as MessageBuilder;
app.activeSessionId = 's1';
(appContext as { fetch: unknown }).fetch = vi.fn(async () => ({
json: async () => ({ data: { messages: [] } }),
}));
await app.loadFullContext();
await app.loadFullContext();
await app.loadFullContext();
expect(body.querySelectorAll('.rv-notice')).toHaveLength(1);
expect(body.textContent).toContain('No response yet');
// More stays clickable: it is the only retry path once a transcript lands.
expect(more.style.display).toBe('');
document.body.innerHTML = '';
});
});
+15
View File
@@ -10,6 +10,7 @@ import { Readable } from 'node:stream';
import { createRouteTestHarness, type RouteTestHarness } from './_route-test-utils.js';
import { registerFileRoutes } from '../../src/web/routes/file-routes.js';
import { ApiErrorCode } from '../../src/types.js';
import { CASES_DIR } from '../../src/web/route-helpers.js';
// Mock fs/promises for file operations
vi.mock('node:fs/promises', () => ({
@@ -114,6 +115,20 @@ describe('file-routes', () => {
]);
});
it('defaults to the Codeman Cases root, not Home, when linking a case with no path chosen yet', async () => {
// The "Link Existing" case picker opens with an empty path and no
// sessionId. `Home` and `Codeman Cases` are unrelated bind mounts under
// Docker, so falling back to whichever root happened to be listed first
// could open the picker somewhere with no cases in it at all — and, worse,
// make a stale directory from a since-changed CODEMAN_CASES_PATH look like
// a normal thing to stumble across while browsing for one to link.
const res = await harness.app.inject({ method: 'GET', url: '/api/filesystem/browse' });
expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body);
expect(body.data.path).toBe(CASES_DIR);
});
it('rejects paths outside the configured roots', async () => {
const res = await harness.app.inject({
method: 'GET',
+69
View File
@@ -115,6 +115,75 @@ describe('hook-event-routes', () => {
);
});
/**
* The pane's live conversation id, reported by the CLI process itself. This
* is what lets the response viewer stop guessing from ~/.claude/history.jsonl
* — a guess that could never run at all for a pane the user drives by
* attaching to tmux, because `lastSubmitAt` only ever saw Codeman's own
* write path.
*/
it('adopts the conversation id first-hand from a prompt_submitted hook', async () => {
const session = harness.ctx._session;
const before = session.lastSubmitAt;
const res = await harness.app.inject({
method: 'POST',
url: '/api/hook-event',
payload: {
event: 'prompt_submitted',
sessionId: harness.ctx._sessionId,
data: { hook_event_name: 'UserPromptSubmit', session_id: 'conv-1', source: 'user' },
},
});
expect(res.statusCode).toBe(200);
expect(session.claudeSessionId).toBe('conv-1');
expect(session.claudeSessionIdIsFirstHand).toBe(true);
expect(session.claudeSessionChain).toEqual(['conv-1']);
expect(session.lastSubmitAt).toBeGreaterThan(before);
expect(harness.ctx.persistSessionState).toHaveBeenCalledWith(session);
});
it('records a /clear successor in the chain and persists it, without duplicating a repeat', async () => {
const session = harness.ctx._session;
const submit = async (conversationId: string) =>
harness.app.inject({
method: 'POST',
url: '/api/hook-event',
payload: {
event: 'prompt_submitted',
sessionId: harness.ctx._sessionId,
data: { hook_event_name: 'UserPromptSubmit', session_id: conversationId },
},
});
await submit('conv-1');
await submit('conv-1'); // every prompt in a conversation reports the same id
await submit('conv-2'); // the user ran /clear
expect(session.claudeSessionChain).toEqual(['conv-1', 'conv-2']);
expect(session.claudeSessionId).toBe('conv-2');
// `/clear` emits no completion event, so the successor is lost on restart
// unless the hook itself persists it.
expect(harness.ctx.persistSessionState).toHaveBeenCalledTimes(2);
});
it('does not leak the prompt text into the broadcast', async () => {
await harness.app.inject({
method: 'POST',
url: '/api/hook-event',
payload: {
event: 'prompt_submitted',
sessionId: harness.ctx._sessionId,
data: { hook_event_name: 'UserPromptSubmit', session_id: 'conv-1', prompt: 'my secret prompt' },
},
});
const broadcast = JSON.stringify(harness.ctx.broadcast.mock.calls);
expect(broadcast).not.toContain('my secret prompt');
expect(broadcast).toContain('conv-1');
});
it('returns 404 for unknown session', async () => {
const res = await harness.app.inject({
method: 'POST',
@@ -60,6 +60,24 @@ const assistantEntry = (text: string, timestamp: string) => ({
message: { content: [{ type: 'text', text }] },
});
/**
* A prompt typed while Claude is working. Shape copied from a real CLI 2.1.251
* row: the CLI's own queue entries carry commandMode 'task-notification' and no
* `origin` key at all, which is what separates them from the human's.
*/
const queuedEntry = (prompt: string, timestamp: string, kind: 'human' | 'task-notification' = 'human') => ({
type: 'attachment',
timestamp,
attachment: {
type: 'queued_command',
prompt,
source_uuid: `src-${timestamp}`,
commandMode: kind === 'human' ? 'prompt' : 'task-notification',
...(kind === 'human' ? { origin: { kind: 'human' } } : {}),
timestamp,
},
});
describe('GET /api/sessions/:id/last-response (claude)', () => {
let harness: LocalHarness;
let testHome: string;
@@ -93,7 +111,7 @@ describe('GET /api/sessions/:id/last-response (claude)', () => {
return { response, body: JSON.parse(response.body) };
}
it('recovers a placeholder tmux session by UUID prefix and groups JSONL fragments into turns', async () => {
it('recovers a placeholder tmux session by UUID prefix and renders one message per model message', async () => {
const restoredId = 'restored-40568a29';
const conversationId = '40568a29-d4eb-4eb6-b671-8401428e4f39';
const session = harness.ctx._session as typeof harness.ctx._session & {
@@ -135,15 +153,60 @@ describe('GET /api/sessions/:id/last-response (claude)', () => {
expect(full.body.data).toEqual({
text: 'Second half.',
timestamp: '2026-07-21T00:00:06Z',
// #169's guarantees all still hold and this array proves them: the replayed
// 'first prompt' row, the replayed 'Checking the files.' snapshot, the
// sidechain row and all five synthetic rows are absent. Only the GROUPING
// UNIT narrows, from one card per human turn to one card per model
// message, carried by `turn` instead of by a '\n\n' joiner.
messages: [
{ role: 'user', text: 'first prompt', timestamp: '2026-07-21T00:00:00Z' },
{
kind: 'prompt',
label: 'Prompt',
role: 'user',
text: 'first prompt',
timestamp: '2026-07-21T00:00:00Z',
turn: 1,
},
{
kind: 'response',
label: 'Response',
role: 'assistant',
text: 'Checking the files.\n\nThe first result is ready.',
text: 'Checking the files.',
timestamp: '2026-07-21T00:00:01Z',
turn: 1,
},
{
kind: 'response',
label: 'Response',
role: 'assistant',
text: 'The first result is ready.',
timestamp: '2026-07-21T00:00:03Z',
turn: 1,
},
{
kind: 'prompt',
label: 'Prompt',
role: 'user',
text: 'second prompt',
timestamp: '2026-07-21T00:00:00Z',
turn: 2,
},
{
kind: 'response',
label: 'Response',
role: 'assistant',
text: 'First half.',
timestamp: '2026-07-21T00:00:04Z',
turn: 2,
},
{
kind: 'response',
label: 'Response',
role: 'assistant',
text: 'Second half.',
timestamp: '2026-07-21T00:00:06Z',
turn: 2,
},
{ role: 'user', text: 'second prompt', timestamp: '2026-07-21T00:00:00Z' },
{ role: 'assistant', text: 'First half.\n\nSecond half.', timestamp: '2026-07-21T00:00:06Z' },
],
});
expect(session.adoptClaudeSessionId).toHaveBeenCalledWith(conversationId);
@@ -175,6 +238,137 @@ describe('GET /api/sessions/:id/last-response (claude)', () => {
['assistant', 'Second answer.'],
]);
});
/**
* A prompt typed while Claude is working is absorbed mid-turn and recorded
* ONLY as an attachment row — 160 of the 347 user cards across a real
* ~/.claude/projects. Reading only `user` rows lost them outright AND lost the
* turn boundary they carry, which is what let an assistant run fuse.
*/
it('surfaces a prompt the user queued while Claude was working', async () => {
const sessionId = harness.ctx._session.id;
const session = harness.ctx._session as typeof harness.ctx._session & {
claudeSessionId: string;
adoptClaudeSessionId: ReturnType<typeof vi.fn>;
};
session.claudeSessionId = sessionId;
session.adoptClaudeSessionId = vi.fn();
writeTranscript(sessionId, [
userEntry('start the job'),
assistantEntry('Working on it.', '2026-07-21T00:00:01Z'),
queuedEntry('actually use PowerShell', '2026-07-21T00:00:02Z'),
queuedEntry('background agent finished', '2026-07-21T00:00:03Z', 'task-notification'),
// The most common attachment subtype; it carries no prompt/origin at all.
{ type: 'attachment', attachment: { type: 'total_tokens_reminder', tokens: 1 } },
assistantEntry('Switched to PowerShell.', '2026-07-21T00:00:04Z'),
]);
const { body } = await getLastResponse(sessionId, true);
const messages = body.data.messages as Array<{ role: string; text: string; turn: number; queued?: boolean }>;
expect(messages.map((message) => [message.role, message.text, message.turn])).toEqual([
['user', 'start the job', 1],
['assistant', 'Working on it.', 1],
['user', 'actually use PowerShell', 2],
['assistant', 'Switched to PowerShell.', 2],
]);
expect(messages[2].queued).toBe(true);
expect(messages[0].queued).toBeUndefined();
});
/**
* Mostly forward insurance. A queued prompt re-emitted as a `user` row AFTER
* its attachment row — the shape that would double-render — is not observed on
* CLI 2.1.220-2.1.251 (0 of 163 measured 2026-09-01). The only exact-text
* collisions are three occurrences of the same one-character nudge in a single
* transcript, and the guard fires on one of them, which is why 163 human
* queued rows yield 162 cards. The guard exists so a CLI that starts writing
* both rows does not double every absorbed prompt.
*/
it('renders an absorbed prompt once when the CLI also writes it as a user row', async () => {
const sessionId = harness.ctx._session.id;
const session = harness.ctx._session as typeof harness.ctx._session & {
claudeSessionId: string;
adoptClaudeSessionId: ReturnType<typeof vi.fn>;
};
session.claudeSessionId = sessionId;
session.adoptClaudeSessionId = vi.fn();
writeTranscript(sessionId, [
userEntry('go'),
assistantEntry('OK.', '2026-07-21T00:00:01Z'),
queuedEntry('switch to PowerShell', '2026-07-21T00:00:02Z'),
userEntry('switch to PowerShell'),
assistantEntry('Done.', '2026-07-21T00:00:03Z'),
]);
const { body } = await getLastResponse(sessionId, true);
const messages = body.data.messages as Array<{ role: string; text: string; queued?: boolean }>;
const absorbed = messages.filter((message) => message.role === 'user' && message.text === 'switch to PowerShell');
expect(absorbed).toHaveLength(1);
expect(absorbed[0].queued).toBe(true);
});
/**
* The brief response is what agent pollers hash (skills/codeman/preamble.sh
* last_text()). It must stay the last assistant row and must NEVER be derived
* from messages.at(-1), which can be the user's own queued prompt.
*/
it('keeps the brief response on the last assistant row while a turn is in flight', async () => {
const sessionId = harness.ctx._session.id;
const session = harness.ctx._session as typeof harness.ctx._session & {
claudeSessionId: string;
adoptClaudeSessionId: ReturnType<typeof vi.fn>;
};
session.claudeSessionId = sessionId;
session.adoptClaudeSessionId = vi.fn();
writeTranscript(sessionId, [
userEntry('go'),
assistantEntry('Let me look.', '2026-07-21T00:00:01Z'),
{ type: 'assistant', message: { content: [{ type: 'tool_use', id: 'x' }] } },
{ type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: 'x' }] } },
]);
const brief = await getLastResponse(sessionId);
expect(brief.body.data).toEqual({ text: 'Let me look.', timestamp: '2026-07-21T00:00:01Z' });
const { body } = await getLastResponse(sessionId, true);
const messages = body.data.messages as Array<{ role: string; text: string }>;
expect(messages.at(-1)).toMatchObject({ role: 'assistant', text: 'Let me look.' });
expect(body.data.text).toBe('Let me look.');
});
/**
* A multi-line paste absorbed mid-turn arrives as N queued rows within a few
* hundred milliseconds (observed: 5 rows inside ~360ms). They are one turn, so
* the viewer renders them under one badge instead of N.
*/
it('groups a burst of queued prompts into one turn', async () => {
const sessionId = harness.ctx._session.id;
const session = harness.ctx._session as typeof harness.ctx._session & {
claudeSessionId: string;
adoptClaudeSessionId: ReturnType<typeof vi.fn>;
};
session.claudeSessionId = sessionId;
session.adoptClaudeSessionId = vi.fn();
writeTranscript(sessionId, [
userEntry('go'),
assistantEntry('OK.', '2026-07-21T00:00:01Z'),
queuedEntry('one more thing', '2026-07-21T00:00:02.100Z'),
queuedEntry('and the requirements are', '2026-07-21T00:00:02.360Z'),
queuedEntry('finally, keep it fast', '2026-07-21T00:00:02.480Z'),
assistantEntry('Understood.', '2026-07-21T00:00:05Z'),
]);
const { body } = await getLastResponse(sessionId, true);
const messages = body.data.messages as Array<{ role: string; turn: number }>;
expect(messages.map((message) => [message.role, message.turn])).toEqual([
['user', 1],
['assistant', 1],
['user', 2],
['user', 2],
['user', 2],
['assistant', 2],
]);
});
});
/**
@@ -232,16 +426,18 @@ describe('GET /api/sessions/:id/last-response (claude conversation pinning)', ()
}
/** Replaces the pre-seeded mock session with a Claude pane in WORKDIR. */
function addPane(id: string, conversationId: string, lastSubmitAt: number) {
function addPane(id: string, conversationId: string, lastSubmitAt: number, firstHand = false) {
const base = harness.ctx._session;
const pane = Object.create(Object.getPrototypeOf(base)) as typeof base & {
claudeSessionId: string;
lastSubmitAt: number;
claudeSessionIdIsFirstHand: boolean;
adoptClaudeSessionId: ReturnType<typeof vi.fn>;
};
Object.assign(pane, base, { id, mode: 'claude', workingDir: WORKDIR, docker: undefined });
pane.claudeSessionId = conversationId;
pane.lastSubmitAt = lastSubmitAt;
pane.claudeSessionIdIsFirstHand = firstHand;
pane.adoptClaudeSessionId = vi.fn((newId: string) => {
pane.claudeSessionId = newId;
});
@@ -286,6 +482,41 @@ describe('GET /api/sessions/:id/last-response (claude conversation pinning)', ()
expect(pane.adoptClaudeSessionId).not.toHaveBeenCalled();
});
/**
* The whole point of the UserPromptSubmit hook: a pane driven by attaching to
* tmux directly never bumps `lastSubmitAt` (only Codeman's own write path
* does), so before this the correlation could not run at all for it and the
* viewer stayed pinned to the launch conversation for the pane's whole life.
*/
it("trusts the pane's own hook over any history correlation", async () => {
const pane = addPane('pane-1', 'hook-conversation', 0, true);
writeTranscript('hook-conversation', 'the answer this pane gave', NOW - 60_000);
// A newer, closer entry that the correlation would otherwise have claimed.
writeTranscript('decoy-conversation', 'a stranger answer', NOW);
writeHistory([{ sessionId: 'decoy-conversation', timestamp: NOW }]);
expect(await getLastResponse('pane-1')).toEqual({
text: 'the answer this pane gave',
timestamp: expect.any(String),
});
expect(pane.adoptClaudeSessionId).not.toHaveBeenCalled();
});
it('never lets a correlation override a first-hand id, even a well-anchored one', async () => {
// Same shape as the /clear-following test above, which DOES adopt — the only
// difference is that this pane's id came from its own hook.
const pane = addPane('pane-1', 'before-clear', NOW, true);
writeTranscript('before-clear', 'answer before clear', NOW - 60_000);
writeTranscript('after-clear', 'answer after clear', NOW + 500);
writeHistory([{ sessionId: 'after-clear', timestamp: NOW + 120 }]);
expect(await getLastResponse('pane-1')).toEqual({
text: 'answer before clear',
timestamp: expect.any(String),
});
expect(pane.adoptClaudeSessionId).not.toHaveBeenCalled();
});
it('credits a shared-cwd entry to the pane whose Enter is closest to it', async () => {
const near = addPane('pane-near', 'near-conversation', NOW);
const far = addPane('pane-far', 'far-conversation', NOW - 4_000);
@@ -0,0 +1,120 @@
/**
* @fileoverview Session.claudeSessionChain — the record of which Claude
* conversations a pane has actually been on.
*
* Which conversation the response viewer reads is `Session.claudeSessionId`,
* and `start()` reassigns it to the launch id at THREE separate points. That is
* correct for a fresh pane and a lie for a re-attached one: a mux session that
* survived a Codeman restart never stopped, so the CLI may have `/clear`ed hours
* ago and moved to a conversation the launch id knows nothing about. The chain
* is what carries that across the restart, and its tail must therefore outrank
* the launch id on the restored path only.
*
* Two properties are pinned here because both were broken in ways nothing else
* caught:
*
* 1. **Only a first-hand adoption extends the chain.** The id has to come from
* the CLI's own hook payload, delivered under the pane's `$CODEMAN_SESSION_ID`.
* A history-correlated guess writing into this record would make the
* "showed a stranger's conversation" bug permanent instead of transient.
* 2. **A restored conversation survives every reset point.** The mux branch and
* the unconditional "third reset point" after it both reassign the field, so
* patching only the first leaves the restore silently undone.
*
* Port: N/A
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, it } from 'vitest';
import { Session } from '../src/session.js';
describe('Session claude conversation chain', () => {
it('extends the chain only for a first-hand adoption', () => {
const session = new Session({ workingDir: '/tmp', mode: 'claude' });
// A correlated guess: adopted for display, but never recorded.
session.adoptClaudeSessionId('guessed-conversation');
expect(session.claudeSessionId).toBe('guessed-conversation');
expect(session.claudeSessionChain).toEqual([]);
expect(session.claudeSessionIdIsFirstHand).toBe(false);
// The CLI's own hook: recorded.
session.adoptClaudeSessionId('hook-conversation', { firstHand: true });
expect(session.claudeSessionChain).toEqual(['hook-conversation']);
expect(session.claudeSessionIdIsFirstHand).toBe(true);
});
it('records a /clear successor once, however many prompts report it', () => {
const session = new Session({ workingDir: '/tmp', mode: 'claude' });
session.adoptClaudeSessionId('conv-1', { firstHand: true });
session.adoptClaudeSessionId('conv-1', { firstHand: true }); // every prompt reports the same id
session.adoptClaudeSessionId('conv-2', { firstHand: true }); // the user ran /clear
expect(session.claudeSessionChain).toEqual(['conv-1', 'conv-2']);
expect(session.claudeSessionId).toBe('conv-2');
});
it('moves a resumed conversation to the tail instead of duplicating it', () => {
const session = new Session({ workingDir: '/tmp', mode: 'claude' });
session.adoptClaudeSessionId('conv-1', { firstHand: true });
session.adoptClaudeSessionId('conv-2', { firstHand: true });
session.adoptClaudeSessionId('conv-1', { firstHand: true }); // /resume back
expect(session.claudeSessionChain).toEqual(['conv-2', 'conv-1']);
});
it('round-trips the chain through toState and re-pins the conversation on restore', () => {
const original = new Session({ workingDir: '/tmp', mode: 'claude' });
original.adoptClaudeSessionId('conv-1', { firstHand: true });
original.adoptClaudeSessionId('conv-2', { firstHand: true });
const state = original.toState() as { claudeSessionChain?: string[] };
expect(state.claudeSessionChain).toEqual(['conv-1', 'conv-2']);
// Boot recovery rebuilds the pane from that state. The launch id would point
// the viewer at the pre-/clear conversation; the chain's tail corrects it.
const restored = new Session({
workingDir: '/tmp',
mode: 'claude',
id: original.id,
claudeSessionChain: state.claudeSessionChain,
});
expect(restored.claudeSessionId).toBe('conv-2');
// ⚠️ NOT restored: a persisted claim is not a fact. The pane re-earns the
// guess-free path from its next hook.
expect(restored.claudeSessionIdIsFirstHand).toBe(false);
});
it('omits the chain from toState when the pane never moved conversation', () => {
const session = new Session({ workingDir: '/tmp', mode: 'claude' });
expect((session.toState() as { claudeSessionChain?: string[] }).claudeSessionChain).toBeUndefined();
});
it('applies the restored conversation at EVERY reset point in start()', () => {
// ⚠️ Structural pin, not a behavioural one: exercising start() needs a real
// PTY and mux. start() reassigns _claudeSessionId at three points, and the
// last one runs unconditionally AFTER the mux branch — so patching only the
// mux branch leaves the restore silently undone, which is what shipped
// before this existed. Every assignment built from the launch-id fallback
// must therefore carry `restoredConversation` first.
const source = readFileSync(resolve(import.meta.dirname, '../src/session.ts'), 'utf8');
// The tail of the chain grows as each CLI gains a resume alias of its own
// (omp, then codex), so the pattern pins the two ends and lets the middle
// widen. A `[^;]` run cannot cross a statement boundary, so each match is
// still one assignment.
const fallbackAssignments = source.match(/_claudeSessionId =[^;]*?_resumeSessionId[^;]*?this\.id;/g);
expect(fallbackAssignments).not.toBeNull();
expect(fallbackAssignments!.length).toBeGreaterThanOrEqual(2);
for (const assignment of fallbackAssignments!) {
expect(assignment).toContain('restoredConversation ||');
}
});
it('leaves a fresh pane on its launch id', () => {
const session = new Session({ workingDir: '/tmp', mode: 'claude' });
expect(session.claudeSessionId).toBe(session.id);
expect(session.claudeSessionChain).toEqual([]);
});
});
+4
View File
@@ -41,6 +41,10 @@ delete process.env.CODEMAN_USERNAME;
// __codemanGestureAvailable flag), breaking byte-identity assertions
// (test/server-index-title.test.ts) when the shell exports CODEMAN_GESTURE=1.
delete process.env.CODEMAN_GESTURE;
// CODEMAN_BASE_URL (#381) is read by the WebServer constructor as a fallback; an
// operator who exports it (exactly who the feature is for) would otherwise see the
// root-install byte-identity assertions fail.
delete process.env.CODEMAN_BASE_URL;
// Instance selection is PROCESS-WIDE and is what `src/config/instance.ts` derives
// both the data dir and the tmux socket from, so a shell that exports any of these
+1
View File
@@ -30,6 +30,7 @@ const STRIPPED_ENV_VARS: Array<[name: string, why: string]> = [
['CODEMAN_PASSWORD', 'auth from a running instance would make protected routes behave differently'],
['CODEMAN_USERNAME', 'same, and it changes which owner scoping resolves to'],
['CODEMAN_GESTURE', 'flips renderIndexHtml output and breaks byte-identity assertions'],
['CODEMAN_BASE_URL', 'mounts the server under a sub-path and breaks the root-install byte-identity assertions'],
['CODEMAN_INSTANCE', 'moves the data dir to ~/.codeman-<name> and the tmux socket to codeman-<name>'],
['CODEMAN_DATA_DIR', 'ABSOLUTE override: bypasses the temp HOME and points the suite at a real data dir'],
['CODEMAN_TMUX_SOCKET', 'renames the socket resolveTmuxSocketName() returns'],
+36
View File
@@ -684,3 +684,39 @@ describe('referrer policy on proxied responses', () => {
expect(headers['referrer-policy']).toBe('same-origin');
});
});
describe('reverse-proxy base path', () => {
const BASE = '/codeman';
const BASED_PREFIX = `${BASE}/webview/${CAP}/`;
it('rides the mount into the iframe prefix', () => {
expect(proxyPrefixFor(CAP, BASE)).toBe(BASED_PREFIX);
expect(proxyPrefixFor(CAP, '')).toBe(PREFIX); // root unchanged
});
it('rewrites HTML (base tag, root-absolute attrs, shim) under the mount', () => {
const out = rewriteHtml('<html><head></head><body><img src="/logo.png"></body></html>', CAP, BASE);
expect(out).toContain(`<base href="${BASED_PREFIX}">`);
expect(out).toContain(`src="${BASED_PREFIX}logo.png"`);
// The runtime shim's rewrite target is the base-prefixed path.
expect(out).toContain(JSON.stringify(BASED_PREFIX));
});
it('rebases Set-Cookie Path onto the mounted prefix so the browser sends it back', () => {
expect(rewriteSetCookie('sid=abc; Path=/', CAP, true, BASE)).toContain(`Path=${BASED_PREFIX}`);
expect(rewriteSetCookie('sid=abc; HttpOnly', CAP, true, BASE)).toContain(`Path=${BASED_PREFIX}`);
});
it('rewrites a same-origin Location into the mounted prefix', () => {
const requestUrl = new URL('http://127.0.0.1:4000/app');
expect(rewriteLocation('/dashboard?x=1', requestUrl, CAP, BASE)).toBe(`${BASED_PREFIX}dashboard?x=1`);
});
it('extracts the capability from a browser Referer that carries the mount prefix', () => {
expect(capabilityFromReferer(`https://box.ts.net${BASED_PREFIX}page`, BASE)).toBe(CAP);
// A same-named sibling path must not be mistaken for the mount.
expect(capabilityFromReferer(`https://box.ts.net/codeman-docs/webview/${CAP}/page`, BASE)).toBeNull();
// Without the base arg the prefixed Referer no longer matches (documents why the arg exists).
expect(capabilityFromReferer(`https://box.ts.net${BASED_PREFIX}page`)).toBeNull();
});
});