Compare commits

..
Author SHA1 Message Date
Codeman maintainer c03714eb74 chore: version packages
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 16:21:09 +02:00
Codeman maintainer 1ca0a33830 chore: version packages
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 16:20:36 +02:00
Ark0N 0c00a40530 Merge pull request #407 from Ark0N/feat/iphone-duo
iPhone Duo support: fold-aware dialogs, and a fold is no longer mistaken for the keyboard
2026-09-14 16:10:38 +02:00
Codeman maintainer e46089bc7f fix(statusline): print nothing instead of the bare word codeman
Ported from #416 (discussion #405): a statusline reading just `codeman`
is what a hand-run claude in a managed repo showed, and it reads as a
broken config rather than a footer. Three paths produced it and all
three now yield an empty footer: the exporter's `|| echo codeman`
fallback (now `curl -sfk ... || true`, with -f keeping an HTTP error
body off stdout), the unknown-session answer of POST /api/status-telemetry,
and formatSessionStatusText() with nothing to show. The exporter script
marker moves to V4 so live installs pick the new content up on the next
spawn.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 15:59:00 +02:00
Codeman maintainer fa1ea8d9fe fix(statusline): unset a stale user statusline var, write the exporter script atomically
Three small follow-ups from the #361 review.

A tmux setenv survives respawn-pane, so _configureStatusLineUserCommand
returning early when the user has no statusline left a previously
exported CODEMAN_USER_STATUSLINE_CMD in place: a user who deleted their
own statusline kept getting the stale one wrapped, and lost Codeman's
footer print-through, until the tmux session was recreated. It now
issues `setenv -u` in that case, the same shape as the effort-level
cleanup in applyEnvOverrides.

ensureStatusLineExporterScript truncated and rewrote a script that live
sessions execute on every statusline render, and chmod'd it after the
write. It now writes a temp file next to the target, chmods that, and
rename()s it into place.

The non-tmux direct-PTY fallback carries no exporter; that is now stated
at the spawn site and in the architecture-invariants paragraph rather
than left as a silent gap.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 15:59:00 +02:00
Codeman maintainer 707ea345eb fix(statusline): GET /api/settings never writes, and a save sends the collection switch only on a flip
Two follow-ups to #361's sticky telemetry switch.

GET /api/settings reconciled an absent showPlanUsageLimits by persisting
true, but readJsonConfig() answers {} for ANY read failure (a parse
error, EACCES, EMFILE, a read landing inside PUT's non-atomic write), not
only ENOENT, and every page load calls this route, so one unlucky read
replaced the whole settings file with a one-key file. The route is a
plain read again and the default moved into the reader:
readPlanUsageTelemetryEnabled() treats an absent key as ON, the same way
readWorkspaceHooksEnabled() does, which is what the desktop chip already
shows for an install that never touched the setting.

saveAppSettings() sent showPlanUsageLimits on every save. The chip
defaults OFF on handhelds, so a phone saving its font size persisted
false and switched collection off for every desktop, whose chip then
went stale with no error anywhere. The key is now stripped like the
other per-device display keys and re-added only when the save FLIPS the
chip relative to what the device had (planUsageCollectionFlip), so an
explicit toggle on any device still writes it in either direction.

Tests pin both: the GET route with a mocked filesystem (absent, missing,
EACCES, garbage, explicit), the reader default, and the flip helper plus
its wiring in saveAppSettings.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 15:59:00 +02:00
Ark0N b2b2c767ea Merge pull request #361 from timkjr/fix/statusline-injection-opt-out
fix(statusline): inject plan-usage telemetry via ephemeral CLI flag, never disk
2026-09-14 15:58:48 +02:00
timkjrandClaude Sonnet 5 aeb55c92b0 fix(settings): reconcile showPlanUsageLimits default on first read
planUsageChipEnabled() (settings-ui.js) shows the header chip and the App
Settings checkbox as already ON whenever showPlanUsageLimits has never been
set — a discoverability default from 1.9.3. readPlanUsageTelemetryEnabled()
(hooks-config.ts) deliberately treats an absent key as "no telemetry" — a
privacy default, pinned by its own unit tests (never POST usage data
without an explicit persisted yes). Nothing reconciled those two
independent guesses, so a fresh install showed a checked box that silently
collected nothing until the user opened Settings and hit Save at least
once.

Verified live: an install that had never touched this setting had no
showPlanUsageLimits key in settings.json at all, and its running Claude
process's argv carried no --settings flag — zero telemetry ever collected
despite the chip rendering as enabled.

GET /api/settings now persists the resolved default (true) the first time
the key is truly absent — not explicit false — so "chip visible" and
"telemetry collected" become the same fact. readPlanUsageTelemetryEnabled's
own absent-means-false contract is untouched; after this runs once the key
is never absent again, so that branch stays correct in isolation while
being unreachable in practice for any install that has ever called this
route. An explicit false set afterward is respected forever.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-10 19:10:25 -05:00
timkjrandClaude Sonnet 5 d5b75af628 fix(statusline): sticky telemetry collection, footer print-through, EOF fix
Responds to Ark0N's review round on the ephemeral-CLI-flag statusline
injection rework:

- Rebase-detail fixes: registry-gated telemetry eligibility via
  getCli(mode)?.capabilities.statusLineTelemetry instead of a hardcoded
  mode === 'claude' check, using the capability flag master's CLI-registry
  refactor already declares for exactly this purpose.

- Design question settled: sticky (a). Rather than persisting the toggle
  as a new field and threading it through every session-creation path
  (cron, Ralph Loop API, quick-start), eliminated the per-session field
  entirely. readPlanUsageTelemetryEnabled() (hooks-config.ts) reads the
  existing showPlanUsageLimits setting fresh from settings.json at every
  claude create/respawn (TmuxManager.createSession/respawnPane) - no
  per-session state to survive a restart, and it applies uniformly to
  every creation path for free, since they all flow through the same
  TmuxManager methods.

  This required fixing a real bug found along the way: showPlanUsageLimits
  was not actually round-tripping through settings.json on save -
  settings-ui.js explicitly excluded it from the PUT body as a pure
  per-device display key. It now flows through normally (both true and
  false); the load-side per-device merge behavior is unchanged.

  Removed entirely as a result: the statusLineTelemetry field from
  CreateSessionSchema/SettingsUpdateSchema, CreateSessionOptions/
  RespawnPaneOptions, Session._statusLineTelemetry (this is what makes
  the restart-persistence bug moot rather than patched), and the
  frontend send sites.

- Footer print-through restored: the no-user-statusline branch of the
  exporter script now runs the telemetry POST in the foreground so its
  own stdout becomes the in-terminal footer, falling back to a plain
  "codeman" marker only on curl failure.

- Background-subshell EOF fix: the wrap-a-real-statusline branch closes
  stdin too, not just stdout/stderr (`>/dev/null 2>&1 </dev/null &`) -
  the un-redirected subshell process itself, not curl, was what held a
  reader-to-EOF's pipe open for however long curl took to finish. Added
  curl --max-time 5 so a hung (not just refused) Codeman cannot wedge
  the render.

Tests: real-shell-execution tests for the footer/EOF fixes (fake curl
stand-in on PATH, real sh subprocess spawns, real elapsed-time
measurements - verified non-vacuous against a hand-reconstructed
old-style script), unit tests for readPlanUsageTelemetryEnabled.
Adapted two existing tests whose payloads referenced the removed field.
Fixed during independent code review: a stray indentation break and a
test exercising the wrong (legacy) exporter code path.

Docs synced: CLAUDE.md, docs/usage-limits-display-plan.md (old
disk-based section marked superseded, kept for history),
docs/architecture-invariants.md.

Full suite green: 352 files, 6780 passed, 12 skipped, 0 failed.
tsc/lint/format:check/frontend-syntax all clean.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-07 20:37:29 -05:00
timkjrandClaude Sonnet 5 e15e8e43e8 feat(statusline): wrap the user's own real statusline instead of skipping it
Now that the exporter no longer lives in a fixed per-case file, it can
compose with the user's actual configured statusline rather than just
backing off when one is found.

findEffectiveUserStatusLineCommand() walks Claude Code's own settings
precedence for a workspace: project-local .claude/settings.local.json
> project-shared .claude/settings.json > the user's global
~/.claude/settings.json. A legacy Codeman-marked entry left behind in
the project's own settings.local.json is never treated as a real user
command — it's skipped and precedence continues to the next layer.

The shared exporter script (bumped to a V2 marker so stale copies
self-heal) now fires the telemetry POST in a background subshell —
its own stdout/stderr discarded so nothing leaks into the visible
statusline, and confirmed non-blocking (~4ms, even against an
unreachable endpoint) — then, if the pane's environment carries
CODEMAN_USER_STATUSLINE_CMD, feeds it the same stdin blob and relays
its stdout as ours. Otherwise it falls back to the plain "codeman"
marker as before.

The discovered command is threaded to the pane via `tmux setenv
CODEMAN_USER_STATUSLINE_CMD` (_configureStatusLineUserCommand) rather
than embedded in the spawn command line, for the same
premature-shell-expansion reason as the parent commit: tmux stores a
setenv value verbatim and never re-parses it, so once shellescape()d
for that one command, the command's own $/quotes survive untouched
into the pane's environment.

Verified live via direct shell execution of the generated script
(both branches: fallback and user-command wrapping) before deploy.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015GyMnFWnUzc41TDeHg9juW
2026-09-07 19:18:36 -05:00
timkjrandClaude Sonnet 5 d4aa3c8cca fix(statusline): inject plan-usage telemetry via ephemeral CLI flag, never disk
Codeman's plan-usage chip wrote a statusLine.command into the case's
.claude/settings.local.json to receive Claude Code's rate_limits blob.
That file-based statusLine took precedence over the user's own
global/project statusline for ANY `claude` run in that directory,
including entirely outside Codeman, with no disclosure in the App
Settings UI (labeled only as a header-display toggle) and no way to
remove it once written (the removal code path was unreachable dead
code — nothing ever called it with false).

Replace the disk write with an EPHEMERAL `claude --settings
'{"statusLine":{...}}'` CLI flag, resolved fresh at spawn time
(resolveStatusLineCliCommand in hooks-config.ts) and merged with
effort/ultracode into one --settings object (buildClaudeSettingsFlag
in tmux-manager.ts, since Claude Code accepts only one --settings
flag). Never touches disk, so a plain `claude` run outside Codeman is
untouched. Self-healing: any legacy disk-written exporter from an
older build is stripped the first time a session starts in that
workspace again. Still respects a user's own hand-authored statusLine
(skips the flag entirely rather than overriding it).

Mid-fix bug found and fixed: the exporter's command legitimately
depends on $CODEMAN_SESSION_ID/$CODEMAN_API_URL/$CODEMAN_HOOK_SECRET_FILE
and an internal $INPUT, all meant to be expanded only when Claude Code
itself executes the statusline, using the pane's tmux-setenv'd
environment. Passing that text through --settings routed it through
execSync's own implicit /bin/sh -c first (tmux respawn-pane's
`bash -c "..."` wrapper) — POSIX double quotes don't suppress $
expansion, so those vars got expanded prematurely against the
server's own environment (unset there), producing malformed JSON that
printed as literal error text in the statusline. Fixed by writing the
exporter as a real, shared script file (ensureStatusLineExporterScript,
marker-versioned so stale copies self-heal) and passing only its bare
path via --settings — nothing for any intermediate shell to mangle.
Verified against a real Claude CLI on an isolated tmux socket, and via
direct execSync reproduction of the exact nested wrapping
createSession/respawnPane use.

A hard "never inject, even ephemerally" kill-switch was added and then
removed in the same pass: with the disk-leak fixed, disabling
injection only cost the plan-usage telemetry the feature exists to
provide, for no remaining benefit.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015GyMnFWnUzc41TDeHg9juW
2026-09-07 19:15:54 -05:00
31 changed files with 1169 additions and 178 deletions
-48
View File
@@ -1,48 +0,0 @@
---
'aicodeman': minor
---
`install.sh` and the Docker agent image now read the shipped CLI catalogue instead of
hand-maintaining their own lists.
Adding a CLI to `src/config/cli-registry/stock.ts` and running
`npm run generate:cli-catalog` wires it into the installer's detection, its install menu and
its closing reminder, and into the agent image's npm layer. Previously each of those was a
separate hand-written list that had to be kept in step and was not: upstream `b6d0f1fa` is
"wire OMP into install.sh's CLI detection (it had none)", where a user with only `omp`
installed was told no AI CLI was found and offered Claude Code, and the section comment above
that code named six of the nine CLIs.
The generator emits two committed artifacts, because neither consumer can import TypeScript:
`config/clis.stock.json` for the Docker build, and a marked block inside `install.sh` itself,
which runs via `curl | bash` before any checkout exists. The embedded copy is the FULL
catalogue: an earlier attempt fetched it and fell back to a hardcoded two-CLI list, degrading
silently on an empty response, and there is no degraded mode to fall into now — nor a network
fetch at all, since a `curl | bash` from master already carries a catalogue exactly as fresh as
the script itself.
**Trust model is unchanged and now mechanical.** The server still never executes an entry's
install command. `install.sh` executes only commands embedded in itself — same file, same TLS
fetch, same commit as the `curl | bash` line that fetched it — and nothing pulled from the
network at install time is ever run, because nothing is fetched at install time at all.
**The agent image respects `enabled`.** The generated catalogue carries that flag, so a CLI
shipping disabled is no longer baked into every image. It reads the stock catalogue rather than
the merged registry, so a user's `~/.codeman/clis.json` cannot change what is inside an image
tagged `codeman/agent:base`.
User-visible changes, all in the installer:
- The install menu is built from the catalogue, so it offers every enabled CLI with an install command that can drive a pane on its own — eight today, rather than the previous fixed two. Gemini had a command in the registry and appeared in no list in the script at all. DeepSeek is the one enabled CLI with a registry command that is deliberately NOT offered: `npm install -g @deepseek-ai/dsh` installs only the launcher, which ships no profile that can drive a terminal on its own, so choosing it used to leave the user with an AI CLI the installer considered "found" but that could not actually run anything. It still gets a hint pointing at its docs.
- Its entries use the registry's labels ("Claude" rather than "Claude Code"), the same trade already made for `codeman doctor` rows. A suffix map would just be the hand-maintained list again.
- On a `wget`-only host, only the menu entries that actually need `curl` are held back (still shown as copy-paste hints); the `npm install -g` entries, which never needed it, are unaffected. Rewriting `curl` to `wget` inside a string about to be executed is the wrong instinct either way.
- `CODEMAN_NONINTERACTIVE=1` still defaults to Claude Code, unchanged.
`install.sh` remains bash 3.2 compatible (macOS ships it): parallel indexed arrays with
offset/length windows instead of delimiters, no associative arrays, namerefs, `mapfile` or
here-strings. CI now runs `bash -n`, executes the script inside a real `bash:3.2` container —
which is what catches expanding an empty array under `set -u`, a runtime abort `bash -n` cannot
see — and checks the generated artifacts are in sync.
`docker/server.Dockerfile` is deliberately untouched; its narrower CLI list is now asserted as
a declared omission list so the divergence is visible rather than accidental.
+1 -1
View File
@@ -10,7 +10,7 @@
"name": "codeman",
"source": "./plugins/codeman",
"description": "Drive Codeman from inside a Claude Code session: spawn worker sessions, prompt them, wait for them, read their answers, clean up. Acts only inside a Codeman-managed session.",
"version": "1.28.1",
"version": "1.28.2",
"author": {
"name": "Ark0N",
"url": "https://github.com/Ark0N"
+73 -6
View File
@@ -1,5 +1,78 @@
# aicodeman
## 1.28.2
### Patch Changes
- **Terminal font weight** (#417, from discussion #403). App Settings → Terminal → Font gains two
per-device rows, Normal font weight and Bold font weight, each a select from Default plus 100 to 900. Claude Code marks bold with a bare `ESC[1m` and no colour change, so with a family that ships
only a regular and a bold face a bold heading reads as body text; setting normal to 300 turns that
one small step into an obvious one. Both slots resolve against their own xterm default (an unset
bold never inherits normal), apply live to the terminal, both echo overlays and open Agent Teams
panes, and the bundled JetBrains Mono `@font-face` is declared over the font's real 100 to 800 axis
instead of 400 to 700, without which every weight below 400 rendered identically to 400 on a stock
install.
**Phones up to 599px get the phone layout** (#390, fixes #389). The phone tier's cutoff moves
from 430px to 600px in the JS classifier, mobile.css and every test and doc that pins it, so the
iPhone Plus and Pro Max sizes, the Pixel Pro and the Z Fold cover display (430 to 460px) get the
phone header, the Enter key and the accessory bar instead of the tablet layout. Verified on a real
iPhone 17 Pro Max; a Safari page zoom below 100% widens the reported viewport, which is why the
cutoff is 600 rather than 480.
**The plan-usage statusline exporter no longer touches your settings files** (#361, diagnosed in
#405). Codeman used to write its exporter into a workspace's `.claude/settings.local.json`, which
Claude Code ranks above `~/.claude/settings.json`, so it replaced your own statusline for ANY
`claude` run in that directory, including outside Codeman, and rendered the bare word `codeman`
when run by hand. The exporter is now passed to `claude` as an ephemeral `--settings` flag when
Codeman spawns it and is never written to disk; your own statusline (project-local, project, then
`~/.claude/settings.json`) is wrapped and printed through inside Codeman sessions, and a hand-run
`claude` sees nothing of Codeman. Workspaces an older Codeman wrote to self-heal the first time a
session starts there. Telemetry collection follows the Plan Usage chip setting, read fresh at every
Claude session create and respawn; an absent setting means on, and a device writes the switch only
when it flips the chip, so a phone (chip off by default) saving its font size can no longer switch
collection off for the desktop. The exporter prints nothing when it cannot reach Codeman, the
telemetry route answers an unknown session with an empty body, and the footer is empty rather than
a brand word. Known limit: sessions inside a Docker case do not feed the chip yet (the flag rides
local spawns only; the chip is account-wide, so any local Claude session covers it).
**`install.sh` and the Docker agent image read the CLI catalogue** (#380). Adding a CLI to
`src/config/cli-registry/stock.ts` and running `npm run generate:cli-catalog` wires it into the
installer's detection, install menu and closing reminder, and into the agent image's npm layer;
each of those was a separate hand-kept list before, and OMP had been missing from the installer's
detection entirely. The install menu offers every enabled CLI that can drive a pane (eight, rather
than the fixed two), DeepSeek is deliberately withheld because `npm install -g @deepseek-ai/dsh`
installs only a launcher with no runnable profile, a wget-only host keeps the entries that never
needed curl, and the agent image respects `enabled`. The script stays bash 3.2 compatible and CI
now executes it inside a real `bash:3.2` container. Choosing "s" (Skip) in the menu continues to
the clone and build instead of aborting.
**iPhone Duo support** (#407). A visual-viewport resize that changes the WIDTH is the device
changing shape and is never read as the virtual keyboard: closing an iPhone Duo (626 to 466pt wide)
or rotating any phone used to latch the keyboard layout with no keyboard on screen, sticky until the
device was opened again. The seven centred overlays keep their dialogs out of the hinge through the
CSS Viewport Segments variables (inert on devices that do not fold), the phone path picker and
preview stay flush under 600px, and a shape change with the keyboard up baselines to the layout
viewport so the settle event after a rotation no longer closes the keyboard layout. Two Duo device
profiles join the test matrix.
**Codeman is its own Claude Code plugin marketplace.** `/plugin marketplace add Ark0N/Codeman`
followed by `/plugin install codeman@codeman` installs the codeman agent skill as a plugin, from
`plugins/codeman/` (a mirror of `skills/codeman/` kept byte-identical by a test), which is a small
separate directory on purpose: a plugin root carrying a `package.json` gets an `npm install` on
every installer's machine. A Claude Code holding both the plugin and a user-level or per-case copy
lists the skill twice; pick one route.
Housekeeping: the maintainer's Telegram PR bot moved out of this repository (it is a client of the
HTTP API like any other), the COM flow gained a Discussions announcement step, and the changelog's
Thanks sections were backfilled for 1.22.0 to 1.28.1.
### Thanks
- @irisitymichaelgrundberg for the font-weight analysis in #403 that this release implements, and the statusline diagnosis in #405
- @JDProfresh for the phone breakpoint fix (#390)
- @timkjr for moving the statusline exporter off disk (#361)
- @opticon454 for driving the installer and the agent image from the CLI catalogue (#380)
## 1.28.1
### Patch Changes
@@ -28,7 +101,6 @@
### Thanks
1.28.1 is a same-day follow-on to 1.28.0, so the thanks for this pair belong here too:
- **@shenlvkang-collab** for the path picker's typed-path jump and name/date sort (#399), and for the care in the edges: the retry is bounded to one parent level, a typo keeps the listing you had instead of resetting to the root, and a full file path lands in its folder with the entry already selected.
- **@irisitymichaelgrundberg** for Claude truecolor in panes (#409), and above all for flagging the one reading they could not prove: that suppressing truecolor may have made Claude's block collapse into the background rather than fixing anything. That paragraph is why this got measured instead of taken on trust, and the measurement changed the changelog.
- **@timkjr** for trapping Ctrl+Z in agent sessions (#404), for finding that Caps Lock flips `ev.key` to `'Z'` without setting `shiftKey` so a plain `=== 'z'` check misses exactly the keystroke the guard exists for, and for stating up front that an agent CLI already holds its tty with ISIG off rather than overselling the fix.
@@ -209,7 +281,6 @@
### Thanks
1.26.0 carries no contributor PRs of its own. It lands the day after 1.25.0, so the thanks for that pair belong here too:
- @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).
@@ -311,7 +382,6 @@
### Thanks
1.24.4 is a same-day follow-on to 1.24.3, so the thanks for that pair belong here too:
- @opticon454 for #349, and for a write-up that made an infrastructure PR quick to review
## 1.24.3
@@ -397,7 +467,6 @@
### Thanks
1.24.2 is a hotfix on top of 1.24.1, so the thanks for that pair belong here too:
- @opticon454 for #350, with a reproduction that made this a confirmation rather than a hunt
- @timkjr for reporting #352, and for finding it while verifying Docker support for someone else's PR
@@ -503,7 +572,6 @@
### Thanks
1.23.0 carries no contributor PRs of its own. It lands the day after 1.22.0, so the thanks for that pair belong here too:
- **@aakhter** built both halves of the new tab experience: the owner-scoped, server-authoritative tab-layout foundation with recipient-safe SSE publication and an unusually deep test suite (#335), and the resizable vertical session rail with accessible pointer/keyboard sizing and careful FitAddon handoff (#334). Fifth and sixth merged PRs, and the layout work also fixed real multi-user ordering leaks along the way.
## 1.22.0
@@ -519,7 +587,6 @@
- Fix the file preview's dead pop-out control: a real detach button now opens the previewed file in a browser tab (raw route for PDFs/images/media/text, converted-PDF preview for docx/pptx) and the copy button reports when a preview has no text to copy instead of silently doing nothing. Review-driven hardening for the new tab features: PUT /api/session-order drops unknown ids again instead of rejecting the whole write (a session deleted inside the browser's debounce window could silently lose the user's reorder), a failed mux restore no longer blocks explicit session/webview deletion for the process lifetime (the automated stale sweep stays fail-closed), and the vertical rail gains the axis-awareness the sidebar-only predicates missed: correct drag-reorder insertion, active-tab scroll-into-view, floating windows anchored beside rail tabs, connector redraws on rail scroll, server-seeded orientation applied on first load, a pre-paint stamp so vertical mode no longer flashes through the header strip, and a 12px session-name default matching the sidebar's historical size so untouched installs are not restyled.
### Thanks
- **@aakhter** built both halves of the new tab experience: the owner-scoped, server-authoritative tab-layout foundation with recipient-safe SSE publication and an unusually deep test suite (#335), and the resizable vertical session rail with accessible pointer/keyboard sizing and careful FitAddon handoff (#334). Fifth and sixth merged PRs, and the layout work also fixed real multi-user ordering leaks along the way.
## 1.21.0
+2 -2
View File
@@ -77,7 +77,7 @@ When user says "COM":
CI runs `npm run check:lockfile` on every push/PR, so lockfile drift fails the build even if the `version-packages` script is bypassed.
**Version**: 1.28.1 (must match `package.json`)
**Version**: 1.28.2 (must match `package.json`)
## Project Overview
@@ -209,7 +209,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
**Auto-resume on usage limit** (opt-in per session, top of the Respawn tab): when Claude halts on a subscription limit, `usage-limit-patterns.ts` (pure, unit-tested) parses the reset time and `SessionAutoOps` arms a timer for reset+2min, then sends Esc + `continue`. ⚠️ Respawn cycles are blocked while paused (`isLimitPaused` guard in `onIdleDetected`), which is what prevents `/clear` from wiping the paused conversation. Claude-mode only. → [architecture-invariants#auto-resume-on-usage-limit](docs/architecture-invariants.md#auto-resume-on-usage-limit)
**Plan-usage chip** (`showPlanUsageLimits`, per-device: desktop default **ON**, handhelds OFF via the mobile block in `getDefaultSettings()`): resolve it ONLY through `planUsageChipEnabled()` in settings-ui.js, which backs all three call sites (the App Settings checkbox, the chip's visibility, and the Claude `statusLineTelemetry` flag on session create). It renders compact Claude and Codex provider rows. Claude data comes from Codeman's marked `statusLine.command` exporter, which POSTs `rate_limits` to `POST /api/status-telemetry`, never overwrites a user's hand-authored statusLine, and prints the footer through. Main Codex usage comes from a read-only host `account/rateLimits/read` app-server poll at startup and every 5 minutes; exclude model-specific buckets such as Spark, and omit the Codex row when no signed-in limit is available. Distinct from auto-resume, which reacts to Claude's limit *message* rather than showing live %. → [architecture-invariants#plan-usage-chip-statusline-telemetry](docs/architecture-invariants.md#plan-usage-chip-statusline-telemetry), `docs/usage-limits-display-plan.md`
**Plan-usage chip** (`showPlanUsageLimits`, per-device: desktop default **ON**, handhelds OFF via the mobile block in `getDefaultSettings()`): resolve DISPLAY ONLY through `planUsageChipEnabled()` in settings-ui.js, which backs the two call sites that must never disagree (the App Settings checkbox, the chip's visibility). The SAME persisted setting also doubles as the server-side telemetry COLLECTION switch — `readPlanUsageTelemetryEnabled()` (hooks-config.ts) reads it fresh from `settings.json` at every claude session create/respawn (`TmuxManager.createSession`/`respawnPane`), so it applies uniformly to every claude-creation path (interactive Run, cron, Ralph Loop API, quick-start) with no per-session state and no per-request field — a Codeman restart cannot silently kill it (there is nothing per-session to lose). ⚠️ An ABSENT key reads as ON (mirroring `readWorkspaceHooksEnabled()`), so the default is resolved by the READER and `GET /api/settings` stays a plain read that never writes: a reconcile write there ran on every page load and could replace an unreadable `settings.json` with a one-key file. ⚠️ A save sends `showPlanUsageLimits` ONLY when it FLIPS the chip on that device (`planUsageCollectionFlip()` in settings-ui.js): the chip defaults OFF on handhelds, so a phone saving its font size used to persist `false` and switch collection off for every desktop. Claude data comes from Codeman's marked `statusLine.command` exporter (injected as an EPHEMERAL `claude --settings` CLI flag, never written to disk — see `resolveStatusLineCliCommand`), which POSTs `rate_limits` to `POST /api/status-telemetry`, never overwrites a user's hand-authored statusLine (it WRAPS it instead — `findEffectiveUserStatusLineCommand`), and prints the footer through. Main Codex usage comes from a read-only host `account/rateLimits/read` app-server poll at startup and every 5 minutes; exclude model-specific buckets such as Spark, and omit the Codex row when no signed-in limit is available. Distinct from auto-resume, which reacts to Claude's limit *message* rather than showing live %. → [architecture-invariants#plan-usage-chip-statusline-telemetry](docs/architecture-invariants.md#plan-usage-chip-statusline-telemetry), `docs/usage-limits-display-plan.md`
**Orchestrator**: State machine that turns a user goal into a phased plan and drives it to completion: `idle → planning → approval → executing → verifying → (replanning) → completed/failed`. `OrchestratorLoop` (engine) delegates plan generation to `orchestrator-planner` and per-phase verification gates to `orchestrator-verifier`, executing phases via team agents/`task-queue`. State persists under the `orchestrator` key in `state.json`. Distinct from Ralph (single-session autonomous loop) — orchestrator coordinates multi-phase, multi-agent execution. See `docs/orchestrator-loop-architecture.md`.
+1 -1
View File
@@ -92,7 +92,7 @@ Tests: `test/docker-hosts.test.ts`, `test/docker-exec-options.test.ts`, `test/do
### Plan-usage chip (statusLine telemetry)
**Plan-usage chip** (`showPlanUsageLimits`, per-device: desktop default **ON** since 1.9.3, handhelds OFF) renders compact Claude and Codex provider rows. Claude Code (v2.1.80+) pipes a JSON blob to a configured `statusLine.command` on each render; on Pro/Max it carries a `rate_limits` object (`five_hour`/`seven_day` windows only — no Opus weekly field — each `{used_percentage 0-100, resets_at epoch-SECONDS}`). Codeman injects its OWN statusLine exporter (`generateStatusLineCommand()` in `hooks-config.ts`, identified by the `/api/status-telemetry` marker — it only ever adds/updates/removes a statusLine that is _ours_, never a user's hand-authored one) that POSTs the blob to `POST /api/status-telemetry`. That route (auth-exempt like `/api/hook-event` — localhost-only, hook-secret-gated whenever auth is active, COD-91) parses via `usage-telemetry.ts` (pure, unit-tested), broadcasts SSE `session:statusTelemetry` (de-duped per session by `telemetrySignature` since the statusline fires on every assistant message), and returns a compact plain-text footer for the exporter to **print-through**. Main Codex subscription usage comes from the signed-in host CLI's read-only app-server `account/rateLimits/read` request at startup and every 5 minutes; `usage-telemetry.ts` selects only the main `codex` bucket (never model-specific buckets such as Spark), maps whatever 5-hour/7-day windows it supplies, and omits the provider row when unavailable. Credentials stay inside the CLI and no auth material is sent to the browser. `plan-usage-latest.ts` merges both process-wide sources and replays them in the SSE init snapshot (`getLightState`) so `#planUsageChip` renders immediately on page load/reconnect. `planUsageChipEnabled()` remains the single resolver behind the checkbox, chip visibility, and Claude create-time exporter flag. **Distinct from auto-resume** (which reacts to the Claude limit _message_; this proactively shows live percentages). Design: `docs/usage-limits-display-plan.md`. Tests: `test/usage-telemetry.test.ts`, `test/codex-plan-usage.test.ts`, `test/plan-usage-chip.test.ts`, `test/plan-usage-latest.test.ts`.
**Plan-usage chip** (`showPlanUsageLimits`, per-device: desktop default **ON** since 1.9.3, handhelds OFF) renders compact Claude and Codex provider rows. Claude Code (v2.1.80+) pipes a JSON blob to a configured `statusLine.command` on each render; on Pro/Max it carries a `rate_limits` object (`five_hour`/`seven_day` windows only — no Opus weekly field — each `{used_percentage 0-100, resets_at epoch-SECONDS}`). ⚠️ **Injected as an EPHEMERAL `claude --settings` CLI flag at spawn (2026-09-07), never written to disk** — `resolveStatusLineCliCommand()`/`ensureStatusLineExporterScript()` in `hooks-config.ts` (`generateStatusLineCommand()`/`applyStatusLineConfig()` remain, but only as the legacy disk-write self-heal path: a workspace an older Codeman build touched gets its stale `.claude/settings.local.json` entry stripped the first time a session starts there again). The exporter WRAPS a user's own real statusline (`findEffectiveUserStatusLineCommand()`, walking Claude Code's own settings precedence) rather than replacing it, and POSTs the `rate_limits` blob to `POST /api/status-telemetry`. That route (auth-exempt like `/api/hook-event` — localhost-only, hook-secret-gated whenever auth is active, COD-91) parses via `usage-telemetry.ts` (pure, unit-tested), broadcasts SSE `session:statusTelemetry` (de-duped per session by `telemetrySignature` since the statusline fires on every assistant message), and returns a compact plain-text footer for the exporter to **print-through** (foreground POST in the no-wrap branch so its own stdout becomes the footer, printing NOTHING on failure, `curl -sfk` plus `|| true`, since a bare brand word on the statusline is what discussion #405 opened with; backgrounded — `>/dev/null 2>&1 </dev/null &`, closing stdin too — only in the wrap branch, where the user's own command owns the footer; `curl --max-time 5` bounds a hung, not just refused, Codeman). Main Codex subscription usage comes from the signed-in host CLI's read-only app-server `account/rateLimits/read` request at startup and every 5 minutes; `usage-telemetry.ts` selects only the main `codex` bucket (never model-specific buckets such as Spark), maps whatever 5-hour/7-day windows it supplies, and omits the provider row when unavailable. Credentials stay inside the CLI and no auth material is sent to the browser. `plan-usage-latest.ts` merges both process-wide sources and replays them in the SSE init snapshot (`getLightState`) so `#planUsageChip` renders immediately on page load/reconnect. `planUsageChipEnabled()` remains the single resolver behind the checkbox and chip visibility (DISPLAY only) — the SAME `showPlanUsageLimits` setting also doubles as the server-side telemetry COLLECTION switch, read FRESH from `settings.json` by `readPlanUsageTelemetryEnabled()` at every claude session create/respawn (`TmuxManager.createSession`/`respawnPane`), never cached, with no per-session field and no per-request wire field — applies uniformly across every claude-creation path (interactive Run, cron, Ralph Loop API, quick-start) and survives a Codeman restart by construction (nothing per-session to lose). ⚠️ An ABSENT key reads as ON, the same way an absent `workspaceHooksEnabled` does: the desktop chip already shows as on for an install that never touched the setting, and the exporter posts only to this Codeman over loopback. Resolving the default in the reader is what keeps `GET /api/settings` a plain read. It briefly reconciled the key on first read (persisting `true` when absent), but `readJsonConfig()` answers `{}` for ANY read failure, not only ENOENT, and every page load hits that route, so one unlucky read replaced the whole settings file with a one-key file; pinned by `test/routes/system-routes-settings-get-plan-usage-default.test.ts`. ⚠️ The client sends `showPlanUsageLimits` in a settings save ONLY when that save FLIPS the chip relative to what the device had (`planUsageCollectionFlip()` in settings-ui.js): the chip defaults OFF on handhelds, so sending it on every save let a phone saving its font size persist `false` and switch collection off for every desktop, whose chip then went stale with no error anywhere. An explicit toggle on any device still writes the switch. Injection covers LOCAL tmux-spawned claude sessions only: the non-tmux direct-PTY fallback (`Session.startInteractive` when tmux is unavailable) and the remote/docker pane builders do not carry the flag. Registry-gated on `getCli(mode)?.capabilities.statusLineTelemetry` rather than a hardcoded mode string. **Distinct from auto-resume** (which reacts to the Claude limit _message_; this proactively shows live percentages). Design: `docs/usage-limits-display-plan.md`. Tests: `test/usage-telemetry.test.ts`, `test/codex-plan-usage.test.ts`, `test/plan-usage-chip.test.ts`, `test/plan-usage-latest.test.ts`, `test/hooks-config.test.ts` (statusline exporter script + `readPlanUsageTelemetryEnabled`), `test/statusline-cli-flag.test.ts`.
### Cron jobs
+12 -10
View File
@@ -2,6 +2,8 @@
> **Status: SHIPPED — deployed to prod + pushed to master, not yet released (2026-06-14).** App Settings → Display → **Plan Usage Limits** (`showPlanUsageLimits`). **Default changed in 1.9.3: desktop now defaults ON, handhelds stay OFF, resolved via `planUsageChipEnabled()`.** The per-device notes further down describing it as opt-in/synced record the original 2026-06-14 shape, not current behavior. Commits `c82f6c8` (feature) → `4d9d93d` (end-to-end fixes) → `eae225b` (per-user reconcile) → `95fb5fc` (init-snapshot replay). Full suite green (2869), CI green. No changeset/version bump yet.
>
> **2026-09-07 rework — the "Injection lifecycle" section below (disk-write reconcile via `applyStatusLineConfig`) is SUPERSEDED and describes the OLD mechanism, kept for history.** That disk write let a Codeman-marked `statusLine.command` in `.claude/settings.local.json` take precedence over the user's own global/project statusline for ANY `claude` run in that directory — including entirely outside Codeman — with no disclosure and no way to undo it (real bug, found 2026-08-31). The exporter is now injected as an EPHEMERAL `claude --settings` CLI flag at spawn (`resolveStatusLineCliCommand`/`ensureStatusLineExporterScript`, hooks-config.ts) — never written to disk — and it WRAPS the user's own real statusline (`findEffectiveUserStatusLineCommand`) rather than replacing it. `showPlanUsageLimits` now doubles as the telemetry COLLECTION switch too: `readPlanUsageTelemetryEnabled()` reads it fresh from `settings.json` at every claude session create/respawn (`TmuxManager.createSession`/`respawnPane`), so it applies uniformly across every claude-creation path — interactive Run, cron, the Ralph Loop API, quick-start — with no per-session state (a Codeman restart cannot silently kill it) and no per-request field on the wire at all. An absent key reads as ON (the reader resolves the default; `GET /api/settings` never writes), and a settings save carries the key only when it flips the chip on that device, so a handheld with the chip off cannot switch collection off for a desktop by saving something unrelated. The exporter prints nothing on failure rather than the bare word `codeman` (discussion #405).
>
> Two surfaces from one `statusLine` callback:
> - **Header chip** (top-right) — account-wide **plan limits**: `5h 35% · 7d 38%`, per-window green/yellow/red.
> - **In-terminal statusline footer** — the **current session's** status: `Opus 4.8 (1M context) in:562,411 out:1,188 ctx:56%`.
@@ -110,33 +112,33 @@ Fixed path (sessionId in the **body**, not the URL) so the auth exemption is an
2. **Fresh load / reconnect:** server stores the latest in `plan-usage-latest.ts`; `getLightState()` includes it as `planUsage`; the per-connection **init snapshot** replays it; `handleInit` paints the chip immediately (authoritative over localStorage). Null until the first telemetry of the process.
3. **Offline / cross-restart:** `restorePlanUsageChip()` reads `localStorage` on load (12h freshness guard).
### 5. Injection lifecycle — works for *any* user, never self-destructs
### 5. Injection lifecycle (SUPERSEDED 2026-09-07 — see header note; kept for history)
The setting `showPlanUsageLimits` is **synced** (in `settings.json`, not a per-device `displayKey`).
- **On toggle** (`PUT /api/settings`, `system-routes.ts`): reconcile the exporter across **all active Claude sessions' working dirs** — inject on enable, remove on disable. Server-side and authoritative, so existing sessions get the footer + feed the chip *immediately*, no new session needed, no dependency on a client's synced localStorage.
- **On session create** (`session-routes.ts`): **ADD-ONLY** — inject when `statusLineTelemetry` is true; **never remove**. Sessions in a repo share one `settings.local.json`, so a single create-with-false (e.g. a client whose synced setting hadn't loaded) must not yank the statusLine out from under other live sessions. Removal happens only via the explicit toggle.
- `applyStatusLineConfig()` is **`isOurs`-guarded** (matches `/api/status-telemetry`), so a user's own hand-authored statusLine is never touched, and it **updates an out-of-date ours-command** so fixes (e.g. `-k`) propagate. **No `CASES_DIR` gate** — runs for linked cases / real repos (where sessions actually run), mirroring `updateCaseModel`.
- ~~**On toggle** (`PUT /api/settings`, `system-routes.ts`): reconcile the exporter across **all active Claude sessions' working dirs** — inject on enable, remove on disable.~~ There is nothing to (re)inject into an already-running session under the new CLI-flag mechanism — the NEXT respawn (a Ralph cycle, `/clear`, a PTY-exit restart) already reads the setting fresh.
- ~~**On session create** (`session-routes.ts`): **ADD-ONLY** — inject when `statusLineTelemetry` is true; **never remove**.~~ There is no `statusLineTelemetry` request field anymore. `TmuxManager.createSession`/`respawnPane` read `readPlanUsageTelemetryEnabled()` fresh at spawn instead, uniformly across every claude-creation path.
- ~~`applyStatusLineConfig()` is **`isOurs`-guarded**~~ — `applyStatusLineConfig` still exists but only for the SELF-HEAL path now (`resolveStatusLineCliCommand` strips a legacy disk-written exporter the first time a session starts in a workspace an older Codeman build touched).
## Codeman-specific considerations
1. **Account-global limits.** The 5h/7d pools are shared across all sessions on the account → one shared header chip (freshest sample wins), not a per-tab bar.
2. **The footer is owned, by necessity.** A statusLine command always replaces Claude's default footer. Since `rate_limits` *only* arrives via statusLine, we reconstruct a useful **session-status** footer (model · tokens · ctx %) from the same payload rather than showing the limits there.
3. **`isOurs`-guarded.** Never removes/overwrites a user's own statusLine on disable; only manages the Codeman exporter.
3. **Never overwrites, now WRAPS.** The exporter composes with a user's own real statusline (`findEffectiveUserStatusLineCommand`) rather than replacing it; `applyStatusLineConfig`'s `isOurs`-guard now only backs the legacy self-heal removal path.
4. **Security envelope unchanged.** The exporter runs arbitrary shell every render — same trust model as the hook curls (localhost + `$CODEMAN_HOOK_SECRET_FILE`); reuses the hook-secret gate.
5. **Claude-only.** OpenCode/Codex emit no `rate_limits` JSON; injection is gated to `mode === 'claude'`.
5. **Claude-only, registry-gated.** Injection is gated on `getCli(mode)?.capabilities.statusLineTelemetry` (currently `true` only for claude) rather than a hardcoded `mode === 'claude'` string.
6. **Future — auto-resume synergy.** Live percentages would let `SessionAutoOps` pre-arm *before* the wall instead of reacting to the stall footer. Not built.
## Files shipped
- `src/usage-telemetry.ts` — pure parse/format (`parseStatusTelemetry`, `parseSessionStatus`, `formatSessionStatusText`, `telemetrySignature`) + `test/usage-telemetry.test.ts`.
- `src/hooks-config.ts` — `generateStatusLineCommand()` (`curl -sk`), `applyStatusLineConfig()` (add/update/remove, `isOurs`-guarded).
- `src/hooks-config.ts` — `resolveStatusLineCliCommand()`/`ensureStatusLineExporterScript()` (ephemeral CLI-flag injection, never disk), `findEffectiveUserStatusLineCommand()` (wrap the user's real statusline), `readPlanUsageTelemetryEnabled()` (fresh global-setting read), `applyStatusLineConfig()` (legacy self-heal removal only now).
- `src/session-cli-registry-bridge.ts` — merges the exporter path into the SAME `--settings` JSON object as effort/ultracode (Claude Code accepts only one `--settings` flag per invocation).
- `src/web/routes/status-telemetry-routes.ts` — `POST /api/status-telemetry`.
- `src/web/plan-usage-latest.ts` — process-wide last-known store for init replay.
- `src/web/schemas.ts` — `StatusTelemetrySchema` + `showPlanUsageLimits` + create-payload `statusLineTelemetry`.
- `src/web/schemas.ts` — `StatusTelemetrySchema` + `showPlanUsageLimits` (no separate create-payload or action field anymore).
- `src/web/middleware/auth.ts` — exemption extended to `/api/status-telemetry`.
- `src/web/routes/session-routes.ts` — add-only create-time injection.
- `src/web/routes/system-routes.ts` — settings-toggle reconcile.
- `src/tmux-manager.ts` — `createSession`/`respawnPane` read `readPlanUsageTelemetryEnabled()` fresh at spawn.
- `src/web/server.ts` — `getLightState().planUsage` (init snapshot).
- `src/web/sse-events.ts` + `constants.js` — `session:statusTelemetry`.
- Frontend: `app.js` (`_onSessionStatusTelemetry`, `updatePlanUsageChip`, `restorePlanUsageChip`, `handleInit`), `settings-ui.js` (toggle + `applyHeaderVisibilitySettings`), `index.html` (chip + toggle row), `styles.css` (chip + colors), `session-ui.js` (create payload).
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "aicodeman",
"version": "1.28.1",
"version": "1.28.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "aicodeman",
"version": "1.28.1",
"version": "1.28.2",
"hasInstallScript": true,
"license": "MIT",
"workspaces": [
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "aicodeman",
"version": "1.28.1",
"version": "1.28.2",
"description": "Mission control for AI coding agents - run 20 autonomous agents with real-time monitoring and session persistence",
"type": "module",
"main": "dist/index.js",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "codeman",
"description": "Drive Codeman, the self-hosted session manager for AI coding agents, from inside a Claude Code session: spawn worker sessions, prompt them, wait for them, read their answers, clean up. Acts only inside a Codeman-managed session.",
"version": "1.28.1",
"version": "1.28.2",
"author": {
"name": "Ark0N",
"url": "https://github.com/Ark0N"
+218 -6
View File
@@ -31,7 +31,7 @@
import { randomBytes } from 'node:crypto';
import { existsSync } from 'node:fs';
import { readFile, writeFile, mkdir, lstat, readdir, realpath, rename, unlink, rmdir } from 'node:fs/promises';
import { readFile, writeFile, mkdir, lstat, readdir, realpath, rename, unlink, rmdir, chmod } from 'node:fs/promises';
import { homedir } from 'node:os';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -39,6 +39,7 @@ import { fileURLToPath } from 'node:url';
import type { HookEventType } from './types.js';
import { HOOK_TIMEOUT_SECONDS } from './config/auth-config.js';
import { dataPath } from './config/instance.js';
import { readJsonConfig, SETTINGS_PATH } from './web/route-helpers.js';
/**
* Serializes read-modify-write access to a `settings.local.json` path. Every
@@ -855,17 +856,19 @@ const STATUSLINE_MARKER = '/api/status-telemetry';
* (present in every managed session via tmux setenv), so the config is static.
*/
export function generateStatusLineCommand(): string {
// `curl -sk`: CODEMAN_API_URL is loopback HTTPS with a self-signed cert in the
// `curl -sfk`: CODEMAN_API_URL is loopback HTTPS with a self-signed cert in the
// production setup; without -k curl returns 000 and the statusline shows
// nothing. -k is safe here (loopback only). Falls back to a brand string so the
// footer is never blank if Codeman is unreachable.
// nothing. -k is safe here (loopback only); -f keeps an HTTP error body off
// the statusline. On any failure it prints NOTHING: the old `|| echo codeman`
// is the bare word that a hand-run `claude` in a managed repo rendered, and
// that reads as a broken config (discussion #405).
return (
`INPUT=$(cat 2>/dev/null || echo '{}'); ` +
`printf '{"sessionId":"%s","data":%s}' "$CODEMAN_SESSION_ID" "$INPUT" | ` +
`curl -sk -X POST "$CODEMAN_API_URL${STATUSLINE_MARKER}" ` +
`curl -sfk -X POST "$CODEMAN_API_URL${STATUSLINE_MARKER}" ` +
`-H 'Content-Type: application/json' ` +
`-H "X-Codeman-Hook-Secret: $(cat "$CODEMAN_HOOK_SECRET_FILE" 2>/dev/null)" ` +
`--data @- 2>/dev/null || echo codeman`
`--data @- 2>/dev/null || true`
);
}
@@ -906,6 +909,215 @@ export async function applyStatusLineConfig(casePath: string, enabled: boolean):
});
}
/**
* Version-agnostic marker embedded as a comment in the generated exporter
* SCRIPT (see ensureStatusLineExporterScript) — bump the numeric suffix
* whenever the script content changes so `ensureStatusLineExporterScript`'s
* content comparison rewrites stale copies on next use.
*/
const STATUSLINE_EXPORTER_SCRIPT_MARKER = 'CODEMAN_STATUSLINE_EXPORTER_V4';
function statusLineExporterScriptContent(): string {
// Where the telemetry POST runs depends on who owns the footer. When the pane's
// env carries CODEMAN_USER_STATUSLINE_CMD (set via tmux setenv by TmuxManager
// when findEffectiveUserStatusLineCommand found the user's own REAL statusLine —
// see that function's doc comment), the user's command owns the footer, so the
// POST runs in a BACKGROUND subshell with stdin/stdout/stderr all closed
// (`>/dev/null 2>&1 </dev/null &`) — closing stdout/stderr keeps it from adding
// latency or leaking into the visible statusline, and closing stdin too is what
// lets a host reading this script's own stdout to EOF (`sh script | cat`) see
// that EOF promptly: without it the backgrounded curl keeps the pipe's write end
// open until IT exits, so the reader blocks for however long curl takes (measured
// ~5s with a stand-in) instead of the ~9ms it takes once stdin is closed too.
// Absent a user statusline, NOTHING else will print the footer, so the POST runs
// in the FOREGROUND and ITS OWN stdout becomes the footer — `/api/status-telemetry`
// returns formatSessionStatusText(...) (model/tokens/context %) precisely so this
// can happen. If curl itself fails (refused/unreachable Codeman, or an HTTP
// error, which `-f` keeps off stdout) the footer is simply EMPTY (`|| true`):
// the old `|| echo codeman` rendered a bare brand word that reads as a broken
// config, the symptom discussion #405 opened with. `--max-time` bounds a
// HUNG (not just refused) Codeman so it cannot wedge the render indefinitely.
const post =
`printf '{"sessionId":"%s","data":%s}' "$CODEMAN_SESSION_ID" "$INPUT" | ` +
`curl -sfk --max-time 5 -X POST "$CODEMAN_API_URL${STATUSLINE_MARKER}" ` +
`-H 'Content-Type: application/json' ` +
`-H "X-Codeman-Hook-Secret: $(cat "$CODEMAN_HOOK_SECRET_FILE" 2>/dev/null)" ` +
`--data @-`;
return (
`#!/bin/sh\n` +
`# ${STATUSLINE_EXPORTER_SCRIPT_MARKER} — auto-generated by Codeman; safe to delete, regenerated on demand.\n` +
`INPUT=$(cat 2>/dev/null || echo '{}')\n` +
`if [ -n "$CODEMAN_USER_STATUSLINE_CMD" ]; then\n` +
` ( ${post} ) >/dev/null 2>&1 </dev/null &\n` +
` printf '%s' "$INPUT" | sh -c "$CODEMAN_USER_STATUSLINE_CMD"\n` +
`else\n` +
` ${post} 2>/dev/null || true\n` +
`fi\n`
);
}
async function readStatusLineCommandFromFile(settingsPath: string): Promise<string | undefined> {
if (!existsSync(settingsPath)) return undefined;
try {
const parsed = JSON.parse(await readFile(settingsPath, 'utf-8'));
const current = parsed.statusLine as { command?: unknown } | undefined;
return current && typeof current.command === 'string' ? current.command : undefined;
} catch {
return undefined; // Malformed — treat as absent, same posture as applyStatusLineConfig.
}
}
/**
* Walk Claude Code's OWN settings precedence for `workingDir` to find whatever
* statusLine command is ACTUALLY effective there right now: project-local
* `.claude/settings.local.json` > project-shared `.claude/settings.json` >
* the user's global `~/.claude/settings.json`. Returns undefined when none of
* the three configures one.
*
* A legacy Codeman-marked entry in the project's OWN settings.local.json
* (written by an older build's disk-based mechanism) is never treated as a
* real user command — resolveStatusLineCliCommand strips it before this ever
* runs, so ordinarily this function never even sees one; the marker check
* here is a second, defensive guard in case something else wrote a copy in
* between, and precedence simply continues to the next layer instead of
* stopping on it.
*/
export async function findEffectiveUserStatusLineCommand(workingDir: string): Promise<string | undefined> {
const projectLocal = await readStatusLineCommandFromFile(join(workingDir, '.claude', 'settings.local.json'));
if (projectLocal && !projectLocal.includes(STATUSLINE_MARKER)) return projectLocal;
const projectShared = await readStatusLineCommandFromFile(join(workingDir, '.claude', 'settings.json'));
if (projectShared) return projectShared;
return readStatusLineCommandFromFile(join(homedir(), '.claude', 'settings.json'));
}
/**
* Write (or refresh) the SHARED, single exporter script every claude session
* points its ephemeral --settings statusLine flag at, and return its absolute
* path. Idempotent: only rewrites when the marker-versioned content differs.
*
* This is the fix for a real bug found live 2026-08-31: the exporter's
* command string legitimately depends on `$CODEMAN_SESSION_ID`,
* `$CODEMAN_API_URL`, `$CODEMAN_HOOK_SECRET_FILE`, and its own internal
* `$INPUT` — all meant to be expanded ONLY when Claude Code itself finally
* executes the statusLine command, using the PANE's tmux-setenv'd
* environment. Passing that command as literal TEXT through
* `--settings '...'` routes it through this server's OWN spawn-time shell
* layers first (tmux respawn-pane's `bash -c "..."`, itself invoked via
* execSync's implicit `/bin/sh -c`) — and POSIX double quotes do NOT
* suppress `$` expansion, so those vars got expanded there and then, against
* the SERVER process's environment (where they are unset), producing a
* mangled curl call that posted malformed JSON and printed the server's raw
* error response as the statusline text itself. A bare file PATH has no `$`,
* quotes, or pipes for any of those intermediate shells to mangle — the
* script's own content (containing the real `$VAR`s) is never touched by a
* shell until Claude Code executes the file itself, at which point the
* pane's real environment is in scope. This mirrors the existing #208 fix in
* tmux-manager.ts (never embed a literal `$SHELL` meant for later
* expansion — resolve it, or in this case reference a file, instead).
*/
export async function ensureStatusLineExporterScript(): Promise<string> {
const scriptPath = dataPath('statusline-exporter.sh');
const desired = statusLineExporterScriptContent();
let current: string | null = null;
try {
current = await readFile(scriptPath, 'utf-8');
} catch {
// Doesn't exist yet.
}
if (current !== desired) {
// Temp file + rename: live sessions execute this script on every statusline
// render, and a truncate-then-write (plus a chmod AFTER the write) opened two
// windows in which Claude Code could run an empty or non-executable file.
// rename() swaps the complete, already-executable file in atomically.
const tmpPath = `${scriptPath}.${process.pid}.${Date.now()}.tmp`;
await writeFile(tmpPath, desired);
await chmod(tmpPath, 0o755);
await rename(tmpPath, scriptPath);
}
return scriptPath;
}
/**
* Whether plan-usage telemetry collection is CURRENTLY wanted — read FRESH
* from the persisted `showPlanUsageLimits` setting on every call, never
* cached and never per-session. Reusing that setting rather than inventing a
* second persisted flag: it's the SAME boolean the App Settings chip checkbox
* already writes (see `planUsageChipEnabled()` in settings-ui.js).
*
* This is what lets the on/off decision survive a Codeman restart (there is
* no per-session state to lose — see the now-removed `Session._statusLineTelemetry`,
* which WAS such a per-session field and went stale on every restart) and
* apply uniformly across every claude session-creation path — interactive
* create, cron, the Ralph Loop API, quick-start — with none of them needing
* to thread a request-time flag through: they all already construct a
* session via TmuxManager.createSession/respawnPane, which reads this at
* spawn time.
*
* An ABSENT key means ON, mirroring readWorkspaceHooksEnabled() above: the
* client shows the chip and its checkbox as already on for a desktop that has
* never touched the setting (planUsageChipEnabled() in settings-ui.js), and
* the exporter only ever posts to THIS Codeman over loopback, so the honest
* default for an install that never said otherwise is the one the user can
* see. Resolving the default here, in the reader, is what lets
* `GET /api/settings` stay a plain read: a reconcile write there ran on every
* page load and could replace an unreadable settings.json with a one-key
* file. Only an explicit `false` (a save that flipped the chip off on some
* device) turns collection off.
*/
export async function readPlanUsageTelemetryEnabled(): Promise<boolean> {
const settings = await readJsonConfig<Record<string, unknown>>(SETTINGS_PATH, 'settings.json', {});
return settings.showPlanUsageLimits !== false;
}
/**
* Resolve the statusLine command to pass as an EPHEMERAL `claude --settings`
* CLI flag for this one process (see buildSpawnCommandFromRegistry in
* session-cli-registry-bridge.ts) — never written to disk. This supersedes
* the old applyStatusLineConfig(path, true) disk-write: a file-based
* statusLine leaked into any plain `claude` run in that directory outside
* Codeman entirely (it took precedence over the user's own global/project
* statusline with no disclosure and no way to remove it — found live
* 2026-08-31).
*
* Also self-heals: if an OLDER Codeman build already wrote its marked
* exporter into this workspace's settings.local.json, it is stripped here
* (isOurs-guarded, same as applyStatusLineConfig's removal branch) so every
* workspace migrates off the disk-based mechanism the first time a session
* starts there again — no manual cleanup required. This self-heal runs
* regardless of `telemetryEnabled`, so a legacy leftover is cleaned up even
* while the setting is currently off.
*
* Returns undefined when telemetry isn't currently enabled (see
* readPlanUsageTelemetryEnabled), or when the workspace already has its OWN
* hand-configured statusLine (never override a real one).
*/
export async function resolveStatusLineCliCommand(
casePath: string,
telemetryEnabled: boolean
): Promise<string | undefined> {
const settingsPath = join(casePath, '.claude', 'settings.local.json');
let userHasOwnStatusLine = false;
if (existsSync(settingsPath)) {
try {
const existing = JSON.parse(await readFile(settingsPath, 'utf-8'));
const current = existing.statusLine as { command?: unknown } | undefined;
if (current && typeof current.command === 'string') {
if (current.command.includes(STATUSLINE_MARKER)) {
await applyStatusLineConfig(casePath, false); // strip legacy disk-written exporter
} else {
userHasOwnStatusLine = true;
}
}
} catch {
// Malformed — leave it alone, same guard applyStatusLineConfig itself uses.
}
}
if (!telemetryEnabled || userHasOwnStatusLine) return undefined;
return ensureStatusLineExporterScript();
}
// ─── Agent skill injection ───────────────────────────────────────────────────
/**
+25 -2
View File
@@ -56,6 +56,14 @@ export interface SpawnBridgeOptions {
effort?: EffortLevel;
sessionName?: string;
claudeCliVersion?: string | null;
/**
* Resolved by resolveStatusLineCliCommand (hooks-config.ts) — undefined skips the
* exporter. Claude only. Rides the SAME `--settings` JSON object as `effortSettingsJson`
* (see buildSpawnCommandFromRegistry): Claude Code accepts only one `--settings` flag
* per invocation, so the two must be merged before reaching the argv engine rather than
* rendered as two independent params.
*/
statusLineCommand?: string;
}
/**
@@ -186,8 +194,23 @@ export function buildSpawnCommandFromRegistry(entry: CliEntry, options: SpawnBri
// than re-deriving the ultracode special case) keeps the EFFORT_LEVELS allowlist and the
// settings-JSON shape single-sourced in session-cli-builder.ts.
const [effortFlag, effortValue] = buildEffortCliArgs(options.effort);
if (effortFlag === '--settings') engineValues.effortSettingsJson = effortValue;
else if (effortFlag === '--effort') engineValues.effortLevel = effortValue;
if (effortFlag === '--effort') {
engineValues.effortLevel = effortValue;
}
// Fold the ephemeral plan-usage statusLine exporter (see resolveStatusLineCliCommand in
// hooks-config.ts) into the SAME `--settings` JSON object as ultracode/ effort, since Claude
// Code accepts only one `--settings` flag per invocation — rendering them as two independent
// params would let the second one silently win. Claude-only in practice (statusLineCommand
// is resolved claude-mode-only upstream), but this merge is mode-agnostic.
if ((effortFlag === '--settings' && effortValue) || options.statusLineCommand) {
const settingsObj: Record<string, unknown> =
effortFlag === '--settings' && effortValue ? JSON.parse(effortValue) : {};
if (options.statusLineCommand) {
settingsObj.statusLine = { type: 'command', command: options.statusLineCommand };
}
engineValues.effortSettingsJson = JSON.stringify(settingsObj);
}
// Preserves buildSpawnCommand's original fallback exactly: an EXPLICIT `undefined` probes
// the local claude CLI (getClaudeCliVersion, null under vitest); an explicit `null` means
+6 -1
View File
@@ -2174,7 +2174,12 @@ export class Session extends EventEmitter {
}
try {
// Pass --session-id to use the SAME ID as the Codeman session
// This ensures subagents can be directly matched to the correct tab
// This ensures subagents can be directly matched to the correct tab.
// No plan-usage statusLine exporter on this path: the ephemeral
// `--settings` injection (resolveStatusLineCliCommand, hooks-config.ts)
// is wired into the tmux spawn builders only, so a direct-PTY session
// has no Claude telemetry in the header chip. Documented in
// architecture-invariants (Plan-usage chip); tmux is the supported path.
const args = buildInteractiveArgs(
this.id,
this._claudeMode,
+63
View File
@@ -67,6 +67,11 @@ import {
legacyConfigForMode,
} from './session-cli-registry-bridge.js';
import type { CliEntry } from './config/cli-registry/types.js';
import {
resolveStatusLineCliCommand,
readPlanUsageTelemetryEnabled,
findEffectiveUserStatusLineCommand,
} from './hooks-config.js';
import {
buildSshConnectionArgs,
defaultRemoteCommandForMode,
@@ -728,6 +733,8 @@ export function buildSpawnCommand(options: {
ompConfig?: OmpConfig;
resumeSessionId?: string;
effort?: EffortLevel;
/** Resolved by resolveStatusLineCliCommand (hooks-config.ts) — undefined skips the exporter. Claude only. */
statusLineCommand?: string;
/** Codeman session name, passed to claude as `--name` (version-gated, sanitized; local spawns only). */
sessionName?: string;
/**
@@ -1832,6 +1839,38 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
}
}
/**
* Export the user's own REAL statusLine command (found by
* findEffectiveUserStatusLineCommand) via tmux setenv, so the shared
* exporter script (statusLineExporterScriptContent in hooks-config.ts) can
* wrap it. Via setenv rather than embedding it in the spawn command line:
* tmux stores a setenv value verbatim and never re-parses it as shell
* syntax, so once safely escaped for THIS one command, the command's own
* `$`/quotes survive untouched into the claude process's environment — the
* same reasoning that made the exporter script itself necessary (see
* ensureStatusLineExporterScript's doc comment). Only this ONE line needs
* shellescape(); the stored value itself is opaque to tmux from then on.
*
* With NO user command the variable is UNSET rather than left alone: a tmux
* setenv survives respawn-pane, so a user who deleted their own statusline
* would otherwise keep getting the stale one wrapped (and lose Codeman's
* footer print-through) until the tmux session was recreated. Same shape as
* the CLAUDE_CODE_EFFORT_LEVEL cleanup in applyEnvOverrides.
*/
private _configureStatusLineUserCommand(muxName: string, command: string | undefined): void {
const setOrUnset = command
? `CODEMAN_USER_STATUSLINE_CMD ${shellescape(command)}`
: '-u CODEMAN_USER_STATUSLINE_CMD';
try {
execSync(`${this.tmux()} setenv -t ${shellescape(muxName)} ${setOrUnset}`, {
timeout: EXEC_TIMEOUT_MS,
stdio: 'ignore',
});
} catch {
// Non-critical: the exporter prints its own footer, or nothing.
}
}
/**
* Creates a new tmux session wrapping Claude CLI or a shell.
* In test mode: creates an in-memory session only (no real tmux session).
@@ -1915,6 +1954,19 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
const envExportsStr = this.buildEnvExports(sessionId, muxName, mode).join(' && ');
// Registry-gated (capabilities.statusLineTelemetry — claude only today), local
// spawns only (remote/docker have their own separate command builders — out of
// scope here). Also self-heals: strips any legacy disk-written exporter from an
// older Codeman build the first time a session starts in that workspace again.
const statusLineCommand =
getCli(mode)?.capabilities.statusLineTelemetry && !remote && !docker
? await resolveStatusLineCliCommand(workingDir, await readPlanUsageTelemetryEnabled())
: undefined;
// The user's own REAL statusLine, if any (walked via Claude Code's own
// settings precedence) — exported below so the shared exporter script
// can wrap it. Only worth discovering when we're actually injecting.
const userStatusLineCommand = statusLineCommand ? await findEffectiveUserStatusLineCommand(workingDir) : undefined;
const baseCmd = buildSpawnCommand({
mode,
sessionId,
@@ -1931,6 +1983,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
ompConfig,
resumeSessionId,
effort,
statusLineCommand,
sessionName: name,
});
@@ -1993,6 +2046,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
mode,
legacyConfigForMode(mode, options as unknown as Record<string, unknown>)
);
this._configureStatusLineUserCommand(muxName, userStatusLineCommand);
// Apply user-supplied env overrides (e.g., CLAUDE_CODE_EFFORT_LEVEL) via tmux setenv
// so secret values stay off the bash command line. Must run before respawn-pane.
@@ -2170,6 +2224,13 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
const envExportsStr = this.buildEnvExports(sessionId, muxName, mode).join(' && ');
// See createSession()'s identical resolution for rationale.
const statusLineCommand =
getCli(mode)?.capabilities.statusLineTelemetry && !remote && !docker
? await resolveStatusLineCliCommand(workingDir, await readPlanUsageTelemetryEnabled())
: undefined;
const userStatusLineCommand = statusLineCommand ? await findEffectiveUserStatusLineCommand(workingDir) : undefined;
const baseCmd = buildSpawnCommand({
mode,
sessionId,
@@ -2186,6 +2247,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
ompConfig,
resumeSessionId,
effort,
statusLineCommand,
sessionName: name,
});
const config = niceConfig || DEFAULT_NICE_CONFIG;
@@ -2205,6 +2267,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
mode,
legacyConfigForMode(mode, options as unknown as Record<string, unknown>)
);
this._configureStatusLineUserCommand(muxName, userStatusLineCommand);
// Re-apply user env overrides before respawn so the new shell inherits them.
this.applyEnvOverrides(muxName, envOverrides);
+6 -3
View File
@@ -173,10 +173,13 @@ export function parseSessionStatus(data: RawStatuslinePayload | undefined): Sess
* Format the in-terminal statusline footer: the CURRENT SESSION's status —
* `Opus 4.8 (1M context) in:562,411 out:1,188 ctx:56%` — NOT the plan limits,
* which live in the Codeman header chip. Claude requires a statusLine command to
* emit the rate_limits JSON at all, so this is what that command prints back.
* emit the rate_limits JSON at all, so this is what that command prints back
* when it has no statusline of the user's own to wrap. With nothing to show it
* returns '' rather than a brand word: a bare `codeman` on the statusline is
* the symptom discussion #405 opened with.
*/
export function formatSessionStatusText(s: SessionStatus | null): string {
if (!s) return 'codeman';
if (!s) return '';
const groups: string[] = [];
if (s.modelDisplayName) groups.push(s.modelDisplayName);
const tok: string[] = [];
@@ -184,7 +187,7 @@ export function formatSessionStatusText(s: SessionStatus | null): string {
if (s.outputTokens != null) tok.push(`out:${withCommas(s.outputTokens)}`);
if (tok.length) groups.push(tok.join(' '));
if (s.contextUsedPercentage != null) groups.push(`ctx:${Math.round(clampPct(s.contextUsedPercentage))}%`);
return groups.length ? groups.join(' ') : 'codeman';
return groups.length ? groups.join(' ') : '';
}
/**
-7
View File
@@ -1062,13 +1062,6 @@ Object.assign(CodemanApp.prototype, {
...(hasEnvOverrides ? { envOverrides } : {}),
...(effort ? { effort } : {}),
...(modelOverride !== undefined ? { modelOverride } : {}),
// Plan-usage statusLine exporter (App Settings → Display). The server
// ADDS our exporter on create when true; when false it intentionally
// leaves any existing exporter in place (a per-repo settings.local.json
// is shared by sibling sessions, so create-with-false must not yank it
// — see the comment in session-routes create). Disabling the setting
// removes it via the App Settings toggle path (system-routes), not here.
statusLineTelemetry: this.planUsageChipEnabled(globalSettings),
})
}).then(r => r.json())
);
+38 -15
View File
@@ -2310,15 +2310,23 @@ Object.assign(CodemanApp.prototype, {
// Save to server (includes notification prefs for cross-browser persistence).
// Strip device-specific DISPLAY keys so they never sync across devices —
// localEcho/cjk/extendedKeyboard/skin are per-platform, and showPlanUsageLimits
// is per-device too (desktop can show the usage chip while mobile stays hidden).
// localEcho/cjk/extendedKeyboard/skin are per-platform.
// webglRendererEnabled is per-device as well (renderer choice is GPU-specific,
// and syncing would leak mobile's hidden-checkbox false onto desktop); it's
// also absent from SettingsUpdateSchema, which is .strict() — sending it
// would 400 the whole settings PUT.
// Telemetry COLLECTION is requested out-of-band via statusLineTelemetry (sent on
// ENABLE only, so a device with the chip OFF never strips the exporter that
// another device's chip depends on — see system-routes settings handler).
// showPlanUsageLimits is per-device for DISPLAY (loadAppSettingsFromServer
// only seeds it into localStorage when a device has no value yet, like every
// other display key) but ALSO doubles as the server-side plan-usage telemetry
// COLLECTION switch (readPlanUsageTelemetryEnabled in hooks-config.ts, read
// fresh at every claude session create/respawn). So it is stripped here like
// the others and re-added below ONLY when this save FLIPS it on this device
// (planUsageCollectionFlip): the chip defaults OFF on handhelds, so sending
// it on every save let a phone saving its font size persist `false` and
// switch collection off for every desktop, whose chip then went stale with
// no error anywhere. An explicit toggle on any device still writes it, in
// either direction.
const _chipFlip = this.planUsageCollectionFlip(_prev, settings.showPlanUsageLimits);
const {
localEchoEnabled: _leo,
cjkInputEnabled: _cjk,
@@ -2360,7 +2368,7 @@ Object.assign(CodemanApp.prototype, {
try {
const res = await this._apiPut('/api/settings', {
...serverSettings,
...(settings.showPlanUsageLimits ? { statusLineTelemetry: true } : {}),
...(_chipFlip !== undefined ? { showPlanUsageLimits: _chipFlip } : {}),
notificationPreferences: notifPrefsToSave,
voiceSettings,
});
@@ -2624,15 +2632,28 @@ Object.assign(CodemanApp.prototype, {
// Resolved per-device state of the plan-usage chip. Desktop defaults ON,
// handhelds default OFF (the mobile block in getDefaultSettings() sets false,
// and the mobile-header-buttons-policy guard depends on that staying false).
// Single source of truth for THREE call sites that must never disagree: the
// App Settings checkbox, the chip's visibility, and the statusLineTelemetry
// flag sent on session create. A chip shown without telemetry renders "—"
// forever, which is exactly the drift this helper prevents.
// Single source of truth for the two call sites that must never disagree:
// the App Settings checkbox and the chip's visibility. Telemetry COLLECTION
// no longer has a THIRD client-side call site here at all — the server reads
// this same persisted setting directly (readPlanUsageTelemetryEnabled in
// hooks-config.ts), fresh, at every claude session create/respawn.
planUsageChipEnabled(settings = null) {
const s = settings ?? this.loadAppSettingsFromStorage();
return s.showPlanUsageLimits ?? this.getDefaultSettings().showPlanUsageLimits ?? true;
},
// What a settings save tells the server about plan-usage COLLECTION: the new
// chip value when this save FLIPS it relative to what this device resolved
// before (stored value, else the per-device default), otherwise undefined,
// meaning "say nothing". The server reads an absent key as ON, so a device
// that never touched the chip leaves collection alone, and a handheld (chip
// default OFF) cannot switch it off for every desktop by saving its font
// size. Pure so test/plan-usage-collection-flip.test.ts can drive it.
planUsageCollectionFlip(prevSettings, now) {
const before = this.planUsageChipEnabled(prevSettings ?? {});
return now === before ? undefined : now;
},
applyHeaderVisibilitySettings() {
const settings = this.loadAppSettingsFromStorage();
const defaults = this.getDefaultSettings();
@@ -3127,11 +3148,13 @@ Object.assign(CodemanApp.prototype, {
'sessionLineageLines',
]);
// The plan-usage chip is a PER-DEVICE display setting (desktop default ON,
// handheld default OFF): desktop can show it while mobile stays hidden. It
// used to sync, so an older server.json may still carry a value — drop it
// so the server value is NEVER
// seeded into a device that didn't explicitly enable it (collection is handled
// separately via the statusLineTelemetry action, not this display flag).
// handheld default OFF): desktop can show it while mobile stays hidden. Drop
// the server's stored value here so it is NEVER seeded into a device that
// didn't explicitly enable it — even though this SAME setting also drives
// server-side telemetry collection now (readPlanUsageTelemetryEnabled in
// hooks-config.ts), that's a read the server does directly from settings.json
// at spawn time; it has nothing to do with what gets merged into THIS
// device's local display preference.
delete appSettings.showPlanUsageLimits;
// Merge settings: non-display keys always sync from server,
// display keys only seed from server when localStorage has no value
+13 -22
View File
@@ -94,7 +94,6 @@ import {
writeHooksConfig,
updateCaseModel,
stripCaseEnvKeys,
applyStatusLineConfig,
applyAgentSkill,
refreshUserAgentSkill,
seedAgentSessionPreamble,
@@ -949,27 +948,19 @@ export function registerSessionRoutes(
await updateCaseModel(workingDir, body.modelOverride || null);
}
// Plan-usage statusLine exporter (App Settings → Display → "Plan Usage
// Limits"). Claude-only; runs for ANY working dir (linked cases / real repos,
// where most sessions live), mirroring updateCaseModel above.
//
// ADD-ONLY: we never remove on create. Sessions in a repo share one
// settings.local.json, so a single create-with-false (e.g. a client whose
// synced setting hadn't loaded yet) must NOT yank the statusLine out from
// under other live sessions in that repo — that breaks their footer + the
// chip's data feed for everyone. The exporter is benign when the chip is off
// (the footer just shows session status). isOurs-guarded so a user's own
// statusLine is never touched.
//
// Same guard as the hooks call below (499d355): never for a remote attach
// (workingDir is a user@host:session pseudo-path — the mkdir inside
// applyStatusLineConfig would create it as a junk local dir), and only when
// the caller named a workingDir — the process-cwd fallback is $HOME under
// installer-created services, and a statusLine materializing in
// ~/.claude/settings.local.json was never asked for.
if (!remote && body.workingDir && (body.mode ?? 'claude') === 'claude' && body.statusLineTelemetry === true) {
await applyStatusLineConfig(workingDir, true);
}
// Plan-usage telemetry (App Settings → header chip): no request-time field
// here anymore, and NO disk write — a settings.local.json statusLine used
// to take precedence over the user's own global/project statusLine for ANY
// `claude` run in that directory, including entirely outside Codeman, with
// no disclosure and no way to undo it (real bug, found 2026-08-31).
// TmuxManager.createSession reads the persisted `showPlanUsageLimits`
// setting FRESH at spawn (readPlanUsageTelemetryEnabled in hooks-config.ts)
// and resolves it into an EPHEMERAL `claude --settings` CLI flag — never
// written to disk, so a plain `claude` run outside Codeman is untouched —
// and applies uniformly to every claude creation path (this route, cron,
// the Ralph Loop API, quick-start), not just this one. That resolution
// also self-heals: it strips any legacy disk-written exporter an older
// Codeman build left behind.
// Hooks for the workspace this session runs in (install vs refresh-only is the
// `workspaceHooksEnabled` setting; see applyWorkspaceHooks). Never for a remote
+6 -4
View File
@@ -8,8 +8,9 @@
* (localhost-only; hook-secret-gated while a tunnel runs — see middleware/auth).
*
* Returns a compact plain-text status string for the exporter to print as the
* in-terminal footer (print-through), so injecting our statusLine doesn't leave
* the terminal footer blank.
* in-terminal footer (print-through) when it has no statusline of the user's
* own to wrap. An unknown session gets an EMPTY body: the old brand-word
* answer rendered as the statusline itself (discussion #405).
*/
import { FastifyInstance } from 'fastify';
@@ -36,10 +37,11 @@ export function registerStatusTelemetryRoutes(app: FastifyInstance, ctx: Session
reply.type('text/plain; charset=utf-8');
// Unknown session — minimal footer, no broadcast.
// Unknown session: nothing to broadcast and nothing to print. Never a brand
// word here, it would render as the statusline.
if (!ctx.sessions.has(sessionId)) {
lastSig.delete(sessionId);
return 'codeman';
return '';
}
const payload = data as RawStatuslinePayload | undefined;
+32 -22
View File
@@ -5,7 +5,6 @@
*/
import { FastifyInstance } from 'fastify';
import { getCli } from '../../config/cli-registry/registry.js';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { existsSync, mkdirSync, readdirSync } from 'node:fs';
@@ -33,7 +32,6 @@ import {
import { subagentWatcher } from '../../subagent-watcher.js';
import { imageWatcher } from '../../image-watcher.js';
import { workflowRunWatcher } from '../../workflow-run-watcher.js';
import { applyStatusLineConfig } from '../../hooks-config.js';
import { getLifecycleLog } from '../../session-lifecycle-log.js';
import {
buildAwayDigest,
@@ -938,6 +936,17 @@ export function registerSystemRoutes(
// ========== Settings ==========
app.get('/api/settings', async () => {
// A plain read. This route must NEVER write settings.json: readJsonConfig()
// answers `{}` for ANY read failure (a parse error, EACCES, EMFILE, a read
// that lands inside PUT's non-atomic write), not only for a missing file,
// and every page load calls this route, so a "persist the default when the
// key is absent" reconcile here replaced a whole settings file with one key
// on the first unlucky read. The plan-usage default is resolved by the
// READERS instead: an absent `showPlanUsageLimits` means ON to
// readPlanUsageTelemetryEnabled() (hooks-config.ts), the same way an absent
// `workspaceHooksEnabled` means ON, and the client resolves its own display
// default through planUsageChipEnabled(). Pinned by
// test/routes/system-routes-settings-get-plan-usage-default.test.ts.
return readJsonConfig(SETTINGS_PATH, 'settings', {});
});
@@ -992,9 +1001,9 @@ export function registerSystemRoutes(
} catch {
/* ignore */
}
// statusLineTelemetry and acknowledgeUnauthTunnel are ACTION fields (not stored
// settings) — strip them before persisting so settings.json stays clean.
const { statusLineTelemetry, acknowledgeUnauthTunnel, ...settingsToStore } = settings;
// acknowledgeUnauthTunnel is an ACTION field (not a stored setting) — strip
// it before persisting so settings.json stays clean.
const { acknowledgeUnauthTunnel, ...settingsToStore } = settings;
const merged = { ...existing, ...settingsToStore };
await fs.writeFile(SETTINGS_PATH, JSON.stringify(merged, null, 2));
@@ -1007,7 +1016,7 @@ export function registerSystemRoutes(
// Service toggles resolve from `merged` (existing + incoming), NEVER from the
// raw request body. A PARTIAL PUT omits keys it does not intend to change, and
// reading the body directly turned every omission into "apply the default":
// a body of just `{statusLineTelemetry:true}` would START the subagent watcher
// a body of just `{showPlanUsageLimits:true}` would START the subagent watcher
// (`?? true`) and STOP the workflow + image watchers (`?? false`), silently
// undoing the user's persisted config. Reading `merged` makes any PUT reconcile
// services to the effective stored settings instead, which also self-heals
@@ -1033,22 +1042,23 @@ export function registerSystemRoutes(
}
});
// Plan-usage chip: its DISPLAY is per-device (client-side, see settings-ui.js).
// Telemetry COLLECTION is server-side and enable-sticky — when a client turns
// the chip ON it sends statusLineTelemetry:true and we (re)inject our exporter
// into every ACTIVE Claude session's working dir so the live % starts flowing
// immediately (no new session needed). We deliberately never auto-REMOVE here:
// the exporter is benign/print-through and a per-repo settings.local.json is
// shared by sibling sessions, so one device's "off" must not yank the exporter
// another device's chip depends on. Each dir handled once.
if (statusLineTelemetry === true) {
const dirs = new Set<string>();
for (const session of ctx.sessions.values()) {
if (getCli(session.mode)?.capabilities.statusLineTelemetry && session.workingDir)
dirs.add(session.workingDir);
}
await Promise.all([...dirs].map((dir) => applyStatusLineConfig(dir, true).catch(() => {})));
}
// Plan-usage chip: its DISPLAY is per-device (client-side, see settings-ui.js),
// but `showPlanUsageLimits` ALSO doubles as the telemetry COLLECTION switch,
// persisted here in settingsToStore like any other setting (no special-casing
// needed — see readPlanUsageTelemetryEnabled's doc comment in hooks-config.ts).
// Telemetry COLLECTION used to be a SEPARATE, action-only, sticky mechanism
// here: toggling the chip ON re-injected a statusLine.command into every
// ACTIVE Claude session's settings.local.json so live % started flowing
// without a new session. That disk write was the bug fixed 2026-08-31 (it
// took precedence over the user's own statusline for ANY `claude` run in
// that directory, including outside Codeman, with no way to undo it).
// Collection is now decided by TmuxManager.createSession/respawnPane reading
// `showPlanUsageLimits` FRESH from settings.json at spawn time — no
// per-session field, no per-request threading through cron/Ralph-loop/
// quick-start/interactive-create (they all reach the same read), and no
// (re)injection into an already-running session needed here: the NEXT
// respawn (a Ralph cycle, `/clear`, a PTY-exit restart) already picks up
// whatever this PUT just persisted.
// Handle tunnel toggle dynamically
if ('tunnelEnabled' in settings) {
+6 -8
View File
@@ -524,8 +524,6 @@ export const CreateSessionSchema = z.object({
effort: effortLevelSchema,
/** Model override to write to .claude/settings.local.json (e.g., "opus[1m]"). Empty string clears. */
modelOverride: z.string().max(50).optional(),
/** Inject the Claude statusLine source for the shared plan-usage chip. Claude sessions only; Codex is host-polled. */
statusLineTelemetry: z.boolean().optional(),
openCodeConfig: OpenCodeConfigSchema,
codexConfig: CodexConfigSchema,
geminiConfig: GeminiConfigSchema,
@@ -1298,13 +1296,13 @@ export const SettingsUpdateSchema = z
showFileBrowser: z.boolean().optional(),
showSubagents: z.boolean().optional(),
showMultiMonitorButton: z.boolean().optional(),
// Doubles as the plan-usage telemetry COLLECTION switch, read fresh from
// disk by readPlanUsageTelemetryEnabled() (hooks-config.ts) at every claude
// session create/respawn — not just the chip's DISPLAY preference. See that
// function's doc comment for why one persisted field serves both. Absent
// means ON there, and the client sends it only on a save that flips the
// chip (planUsageCollectionFlip in settings-ui.js), never on every save.
showPlanUsageLimits: z.boolean().optional(),
// Action field (NOT persisted as a setting): when true, (re)injects the
// plan-usage statusLine exporter into active Claude sessions so live usage %
// starts flowing. Sent on ENABLE only — the chip's DISPLAY is per-device
// (client-side), but telemetry COLLECTION is server-side, so the per-device
// toggle signals it out-of-band here rather than via showPlanUsageLimits.
statusLineTelemetry: z.boolean().optional(),
showRedrawButton: z.boolean().optional(),
// Input
gestureControlEnabled: z.boolean().optional(),
+4 -1
View File
@@ -1450,7 +1450,10 @@ export class WebServer extends EventEmitter {
// PER-DEVICE by the client (settings-ui.js applyHeaderVisibilitySettings). It
// used to be server-revealed from a synced setting, but that leaked the desktop
// choice onto mobile — display is now per-device only (like the response viewer).
// Telemetry collection stays server-side via the statusLineTelemetry action.
// Telemetry collection stays server-side, reading `showPlanUsageLimits` fresh
// from settings.json at every claude session create/respawn (see
// readPlanUsageTelemetryEnabled in hooks-config.ts) — the same setting this
// display-visibility check reads, doing double duty.
// Detached single-session ("solo") window: inject the target session id so
// the client can enter solo mode even if a (network-first) service worker
// later serves a cached shell. The client primarily detects solo mode from
+310 -2
View File
@@ -6,17 +6,34 @@
*/
import { describe, it, expect, beforeAll, beforeEach, afterAll, afterEach } from 'vitest';
import { closeSync, existsSync, openSync, readFileSync, writeFileSync, mkdirSync, rmSync, symlinkSync } from 'node:fs';
import {
chmodSync,
closeSync,
existsSync,
openSync,
readFileSync,
writeFileSync,
mkdirSync,
rmSync,
symlinkSync,
statSync,
readdirSync,
} from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { SETTINGS_PATH } from '../src/web/route-helpers.js';
import { tmpdir, homedir } from 'node:os';
import { spawn } from 'node:child_process';
import {
applyStatusLineConfig,
ensureCodemanHooks,
findEffectiveUserStatusLineCommand,
generateBackgroundWakeScript,
generateHooksConfig,
generateStatusLineCommand,
generateSubagentStopGuardScript,
readPlanUsageTelemetryEnabled,
refreshStaleCodemanHooks,
resolveStatusLineCliCommand,
settingsWriteBlocker,
stripCaseEnvKeys,
updateCaseEnvVars,
@@ -1305,3 +1322,294 @@ describe('Hook Config Generation - Extended', () => {
expect(stopHooks[0].hooks[0].command).toContain('stop');
});
});
describe('readPlanUsageTelemetryEnabled', () => {
const backup = existsSync(SETTINGS_PATH) ? readFileSync(SETTINGS_PATH, 'utf-8') : null;
afterEach(() => {
if (backup !== null) {
writeFileSync(SETTINGS_PATH, backup);
} else {
rmSync(SETTINGS_PATH, { force: true });
}
});
it('reads true fresh from the persisted showPlanUsageLimits setting', async () => {
mkdirSync(join(SETTINGS_PATH, '..'), { recursive: true });
writeFileSync(SETTINGS_PATH, JSON.stringify({ showPlanUsageLimits: true }));
expect(await readPlanUsageTelemetryEnabled()).toBe(true);
});
it('reads false when the setting is explicitly false', async () => {
mkdirSync(join(SETTINGS_PATH, '..'), { recursive: true });
writeFileSync(SETTINGS_PATH, JSON.stringify({ showPlanUsageLimits: false }));
expect(await readPlanUsageTelemetryEnabled()).toBe(false);
});
it('defaults to true when the setting is absent or the file is missing (mirrors readWorkspaceHooksEnabled)', async () => {
// The desktop chip shows as ON for an install that never touched the
// setting, so collection must agree with it. Resolving the default HERE
// is what keeps GET /api/settings a plain read (see its route test).
rmSync(SETTINGS_PATH, { force: true });
expect(await readPlanUsageTelemetryEnabled()).toBe(true);
mkdirSync(join(SETTINGS_PATH, '..'), { recursive: true });
writeFileSync(SETTINGS_PATH, JSON.stringify({ someOtherSetting: true }));
expect(await readPlanUsageTelemetryEnabled()).toBe(true);
});
it('only an explicit false turns collection off; junk values read as on', async () => {
mkdirSync(join(SETTINGS_PATH, '..'), { recursive: true });
writeFileSync(SETTINGS_PATH, JSON.stringify({ showPlanUsageLimits: 'no' }));
expect(await readPlanUsageTelemetryEnabled()).toBe(true);
});
it('never caches — a change on disk is visible on the very next call', async () => {
mkdirSync(join(SETTINGS_PATH, '..'), { recursive: true });
writeFileSync(SETTINGS_PATH, JSON.stringify({ showPlanUsageLimits: false }));
expect(await readPlanUsageTelemetryEnabled()).toBe(false);
writeFileSync(SETTINGS_PATH, JSON.stringify({ showPlanUsageLimits: true }));
expect(await readPlanUsageTelemetryEnabled()).toBe(true);
});
});
describe('resolveStatusLineCliCommand', () => {
const testDir = join(tmpdir(), 'codeman-statusline-cli-test-' + Date.now());
beforeEach(() => {
mkdirSync(testDir, { recursive: true });
});
afterEach(() => {
rmSync(testDir, { recursive: true, force: true });
});
it('returns undefined when telemetry was not requested', async () => {
expect(await resolveStatusLineCliCommand(testDir, false)).toBeUndefined();
});
it('returns a bare exporter SCRIPT PATH (never the inline command) when requested', async () => {
// A bare path has no `$`, quotes, or pipes for any intermediate shell
// layer to mangle — see ensureStatusLineExporterScript's doc comment for
// the real bug this guards against.
const cmd = await resolveStatusLineCliCommand(testDir, true);
expect(cmd).toBeDefined();
expect(cmd).not.toContain('$');
expect(cmd).not.toContain("'");
expect(cmd).toMatch(/^\/.*statusline-exporter\.sh$/);
expect(existsSync(cmd!)).toBe(true);
const stat = statSync(cmd!);
expect(stat.mode & 0o111).not.toBe(0); // executable
expect(readFileSync(cmd!, 'utf-8')).toContain('CODEMAN_STATUSLINE_EXPORTER_V');
});
it('refreshes a stale exporter script atomically: executable on arrival, no temp file left behind', async () => {
const scriptPath = (await resolveStatusLineCliCommand(testDir, true))!;
// Simulate a script an older build wrote (different marker suffix).
writeFileSync(scriptPath, '#!/bin/sh\n# CODEMAN_STATUSLINE_EXPORTER_V0\necho stale\n');
chmodSync(scriptPath, 0o644);
const again = await resolveStatusLineCliCommand(testDir, true);
expect(again).toBe(scriptPath);
expect(readFileSync(scriptPath, 'utf-8')).not.toContain('echo stale');
expect(statSync(scriptPath).mode & 0o111).not.toBe(0);
const siblings = readdirSync(join(scriptPath, '..')).filter((f) => f.startsWith('statusline-exporter.sh.'));
expect(siblings).toEqual([]);
});
it('never overrides a real, hand-authored statusLine', async () => {
const claudeDir = join(testDir, '.claude');
mkdirSync(claudeDir, { recursive: true });
writeFileSync(
join(claudeDir, 'settings.local.json'),
JSON.stringify({ statusLine: { type: 'command', command: 'echo my-own-prompt' } }, null, 2)
);
expect(await resolveStatusLineCliCommand(testDir, true)).toBeUndefined();
// The user's own config is untouched — this is a read-only decision, not a write.
const parsed = JSON.parse(readFileSync(join(claudeDir, 'settings.local.json'), 'utf-8'));
expect(parsed.statusLine.command).toBe('echo my-own-prompt');
});
it('self-heals: strips a legacy disk-written exporter from an older Codeman build', async () => {
// Simulate a workspace touched by the pre-fix applyStatusLineConfig(dir, true).
await applyStatusLineConfig(testDir, true);
const settingsPath = join(testDir, '.claude', 'settings.local.json');
expect(JSON.parse(readFileSync(settingsPath, 'utf-8')).statusLine).toBeDefined();
const cmd = await resolveStatusLineCliCommand(testDir, true);
// Cleaned off disk...
expect(JSON.parse(readFileSync(settingsPath, 'utf-8')).statusLine).toBeUndefined();
// ...and telemetry still flows, via the ephemeral CLI flag instead.
expect(cmd).toMatch(/statusline-exporter\.sh$/);
});
it('does not resurrect the legacy exporter when telemetry is off during cleanup', async () => {
await applyStatusLineConfig(testDir, true);
const settingsPath = join(testDir, '.claude', 'settings.local.json');
const cmd = await resolveStatusLineCliCommand(testDir, false);
expect(cmd).toBeUndefined();
expect(JSON.parse(readFileSync(settingsPath, 'utf-8')).statusLine).toBeUndefined();
});
});
describe('statusline exporter script (real shell execution)', () => {
const testDir = join(tmpdir(), 'codeman-statusline-script-exec-test-' + Date.now());
const binDir = join(tmpdir(), 'codeman-statusline-script-exec-bin-' + Date.now());
beforeEach(() => {
mkdirSync(testDir, { recursive: true });
mkdirSync(binDir, { recursive: true });
});
afterEach(() => {
rmSync(testDir, { recursive: true, force: true });
rmSync(binDir, { recursive: true, force: true });
});
// A stand-in for the real `curl` binary, placed FIRST on PATH — same technique
// the exporter's own review used ("an arg-echoing stand-in"). It ignores every
// arg curl would have received; only its own scripted behavior matters here.
function writeFakeCurl(script: string): void {
const curlPath = join(binDir, 'curl');
writeFileSync(curlPath, `#!/bin/sh\n${script}\n`);
chmodSync(curlPath, 0o755);
}
function runExporter(
env: Record<string, string>
): Promise<{ code: number | null; stdout: string; durationMs: number }> {
return resolveStatusLineCliCommand(testDir, true).then(
(scriptPath) =>
new Promise((resolve, reject) => {
const start = Date.now();
const child = spawn('sh', [scriptPath!], {
env: { ...env, PATH: `${binDir}:${process.env.PATH}` },
stdio: ['pipe', 'pipe', 'ignore'],
});
let stdout = '';
child.stdout.setEncoding('utf8');
child.stdout.on('data', (chunk) => {
stdout += chunk;
});
child.on('error', reject);
child.on('close', (code) => resolve({ code, stdout, durationMs: Date.now() - start }));
child.stdin.end('{}');
})
);
}
const baseEnv = {
CODEMAN_SESSION_ID: 'x',
CODEMAN_API_URL: 'http://127.0.0.1:1',
CODEMAN_HOOK_SECRET_FILE: '/dev/null',
};
it('no-user-statusline branch: the POST runs in the foreground and its OWN stdout becomes the footer', async () => {
writeFakeCurl(`echo 'model: opus | 42% used'`);
const result = await runExporter(baseEnv);
expect(result.stdout.trim()).toBe('model: opus | 42% used');
});
it('no-user-statusline branch: prints NOTHING when curl fails (never a bare brand word)', async () => {
writeFakeCurl(`exit 1`);
const result = await runExporter(baseEnv);
expect(result.stdout).toBe('');
expect(result.code).toBe(0);
});
it('asks curl to fail on HTTP errors (-f) so an error body never becomes the footer', async () => {
const scriptPath = await resolveStatusLineCliCommand(testDir, true);
expect(readFileSync(scriptPath!, 'utf-8')).toContain('curl -sfk');
expect(readFileSync(scriptPath!, 'utf-8')).not.toContain('echo codeman');
});
it('wrap branch: never blocks a reader-to-EOF on a slow/hung curl (background subshell closes stdin too)', async () => {
writeFakeCurl(`sleep 3`);
const result = await runExporter({ ...baseEnv, CODEMAN_USER_STATUSLINE_CMD: 'echo my-own-statusline' });
expect(result.stdout.trim()).toBe('my-own-statusline');
expect(result.durationMs).toBeLessThan(1000);
}, 10000);
it('curl is bounded with --max-time so a HUNG (not just refused) Codeman cannot wedge the render', async () => {
const scriptPath = await resolveStatusLineCliCommand(testDir, true);
expect(readFileSync(scriptPath!, 'utf-8')).toContain('--max-time');
});
});
describe('findEffectiveUserStatusLineCommand', () => {
const testDir = join(tmpdir(), 'codeman-statusline-precedence-test-' + Date.now());
const userSettingsPath = join(homedir(), '.claude', 'settings.json');
beforeEach(() => {
mkdirSync(testDir, { recursive: true });
});
afterEach(() => {
rmSync(testDir, { recursive: true, force: true });
rmSync(userSettingsPath, { force: true }); // don't leak into other tests sharing this HOME
});
it('returns undefined when nothing is configured anywhere', async () => {
expect(await findEffectiveUserStatusLineCommand(testDir)).toBeUndefined();
});
it('finds the user global ~/.claude/settings.json when nothing else is set', async () => {
const userClaudeDir = join(homedir(), '.claude');
mkdirSync(userClaudeDir, { recursive: true });
writeFileSync(
join(userClaudeDir, 'settings.json'),
JSON.stringify({ statusLine: { type: 'command', command: 'echo user-global' } })
);
expect(await findEffectiveUserStatusLineCommand(testDir)).toBe('echo user-global');
});
it('project-SHARED settings.json wins over user-global', async () => {
const userClaudeDir = join(homedir(), '.claude');
mkdirSync(userClaudeDir, { recursive: true });
writeFileSync(
join(userClaudeDir, 'settings.json'),
JSON.stringify({ statusLine: { type: 'command', command: 'echo user-global' } })
);
const projectClaudeDir = join(testDir, '.claude');
mkdirSync(projectClaudeDir, { recursive: true });
writeFileSync(
join(projectClaudeDir, 'settings.json'),
JSON.stringify({ statusLine: { type: 'command', command: 'echo project-shared' } })
);
expect(await findEffectiveUserStatusLineCommand(testDir)).toBe('echo project-shared');
});
it('project-LOCAL settings.local.json wins over everything', async () => {
const projectClaudeDir = join(testDir, '.claude');
mkdirSync(projectClaudeDir, { recursive: true });
writeFileSync(
join(projectClaudeDir, 'settings.json'),
JSON.stringify({ statusLine: { type: 'command', command: 'echo project-shared' } })
);
writeFileSync(
join(projectClaudeDir, 'settings.local.json'),
JSON.stringify({ statusLine: { type: 'command', command: 'echo project-local' } })
);
expect(await findEffectiveUserStatusLineCommand(testDir)).toBe('echo project-local');
});
it('skips a legacy Codeman-marked entry in project settings.local.json and falls through', async () => {
await applyStatusLineConfig(testDir, true); // simulates a pre-fix disk-written exporter
const projectClaudeDir = join(testDir, '.claude');
writeFileSync(
join(projectClaudeDir, 'settings.json'),
JSON.stringify({ statusLine: { type: 'command', command: 'echo project-shared' } })
);
expect(await findEffectiveUserStatusLineCommand(testDir)).toBe('echo project-shared');
});
});
+78
View File
@@ -0,0 +1,78 @@
/**
* `planUsageCollectionFlip()` in settings-ui.js: the one place that decides
* whether a settings save carries `showPlanUsageLimits` to the server.
*
* The chip is per-device for DISPLAY (desktop default ON, handhelds OFF) but
* the same persisted key is the server-side telemetry COLLECTION switch, read
* at every claude spawn. Sending it on every save let a phone saving its font
* size persist `false` and turn collection off for every desktop. So the save
* sends the key ONLY when it flips the chip relative to what the device had,
* and the server reads an absent key as ON.
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import vm from 'node:vm';
import { describe, expect, it } from 'vitest';
const SOURCE = readFileSync(resolve(import.meta.dirname, '../src/web/public/settings-ui.js'), 'utf8');
function loadSettingsUi(defaultChip: boolean) {
const CodemanApp = function CodemanApp(this: unknown) {};
const context = vm.createContext({
CodemanApp,
VoiceInput: {},
localStorage: { getItem: () => null, setItem: () => {} },
document: { getElementById: () => null },
console,
});
vm.runInContext(SOURCE, context, { filename: 'settings-ui.js' });
const app = Object.create(CodemanApp.prototype) as {
getDefaultSettings: () => { showPlanUsageLimits: boolean };
planUsageCollectionFlip: (prev: Record<string, unknown> | null, now: boolean) => boolean | undefined;
};
app.getDefaultSettings = () => ({ showPlanUsageLimits: defaultChip });
return app;
}
describe('planUsageCollectionFlip', () => {
it('says nothing when a desktop that never touched the chip saves with it still on', () => {
const desktop = loadSettingsUi(true);
expect(desktop.planUsageCollectionFlip({}, true)).toBeUndefined();
expect(desktop.planUsageCollectionFlip(null, true)).toBeUndefined();
});
it('says nothing when a handheld (chip default OFF) saves an unrelated setting', () => {
const phone = loadSettingsUi(false);
expect(phone.planUsageCollectionFlip({ terminalFontSize: 14 }, false)).toBeUndefined();
expect(phone.planUsageCollectionFlip({ showPlanUsageLimits: false }, false)).toBeUndefined();
});
it('sends false only on the save that turned the chip off', () => {
const desktop = loadSettingsUi(true);
expect(desktop.planUsageCollectionFlip({}, false)).toBe(false);
expect(desktop.planUsageCollectionFlip({ showPlanUsageLimits: true }, false)).toBe(false);
expect(desktop.planUsageCollectionFlip({ showPlanUsageLimits: false }, false)).toBeUndefined();
});
it('sends true when any device, a handheld included, turns the chip on', () => {
const phone = loadSettingsUi(false);
expect(phone.planUsageCollectionFlip({}, true)).toBe(true);
expect(phone.planUsageCollectionFlip({ showPlanUsageLimits: false }, true)).toBe(true);
expect(phone.planUsageCollectionFlip({ showPlanUsageLimits: true }, true)).toBeUndefined();
});
});
describe('saveAppSettings wiring', () => {
it('strips showPlanUsageLimits from the synced payload and re-adds it only through the flip', () => {
const save = SOURCE.slice(
SOURCE.indexOf('async saveAppSettings()'),
SOURCE.indexOf('closeAppSettings()', SOURCE.indexOf('async saveAppSettings()'))
);
// Stripped from serverSettings like the other per-device display keys.
expect(save).toMatch(/showPlanUsageLimits: _pul,/);
// Decided once against the device's prior settings, before they are overwritten.
expect(save).toMatch(/const _chipFlip = this\.planUsageCollectionFlip\(_prev, settings\.showPlanUsageLimits\);/);
// And only a real flip reaches the PUT body.
expect(save).toMatch(/\.\.\.\(_chipFlip !== undefined \? \{ showPlanUsageLimits: _chipFlip \} : \{\}\),/);
});
});
@@ -156,7 +156,7 @@ describe('POST /api/sessions workspace hooks', () => {
const cwdSettings = join(process.cwd(), '.claude', 'settings.local.json');
const before = existsSync(cwdSettings) ? await readFile(cwdSettings, 'utf-8') : null;
const res = await createSession({ name: 'hooks-no-dir', mode: 'claude', statusLineTelemetry: true });
const res = await createSession({ name: 'hooks-no-dir', mode: 'claude' });
expect(res.statusCode).toBe(200);
const after = existsSync(cwdSettings) ? await readFile(cwdSettings, 'utf-8') : null;
@@ -166,8 +166,9 @@ describe('POST /api/sessions workspace hooks', () => {
it('never writes hooks for a remote attach (workingDir is a user@host pseudo-path)', async () => {
// A claude-mode attachRemoteSession create overwrites workingDir with
// `user@host:session` — locally a RELATIVE path, so a mkdir would create it
// as a junk directory under the server cwd. statusLineTelemetry rides along:
// applyStatusLineConfig mkdirs the same way and used to run for remote attaches.
// as a junk directory under the server cwd. The statusLine exporter rides
// along: applyStatusLineConfig mkdirs the same way and used to run for
// remote attaches.
// SAFETY (2026-08-29): write straight to `getDataDir()` — `test/setup.ts`
// already sandboxes the data dir for the whole file (temp HOME, inherited
// CODEMAN_DATA_DIR stripped; same convention as the docker-hosts fixtures
@@ -188,7 +189,6 @@ describe('POST /api/sessions workspace hooks', () => {
const res = await createSession({
name: 'hooks-remote',
mode: 'claude',
statusLineTelemetry: true,
attachRemoteSession: { hostId: 'h1', remoteSessionName: 'codeman-ssh-abc123' },
});
expect(res.statusCode).toBe(200);
+2 -2
View File
@@ -49,10 +49,10 @@ describe('POST /api/status-telemetry', () => {
});
});
it('does not broadcast for an unknown session; returns the brand footer', async () => {
it('does not broadcast for an unknown session; returns an EMPTY footer, never a brand word', async () => {
const res = await post({ sessionId: 'does-not-exist', data: REAL });
expect(res.statusCode).toBe(200);
expect(res.body).toBe('codeman');
expect(res.body).toBe('');
expect(h.ctx.broadcast).not.toHaveBeenCalled();
});
@@ -0,0 +1,114 @@
/**
* @fileoverview GET /api/settings is a plain read and must NEVER write
* settings.json.
*
* PR #361 once made it reconcile `showPlanUsageLimits` on first read: if the
* key was absent, the route persisted `true`. But readJsonConfig() answers
* `{}` for ANY read failure (parse error, EACCES, EMFILE, a read landing inside
* PUT's non-atomic write), not only ENOENT, and every page load calls this
* route, so one unlucky read replaced the whole settings file with a one-key
* file. The default now lives in the readers instead: an absent key means ON
* to readPlanUsageTelemetryEnabled() (pinned in test/hooks-config.test.ts) and
* to planUsageChipEnabled() on the client.
*
* Uses app.inject() with a mocked filesystem. Port: N/A.
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { createRouteTestHarness, type RouteTestHarness } from './_route-test-utils.js';
import { registerSystemRoutes } from '../../src/web/routes/system-routes.js';
// vi.mock factories are hoisted above module-level consts, so the mutable
// "disk" fixture has to be built inside vi.hoisted().
const { state, writeFile } = vi.hoisted(() => ({
// `raw` is what readFile returns; `failWith` makes it throw with that code.
state: { raw: '{}', failWith: null as string | null },
writeFile: vi.fn(async () => {}),
}));
vi.mock('node:fs/promises', () => ({
default: {
readFile: vi.fn(async () => {
if (state.failWith) {
const err = new Error(state.failWith) as NodeJS.ErrnoException;
err.code = state.failWith;
throw err;
}
return state.raw;
}),
writeFile,
},
}));
vi.mock('node:fs', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:fs')>();
return { ...actual, existsSync: vi.fn(() => true), mkdirSync: vi.fn(), readdirSync: vi.fn(() => []) };
});
describe('GET /api/settings never writes settings.json', () => {
let harness: RouteTestHarness;
beforeEach(async () => {
state.raw = '{}';
state.failWith = null;
writeFile.mockClear();
harness = await createRouteTestHarness(registerSystemRoutes);
});
afterEach(async () => {
await harness.app.close();
});
it('returns the file content unchanged when showPlanUsageLimits is absent, and writes nothing', async () => {
state.raw = JSON.stringify({ someOtherSetting: true });
const res = await harness.app.inject({ method: 'GET', url: '/api/settings' });
expect(res.statusCode).toBe(200);
expect(res.json()).toEqual({ someOtherSetting: true });
expect(writeFile).not.toHaveBeenCalled();
});
it('answers {} for a missing settings.json without creating one', async () => {
state.failWith = 'ENOENT';
const res = await harness.app.inject({ method: 'GET', url: '/api/settings' });
expect(res.statusCode).toBe(200);
expect(res.json()).toEqual({});
expect(writeFile).not.toHaveBeenCalled();
});
it('leaves an unreadable settings.json alone (EACCES is not "absent")', async () => {
state.failWith = 'EACCES';
const quiet = vi.spyOn(console, 'error').mockImplementation(() => {});
const res = await harness.app.inject({ method: 'GET', url: '/api/settings' });
quiet.mockRestore();
expect(res.statusCode).toBe(200);
expect(res.json()).toEqual({});
expect(writeFile).not.toHaveBeenCalled();
});
it('leaves a garbage settings.json alone (a parse error is not "absent")', async () => {
state.raw = '{ "showPlanUsageLimits": tru';
const quiet = vi.spyOn(console, 'error').mockImplementation(() => {});
const res = await harness.app.inject({ method: 'GET', url: '/api/settings' });
quiet.mockRestore();
expect(res.statusCode).toBe(200);
expect(res.json()).toEqual({});
expect(writeFile).not.toHaveBeenCalled();
});
it('passes an explicit value through either way', async () => {
for (const value of [true, false]) {
state.raw = JSON.stringify({ showPlanUsageLimits: value });
const res = await harness.app.inject({ method: 'GET', url: '/api/settings' });
expect(res.json().showPlanUsageLimits).toBe(value);
}
expect(writeFile).not.toHaveBeenCalled();
});
});
@@ -4,7 +4,7 @@
* The three service toggles (subagent watcher, workflow-run watcher, image
* watcher) used to read the RAW REQUEST BODY with `??` defaults, so any key the
* caller omitted was treated as "apply the default". A body of just
* `{statusLineTelemetry:true}` therefore STARTED the subagent watcher (`?? true`)
* `{showPlanUsageLimits:true}` therefore STARTED the subagent watcher (`?? true`)
* and STOPPED the workflow + image watchers (`?? false`), silently undoing the
* persisted config. Nothing triggered it in practice only because every shipped
* client sends a full settings payload rebuilt from the DOM.
@@ -91,8 +91,8 @@ describe('PUT /api/settings — partial body must not reset service toggles', ()
const res = await harness.app.inject({
method: 'PUT',
url: '/api/settings',
// Action-only body: the exact shape that used to flip all three watchers.
payload: { statusLineTelemetry: true },
// Minimal single-key body: the exact shape that used to flip all three watchers.
payload: { showPlanUsageLimits: true },
});
expect(res.statusCode).toBe(200);
+23 -2
View File
@@ -411,21 +411,42 @@ describe('system-routes', () => {
// ========== GET /api/settings ==========
describe('GET /api/settings', () => {
it('returns empty object when settings file does not exist', async () => {
// A plain read that never writes. The route briefly reconciled an absent
// showPlanUsageLimits to true on first read, but readJsonConfig() answers {}
// for ANY read failure and every page load hits this route, so one unlucky
// read replaced the whole file with a one-key file. The default now lives in
// readPlanUsageTelemetryEnabled() (absent means ON); see also
// system-routes-settings-get-plan-usage-default.test.ts.
it('answers {} for a missing settings file and creates nothing', async () => {
mockedReadFile.mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }));
mockedWriteFile.mockClear();
const res = await harness.app.inject({ method: 'GET', url: '/api/settings' });
expect(res.statusCode).toBe(200);
expect(JSON.parse(res.body)).toEqual({});
expect(mockedWriteFile).not.toHaveBeenCalled();
});
it('returns parsed settings when file exists', async () => {
it('returns the file unchanged when showPlanUsageLimits is absent', async () => {
const settings = { subagentTrackingEnabled: true, showSystemStats: false };
mockedReadFile.mockResolvedValue(JSON.stringify(settings) as never);
mockedWriteFile.mockClear();
const res = await harness.app.inject({ method: 'GET', url: '/api/settings' });
expect(res.statusCode).toBe(200);
expect(JSON.parse(res.body)).toEqual(settings);
expect(mockedWriteFile).not.toHaveBeenCalled();
});
it('passes an explicit false through untouched', async () => {
const settings = { subagentTrackingEnabled: true, showPlanUsageLimits: false };
mockedReadFile.mockResolvedValue(JSON.stringify(settings) as never);
mockedWriteFile.mockClear();
const res = await harness.app.inject({ method: 'GET', url: '/api/settings' });
expect(res.statusCode).toBe(200);
expect(JSON.parse(res.body)).toEqual(settings);
expect(mockedWriteFile).not.toHaveBeenCalled();
});
});
+96
View File
@@ -0,0 +1,96 @@
/**
* @fileoverview Tests for the plan-usage statusLine exporter riding an EPHEMERAL
* `claude --settings` CLI flag (buildSpawnCommand's statusLineCommand option),
* which superseded writing it into `.claude/settings.local.json` — see
* resolveStatusLineCliCommand in hooks-config.ts and its own tests. Verified
* live against a real Claude CLI (isolated tmux socket, 2026-08-31) that
* `--settings` accepts this exact shape and takes precedence over a file-based
* statusLine.
*
* Extracting and re-parsing the `--settings` argument goes through a REAL
* shell (bash -c) rather than a hand-rolled unescaper: the exporter command
* itself embeds both single and double quotes, so trusting anything but the
* shell's own quoting rules to reverse shellescape() would just be testing
* this file's guess at the algorithm, not the actual behavior a spawned pane
* sees.
*/
import { describe, it, expect } from 'vitest';
import { execFileSync } from 'node:child_process';
import { buildSpawnCommand } from '../src/tmux-manager.js';
const EXPORTER_CMD = 'curl -sfk -X POST "$CODEMAN_API_URL/api/status-telemetry" --data @- 2>/dev/null || true';
/** Extract the `--settings <arg>` fragment from a built command and have a
* real shell resolve its quoting, printing the arg back out verbatim. */
function extractSettingsJson(cmd: string): unknown {
const idx = cmd.indexOf('--settings ');
expect(idx).toBeGreaterThan(-1);
const fragment = cmd.slice(idx);
const out = execFileSync('bash', ['-c', `set -- ${fragment}; printf '%s' "$2"`]).toString();
return JSON.parse(out);
}
describe('buildSpawnCommand statusLineCommand (claude mode)', () => {
it('omits --settings entirely when no statusLineCommand and no effort are given', () => {
const cmd = buildSpawnCommand({ mode: 'claude', sessionId: 'sid-1' });
expect(cmd).not.toContain('--settings');
});
it('embeds the exporter command under a statusLine settings key', () => {
const cmd = buildSpawnCommand({ mode: 'claude', sessionId: 'sid-1', statusLineCommand: EXPORTER_CMD });
expect(cmd).toContain('--settings');
expect(extractSettingsJson(cmd)).toEqual({ statusLine: { type: 'command', command: EXPORTER_CMD } });
});
it('merges statusLine and ultracode into the SAME --settings object', () => {
const cmd = buildSpawnCommand({
mode: 'claude',
sessionId: 'sid-1',
effort: 'ultracode',
statusLineCommand: EXPORTER_CMD,
});
// Only one --settings flag total — never two (Claude Code accepts just one).
expect(cmd.match(/--settings/g)).toHaveLength(1);
expect(extractSettingsJson(cmd)).toEqual({
ultracode: true,
statusLine: { type: 'command', command: EXPORTER_CMD },
});
});
it('keeps a regular --effort flag separate from --settings when both are present', () => {
const cmd = buildSpawnCommand({
mode: 'claude',
sessionId: 'sid-1',
effort: 'high',
statusLineCommand: EXPORTER_CMD,
});
expect(cmd).toContain('--effort');
expect(cmd).toContain('--settings');
expect(extractSettingsJson(cmd)).toEqual({ statusLine: { type: 'command', command: EXPORTER_CMD } });
});
it('shell-escapes an exporter command containing single AND double quotes without breaking the flag', () => {
// The real exporter (generateStatusLineCommand) embeds both — a naive
// `'${value}'` wrap would be broken out of by the single quotes.
const tricky = `echo '{}'; printf '{"a":1}' | curl -sk`;
const cmd = buildSpawnCommand({ mode: 'claude', sessionId: 'sid-1', statusLineCommand: tricky });
expect(extractSettingsJson(cmd)).toEqual({ statusLine: { type: 'command', command: tricky } });
});
it('round-trips the REAL exporter script path unmodified (ensureStatusLineExporterScript)', async () => {
// What resolveStatusLineCliCommand actually hands to buildSpawnCommand at spawn
// time today is a bare script PATH (see that function's doc comment for why —
// never the raw curl command generateStatusLineCommand() builds, which only
// backs the legacy disk-write applyStatusLineConfig path now).
const { ensureStatusLineExporterScript } = await import('../src/hooks-config.js');
const real = await ensureStatusLineExporterScript();
const cmd = buildSpawnCommand({ mode: 'claude', sessionId: 'sid-1', statusLineCommand: real });
expect(extractSettingsJson(cmd)).toEqual({ statusLine: { type: 'command', command: real } });
});
it('never adds --settings for non-claude modes even if statusLineCommand is somehow set', () => {
const cmd = buildSpawnCommand({ mode: 'omp', sessionId: 'sid-1', statusLineCommand: EXPORTER_CMD } as never);
expect(cmd).not.toContain('--settings');
});
});
+26
View File
@@ -99,6 +99,32 @@ describe('TmuxManager (unit)', () => {
});
});
describe('statusline user-command env', () => {
// A tmux setenv survives respawn-pane, so the absence of a user statusline
// must UNSET the variable rather than leave a stale one for the exporter
// to wrap.
it('unsets CODEMAN_USER_STATUSLINE_CMD when the user has no statusline', () => {
mockedExecSync.mockClear();
(
manager as unknown as { _configureStatusLineUserCommand: (m: string, c?: string) => void }
)._configureStatusLineUserCommand('codeman-abc', undefined);
const cmds = mockedExecSync.mock.calls.map((c) => String(c[0]));
expect(cmds.some((c) => c.includes("setenv -t 'codeman-abc' -u CODEMAN_USER_STATUSLINE_CMD"))).toBe(true);
});
it('sets CODEMAN_USER_STATUSLINE_CMD, shell-escaped, when the user has one', () => {
mockedExecSync.mockClear();
(
manager as unknown as { _configureStatusLineUserCommand: (m: string, c?: string) => void }
)._configureStatusLineUserCommand('codeman-abc', `printf '%s' "$1" | jq -r .model`);
const cmds = mockedExecSync.mock.calls.map((c) => String(c[0]));
const setCmd = cmds.find((c) => c.includes('CODEMAN_USER_STATUSLINE_CMD'));
expect(setCmd).toBeDefined();
expect(setCmd).not.toContain(' -u ');
expect(setCmd).toContain("setenv -t 'codeman-abc' CODEMAN_USER_STATUSLINE_CMD ");
});
});
describe('Codex command builder', () => {
it('controls decorative TUI animation through Codex config', () => {
expect(buildCodexCommand({ animations: false })).toBe('codex --config tui.animations=false');
+3 -2
View File
@@ -119,8 +119,9 @@ describe('formatSessionStatusText', () => {
expect(formatSessionStatusText({ modelDisplayName: 'Opus 4.8 (1M context)' })).toBe('Opus 4.8 (1M context)');
});
it('falls back to a brand string when there is no data', () => {
expect(formatSessionStatusText(null)).toBe('codeman');
it('prints nothing when there is no data (a bare brand word reads as a broken statusline)', () => {
expect(formatSessionStatusText(null)).toBe('');
expect(formatSessionStatusText({} as never)).toBe('');
});
});