Compare commits

...
Author SHA1 Message Date
Codeman maintainer 9cfd8e8989 fix(docker): survive xAI installer's own /usr/local/bin/grok symlink
The agent-image grok step copied /root/.grok/bin/grok onto /usr/local/bin/grok
with cp -L. Newer versions of xAI's install.sh already create
/usr/local/bin/grok as a symlink to that same binary, so the copy failed with
'same file' and the --no-cache rebuild died at the grok layer (2026-08-24).
Stage the copy under a temp name, drop whatever the installer left at the
destination, then move into place - correct against both old and new
installers.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 01:12:38 +02:00
Codeman maintainer 8fe393826b chore: version packages 2026-08-24 01:00:51 +02:00
Codeman maintainer 7a340fe7bc fix(tabs): review-driven hardening for the tab-layout foundation and vertical rail
Post-merge follow-ups from the deep review of #334 and #335, so they ship in
the same release as the features.

Tab-layout foundation (#335):
- PUT /api/session-order drops unknown/foreign ids again instead of 400ing
  the whole write, in both the owner and the admin path (single-user requests
  are the synthetic admin, so that path is the one the browser hits). The
  frontend debounces its reorder push and swallows errors, so a session
  deleted inside the debounce window silently cost the user the entire
  reorder - and the endpoint sits on the stable /api/v1 surface, where the
  pre-layout server merged leniently.
- A failed mux restore no longer locks explicit deletions into 500s for the
  process lifetime: runSessionDeletion and webviewDeleted degrade to
  best-effort without layout coordination, while the automated stale sweep
  (runStaleSessionCleanup) stays fail-closed.
- sse-events doc comment: no 'suppressed' hook event exists; hooks stay 8.
- registerSessionWithLayout resolves its owner through ownerLayoutKey()
  instead of a hardcoded '@single'.

Vertical rail (#334) - all rail-awareness gaps in sidebar-only predicates,
unified behind the new _isVerticalTabList() (sidebar OR rail):
- Drag-reorder read the insertion side from clientX in the rail, so
  before/after was effectively arbitrary on vertical rows; the drag-over
  indicators now draw as top/bottom edges there like the sidebar's.
- The active tab is scrolled into view in the rail (Alt+N/palette selection
  used to leave the row below the fold).
- Floating subagent/ultracode windows anchor to the RIGHT of rail tabs, and
  the connector redraw gates (render tail + strip scroll) cover the rail.
- Server-seeded tabOrientation is applied when the async settings load
  resolves, not only at boot, so a fresh device shows the rail immediately.
- The pre-paint script stamps data-tab-orientation and --tab-rail-width
  (sidebar-wins and solo carve-outs included), removing the flash of the
  header strip on every vertical-mode load.
- The session name font defaults to 12px, the sidebar's historical 0.75rem
  size, so installs that never touch the new slider are not restyled.

Also documents the rail in CLAUDE.md (second #sessionTabs host, mover
ordering, the axis-predicate rule) and gives tab-rail-resize.js its
@dependency/@loadorder header. Full gate green (6093 tests); the excluded
browser suite was run by hand - only the known environmental failures
(opencode/codex binaries) remain, identical to pristine master.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 00:59:48 +02:00
Codeman maintainer f3c615b669 fix(files): give the file preview a working detach button
The button next to the file preview's close icon was Copy Content, whose
overlapping-pages glyph reads as a pop-out control - and for a PDF or any
media/binary preview it was completely dead: those branches never fill
filePreviewContent, so the click hit an empty-content guard and did nothing,
with no feedback.

There is now a real detach button that opens the previewed file in a browser
tab (raw route for PDFs/images/media/text, the server-converted PDF preview
for docx/pptx), severs window.opener by hand so a blocked pop-up stays
detectable, closes the overlay on success (which also stops any playing
media), and disarms on close so it can never open a stale file. The copy
button now toasts 'Nothing to copy in this preview' instead of staying
silent.

Verified live with Playwright against an isolated instance: button visible
and armed on a PDF preview, file-raw answers 200, clicking opens the URL and
tears the overlay down, text previews keep a working copy buffer.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 00:59:27 +02:00
Ark0N 82f81d21c4 Merge pull request #333 from Ark0N/feat/grok-mode
feat(grok): add Grok Build (xAI) as a seventh CLI run mode
2026-08-24 00:43:04 +02:00
Codeman maintainer c173ae0264 Merge remote-tracking branch 'origin/master' into worktree-grok-mode
# Conflicts:
#	src/web/public/app.js
2026-08-24 00:32:25 +02:00
Ark0N e9dd55e5fd Merge pull request #334 from aakhter/pr/cod-358-vertical-rail
feat(tabs): add a resizable vertical session rail
2026-08-24 00:14:10 +02:00
Ark0N dd96f252ea Merge pull request #335 from aakhter/pr/cod-359-tab-layout
feat(tabs): add owner-scoped tab layout foundation
2026-08-24 00:12:20 +02:00
Aamer Akhter 74194e4fc0 feat(tabs): COD-359 add owner-scoped tab layouts 2026-08-23 14:46:10 -04:00
Aamer Akhter c45c6c3846 merge upstream master into COD-358 2026-08-23 14:15:07 -04:00
Aamer Akhter 17b141dc25 test(workflows): keep recent-run fixture clock-independent 2026-08-23 14:12:38 -04:00
Codeman maintainer 57f326ab8f docs(grok): fix the mode counts and line refs the seventh mode invalidated
The agent skill's endpoints.md is what other agents read as ground truth, and
three of its facts went stale when grok landed:

- `/api/v1/grok/status` was added to the probe list, but the sentence after it
  still said only Pi's response carries `.data.version`. Grok's carries it for
  the same reason (a squatted binary name), and an agent that trusts the old
  wording has no way to tell a misresolved grok from an absent one.
- the `active-tools` bullet listed grok among the modes it stays empty for, then
  claimed in the same breath that `isExternalCliMode` "lists only those five".
- its three source line refs had all drifted: `isExternalCliMode` is now
  session.ts:174-183 (it was already wrong before this branch), the external-CLI
  early return is session.ts:2261, and TEXT_COMMAND_PATTERN is
  bash-tool-parser.ts:89.

CLAUDE.md and architecture-invariants.md counted modes in their Docker-cases and
Web-tabs paragraphs ("any of the five CLI backends", "never a sixth
SessionMode"). Both numbers were already stale before grok (antigravity and pi
had made it seven) and grok is now in the agent image, so the counts are gone
rather than incremented: the invariant those sentences carry is that Docker and
web tabs are not modes at all, which no number has ever helped state. The two
plan docs keep their original wording, being historical design records.
2026-08-23 19:57:13 +02:00
Codeman maintainer 6b0b6d10ad fix(test): anchor the workflow-run fixture to now instead of a pinned epoch
test/workflow-run-watcher.test.ts pinned its fixture's newest activity at
2026-06-14T20:06:40Z and then asked getRecentRunSummaries(100000) to return
it. That argument is MINUTES, so the window is 69.4 days: the assertion
expired at 2026-08-23T06:46:40Z and the file has failed on every branch
since, on a suite nobody had touched. The last green CI run finished at
06:47:43Z, about a minute inside the boundary, which is why it landed as a
surprise rather than a bisectable regression.

The fixture epochs now hang off a RUN_ANCHOR of Date.now() - 601s with every
offset preserved verbatim, so the parsed durations, the ordering and the
live-vs-done discriminators are all unchanged, and the recency filter is
still the thing under test. It just cannot rot again.
2026-08-23 19:54:15 +02:00
Aamer Akhter c9ea8bbac5 fix(tabs): COD-358 re-query tab after rename cancel 2026-08-23 13:40:42 -04:00
Aamer Akhter 1795a138b3 test(workflows): document clock-independent fixture fix 2026-08-23 12:47:39 -04:00
Aamer Akhter e3a2fb767f feat(tabs): COD-358 add resizable vertical session rail 2026-08-23 12:21:02 -04:00
Codeman maintainer 3f8c8e99d1 feat(grok): add Grok Build (xAI) as a seventh CLI run mode
SessionMode gains 'grok', a first-class backend alongside Claude Code,
shell, OpenCode, Codex, Gemini, Antigravity and Pi: its own PTY, tmux
session, charcoal tab identity ('gk' badge), welcome button, run-mode
entry, cron agentType, Docker and remote-SSH command defaults, and
clone-repo Brain option. Flag surface verified live against grok 1.0.5.

Grok mixes two existing shapes and the wiring follows from that:

- Codex-shaped on permissions: the bypass switch is GrokConfig.alwaysApprove
  (--always-approve, grok's bypassPermissions mode; config-level deny rules
  still apply on top). The Run button sends it true, like runAntigravity(),
  and clampExternalCliBypassForOwner() puts grok in the only-if-sent branch:
  a bare grok spawn is grok's own ask-mode default, which is already safe,
  so only a sent config needs the flag forced off. Cron needs nothing for
  the same reason.
- OpenCode-shaped on rendering: grok is a fullscreen alternate-screen TUI
  with mouse support, so it stays OUT of isAltScreenStripMode() and lands
  on the narrow tmux-attach strip and the 'buffer' local-echo fallthrough
  (unmeasured against an authenticated composer; documented fallback is the
  'off' branch).
- Pi-shaped on resolution: 'grok' has npm squatters (@vibe-kit/grok-cli
  also installs a grok bin), so grok-cli-resolver.ts version-probes every
  candidate (grok --version, killSignal SIGKILL, VITEST-gated) and
  GET /api/grok/status surfaces path AND version; GROK_VERSION_REGEX is
  shared with the dependency registry so doctor and run mode cannot drift.

Env allowlist gains GROK_* plus the XAI_* vendor namespace (XAI_API_KEY is
grok's documented headless auth var), the same narrow-vendor reasoning as
GOOGLE_* for gemini. Resume is id-regexed on purpose: grok's own --resume
also matches session titles, which are arbitrary user strings that must
never reach the bash -c spawn line.

Docker: grok is not on npm, so the agent image installs it in its own step
(xAI's installer has no --dir override; the binary is copied to
/usr/local/bin and root's ~/.grok dropped in the same layer), and
credentials are seeded per-file (auth.json, config.toml, pager.toml; the
dir also holds sessions/, memory/ and the ~160MB binary). Remote SSH routes
through the login-shell wrapper like the other agent CLIs.

Verified end to end on an isolated CODEMAN_INSTANCE with grok 1.0.5
installed: /api/grok/status resolves and reports the probed version,
quick-start spawns a pane whose command line ends in 'grok
--always-approve', the real TUI renders (OAuth device screen on an
unauthenticated box), and grokConfig round-trips through state.json.
Docs: docs/grok-integration.md (user guide) + docs/grok-integration-plan.md
(decisions, verification record, follow-ups).

Tests: test/grok-mode.test.ts, test/grok-cli-resolver.test.ts, plus
extended clamp/system-routes/render-index-html/run-mode-ui/mobile-overview/
local-echo-gating coverage. npm test (the CI gate) green: 5910 tests.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-23 08:39:03 +02:00
Codeman maintainer 88bb98de43 chore: version packages 2026-08-22 14:45:08 +02:00
Codeman maintainer 687e9d7565 feat!: retire the sc tmux chooser in favour of codeman tui
scripts/tmux-chooser.sh is deleted. codeman tui replaces it and does the
job better: sc numbered its entries globally but only accepted a single
[1-9] keypress, so sessions 10+ were listed and unselectable, and it
inferred nothing about what an agent was doing. The tui carries the
server's real states, answers permission dialogs, and leaves an attach
with one key.

install.sh no longer creates the tmux-chooser symlink or the sc alias.
It now sweeps both up instead, on update AND uninstall, so an update
cannot leave a symlink pointing at a script this version stopped
shipping. The alias removal is marker-owned: it matches the exact line
the installer wrote, so someone's own 'alias sc=' for another tool is
never touched, and it rewrites through 'cat >' so the profile keeps its
mode and ownership. Verified against three profile shapes.

BREAKING CHANGE: the 'sc' command and the 'tmux-chooser' symlink are
gone. Use 'codeman tui' (and 'codeman tui --list' / 'codeman tui <n>').
2026-08-22 14:44:14 +02:00
Codeman maintainer 5d81cc01ca docs: point terminal users at codeman tui instead of the sc chooser
codeman tui supersedes the sc bash chooser: it reaches sessions 10+,
carries the server's real states instead of a static list, and leaves an
attach with one key. Every place that told a user to run sc now names the
tui equivalent, including the two wiki pages and install.sh's next-steps
banner. Both wiki pages also carried the wrong detach chord (Ctrl+A D;
the socket's prefix is C-b), which the tui makes moot.

Source comments that explained themselves as "the sc -l replacement" now
just say what they do. docs/tui-plan.md and CHANGELOG.md are historical
records and keep their references.
2026-08-22 14:36:23 +02:00
Ark0N f49249fb2f Merge pull request #312 from Ark0N/feat/tui
feat: codeman tui, a terminal dashboard with live agent states
2026-08-22 14:32:51 +02:00
Codeman maintainer bc3f9f8a37 docs: record the socket-resolution rule where the mechanism lives
CLAUDE.md gained "any new `tmux -L` caller through `resolveTmuxSocketName()`"
but architecture-invariants.md, which that bullet points at for the
mechanism, still described only the dataPath() half. Say why the rule
exists there too: the TUI is the first non-server process to shell out
to tmux.
2026-08-22 14:25:23 +02:00
Codeman maintainer 97acfc61c3 docs: stop telling sc users to press a key only the TUI binds
The sc chooser runs a plain `tmux attach-session` and binds nothing, so
F1 does not detach from it; only `codeman tui`'s attach claims that key,
and only for its own duration. The line it replaced was wrong too (the
socket's prefix is C-b, not C-a), so name the real chord and say which
command gives you the single key instead.
2026-08-22 14:19:31 +02:00
Codeman maintainer c27363459d docs(tui): stop telling people to press a key that does not work
The guide and the README both said to detach with `Ctrl+B D`. Beta testing
proved that wrong twice over: tmux binds lowercase `d` to `detach-client` and
capital `D` to `choose-client`, and even the correct letter fails for anyone who
keeps Ctrl held, because that sends `Ctrl+D`, which tmux leaves unbound. A
tester followed the documented instruction, stayed attached, and exited the
agent to escape.

Both now say `F1`, and the attach section describes what actually happens: the
session strip across the top of the pane, `Alt+1`..`Alt+9` switching without
returning to the dashboard, and `r` to resume a session whose pane has died.
Also corrected: `1-9` switches rather than jump-attaches, `x` confirms with `y`
rather than a typed name, and a new session opens straight into its pane.

`docs/tui-plan.md` is deliberately untouched — it is the design record of what
was planned, not a description of what shipped.
2026-08-22 14:13:58 +02:00
Codeman maintainer 737c2ed7f8 fix(tui): escape the separator in the switch binding, closing the sizing leak
The loose end from 777f974, now explained. Sessions came back from a detach on
`window-size latest` instead of `manual`, and the restore primitive round-tripped
correctly in isolation, so the corruption had to be upstream of it. It was: the
snapshot was taken from state this code had already broken.

`bindSwitchKey` passed a bare `;` between the two commands it wanted in one
binding. That is a command separator to tmux's OWN parser, not an argument: it
ended the `bind-key` and executed what followed immediately. So the binding kept
only `switch-client`, and `set-window-option ... window-size latest` RAN against
every switchable session at attach time — before the sizing snapshot was taken.
Every session was therefore snapshotted as `latest` and faithfully restored to
`latest`.

Proven against real tmux both ways before fixing: a bare `;` leaves the session
on `latest` and stores a one-command binding, while `\;` leaves it `manual` and
stores both commands.

Verified end to end: 7 sessions manual before, 1 latest + 6 manual during the
attach (the attached one follows the terminal, the rest are pre-sized), no dot
padding on a switch, and all 7 back to 120x40 manual after the detach.

This also means the "follow the terminal after switching" half of 777f974 never
actually worked — it was never in the binding.
2026-08-22 14:13:58 +02:00
Codeman maintainer bb24d2c256 fix(tui): stop the preview stacking every repaint of a session
The overview showed the same session twice, one frame above another, after
switching sessions (reported from the beta with a screenshot).

Claude repaints by ABSOLUTE CURSOR POSITIONING, not by clearing: a 198KB pane
tail carries 1142 `CSI r;c H` and exactly one `CSI 2J`. The replay honoured the
COLUMN of those sequences and ignored the ROW, so a repaint could never
overwrite what came before and was appended instead. That same tail replayed as
FIFTY stacked copies of one frame. The preview shows the last N lines, so on a
short terminal you saw the newest frame by luck and on a tall one you saw the
end of the previous frame above it.

A cursor HOME now starts the buffer over. That is not a heuristic but the
line-based equivalent of what a home means: a full-screen app announcing it is
repainting from the top, with everything on screen about to be overwritten in
place. Only row 1 column 1 counts — any other address is a write position
inside the frame being painted, and resetting on those would erase live
content.

Measured on the real tail that produced the screenshot: 198599 bytes and 50
copies of the welcome frame collapse to 40 lines carrying exactly one.

The old test pinned the append behaviour, including a spurious leading empty
line that the initial CUP produced; both are gone.
2026-08-22 14:13:58 +02:00
Codeman maintainer bc1821661f fix(tui): say alt+1-9 on the bar, and stop the dot grid when switching
The bar now reads "alt+1-9 switch · F1 back to the codeman dashboard", so the
switch keys are discoverable instead of secret. Shown only when those keys were
actually claimed, the same rule the way-out key follows: a bar naming a key
that does nothing is the bug this series started with.

THE DOT GRID. Switching landed in a pane occupying part of the terminal with
tmux's dot fill everywhere else. It was never a size mismatch — the window was
already the right size. `window-size latest` only resizes a window while a
client is ON it, and the sessions behind the tab strip have none until you
switch, so the resize happened AT the switch: tmux painted the newly-available
area with dots and an idle claude had no reason to redraw into it. Every
switchable session is now pre-sized to the attaching terminal, which moves that
repaint to attach time while the user is still looking at the first session,
and the switch binding restores `window-size latest` on arrival so a mid-attach
terminal resize still follows. Measured: 14 consecutive switches across 7
sessions, zero dot-padded rows, against 1-in-6 before.

⚠️ Known loose end, deliberately not papered over: after a detach the window
SIZE is restored exactly but the window-size MODE can come back as `latest`
rather than `manual`. The restore primitive round-trips correctly in isolation
(manual -> presize -> latest -> restore = manual) and no call site in the TUI
or the server sets `latest` afterwards, so the cause is not yet identified. The
practical effect is nil: the remaining client keeps the window at its own size
and Codeman re-pins `manual` on the browser's next resize.
2026-08-22 14:13:58 +02:00
Codeman maintainer 74c9879359 fix(tui): size every switchable session, not just the one being attached
Switching with Alt+N landed in a pane that filled part of the terminal with
tmux padding the rest as a dot grid — reported from the beta with a screenshot
showing the pane in the left half and dots everywhere else.

Codeman pins every window `window-size manual` at the BROWSER's size
(tmux-manager.ts), so no attaching client can resize it. The attach already
lifted that for the session it opened, which is why a plain attach looked
right; `switch-client` then moved the user into a session that had never been
lifted, and the old pin reasserted itself. `window-size latest` now goes on
every session the strip can reach, alongside the bar those sessions already
get, and each one's original sizing is snapshotted and restored on detach.

Verified by round-tripping a session pinned at 120x40 manual: latest 190x49
while attached, back to 120x40 manual after, with no dot rows at either step
and the bar intact at full width after a switch.
2026-08-22 14:13:58 +02:00
Codeman maintainer 499d3d6e4d fix(tui): finish the 1-9 rename in the fallback footer
The renderer's own FOOTER_KEYS table still said 'jump'. It is only reached when
the app layer supplies no footerKeys, so nothing visible was wrong, but a
fallback that contradicts the live footer is exactly the kind of drift that
turns into a bug report later.
2026-08-22 14:13:58 +02:00
Codeman maintainer 9b29666e03 fix(tui): keep the way out on the bar, and make Alt+1..9 actually switch
Four faults, all reported at once, and three of them were mine from the last
two commits.

THE HINT VANISHED. Two independent causes. First, a leaked F1 binding: an
attach whose TUI was killed leaves `F1 -> detach-client` in tmux's root table,
and the claim treated "already bound" as someone else's key, so every later
attach fell back to advertising the tmux chord — the bar stopped saying F1
while F1 still worked. A key already bound to `detach-client` now counts as
ours. Second, width: tmux truncates a status line that overflows and drops the
RIGHT-aligned segment, which is the hint. The strip now gets a budget measured
from the terminal's width minus the hint, and it drops tabs from the far end
until it fits. ⚠️ Measured on VISIBLE columns, not format bytes: `#[reverse]`
costs zero columns, and counting it made a strip that "fitted" still truncate
the hint at 80, 100, 120 and 176 columns on a real terminal.

ALT+N DID NOT SWITCH. On the dashboard, a bare digit meant jump AND ATTACH, and
a terminal sends Alt+N as ESC then N: when those land in separate reads —
routine over SSH — the chord decodes as Escape plus a bare digit, so "switch to
tab 2" threw the user into tab 2's pane. A digit now SELECTS, matching what
Alt+N means in the web UI; Enter is how you go in. Inside a pane the keys never
reached the TUI at all, since tmux owns the terminal, so the attach now binds
Alt+1..9 in tmux's root table to `switch-client` — the strip is usable rather
than decorative. ⚠️ The bar is applied to every session the strip can reach,
each highlighting its own tab: with it on the attached session only, switching
landed the user in a pane with no strip and no way out on screen.

⚠️ The leaked-state sweep was missing `status-position`, so it removed the
marker and left the position behind — and with no marker the leftover no longer
matched, making it permanently unsweepable. Found by diffing every session's
options after a detach.
2026-08-22 14:13:58 +02:00
Codeman maintainer aec6516638 feat(tui): keep the session tabs visible inside a pane, and move the way out to F1
Attaching made every other session disappear: the dashboard is gone, tmux owns
the terminal, and there is nothing left saying what else is running. The attach
bar now carries the session strip, numbered exactly as the dashboard numbers
them, with the session you are in inverted, and it sits at the TOP of the pane
where the web UI keeps its tabs.

The strip is a WINDOW around the active tab, not the whole list, with ellipses
marking each end that is actually cut. The bar is one line shared with the way
out, and that hint is the only instruction a user gets while tmux has the
terminal, so it must never be crowded off; a test drives 20 long-named sessions
through the bar and asserts it survives.

⚠️ The strip is a snapshot taken at attach time and never refreshed. The TUI is
blocked in `spawnSync` for the whole attach so there is no loop to update from,
and tmux's own format language cannot map a `codeman-<hex>` session name back
to a label a human recognises. Slightly stale beats absent.

The way out moves from F12 to F1, which sits beside Esc where a hand backing
out already goes. Verified against BOTH encodings a terminal sends for it:
xterm's SS3 (ESC O P) and PuTTY's default (ESC [ 1 1 ~).

`status-position` joins the snapshot, so a session that had its bar at the
bottom gets it back there on detach along with everything else.
2026-08-22 14:13:58 +02:00
Codeman maintainer c59f006bb6 fix(tui): stop drawing from the unicode blocks a plain terminal font lacks
Three separate "why are there boxes" reports, and I fixed them one glyph at a
time instead of as a class, so the next one was always waiting. Grouping the
tester's terminal by unicode block made the rule obvious:

  RENDERS   Latin-1 (·), Box Drawing (─ │), Block Elements (█ ▛ ▐),
            Geometric Shapes (○ ▶), General Punctuation (…), Arrows
  TOFU      Miscellaneous Technical (⏎ U+23CE, ⏵ U+23F5), the sparse end
            of Dingbats (❯ U+276F)

That is an ordinary font, not a broken one, so it is the profile to design
against. The working spinner moves off Dingbats and Math Operators onto
quadrant blocks (▖▘▝▗) — the same block as the `▛█▐` art claude itself draws,
which that font renders fine — and the blocked marker moves off `⚠`
(Misc Symbols, emoji presentation on many terminals) onto `▲`, the block that
already gives us `▶` and `○`.

The preview fold gains claude's own spinner dingbats (✢ ✳ ∗ ✻ ✽ ✴ → `*`) and
`⚠` → `!`. Its animated status line is exactly where a reader looks, so tofu
there is the most visible kind there is.

A test now enforces this as a CLASS: no glyph in the unicode set may come from
Misc Technical, Misc Symbols or Dingbats, with U+2714 the single documented
exception because it was observed rendering on the very font that failed the
others. Verified by scanning a live frame driven with the tester's exact
environment: zero glyphs from any of the three blocks.
2026-08-22 14:13:58 +02:00
Codeman maintainer b2ac6c1bd9 fix(tui): confirm a kill with y, and make the dialog say what it would kill
Killing demanded the session's NAME typed out in full. That is the right
ceremony for dropping a production database and the wrong one for closing a
pane you are looking at; the beta tester's verdict was "thats stupid, just make
me type Y to confirm". `x` then `y` is already two deliberate keystrokes on a
row the user selected, and the conversation lives in its transcript, which a
kill does not touch.

Everything that is not `y` CANCELS rather than being ignored, so a stray key
closes the dialog instead of leaving a destructive prompt armed and waiting for
whatever gets typed next. Enter cancels too: it is the key most likely to be
hit by reflex, and this is the one dialog that destroys something.

⚠️ Found while verifying the new dialog: it did not name the session. The label
was computed as `row.session.name ?? id.slice(0, 8)`, and `??` falls back only
on null or undefined, so every session the server left with an EMPTY name — all
of them, until the TUI started naming its own — sailed through and the box read
"Kill ?". A destructive prompt that cannot say what it will destroy is worse
than no prompt, and it is now a single keystroke. The caller passes the same
label the LIST shows, so the dialog names the row in front of the user.

The typed-name machinery goes with it: TuiConfirmState.typed, setConfirmInput(),
confirmAccepts() and the 'typing'/'reject' steps are all removed rather than
left as unreachable branches.
2026-08-22 14:13:58 +02:00
Codeman maintainer 7b1150ca4f fix(tui): start a session straight into it, and drop two unsafe glyphs
Two reports from the same beta screenshot.

Starting a session left the user on the dashboard next to the row they had just
asked for, which reads as the create having silently failed. Starting a session
is a request to WORK in it, so the terminal now goes there as soon as the pane
exists, and the CLI booting is worth watching. If the pane is slow the notice
says so and the row is left selected, exactly as the resume path does.

The footer's `↵` was drawing as an empty box: `⏎` (U+23CE) has poor font
coverage, on the same terminal that renders `·`, `─`, `│`, `○`, `▶` and `✔`
perfectly. It is now U+21B5, from the Arrows block every monospace font ships.

`✋` (U+270B) was worse than a coverage problem: it is East Asian WIDE, so the
renderer, which addresses cells by column, was reserving two cells for it. The
golden frames had the age column shifted a space left to match, which is how
long that had been wrong. It is now `!`, and the frames align correctly.

A test walks the whole unicode glyph set and fails on any entry wider than one
cell, so a glyph that shifts the layout cannot be added again. The comment on
the table spells out both bars a glyph has to clear, because the tier check
answers neither: it asks whether the LOCALE is UTF-8, which says nothing about
whether a font has the glyph or how wide it draws.
2026-08-22 14:13:58 +02:00
Codeman maintainer 95a1f540b5 feat(tui): switch sessions with the web UI's shortcuts
Alt+1..9 switches to that session, and `[` / `]` / Tab step through them, so the
muscle memory from the web UI carries over.

Alt+N SELECTS rather than attaches, which is what the web UI's Alt+N does:
switching which tab you look at is cheap and reversible, and the terminal
equivalent is moving the selection and its preview, not handing the whole
terminal to a pane. Bare 1-9 keeps its documented jump-and-attach meaning.

Two of the web UI's chords cannot cross into a terminal, so the nearest
transmittable keys carry them instead:

  Alt+[ / Alt+]  ESC+[ IS the CSI introducer every arrow key arrives on, and
                 ESC+] is OSC, so neither chord is distinguishable from a
                 sequence. Bare `[` and `]` do the job.
  Ctrl+Tab       a terminal cannot report the Ctrl, so plain Tab carries it.

⚠️ The parser now decodes ESC + a printable character in ONE read as an Alt
chord, and the app replays every chord it does not claim as `escape` then that
character. That fallback is load-bearing, not tidiness: a real Esc landing in
the same read as the next keystroke is byte-identical to a chord, and without
the replay "Esc then q" typed quickly decoded as Alt+Q, matched nothing and was
swallowed. The e2e suite caught exactly that as the dashboard refusing to quit.
A lone Esc is still held and flushed on the caller's timer, which is what keeps
the two separable at all.
2026-08-22 14:13:58 +02:00
Codeman maintainer e7b7e90a1b fix(tui): fold rare prompt glyphs in the preview so they stop rendering as boxes
A beta tester photographed claude's `❯` prompt and its `⏵⏵` bypass-permissions
marker rendering as empty boxes in the preview pane. Their font has no coverage
for those codepoints while drawing `·`, `─`, `│` and `▶` perfectly.

The glyph TIER cannot help here. It answers "can this terminal do Unicode at
all", which is a locale question, and it correctly says yes for exactly the
terminals this affects. Coverage is per-glyph and undetectable from inside the
process, so the handful of rare glyphs CLIs use as chrome are folded to the
ASCII arrows they already look like, and everything a plain font does render is
left alone.

Scoped tightly: the preview only, never the TUI's own chrome, and skipped
entirely at the `nerd` tier where the user has declared a font that can draw
anything. The table is short and every entry was seen as tofu in a real
terminal rather than guessed at. The fold is length-preserving, so the preview
pane's column arithmetic is unaffected.
2026-08-22 14:13:58 +02:00
Codeman maintainer 84f8a8a2fe feat(tui): offer r to resume a session whose pane has died
Refusing the attach stopped the freeze but told the user to throw the session
away (`x` to close, `n` for new), which loses the conversation. tmux's own
dead-pane screen already says what to do instead: `claude --resume "<name>"`.

The Error card now offers `r` when the row can actually be resumed (claude,
with a conversation id and a working directory), and the footer says so. One
press resumes into a fresh pane and attaches to it, so a dead end becomes
recovery.

⚠️ Three things keep this from becoming the resume runaway that once spawned 35
sessions in 40 seconds. The offer holds a session ID, not a row, and is
re-resolved from the model when the key is pressed: a row captured when the
card opened is stale by then. It disarms BEFORE anything async, so a second `r`
cannot start a second resume. And it routes through resumeSelected(), which
owns the `resuming` flag and ends in attachToSession() rather than the group
dispatch.

⚠️ The `r` branch has to run BEFORE the generic dismiss, because a message
overlay is dismissed by ANY key: without that ordering the offer is consumed as
"some key was pressed" and the card merely closes. `help` keeps the any-key
behaviour, so the two modes no longer share a case.

Verified end to end against a genuinely dead claude pane: card, footer, one
press, one new session, and F12 back to the dashboard.
2026-08-22 14:13:58 +02:00
Codeman maintainer 6ad9145417 feat(tui): leave an attach with ONE key, F12, and no modifier
Three beta rounds died on tmux's native way out, and the last one died on the
instruction rather than the mechanism: "press Ctrl+B, release Ctrl, then d" is,
in the tester's words, very unclear, and holding the modifier through both keys
silently does nothing.

So the way out stops being a chord. The attach claims F12 in tmux's prefix-less
`root` table for its own duration, and the bar reads "press F12 to get back to
the codeman dashboard" — one keystroke, nothing to hold, nothing to release,
no order to get right. F12 because stock tmux ships an empty root table apart
from mouse bindings, and none of the CLIs that run in these panes want the key.

⚠️ The bar names the one key ONLY when the claim succeeded, and falls back to
the chord wording otherwise. A bar advertising a key that does nothing is the
bug this whole series started with, and it must not come back in a new costume.
Same claim rules as the prefix alias: taken only when tmux reports the key
unbound, given back only while it still means `detach-client`.

The chord and the held-Ctrl alias both keep working; they are simply no longer
what the user is told to press.
2026-08-22 14:13:58 +02:00
Codeman maintainer ab4a868688 fix(tui): make the detach chord work when Ctrl is never released
Reported three times as "Ctrl+B and d is still not working", on a build whose
bar already named the right key. Measured against a live pane: of the three
ways a person types this, only one worked.

  Ctrl+B, release Ctrl, then d   detaches
  Ctrl+B then Ctrl+D (held)      nothing happens
  Ctrl+B then Shift+D            nothing happens

Holding Ctrl through both keys sends 0x02 then 0x04, and tmux ships `C-d`
unbound in the prefix table, so the keystroke is swallowed in silence and the
attach looks frozen. That is not a user error worth documenting around: holding
the modifier is how most people type a two-key chord.

The attach now claims the held-Ctrl form of whatever key detaches (`d` → `C-d`)
for its own duration and gives it back on restore, and the bar advertises it
only once the claim succeeded, so it can never name a key that does nothing.
⚠️ The key is claimed ONLY when tmux reports it unbound, and released only
while it still means `detach-client`, so a binding of the user's own is never
shadowed or removed. The alias is deliberately excluded from the leaked-state
sweep: key tables are server-global, so the sweep cannot tell a leak from a
second TUI's live claim, and a stray `C-d`→detach is harmless either way.

Ruled out along the way, with evidence rather than assumption: the encoding.
tmux negotiates no extended-key mode upstream on attach (no kitty CSI-u, no
modifyOtherKeys, no DECSET 2017), so Ctrl+B does arrive as a plain 0x02 even
from a Claude pane, which has its own keyboard protocol.
2026-08-22 14:13:58 +02:00
Codeman maintainer 35b2c1baa5 fix(tui): refuse to attach to a dead pane, and stop naming sessions after CLI noise
Two more from the same beta round, both reported as "basic things are broken".

Attaching to a DEAD pane trapped the user. Codeman sets `remain-on-exit on`, so
a session whose agent has exited does not disappear: the row looks ordinary,
the server still reports it idle, and Enter handed the terminal to a pane that
reads no input. With the detach chord also wrong at the time, that was a hard
freeze with no way out. Enter now probes `#{pane_dead}` first and refuses with
an Error card naming the session and what to do instead. The probe fails OPEN,
so it can never block an attach to a live pane. ⚠️ It also has to paint: the
keypress that reaches attachToSession() has already painted by the time an
awaited probe resolves, so message() alone left the refusal invisible and Enter
looked inert, which is the bug it was added to fix.

A session started from the TUI came out unnamed, because startSession() sent no
sessionName and rowLabel() then fell back to the transcript's first line. A
brand-new session has no prompt to be named after, so the list showed a
perfectly healthy session called "Login interrupted" — the CLI's startup
output, reading like a failure report. Sessions the TUI starts are now named
`w<n>-<case>` like the web UI's, and rowLabel() prefers the case directory over
a scraped prompt for any row with a mux name, since a LIVE pane is identified
by where it runs while a history row genuinely is its prompt.
2026-08-22 14:13:58 +02:00
Codeman maintainer bf860382a2 fix(tui): sweep an attach status bar a killed terminal left behind
restore() runs after spawnSync returns, which covers detaching and the agent
exiting inside the pane, but not the terminal dying while attached. Closing the
window or dropping the SSH kills the TUI where it stands, and the bar it
installed stays pinned on the session: the next attach wears a stale bar naming
a different session, and the pane is a row shorter for good. Seen on the beta,
where the tester closed the window instead of detaching.

One sweep at startup, fire-and-forget so it can neither delay the first frame
nor fail a start. Only a bar carrying our own marker is touched, and the marker
is now the single source of the bar's own wording so the two cannot drift; a
user's hand-written status bar on the same session is left exactly as it is.
The session goes back to `status off`, which is how Codeman creates every pane
it owns and the only state this bar is ever applied over.
2026-08-22 14:13:58 +02:00
Codeman maintainer aa487f13ce fix(tui): advertise the key that actually detaches, and stop tmux painting it green
Two things the attach status bar got wrong, both found in a beta test.

The bar read `Ctrl+B D`. tmux key tables are case-sensitive: lowercase `d` is
`detach-client`, capital `D` is `choose-client`. Pressing what the bar said
opened a client chooser and left the tester attached, with the way out on
screen and inert. The key is now READ from `list-keys -T prefix` the same way
the prefix already was, rather than hardcoded, so a rebound tmux is followed
too and the label cannot drift from the binding again. It never goes through
formatPrefixKey(), which uppercases.

The bar also rendered as a full-width bright green slab. Only `status-format[0]`
was styled, so tmux's stock `status-style` (`bg=green,fg=black`) stayed
underneath it and won; `#[reverse]` on top could not undo it. `status-style` is
now set explicitly to `bg=default,fg=default` and snapshotted/restored with the
rest, so the bar sits on the terminal's own background and reads as a hint
line.

Tests pin both: that the chord ends in lowercase `d` and never ` D`, that a
rebound key prints verbatim, that `status-style` is part of the banner, and
that parseDetachKey() picks `d` out of verbatim tmux 3.4 `list-keys` output
while ignoring `detach-client -a`/`-P`, which act on other clients.
2026-08-22 14:13:58 +02:00
Codeman maintainer 0919f9da62 fix(tui): make an attach fit the terminal, show the way out, and resume history
Three things the first beta test surfaced.

1. Attaching from a terminal of a different shape showed the pane clipped to the
   browser's size, with tmux's dot padding filling the rest. Codeman pins every
   window it owns to `window-size manual` at whatever the web client reports
   (tmux-manager.ts), so no attaching client can resize it. The handoff now
   brackets the attach with `window-size latest` and restores the snapshot on
   detach. `latest`, rather than a one-off resize to our own size, is also what
   lets a terminal resized MID-attach follow along: tmux recomputes on every
   SIGWINCH while the TUI is blocked in spawnSync and cannot.

2. Nothing on screen said how to get back out, because Codeman keeps the status
   bar off on its panes (the web UI carries that information around the terminal
   instead). The tester exited the agent looking for the exit, leaving a dead
   pane. An attach now wears a `status-format[0]` bar reading "<prefix> D
   detach, back to the codeman dashboard", with the prefix READ from tmux rather
   than assumed, and the session's options are put back exactly as they were on
   detach. One option, not status-left/status-right, so tmux draws no window
   list beside it; `reverse` so it inherits the terminal's own theme. Restoring
   an array option unsets the BASE name, since dropping the `[0]` index leaves
   an empty array, which renders as a blank bar on a session that had one. The
   help overlay names the chord, and the dashboard confirms the detach.

3. Enter on a RECENT row said resuming was not wired up. It now creates a
   session carrying that conversation (`resumeSessionId` plus `/interactive`,
   the path the web UI's Resume Conversation list already uses), in the
   directory it ran in and under its old name, then attaches to it.

   The attach mechanics deliberately sit in a method the group dispatch cannot
   reach, plus a re-entrancy flag: routing resume back through the Enter handler
   re-dispatched on "this row is RECENT" and spawned one session per pass, 35 in
   about 40 seconds on the beta before it was killed. test/tui/tui-e2e.test.ts
   pins one press to one session with a pane that never appears, which is
   exactly the case that looped.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 14:13:58 +02:00
Codeman maintainer 75b272ff0a perf: pace the refetch and back the tail poll off a quiet pane
Both of the dashboard's periodic reads hit endpoints that are far more
expensive than their cadence assumed, and the cost lands on the SERVER's
event loop, so it is paid by every browser client too.

`GET /api/sessions/unified` is ~550ms against 11 live sessions: it scans
every Claude transcript plus the lifecycle log, uncached, and republishes
the search index. `scheduleRefresh()` was a 250ms trailing debounce with no
floor, and a queued refresh re-ran the instant the previous one returned
(by recursing, which also chained one pending promise per iteration), so a
stream of events paced the refetches at the endpoint's own latency: with
`session:updated` broadcast per session per 500ms while anything is
working, the scans ran back to back. `resyncDelayMs()` now keeps ambient
refetches 3s apart, measured start-to-start. The user's own actions call
`refresh()` directly and are unaffected, so what this paces is only
"notice what changed elsewhere".

`GET /api/sessions/:id/terminal` is ~80-100ms: two `execSync` tmux calls,
then the whole byte buffer normalized before the tail is taken. It was
polled every second for as long as a live row was selected. It now backs
off 1s, 2s, 4s, 5s while consecutive reads change nothing, and resets to 1s
on any change, when the selection moves, when this dashboard sends input or
answers a dialog, and on return from an attach. A pane that is printing is
still read every second; a pane at its composer is not.

The poll also kept running in three places it had nothing to draw for: the
whole time the user was attached in tmux (an attach can last hours), and
behind the message overlays that an async action opens (answered, killed,
started), which are not keystroke-driven and so never reached the
`afterInput()` path that stops it. `setInterval` becomes a chained
`setTimeout`, since the delay now varies.

Measured against the live server, same idle row selected, 25s window:
22 tail reads before, 5 after. With a working pane selected it stays at 22,
which is the intended cadence for a pane whose output you are watching.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 14:13:58 +02:00
Codeman maintainer 1385415e53 refactor: drop the two store members nothing consults
`TuiModelStore.confirmSatisfied()` and `approvalFor()` had no caller
outside their own tests. The first one mattered: it answered "does the
typed text authorize this kill?" with an exact name match, while the rule
actually consulted (`confirmAccepts()` in tui-app) also accepts the
8-character id prefix a mux name carries. Two divergent answers to one
question, the stricter one unreachable and waiting to be picked up by
mistake. knip cannot see class members, so the dead-code sweep never
flagged either.

The tests they existed for now assert observable state instead, and the
approvals one got stronger on the way: it checks that a session id coming
back does not inherit the dead session's dialog, which is the invariant
`removeSession()` is actually keeping.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 14:13:58 +02:00
Codeman maintainer 954a9ac26a fix: date a working row by its turn, not by the session age
`TuiSessionRow` declared `lastSubmitAt`/`inputTokens`/`outputTokens`,
`stateSince()` ordered the WORKING group by the first of them and
`renderRowLines()` painted the other two, but nothing ever filled any of
them in: the unified list carries none, and the `session:updated` payload
that does was discarded (an event only schedules a refetch).

So a running turn was dated by its SESSION's creation instead. Measured
against the live server before the fix: w65 (created 21h ago, turn started
one minute earlier) outranked w67 (created 15 minutes ago, turn started
five minutes earlier), the reverse of the rule docs/tui.md states, and the
elapsed column read `21h` for a turn a minute old. The token column was
unreachable code for the same reason.

`fetchLiveSessionMetrics()` reads the three fields from `GET /api/sessions`
and `applyLiveMetrics()` folds them onto the rows. That route answers from
the server's cached LIGHT state (no terminal buffers): 10-20ms measured,
against the ~550ms the unified list in the same `Promise.all` already
costs, so it is cheap enough to ride every refresh. It is best-effort like
the approvals and tmux reads beside it, because losing the anchor is
better than losing the list.

A ZERO is treated as unknown rather than merged: `stateSince()` reads
`lastSubmitAt ?? createdAt` and 0 is not nullish, so a merged 0 would date
every never-submitted session to the epoch.

The snapshot path gets the same merge, or `codeman tui --list` would number
the WORKING group differently from the dashboard that `codeman tui <n>`
indexes into.

Verified live: working rows now show 28m/8m (turn age, tokens 280.5k/65.2k)
where they showed 21h/34m and no tokens. The e2e assertion fails on master's
wiring with `[*] 10m` against a session that pressed Enter one minute ago.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 14:13:58 +02:00
Codeman maintainer 5fd6c5dd44 docs: extend the instance-isolation rule to tmux socket resolution
The data-dir half was already spelled out; the socket half only lived in
a function docstring, and the TUI is the first code that shells out to
`tmux -L` from a process that is not the server.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:58 +02:00
Codeman maintainer 8b5fc974b0 fix: cover tui in the CLI inventory and drop the em-dashes it printed
The inventory test predates the `tui` command, so a rename or an
accidental removal would have gone unnoticed: it now asserts the command,
its `-l`/`--list` flag and its optional position operand.

The digest and search-result lines joined their halves with an em-dash,
which the repo's own convention rules out, so both now use the middle dot
the surrounding lines already use. The one em-dash left in `src/tui/` is
load-bearing: `search-service.ts` builds a session snippet with it, and
the pattern that strips the repeated label has to match it.

Also moves `buildSearchEntries`'s doc comment back onto
`buildSearchEntries`; it had ended up stacked above a helper.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:58 +02:00
Codeman maintainer a52abd9f96 fix: drop the two keymap and style entries nothing reaches
`mark()` had no callers (knip's only finding on this branch), and the
renderer's fallback help list advertised `r` resume, which is deferred
with the rest of phase 3: a help screen naming a verb the build does not
implement is worse than no help.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:58 +02:00
Codeman maintainer 008dfddc23 docs: document codeman tui
The user guide covers what the dashboard is (and is not), the two
non-interactive fast paths, the four groups and their ordering, the full
keymap, what answering an approval does server-side, and the SSH/narrow
and degraded cases. The example frame is a real 100x30 capture against
the E2E fake server, not a drawing.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:58 +02:00
Codeman maintainer 32549789c7 fix: keep the plan-usage chip across a degraded-to-connected upgrade
A server that comes up mid-run was upgrading the header's hostname and
version but not its chip, which then stayed blank until the next telemetry
event. Also swaps a typographic apostrophe out of a preview error, which is
not renderable on the ASCII glyph tier.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:58 +02:00
Codeman maintainer 29d9a55eb6 fix: drop stale approvals and re-check the preview when the world changes
Two small honesty fixes at the edges: a server that goes down leaves the
dashboard holding prompts nothing can classify any more and whose answer
route is unreachable, so degraded mode clears them; and a resize can cross
the narrow breakpoint, where there is no preview pane to poll for.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:58 +02:00
Codeman maintainer ef812236b0 fix: read a row-addressed repaint as lines in the preview
Measured against a live Claude pane: an Ink TUI paints by ROW and emits
almost no newlines, so dropping cursor-position sequences collapsed a whole
screen into one unreadable line, and a tail cut mid-sequence printed the
remains of it (";1H") as text. Now a jump to column 1 starts a display line,
a jump inside a row moves the write position (capped, since a stream may
address a column no terminal has), and a severed CSI head is dropped before
parsing.

The preview is readable against a real session as a result: tool calls, the
working line and the composer all land where they belong.

Also drop the repeated session name from a search row, whose snippet opens
with the name the row already shows in its first column.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:58 +02:00
Codeman maintainer b51abe2c27 test: drive the phase-2 verbs end to end under a pty
The fake API server grows the routes the dashboard now calls (terminal tail,
input, approvals answer, search, away digest, plan usage on status), and the
new cases assert on what the server RECEIVED rather than on the frame: the
prompt arrives as one line ending in a carriage return, and the answers as
the exact action and option digit.

Also covered: the tail refreshing in place, the search overlay selecting a
live session, the digest rendering, one bell for an item announced twice,
and the 409 path reported as "no longer on screen".

The plan-usage chip is punctuated with the glyph tier's separator, so an
ASCII terminal no longer gets a stray middle dot in the header.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:58 +02:00
Codeman maintainer eb8958ddd0 feat: answer approvals and send prompts from the dashboard
The dashboard stops being read-only. The selected session's tail is polled
once a second while the plain list has focus and the layout is wide, and an
unchanged tail never reaches the model, so a quiet session costs no repaint.
A row with no live buffer says so instead of polling forever.

Keys: y/n and the parsed digits answer the selected session's dialog through
`POST /api/approvals/:id/answer` (never a blind keystroke: that route
re-captures the pane and 409s when the dialog has moved on, which the TUI
reports as "no longer on screen"); `p` opens a one-line composer aimed at
the selected session; `/` searches with a 250ms debounce and Enter switches
to a live session result; `g` shows the away digest. A new prompt rings the
bell exactly once, tracked by item id so a repaint or a refetch cannot
stutter, and the plan-usage chip rides `GET /api/status` plus its telemetry
event.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:58 +02:00
Codeman maintainer 953a560eee feat: render the approval card, composer, search and digest
The preview pane now leads with the pending dialog when the selected session
has one: the question, the options with their digits, and the keys that
answer them, red for a dialog and yellow for a waiting prompt. The card is
capped at half the pane, because the tail is why the pane exists.

Around it: a header badge counting prompts that need a human, a preview
title that sacrifices the path rather than the state word, the footer
becoming the composer line while one is open (with the cell the terminal
cursor belongs in, so it can be shown there and hidden everywhere else), and
the search and digest panels as overlays with a stable width.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:58 +02:00
Codeman maintainer dc89f05b14 feat: hold composer, search and digest state in the TUI model
The store gains the three overlays phase 2 needs, each taking the keyboard
when it is set and all of them cleared together by closeOverlay(), plus the
pure flattening of `GET /api/search`'s typed groups into rows a cursor can
move over: headers are chrome, and only a session that is on the list counts
as selectable, since a history hit has no row to move the cursor to.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:58 +02:00
Codeman maintainer bb73400afa feat: add the TUI's editor, approval and digest pure cores
Three small pure modules the phase-2 verbs are built on:

- tui-composer: the single-line editor behind `p` and `/`, holding text as
  code points so a cursor can never split a surrogate pair, with the scroll
  window derived from the width rather than remembered.
- tui-approvals: what an approvals-inbox item's card says, which keys are
  live for it (a digit answers only when the server parsed that option, and
  an idle prompt answers to none of them), and which ids the bell has not
  rung for yet.
- tui-digest: the away digest as compact lines, counts first and one line
  per entry, with a capped tail per section.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:58 +02:00
Codeman maintainer 9d7dd2ab62 test: drive codeman tui end to end under a pty
Spawns the real command in a pseudo-terminal against a fake API server
(canned status/unified/approvals plus an SSE stream the test pushes
into), which is the only way to cover raw-mode key decoding, frames
reaching a terminal, SSE-driven refresh and the exit sequence that has to
restore the user's screen.

Two details the assertions depend on: frames are addressed absolutely
rather than newline-separated, so the parser takes the last COMPLETE
frame (the pty delivers one in several chunks, and reading a half-written
frame would be racy), and it reads the sidebar column only, or a name
echoed in the preview pane could answer for a row.

The child gets its own data dir and a tmux socket name nothing runs on,
so nothing here can see or touch the machine's real sessions.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:58 +02:00
Codeman maintainer 3f88226d50 feat: register the tui command with its two fast paths
`codeman tui` opens the dashboard, `codeman tui --list` prints the
numbered list and exits (the `sc -l` replacement, plain when piped) and
`codeman tui <n>` attaches straight to a row (the `sc 2` replacement).
Both fast paths short-circuit before any screen setup, and both refuse
the numbers path without a terminal instead of half-opening a UI.

Bare `codeman` still prints help: the web UI stays the primary surface.
The TUI module is imported lazily so the other commands do not pay for it
at startup.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:58 +02:00
Codeman maintainer e5ae2826c6 feat: add the codeman tui dashboard
The IO half of src/tui: it owns the terminal, the timers, stdin and the
tmux handoff, and every decision it makes that is a function of its
inputs is an exported pure helper with unit tests (attach planning, the
typed kill confirmation, keymap selection, the repaint test, degraded
rows).

What it does: live session list over the unified API with SSE-driven
resync (debounced, with a 2s poll fallback the client asks for), cursor
and 1-9 navigation, attach and return, kill behind a typed confirmation
that refuses history rows and the session hosting the TUI, a new-session
case and CLI picker over quick-start, and degraded mode straight from
tmux when no server answers, re-probing so a server that starts upgrades
the dashboard in place.

Restoring the terminal is the part that has to be bulletproof: leave() is
idempotent and runs from normal quit, SIGINT/SIGTERM, a process exit hook
and prepended fatal handlers (src/index.ts already handles those by
exiting, so a listener registered after it would never run).

Attach is a handoff, never a proxy: the screen is restored and tmux gets
the real terminal. Inside tmux on the same socket there is nothing to
hand off to, so it issues switch-client and exits.

The preview pane, approvals answering, the prompt composer, search and
the digest are the next step; the region renders a placeholder rather
than pretending to load something.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:58 +02:00
Codeman maintainer 85b69e0923 feat: render the TUI picker overlay and a caller-supplied keymap
The footer and the help overlay held the plan's full keymap, which would
advertise verbs (prompt, search, digest, answer, resume) that the build
does not implement yet and teach users that the TUI ignores keys. Both
now take their entries from the render options when the caller passes
them; the built-in lists stay as the fallback.

The picker overlay windows its items around the cursor rather than
clipping them, so the selected case stays visible in a long list.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:58 +02:00
Codeman maintainer 6682231d68 feat: give the TUI model a revision signal and picker state
The app layer repaints on state change, so the store has to be able to
say that something changed: `revision` is bumped by every mutating
method, and the repaint test compares it against the last painted frame.
Without it an idle dashboard would either redraw on a timer or go stale.

Three additions come with it, all optional so nothing existing changes
shape: `TuiSessionRow.muxName` (the unified list carries no mux name, so
the app fills it in from the local tmux enumeration and a row without one
cannot be attached), a `new-session` UI mode, and `TuiPickerState`, the
one-column chooser behind `n`.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:58 +02:00
Codeman maintainer e140132e45 feat: add the TUI's API, SSE and degraded-mode client
Everything the dashboard needs from outside the process, behind one typed
surface, so the app loop stays a loop. It is a client of the running server and
nothing else: rows come from the unified list, blocked states from the
approvals inbox, and answering goes through the endpoint that re-captures the
pane and refuses with a 409 when the dialog has already been answered in tmux.
That refusal is a typed result rather than an exception, because a human
beating you to a prompt is normal operation.

Discovery mirrors the daemon probe (`CODEMAN_API_URL`, else loopback on
`CODEMAN_PORT`, self-signed TLS accepted) and credentials come from where
`codeman attach` already reads them. An explicit port outranks the ambient
`CODEMAN_API_URL`, which every managed session exports: a caller that named a
port must not be redirected at whatever server owns its shell.

Input is single-line and `\r`-terminated at this layer, so no caller can strand
text on an unsubmitted composer, and each send is tagged for the server's
exactly-once path. The event stream defaults to a `?sessions=` filter that
matches nothing, which drops the terminal firehose while lifecycle, hook and
approval events still arrive. A silent-but-open stream is caught by a watchdog
rather than a socket error, since that failure mode reports nothing at all.

With no server answering, sessions are listed from tmux on the instance socket
(argv, never a shell string) and decorated from a read-only peek at state.json,
which keeps the "the server died, get me to my sessions" path alive.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:58 +02:00
Codeman maintainer 6475c010a6 feat: decode the SSE wire format for the TUI
Node has no EventSource, so the live-update stream is read as raw bytes and
decoded here. Three details are what the parser exists for: a TCP read can end
between the CR and the LF of a CRLF, so a trailing CR is held back rather than
dispatched; the tunnel padding the server appends after a frame is a comment
with no blank line after it and must not split anything; and the keepalive is a
NAMED event, because an SSE comment is invisible to a browser client by spec.

Event classification lives here too, as a set rather than a prefix test:
`session:terminal` is most of the stream and the preview pane pulls its own
tail, so it is deliberately not a resync trigger.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:57 +02:00
Codeman maintainer 64c8048dda refactor: resolve the tmux socket from the instance config
The socket name was computed inside tmux-manager, which the TUI cannot import
just to learn which `-L` name its degraded-mode listing belongs on (that module
is the server's tmux driver, not a lookup table). The resolver moves next to
`dataPath()`, where the other half of the instance identity already lives, so
both processes agree by construction instead of by a copied default.

Behaviour is unchanged: the override still wins only when it is a name that can
be passed to `tmux -L` safely, and TmuxManager keeps warning about one that
cannot.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:57 +02:00
Codeman maintainer 0566ea3453 docs: record why the key parser reads LF as Enter
Ctrl+J is unbindable as a result, which is worth knowing before someone tries
to bind it.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:57 +02:00
Codeman maintainer 6ef3b2ba2e feat: render TUI frames from the model and layout
One absolutely-addressed line per row, each closed with an erase-to-end, so
nothing scrolls and a repaint cannot leave the previous frame's tail behind.
The caller wraps the result in synchronized-output brackets; that is an IO
decision and stays out of the renderer.

Color is passed in rather than detected. chalk's detection is right for the
one-shot CLI but would make a frame non-deterministic, so the palette is raw
SGR in the same semantic roles cli-style uses, and `color: false` emits nothing
but the cursor addressing, the session's own colors in the preview included.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:57 +02:00
Codeman maintainer 74fe2cad9f feat: add the TUI responsive layout math
Below 72 columns the preview pane is dropped and rows take two lines, the
constraint the `sc` chooser was built around and the reason it is still usable
on a phone; above it a clamped sidebar carries the list and the preview takes
the rest.

Every region is clamped to a non-negative size, so a 5x5 terminal degrades to a
header instead of handing the renderer negative widths.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:57 +02:00
Codeman maintainer aa2deea73e feat: add the TUI session model, classification and cursor
Rows are the ones GET /api/sessions/unified already returns and blocked states
are the items the approvals inbox already parsed, both imported as types only
so a CLI process pulls in neither the server nor node-pty. Classification
speaks the web UI's language (red blocked, yellow waiting, green working) so a
user with both surfaces open never has to translate between them.

Groups order by how long a session has been in its state, which is why WORKING
anchors on the pane's last Enter: a working pane repaints about once a second,
so its last-activity stamp always says "now".

Selection is tracked by session id, never by row index: rows re-sort under the
cursor whenever a session starts working or an approval lands, and an
index-tracked cursor would quietly move the selection to another session
between two keystrokes.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:57 +02:00
Codeman maintainer 5d7fdb528b feat: add the TUI raw-mode key parser
Decodes printable UTF-8, the control keys, arrows in both CSI and SS3 forms and
SGR mouse reports out of a byte stream that can tear anywhere, so a sequence
split across two reads decodes the same as one that arrives whole.

A lone ESC cannot be told from the start of an arrow key by looking at bytes,
so the parser holds it and the caller resolves it with flush() once its
disambiguation timer fires. Unknown sequences are swallowed: a stray CSI must
never reach a prompt composer as typed text.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:57 +02:00
Codeman maintainer 64cf8384f2 feat: add the TUI's SGR-aware preview helpers
The preview pane shows a session's raw terminal stream, so it needs the tail
reconstructed rather than emulated: SGR survives, cursor steering and OSC do
not, and a carriage return returns to column 0 so a spinner that repaints its
line 200 times contributes one line instead of 200.

Widths count East Asian Wide characters as two columns, which the clip and pad
helpers rely on to never cut a wide character, a code point or an escape
sequence in half.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:57 +02:00
Codeman maintainer 596c08d20c chore: stop ignoring src/tui
The entry dates from an abandoned prototype (0.1427) and would have kept the
real TUI modules untracked while `git status` stayed silent about it.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:57 +02:00
Codeman maintainer 1d0c3650f9 docs: fix the codeman attach description and the detach prefix
`codeman attach <path>` posts an attachment card for a local file; it
was described as attaching a Claude hook context. And Codeman never
overrides the tmux prefix for local sessions (only remote-SSH and docker
panes get C-q), so the detach hint is Ctrl+B D, matching the chooser.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:57 +02:00
Codeman maintainer b9afd5a57e test: derive the CLI inventory from the real commander program
The file asserted against a hand-written fixture array with its own
argument parser, so it could not see a command being renamed, losing an
alias or disappearing, and it described a `tui` command that does not
exist. It now walks program.commands: names, aliases, subcommands,
option flags, operands, descriptions, and a guard against registering a
name or alias twice at one level.

Assertions are "at least this exists", so a new command (including the
tui one this plan adds later) passes without editing the test.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:57 +02:00
Codeman maintainer 14a911b4f6 fix: color the server startup line and its security warning
The startup banner is now the only one (the CLI printed a duplicate) and
is painted like the rest of the CLI. The non-loopback-without-password
warning was plain console.warn while the CLI's copy of the same warning
was yellow; chalk degrades off a TTY, so journald and web.log stay free
of escape codes.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:57 +02:00
Codeman maintainer 9b1d269943 feat: wire the CLI through the style kit (doctor colors, spinners, confirm)
- doctor is colorized through the ReportStyle hook: verdict glyph and
  failing status text painted, paths and hints muted, versions left
  alone. `doctor --json` still prints raw JSON.
- `codeman web -d`, `web --stop` and `service install` block for up to
  30s polling /api/status; each now runs under a spinner instead of a
  silent terminal.
- `codeman reset` asks a real y/N question on a TTY. Non-interactive
  callers keep the old "Use --force to confirm." refusal, so no script
  can be answered by a question it cannot see.
- `codeman list` was a drifted copy of `codeman session list`; both now
  call one renderer, with the shorthand opting out of the stopped and
  web-server sections.
- `web` no longer prints its own "running at" line: the server prints
  one, and unlike this one it also covers the daemon and service paths.
- every chalk call goes through the palette, so the CLI has one place
  where colors are decided.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:57 +02:00
Codeman maintainer 4e5d0dcbd6 fix: measure the doctor table columns and let the CLI paint them
"Antigravity CLI" is 15 characters and the hardcoded padEnd(14) pushed
that whole row one column right. Widths now come from the widest cell.

The header always said the CLI layer may colorize, but there was no way
to: renderTable now takes an optional ReportStyle whose hooks are
identity by default, so the module still decides nothing about color and
its output stays byte-stable. Padding is applied outside the paint, so a
row with no path detail ends at its status text instead of trailing
spaces inside a color run.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:57 +02:00
Codeman maintainer f9d6c4f0c3 feat: shared CLI style kit
One vocabulary for everything the codeman CLI prints: semantic palette,
the glyph set the commands already used, heading/rule/kv, width-aware
table layout, a stderr spinner and a y/N confirm.

Color detection stays chalk's, so NO_COLOR and non-TTY degradation keep
working with no second detector to disagree with it. The layout math and
glyph selection are pure and exported, which is what lets the dependency
report reuse them while staying color-free.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:57 +02:00
Codeman maintainer 09d6bb9eb0 docs: TUI rework plan (codeman tui, herdr research)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 14:13:57 +02:00
Codeman maintainer a922d301b1 chore: version packages 2026-08-21 20:24:38 +02:00
Ark0N abca552676 Merge pull request #327 from dignfei/fix/terminal-ime-punctuation
fix(terminal): preserve IME punctuation input
2026-08-21 20:23:26 +02:00
Ark0N 12a996b107 Merge pull request #331 from dignfei/fix/shell-history-performance
fix(terminal): bound shell history replay
2026-08-21 20:23:17 +02:00
d fei 458e751a33 fix(terminal): keep shell history loading explicit 2026-08-22 01:55:50 +08:00
d fei dab432b3fd fix(terminal): bound shell history replay 2026-08-21 08:23:31 -04:00
Codeman maintainer 79a0399552 chore: version packages
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-21 02:47:10 +02:00
Codeman maintainer 61251c0b94 fix(cli-resolvers): negative-result caching, SIGKILL on probes, restored VITEST hermeticity, wired not-found diagnostics
Post-merge follow-ups for PR #329 (shared CLI executable resolution):

- Negative-cache resolution misses with a doubling backoff (1min -> 5min
  cap, cliResolveRetryDelayMs, mirroring claudeVersionRetryDelayMs): the
  shared resolver cached success only, so a missing CLI re-ran the whole
  chain - ending in a synchronous interactive login-shell spawn bounded by
  the 5s EXEC_TIMEOUT_MS - on every /api/<cli>/status request and Run
  attempt, stalling the event loop each time, forever. Success still caches
  for the process lifetime, so an installed CLI is picked up within minutes
  without a restart. Tests drive the backoff via an injectable clock
  (createCliExecutableResolver `now` option, threaded through the
  createPiResolverForTest / createAntigravityResolverForTest wrappers).

- Pass killSignal: 'SIGKILL' on the resolver's login-shell spawn and on the
  pi/claude --version probes: execFileSync's timeout only SENDS the kill
  signal and then keeps waiting for the child to exit, and interactive bash
  ignores SIGTERM, so a login shell stuck in a blocking .bash_profile
  survived the timeout and blocked the server permanently.

- Restore test hermeticity (PR #329 deleted pi's VITEST guards, and one
  test pinned the deletion): under vitest the production resolver host now
  replaces un-injected IO primitives with inert stubs - no real PATH
  scanning, no login-shell spawns - and probePiVersion never executes a
  `pi` candidate again (`pi` is a generic binary name, so route tests
  hitting /api/pi/status executed whatever binary the machine carried).
  Tests opt in through the runCommand/isExecutableFile injection hooks or
  allowRealIoUnderVitest for real-filesystem fixtures. The deletion-pinning
  test is replaced by behavioral pins, including a real-executable fixture
  in the new test/pi-cli-resolver.test.ts that fails loudly if the pi gate
  is ever removed again.

- Wire the six get*NotFoundMessage() exports (previously dead) into their
  intended call sites: the createSession throws in tmux-manager and the
  availability gates on POST /api/sessions and POST /api/quick-start in
  session-routes, replacing a third hardcoded copy of the text. A not-found
  error now names where resolution looked (server PATH, login shell,
  checked directories). npm run knip no longer reports any unused export
  from the resolver modules.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-21 02:37:58 +02:00
Codeman maintainer bb4ba79791 fix(repo-status): async git, single-flight TTL cache, credential redaction, local-upstream parse
Post-merge follow-ups for #328 (GET /api/system/repo-status):

- Event-loop blocking: every git invocation in repo-status.ts is now async
  (promisified execFile), never execFileSync — the per-remote ls-remote +
  fetch could hold the event loop (SSE, PTY streaming) for up to ~60s per
  request. The whole computation is single-flight with a 45s TTL cache
  (createSingleFlightCache): concurrent requests share one in-flight
  promise, a fresh result is served without spawning git, and a rejected
  compute is never cached. Route handler shape and response fields
  unchanged; remotes still processed sequentially (concurrent fetches in
  one repo contend on ref locks).

- Credential disclosure: the redaction from git-clone.ts is extracted as
  exported redactGitCredentials() (sanitizeGitOutput now uses it) and
  applied via redactRemoteStatus() to every remote card's url and error
  string, so a scheme://user:token@host remote URL (or git stderr echoing
  it) never reaches a client.

- Non-interactive env: runGit() now uses the shared gitNonInteractiveEnv()
  instead of a partial GIT_TERMINAL_PROMPT/BatchMode env, also closing the
  GIT_ASKPASS/SSH_ASKPASS/SSH_ASKPASS_REQUIRE/DISPLAY/GCM_INTERACTIVE
  prompt paths.

- Upstream parse bug: a local-branch upstream (@{upstream} with no slash,
  e.g. after `git branch -u otherbranch`) made slice(0, indexOf('/')) into
  slice(0, -1) and yielded garbage like "maste". parseTrackingRemote()
  (pure, unit-tested) returns null for it, and the bare ref is dropped so
  it cannot be mistaken for a remote-tracking ref downstream.

Tests extended in test/repo-status.test.ts (parseTrackingRemote,
redactGitCredentials/redactRemoteStatus, createSingleFlightCache
single-flight/TTL/rejection semantics).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-21 02:25:43 +02:00
Codeman maintainer d7ad73bc9b fix(response-viewer): role on full-context blocks, divider ReDoS, pi mode (#326 follow-up)
Three post-merge fixes for the external-CLI response viewer:

- ?context=full blocks now carry role ('user' for prompts, 'assistant'
  for response/status/tool). The frontend's loadFullContext() renders
  via msg.role, so the roleless blocks lost the "You" badge and every
  turn rendered as the agent. kind/label/text are unchanged and the
  frontend needs no change.

- normalizeDividerStatusLine() dropped its backtracking regex
  (/^[─-]+\s*(.+?)\s*[─-]{3,}$/): the lazy middle went catastrophic on
  a long dash run without a 3-dash tail (measured 15.5s at 4,000 chars,
  minutes at 10,000), and pane text is agent-controlled with buffers up
  to 32MB. Replaced by a linear counter walk with the identical accept
  set and captured content, pinned char-for-char against the old regex
  by a brute-force corpus test plus a hostile-input regression test
  that fails by timeout with the RegExp version (same approach as the
  glob-matcher hardening in 68ae9a8).

- 'pi' joins EXTERNAL_CLI_MODES: pi sessions had the identical
  empty-viewer symptom the transcript branch exists to fix. The list
  stays a local duplicate of isExternalCliMode() (importing session.ts
  would drag node-pty into the pure module); a new exhaustive parity
  test asserts the two mode sets can no longer drift.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-21 02:25:43 +02:00
Codeman maintainer 96ee8b536d docs: update the tap-report gate description after #325
#325 renamed _sessionUsesServerMouseStrip to _shouldReportMouseToCli and
added the server-observed cliMouseTracking half of the gate, which also
turned codex tap reports from measured no-ops into not-sent-at-all. The
invariants paragraph still described the old name and the old behavior.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-21 02:13:26 +02:00
Ark0N b7f3b07c79 Merge pull request #330 from aakhter/ralph-loop-reschedule
Ralph loop silently stops polling after two ticks
2026-08-21 02:10:41 +02:00
Ark0N 2073a1b185 Merge pull request #328 from aakhter/repo-status-panel
Report repository status for git-clone installs (GET /api/system/repo-status)
2026-08-21 02:10:38 +02:00
Ark0N f9a8493823 Merge pull request #329 from aakhter/cli-login-shell-resolution
CLIs installed via nvm/Homebrew are not found when Codeman runs as a service
2026-08-21 02:10:35 +02:00
Ark0N d2711ef092 Merge pull request #326 from aakhter/response-viewer-external-cli
Response viewer is empty for OpenCode / Gemini / Antigravity sessions
2026-08-21 02:10:29 +02:00
Ark0N 30a15adbd6 Merge pull request #325 from Ark0N/feat/auto-copy-selection
feat(terminal): Auto Copy, put a finished selection on the clipboard
2026-08-21 02:10:19 +02:00
Aamer Akhter a35438ba34 fix(ralph): loop stops rescheduling after two ticks
The reschedule guard is `this._status === 'running' && this.loopTimer === null`,
but the timer callback never nulls `loopTimer`. So the handle stays non-null from
the first fire onward, the guard is false on every subsequent pass, and the Ralph
loop silently stops polling after exactly two ticks.

It stops without changing status: `status` stays `running`, `stop()` is never
called, and no error is raised — the loop just quietly never runs again, which is
what makes it hard to notice on a long autonomous run.

Null the handle inside the callback before re-entering `runLoop()`, which is the
pattern `orchestrator-loop.ts` already uses for its own reschedule.

Test: a regression case in test/ralph-loop.test.ts that runs a real 5ms-interval
loop for ~16 intervals and asserts it ticks at least 3 times. Against the unfixed
source it reports exactly 2.
2026-08-20 12:58:17 -04:00
Aamer Akhter fef903df98 fix(cli-resolvers): find CLIs installed via nvm/Homebrew when running as a service
A CLI installed by nvm, Homebrew or a user-level npm prefix lives on a PATH that
only a login shell sets up. Codeman running under systemd or launchd does not get
that PATH — launchd hands a job `/usr/bin:/bin:/usr/sbin:/sbin` — so every
resolver reported the CLI as unavailable on installs where it is plainly there
and works from a terminal.

Each of the six resolvers had its own hand-rolled copy of the same PATH walk, so
the fix is factored into one shared `createCliExecutableResolver()` with an
explicit lookup order: the server process PATH, then common install directories in
order, then an interactive login shell as the last resort. Only the last step
spawns anything, and only when the cheap lookups have already missed.

Also adds `formatCliNotFoundMessage()`, so a failure explains where it looked
instead of just asserting the CLI is missing. Its diagnostics are bounded and
control characters are flattened, so a not-found message cannot dump arbitrary
environment data.

Success is cached and failure is retried, so installing a CLI while the server is
running is picked up without a restart.

Net -103 lines across the six resolvers. Behaviour is unchanged wherever the CLI
was already on the process PATH: that remains the first thing checked.

Tests: 20 cases in test/cli-executable-resolver.test.ts covering the precedence
order, login-shell-only resolution, the caching rule, unsafe-name rejection, and
the bounded diagnostics.
2026-08-20 12:47:42 -04:00
Aamer Akhter 02e7d3fcba feat(system): report repository status for git-clone installs
`GET /api/system/update/check` answers "is there a newer published release
tag?", which is the right question for an npm install but not for a git clone
that tracks a branch. Such an install can be many commits behind its own remote
while the latest tag says it is current, and nothing surfaces that.

Adds `GET /api/system/repo-status`: an informational companion that reports what
this CHECKOUT looks like against its own remotes — current branch and commit,
ahead/behind counts per remote, the remote's role (tracking / upstream / other),
and a bounded list of incoming commits.

Read-only and defensive: every git invocation is `execFileSync` with an argv
array and a timeout, a non-git or remote-less install reports a structured
`error` rather than throwing, and nothing here mutates the working tree or
touches the updater's own state.

Tests: 24 cases in test/repo-status.test.ts.
2026-08-20 12:39:28 -04:00
d fei f744719650 fix(terminal): preserve IME punctuation input 2026-08-20 10:35:23 -04:00
Aamer Akhter 63c5ba89da fix(response-viewer): populate the viewer for OpenCode/Gemini/Antigravity panes
`GET /api/sessions/:id/last-response` branches to a Codex-specific reader, then
falls through to scanning `~/.claude/projects` for a transcript. OpenCode, Gemini
and Antigravity render their own TUIs and never write one, so that scan finds
nothing and the response viewer is permanently empty for all three modes.

For these CLIs the pane IS the transcript, so segment it. `response-viewer-transcript.ts`
is a pure, dependency-free parser that splits a terminal buffer into prompt /
response / status / tool blocks, keying off the `›` prompt marker, status
dividers and `• Calling|Called` tool-activity lines. The route uses it to answer
with the LAST response, and to carry the parsed blocks under `?context=full`.

Codex keeps its existing branch: it has real rollout files, which are a better
source than scraped pane text.

The response shape is unchanged for every other mode, and Claude panes are
explicitly pinned to the Claude transcript path so a real transcript can never
be shadowed by scraped text.

Tests: 14 parser cases plus a route suite covering all three modes, the
`?context=full` payload, an empty pane, and the Claude regression guard.
2026-08-20 09:24:37 -04:00
Codeman maintainer 7fc4784d0f fix(approvals): clear the red tab alert when a dialog is answered in the terminal
Confirming an AskUserQuestion left its tab flowing red for the rest of
the turn (owner report: ~8 minutes on a running session, with no dialog
anywhere on screen). Two separate bugs, both live-verified.

The re-capture erased the evidence the staleness check runs on. Claude
Code fires the Notification behind the dialog (measured 6-7s on v2.1.237,
documented up to ~30s), so the 600ms re-capture routinely lands on a
frame the user has ALREADY answered, parses nothing, and applyCapture
overwrote item.options with undefined. A MISSING options is how "we never
could read this dialog" is expressed, and those items stay answerable by
design, so a cleared field was indistinguishable from a never-parsed one
and the item became permanently unsweepable: it survived every
GET /api/approvals and every page reload, cleared only on `stop`, and
still accepted an answer, sending a bare `1` into a composer with no
dialog under it. applyCapture is now ADD-ONLY for options.

Nothing ran the staleness check while a page was open. It lived only in
GET /api/approvals, which seedApprovals() calls on init and reconnect, so
`stop` was the first thing that ever cleared an answered dialog. The
`working` signal now runs the pane-VERIFIED variant (resolveIfDialogGone
-> verifyStillAnswerable): the heuristic only decides when to look, the
screen decides the outcome, so the existing "working can flap" rule is
respected.

A frame that parses no options is now conclusive in two cases, and only
those, so an unreadable capture still keeps the alert: the item once
parsed options, or the frame shows Claude actively running a turn. A
modal dialog BLOCKS the turn, so the two cannot coexist - measured, a
live-dialog frame carries neither the elapsed-timer spinner nor the
"esc to interrupt" footer, which the dialog replaces with "Enter to
select". That second signal is reached by a delayed staleness pass (3s)
scheduled alongside the re-capture, which closes the late-hook case where
the prompt is answered before the hook lands: nothing ever parses, `stop`
may have gone by already, and the alert outlived reloads until the 12h
TTL. The pass is deliberately later than RECAPTURE_DELAY_MS, whose whole
reason for existing is that the hook can beat Ink to the screen.

Frontend: _onHookElicitationComplete cleared only the elicitation entry,
but an AskUserQuestion arrives as permission_prompt, so it was clearing
the wrong alert; it now clears both, matching the server's kind-agnostic
APPROVAL_RESOLVING_EVENTS.

Verified end to end on an isolated beta instance, not just in unit tests:
before, resolution could only come from the stop route (approval:resolved
always immediately preceding hook:stop); after, it arrives from the new
paths, and a simulated late hook resolves at +3.12s with no stop, no
working signal and no GET, while the pane is still working. Tests use
frames captured off a live pane and each new one was confirmed to fail
against the old behaviour.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 12:18:16 +02:00
Codeman maintainer fa7e700834 fix(terminal): report a click to the CLI only when it asked for the mouse
Found while verifying Auto Copy in a browser: a plain left click in a
claude/codex/gemini pane sent a synthetic SGR mouse report into the PTY
whether or not the program in that pane had ever enabled mouse tracking.
When the pane holds a plain shell (the CLI exited, or a shell was started
inside a session of that mode) readline prints the report as literal text
and it garbles the next line typed:

    $ [<0;88;20Mecho hello
    bash: 0: No such file or directory

The cause is that the browser could not know. The full strip
(isAltScreenStripMode) removes the mouse DECSETs from the stream, so
xterm's modes.mouseTrackingMode is permanently 'none' for those modes and
_sendSyntheticSgrTap() hand-encodes reports to stand in for xterm's own
encoder. With no state to consult it had to do that on every click.

What the strip removes, the server now remembers.
_recordStrippedMouseMode() records each sequence as it is stripped,
toState() publishes it as cliMouseTracking, and the browser's
_shouldReportMouseToCli() (renamed from _sessionUsesServerMouseStrip)
requires it at all three report sites: the desktop click, the touchend
tap, and the mobile tap classifier.

Details that are easy to get wrong:

* Only the tracking modes count (1000/1001/1002/1003). 1005/1006 select
  an encoding and 1007 is alt-scroll; a CLI that picks SGR encoding
  without turning tracking on is not asking about clicks, and counting
  those would put the stray reports straight back.
* Modes are held in a Set, so a TUI disabling a mode it never enabled
  cannot clear the ones that are really on.
* The change broadcasts immediately instead of through
  broadcastSessionStateDebounced: the flag flips when a dialog opens, and
  the user can click that dialog well inside the 500ms debounce window.
* It fails toward silence. After a server restart the flag is false until
  the CLI re-emits its DECSET, which tmux does at client attach.

Verified against a live claude 2.x session: the CLI holds a tracking mode
on continuously, so its clicks are still reported byte for byte as
before, while a bash prompt in the same stripped mode now reports
nothing and types cleanly. The flag also propagates live over SSE in both
directions, checked by toggling ?1002h/?1002l from inside the pane.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 11:21:29 +02:00
Codeman maintainer 7936a75e28 feat(terminal): Auto Copy, put a finished selection on the clipboard
App Settings > Terminal & Input > Selection & clipboard > Auto Copy
Selection (`autoCopySelection`, per-device, default OFF). With it on,
highlighting text in the terminal copies it: mouse drag, double-click
word, triple-click line, and the phone long-press selection. Ctrl+C is
untouched and still copies on demand.

Three things decide the shape of it:

* It fires at the END of a gesture, never in onSelectionChange. That
  callback runs for every cell a drag crosses, so copying there would be
  one clipboard write per mouse move. It only arms a pending flag; a
  document-level mouseup listener flushes, and the touch path calls the
  flush itself because it preventDefaults its touchend and no mouseup
  ever arrives there.
* The flush is synchronous inside the handler, because both clipboard
  paths need user activation: Firefox gates navigator.clipboard
  .writeText on it, and execCommand('copy'), the fallback the plain-HTTP
  LAN install lands on, has to run in the gesture's own task. A timer or
  a wait for onSelectionChange loses it, invisibly in Chrome.
* It deliberately does NOT do what copyTerminalSelection() does. That
  one clears the selection (so a second Ctrl+C is an interrupt) and
  focuses the terminal. Clearing would make text vanish under the cursor
  that just highlighted it, and focusing opens the on-screen keyboard
  over it on a phone. Focus is instead restored to whatever held it,
  which only matters for the execCommand fallback.

Guards are pure in decideAutoCopy() (constants.js): off, blank or
whitespace-only text, and a 1M-char cap, since a drag off the top of the
viewport autoscrolls and one gesture can sweep the whole 50k-line
scrollback. Past the cap the copy is refused rather than truncated, with
a toast pointing at Ctrl+C.

Feedback is silent on success except once per page load, so a feature
that works by doing nothing visible can still be told from a dead
toggle; failures and refusals toast, throttled to 10s.

Per-device on both counts the settings rule requires: in `displayKeys`
and absent from the .strict() SettingsUpdateSchema, because clipboard
access differs by device and by origin.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 10:46:11 +02:00
Codeman maintainer 07b9c7fd7b fix(terminal): remove the unreachable copyTerminal(), closing out #322
The last two items of #322: copyTerminal() copied the entire buffer but
was wired to no button, shortcut or call site anywhere, and it wrote
through navigator.clipboard directly, which is undefined on the
plain-HTTP LAN install, so it would have failed there even if it were
reachable. Everything that actually copies goes through
copyTerminalSelection() and _copyText's execCommand fallback; whole-
buffer copy, should anyone want it, is a selectAll() away from that
same working path.

Closes #322

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-20 00:06:20 +02:00
Codeman maintainer c00e054e0e chore: version packages
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 23:43:22 +02:00
Codeman maintainer 68ae9a8c5f fix(files): match glob queries without regex so a hostile query cannot stall the server
The Files search compiled the user's query into a backtracking RegExp:
'*a*a*a...' became '^.*a.*a.*a...$', the classic blowup, evaluated
synchronously against every walked path — a pathological query could
freeze the event loop for the whole server (and every user of it in
multi-user mode). /api/search stays regex-free for exactly this reason.

Globs now match through a two-pointer wildcard walk, O(text · pattern)
worst case, with a 256-char query cap bounding the pattern side; an
overlong query compiles to null, the same answer as an empty one.
Semantics are unchanged (anchored, case-insensitive, * spans slashes)
and the existing tests pass untouched; the pathological pattern gets a
test that fails by timeout with the RegExp version.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 23:35:45 +02:00
Ark0N a49c30d173 Merge pull request #324 from aakhter/feat/files-panel-search
feat(files): search the Files panel by name or path
2026-08-19 23:33:08 +02:00
Codeman maintainer d871d1913f docs: restore the bullet PR #321 dropped off the xterm-zerolag-input gotcha
The new local-echo-overlay gotcha landed as a list item but left the
xterm-zerolag-input entry below it without its leading '- ', splitting
the Common Gotchas bullet list in two.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 23:25:09 +02:00
Ark0N ede3b05c10 Merge pull request #321 from rounakdatta/fix/mobile-link-taps
feat(mobile): links open from a tap, text can be copied, long prompts stay visible, wrapped links open whole
2026-08-19 23:23:51 +02:00
Ark0N c049de75db Merge pull request #320 from comzine/feat/custom-terminal-font
feat: Nerd Font prompt icons out of the box + configurable terminal font
2026-08-19 23:04:50 +02:00
Rounak DattaandClaude Opus 5 aae90599e5 fix(terminal): stitch a wrapped line through the indent its continuation carries
An agent's numbered list wraps its URL, and the link opened a PREFIX of it:

    1. https://github.com/users/someone/packages/container/p
       ackage/thing

opened `…/container/p`. The provider already stitched hard wraps — Ink emits a real
newline, so nothing is flagged `isWrapped` and a row that fills the last column is
taken as continuing — but it joined the row texts VERBATIM, and the continuation
carries the list's own three-space indent. That whitespace lands in the middle of
the token, which is exactly where the URL pattern stops. Flush-left wrapped URLs
(Claude Code's own `/login`) worked, which is why this survived.

The touch-selection helpers had the shallower version of the same bug: they walked
`isWrapped` only, so `Line` grabbed the single row on screen rather than the
logical line, and a long-press on a wrapped token selected only its visible half.

So the reconstruction now lives in ONE place, `terminalLogicalLine` in
constants.js, and both consumers use it — the link provider matching patterns over
its text and the selection helpers measuring words and lines with it. A link that
spans a wrap and a `Line` that stops at the screen edge were the same bug twice.

The helper drops the leading whitespace of a HARD continuation (the program's
indent) and keeps that of a SOFT one (the emulator inserts nothing, so it is real
content), records the dropped width per segment so the offset↔cell mapping stays
exact in both directions, trims only the final row so earlier offsets stay aligned
to cells, and keeps the 12-row bound that stops a screenful of full-width output
from being re-scanned on every hover.

⚠️ Selection spans are computed in CELLS, not text offsets: an xterm selection is
one contiguous run, so a token spanning a hard wrap also covers the indent cells
between its halves. A run that skipped them cannot be expressed, and would not
match what is highlighted.

Tests: `test/terminal-logical-line.test.ts` (8 cases: the indent drop, resolving
from either row, both mapping directions, soft continuations kept verbatim, no
over-reach past a short row, the row bound, final-row trimming, a missing row) and
5 in `terminal-touch-tap.test.ts` (the whole URL from either row, a token selected
across the wrap, `Line` spanning both rows, no reach into the next line). Removing
either half of the fix reds 5 and 8 of them respectively.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-19 19:41:43 +00:00
Rounak DattaandClaude Opus 5 2e58da7479 docs(mobile): document the phone gestures, and translate the selection bar
The three fixes in this branch change what a tap and a long-press MEAN on a
phone, and add a UI surface with its own z-index — all of which this repo keeps
written down rather than discoverable only by reading the handlers.

- `docs/wiki/Mobile-Guide.md` (the published user manual): a new "Tapping, links
  and copying" section, and the long-prompt behaviour in the keyboard section
  where the existing scroll/tap rules live.
- `CLAUDE.md`: the touch-gesture invariants next to the scrollback/wheel material
  (why the caret line is the boundary rather than the tap intent; why all three
  selection guards exist), the overlay's new bottom bound alongside the
  single-source note, and the selection bar in the z-index registry — 900, above
  terminal content and the local-echo overlay and deliberately below floating
  agent windows so it can never cover their controls.
- `i18n.js`: zh-CN for the bar's `Copy` / `Line` / `Clear selection`. The bar is a
  SIBLING of `.xterm`, not a descendant, so `SKIP_SELECTOR` does not cover it and
  the entries actually apply.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-19 19:19:36 +00:00
Rounak DattaandClaude Opus 5 ba843bb272 fix(mobile): keep a long prompt visible instead of hiding it behind the keyboard
Typing a prompt long enough to wrap ran the text off the bottom of the screen: the
tail — the part being typed, where the cursor is — sat behind the on-screen
keyboard, so the user was typing blind. Two independent causes.

**The overlay had no bottom bound.** On touch devices keystrokes are buffered in
the local-echo overlay and do not reach the PTY until Enter, so the CLI never
learns the prompt is long and nothing scrolls or reflows to make room. Meanwhile
the renderer lays its wrapped lines out straight DOWNWARD from the prompt row
(`top = promptRow * cellH`, each line at `i * cellH`) with nothing clamping it to
the visible rows — and with the keyboard up there are only a handful of those.

The block now grows UPWARD once it would pass the last visible row: it is lifted
so its final line lands ON that row. Every line div is opaque, so it covers
transcript above rather than vanishing under the keyboard below — the same thing a
real terminal does when a composer expands. A prompt taller than the whole
viewport keeps its TAIL, for the same reason the fix exists: the end is what the
user is looking at. `startCol` indents only the line that starts at the prompt
marker, so it is dropped along with that line when only the tail fits, and the
cursor follows the last VISIBLE line.

`rows` joins the render key: the layout depends on it, so a keyboard opening —
which changes rows without changing the text — must not be skipped as a redundant
render.

**`_shrinkPaddingToFit()` was reclaiming the bars' own space.** On phones the
toolbar and accessory bar are `position: fixed`, so they occupy no layout space
and `main`'s padding-bottom is the ONLY thing reserving room for them. Shrinking
it by the full sub-row slack pulled the terminal's bottom edge down underneath
them, and the row the following re-fit gained was painted behind them — clipping
the last line of a long prompt. The shrink now has a floor: the MEASURED height of
the currently-visible fixed bars, so genuine over-reservation of the hard-coded
84px is still reclaimed while a device that needs those pixels keeps them. The
floor is `Math.min(currentPadding, measured)`, so it can only ever prevent a
shrink, never cause a grow that would resize the terminal as a side effect.

Overlay behaviour lives in `packages/xterm-zerolag-input/` (single-source; the
vendor bundles are generated), so the fix is in the package with the row count
passed in as an optional `totalRows` — absent, the layout is exactly as before.

Tests: 7 cases in the package's `overlay-renderer.test.ts` (upward lift, tail
retention, indent drop, cursor on the last visible line, and the unclamped
fallbacks) and 7 in a new `test/mobile-keyboard-bottom-padding.test.ts` (reclaim,
floor, partial reclaim, no-grow, hidden bars, CJK strip, whole-row slack). 5 and 4
of them respectively fail without the fix. Package suite 238 pass, including the
codex byte-identity and replay tests.

Verified on Android + Chrome against a live instance: a ~460-character prompt
wrapping ~12 rows stays on screen while typing and arrives at the PTY intact.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-19 19:14:52 +00:00
Rounak DattaandClaude Opus 5 756728e553 feat(mobile): long-press to select terminal text, tap to extend, Copy
There was no way to copy terminal text from a phone at all, and three layers
ruled it out independently: `user-select: none` across the whole terminal subtree
on touch devices (taps are cursor gestures there, so the OS callout had to go),
the WebGL renderer drawing glyphs as pixels with only the accessibility tree
behind them, and xterm's own selection being a mouse DRAG while the touch path
dispatches a zero-movement mousedown/mouseup pair — a click. `copyTerminal()`
exists but is wired to no button and calls `navigator.clipboard` directly, which
is undefined on the plain-HTTP LAN install the installer offers.

So the gesture drives xterm's `select()` directly: public API, renderer-
independent, and the highlight is drawn by xterm itself. Long-press is free real
estate — tap and swipe are taken, long-press and double-tap are used by nothing.

- **Long-press** (350ms, finger still within the shared tap slop) selects the
  run of non-whitespace under the finger. Whitespace is the only delimiter on
  purpose: every punctuation-aware word rule cuts a path, URL or hash in half,
  which is what you came to copy.
- **Drag** while held extends the selection; touchmove diverts from scrolling.
- **Tap** while the bar is up extends it too. That is the ergonomic core:
  picking up a 4px handle with a fingertip is a coin flip, tapping the other end
  is not. Dismissal stays explicit (✕ or Copy), so no tap is spent leaving a mode
  the user is still using.
- **Copy** goes through the existing `copyTerminalSelection()`, so it inherits
  the execCommand fallback that is the only route that works on plain HTTP.
- **Line** takes the whole logical line, wraps included, trailing pad trimmed.

Three guards are what make the gesture survive contact with a real phone, and
each fixes a symptom measured on Android Chrome:

1. **The compat mouse pair after touchend.** xterm focuses from its screen-element
   mousedown and SelectionService resets the model there, so lifting your finger
   popped the keyboard and dissolved the selection in one go. The tap path already
   had a guard for those events; the selection path simply never armed it. Armed
   now, and the touchend is `preventDefault`ed so the synthesis is stopped at the
   source (that listener is no longer passive).
2. **The platform's own long-press.** Android Chrome runs its handling at ~500ms
   and focuses the nearest editable element — xterm's helper textarea, parked at
   the cursor — which no touch handler can preventDefault because it never sees an
   event. A focus guard blurs the terminal input for the duration of the gesture,
   whatever focused it, bounded by a self-expiring deadline so a stuck flag can
   never leave the keyboard unreachable. `contextmenu` is suppressed for the same
   window, and the threshold sits at 350ms so it lands clear of the platform's.
3. **Copy re-focusing the terminal.** `copyTerminalSelection()` ends with
   `terminal.focus()`, which is right on a desktop and wrong on a phone: the
   keyboard covers what was just copied with nothing waiting to be typed.

The bar is built in JS because index.html is read once at server start, and its
styles live in styles.css rather than mobile.css because the gesture is
touch-driven, not width-driven — a touch tablet in landscape gets the gesture and
would otherwise have no bar to copy from.

12 tests in `terminal-touch-tap.test.ts` cover the word rule, forward and
backward extension, cross-row selection, Line, tap-to-extend, the copy path, and
each of the three guards including the focus guard's expiry.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-19 19:14:52 +00:00
Rounak DattaandClaude Opus 5 f2d3a7e3c1 fix(mobile): links open in a new tab from a tap, in the terminal and the chat
On a phone no link was openable, on either surface, for two unrelated reasons.

**Terminal.** xterm resolves the link under the pointer on `mousemove` and
activates it on `mouseup` over its SCREEN element. A touch tap delivers neither:
`touch-action: none` on the terminal subtree plus touchstart's preventDefault for
a 'content' tap suppress the browser's compatibility mouse events,
`_installMobileTapMouseGuard` drops the trusted ones that still arrive inside the
450ms tap window, and the synthetic mousedown/mouseup pair dispatched for mouse
REPORTING goes to the `.xterm` root — an ancestor of the node the linkifier
listens on, so it cannot reach it — and carries no mousemove either way. Every
URL and file path in the terminal was therefore inert on phones and tablets,
Claude Code's own `/login` URL included.

The tap path now activates the link itself, through the SAME provider that feeds
the hover linkifier (`_terminalLinkAtPoint`), so a tap and a desktop click can
never disagree about what is a link or where it ends — containment mirrors
xterm's own `_linkAtPosition`. It runs synchronously inside the touchend handler,
which is what keeps the user gesture that lets `window.open` past the popup
blocker, and before any mouse report, exactly as `_handleDesktopTerminalClick`
already skips the SGR tap for a hovered link.

Two kinds of row keep their existing meaning: the caret's logical line, where a
tap places the cursor and a URL the user typed must stay editable, and TUI-owned
rows, where a numbered choice or an expandable readback is answering a dialog and
routinely carries the very path the tap would otherwise open. The caret line is
the boundary rather than the tap intent, because a plain shell classifies EVERY
tap as 'input' and gating on that would leave every URL in shell output inert.

**Chat.** `marked` emits a bare `<a href>` and the markdown sanitizer's allowlist
carries no `target`, so a tap in the response viewer navigated the current tab
away: on a phone that unloads the whole dashboard — SSE, terminal buffers, unsent
composer text — and there is no middle-click or open-in-new-tab affordance to
work around it. `_renderMarkdown` now decorates anchors in the template pass it
already makes for code blocks. That pass runs AFTER sanitizing, so it is the only
source of both attributes: an agent-authored `target`/`rel` is already stripped,
and `rel="noopener noreferrer"` is set on the same element in the same breath, so
no page Codeman opens gets a `window.opener` handle back. Fragment links stay
in-page; mailto:/tel: are left to the OS rather than stranding an empty tab.

Tests: 10 cases in `terminal-touch-tap.test.ts` (URL, file path, log path,
scrollback, no-double-report, composer, shell mode, dialog row, no provider) and
a new `response-viewer-external-links.test.ts` driving the shipped marked +
DOMPurify + app.js. 7 of them fail without the fix.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-19 19:14:52 +00:00
Aamer Akhter 5cc78669bd feat(files): search the Files panel by name or path
GET /api/sessions/:id/files gains an optional `q`. With one, the endpoint
answers a FLAT match list instead of a nested tree; without one, the response is
exactly what it was, so every existing caller is untouched.

compileFileQuery() (src/utils/file-query.ts) turns the query string into a
reusable predicate, so the walk prunes as it goes rather than streaming the
whole tree to the client to be filtered there. An empty or whitespace-only
query compiles to null, which is what makes "no query" and "blank query" the
same thing.

The search walk deliberately recurses past directories that do not match — a
file whose ancestors don't match is exactly what people are searching for — so
it carries its own maxMatches cap on top of the existing maxFiles and maxDepth
ones, and reports `truncated` when it stops early. Hidden-file and
excluded-directory rules are the same ones tree mode already applies.

Tests: file-query.test.ts covers the matcher; routes/file-search-mode.test.ts
drives the endpoint against a real temp tree and pins the two properties worth
having — that the walk reaches a match under non-matching parents, and that an
absent or whitespace query leaves the tree response alone. Gating the recursion
on a match turns those red.
2026-08-19 09:17:20 -04:00
Ark0N d4ccff07ca Merge pull request #319 from Ark0N/fix/dep-advisories
fix(deps): clear production npm advisories, fix sw.js caching regression
2026-08-19 14:54:21 +02:00
Tobias WeberandClaude Fable 5 108c00e78d feat: bundled Nerd Font symbols fallback + per-device terminal font setting
Shell prompts using Nerd Font glyphs (powerline, p10k/starship folder and
git icons) rendered as missing-glyph boxes: the built-in xterm stack has no
private-use-area symbols, and phones have no Nerd Fonts installed at all.

- Bundle Symbols Nerd Font Mono (icons-only, MIT, 1.2MB woff2) served from
  fonts/ and appended to the terminal stack before monospace — browsers fall
  back per glyph, so icons render everywhere while text stays in the text
  fonts. font-display: block + preload keep tofu out of xterm's glyph atlas.
- New per-device terminalFontFamily setting (App Settings > Terminal &
  Input > Font): prepended to the built-in stack, never a replacement, so
  the symbols fallback and final monospace always survive. Applied live on
  save (refit + echo-overlay refreshFont, mirroring setFontSize).
- Single source for both xterm surfaces: TERMINAL_FONT_DEFAULT_STACK +
  resolveTerminalFontFamily() in constants.js, unit-tested.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VjnbbZRBuvR5E3SDouwXr9
2026-08-19 00:45:19 +02:00
Codeman maintainer 8a54b331e3 fix(deps): clear production npm advisories, fix sw.js caching regression
Resolves the four advisories that reach the production dependency tree. The
other 16 npm audit reports are devDependencies-only (Remotion, Puppeteer,
postcss, the eslint/tsx toolchain) and never ship to users.

- @fastify/static 9.1.3 -> 10.1.3  GHSA-8pvw-jcv7-9cmj (authz bypass via
  non-canonical URL paths). Covers <=10.1.1, so all of 9.x is affected and
  the fix exists only on the 10.x line.
- find-my-way 9.6.0 -> 9.8.0       GHSA-c96f-x56v-gq3h (HTTP/2 DDoS)
- fast-uri 3.1.2 -> 3.1.5          GHSA-v2hh-gcrm-f6hx (host confusion)
- brace-expansion -> 5.0.9/1.1.18  GHSA-3jxr-9vmj-r5cp (expansion DoS)

The last three are transitive and needed only a lockfile re-resolve, so no
overrides were introduced.

The @fastify/static major changes setHeaders' first argument from a Node
ServerResponse to a FastifyReply. Two consequences:

1. res.setHeader() -> reply.header(). The v9 body throws TypeError from
   inside the plugin on every static request.
2. Precedence flips, silently. The callback used to write to the raw
   response and lose to the route's staged reply headers; it now writes to
   the reply and wins. That gave /sw.js a year of immutable in place of the
   no-cache, no-store its route sets, pinning a service worker on every
   client with no server-side recovery. A route that already set
   Cache-Control now keeps it.

Verified against v9 to confirm the sw.js behaviour is a regression and not
a pre-existing bug.

ws appears in npm audit but production is on 8.21.0, outside the vulnerable
range; the only affected copy is bundled under @remotion/renderer (dev-only,
and remotion is pinned at 4.0.473 because the compositor refuses to start on
a version mismatch).

Adds test/static-cache-headers.test.ts, which drives a real server and covers
a caching contract that had no test at all.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-18 23:24:22 +02:00
203 changed files with 30649 additions and 2801 deletions
-2
View File
@@ -93,8 +93,6 @@ packages/gesture-control/.vite/
# Claude Code plan tracking
plan.json
# Unfinished TUI (local development only)
src/tui/
.claude/
media-assets/
commands
+111
View File
@@ -1,5 +1,116 @@
# aicodeman
## 1.22.0
### Minor Changes
- 3f8c8e9: Add Grok Build (xAI `grok`) as a seventh CLI run mode. SessionMode gains 'grok', with its own resolver (version-probed, since the name has npm squatters; GET /api/grok/status surfaces path + version), GrokConfig (model, alwaysApprove -> --always-approve, resume/continue), GROK*\*/XAI*\* env allowlist entries, the multi-user only-if-sent bypass clamp, Docker (own image step + per-file credential seeding) and remote-SSH command defaults, cron agentType, run-mode/welcome/tab UI with a charcoal identity, and docs (grok-integration.md + plan). Verified end to end against grok 1.0.5 on an isolated instance.
- 74194e4: Add the owner-scoped tab-layout model, persistence, API, lifecycle repair, and synchronized legacy ordering foundation.
- e3a2fb7: Add an optional resizable vertical session rail with responsive layout, complete labels, accessible controls, and stable inline rename.
### Patch Changes
- 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.
## 1.21.0
### Minor Changes
- **`codeman tui`: a terminal dashboard for your sessions.** For the times you are in SSH or Termius instead of a browser. The web UI remains the primary surface and bare `codeman` still prints help, so the dashboard itself is strictly additive.
Sessions are grouped NEEDS YOU / WORKING / IDLE / RECENT in the same status language as the web tabs and the phone overview, and the states come from the server (hooks, idle confirmation, the approvals inbox) over the existing HTTP/SSE API rather than being screen-scraped. That is what lets the dashboard answer a permission dialog instead of only reporting one.
- `↑↓`/`j`/`k` select; `1`-`9`, `[`/`]` and `Tab` switch between sessions
- `Enter` attaches and hands the terminal to tmux; **`F1` comes back**, one key, no modifier. Inside the pane a bar across the top carries the session strip and `Alt+1`..`Alt+9` switch without returning to the dashboard first
- `Enter` on a RECENT row resumes that conversation; on a session whose pane has died it refuses and offers `r` to resume it in a fresh pane
- `y`/`n`/digits answer the selected session's pending permission or question card (the server re-captures the pane first, so a keystroke can never land in the composer)
- `p` sends a one-line prompt without attaching, `x` kills (`y` confirms), `n` starts a session and opens straight into it
- `/` cross-session search, `g` away digest, `?` help, live preview pane, plan-usage chip in the header, a terminal bell when a new approval arrives
- `codeman tui --list` and `codeman tui <n>` are scriptable fast paths; with no server running it lists panes straight from the instance's tmux socket, attach-only, and upgrades live when the server comes back
Narrow terminals (under 72 columns, a phone SSH client) drop the preview and get a single-column layout. `NO_COLOR`, non-UTF-8 glyph fallback and a non-TTY refusal are all handled. Zero new dependencies: hand-rolled ANSI over chalk and commander. User guide: `docs/tui.md`.
**Breaking: the `sc` tmux chooser is retired.** `scripts/tmux-chooser.sh` is deleted and `install.sh` no longer creates the `tmux-chooser` symlink or the `sc` alias; it sweeps both up instead, on update and on uninstall. `codeman tui` replaces it and does the job better: `sc` numbered its entries globally but only accepted a single `[1-9]` keypress, so sessions 10+ were listed and could not be selected, and it inferred nothing about what an agent was doing. The alias cleanup is marker-owned, matching the exact line the installer wrote, so a user's own `alias sc=` for another tool is untouched.
**CLI polish that came with it.**
- New shared style kit (`src/cli-style.ts`) used across the CLI: semantic palette, glyphs, width-aware table, spinner, confirm.
- `codeman doctor` is colorized and its table is measured, so the "Antigravity CLI" label no longer pushes its row out of column. `--json` output is unchanged.
- `codeman web` no longer prints its "running at" line twice, and the server's non-loopback security warning is painted like the CLI's (chalk degrades off a TTY, so journald and `web.log` stay free of escape codes).
- Spinners on the silent up-to-30s waits in `codeman web -d`, `codeman web --stop` and `codeman service install`.
- `codeman reset` asks a real y/N confirmation on a TTY; non-interactive callers keep the old `--force` refusal.
- `codeman list` and `codeman session list` share one renderer instead of drifting copies.
- `codeman attach` is described correctly in the README (it shows an attachment card for a local file).
- `test/cli-commands.test.ts` now derives its inventory from the real commander program instead of a hand-written fixture that had drifted.
**Internal.** New `tmux -L` callers resolve the socket through `resolveTmuxSocketName()`, now exported from `config/instance.ts`, so a second process can never point a beta instance at prod's panes. CLAUDE.md and `docs/architecture-invariants.md` both record the rule.
### Thanks
The TUI went through seven rounds of beta testing over PuTTY/SSH by **@Ark0N**, which is where the way out of an attach, the session strip, the preview repaint handling and the glyph set all came from.
## 1.20.1
### Patch Changes
- Terminal input and scrollback fixes (PRs #327, #331):
- IME punctuation preserved (#327): keyCode 229 / `Process` key events are now delegated to xterm's CompositionHelper instead of being suppressed, so an active Chinese IME committing numbers and full-width punctuation (,。!? and friends) reaches the terminal correctly. The CJK input field sends the browser's committed text instead of guessing from `KeyboardEvent.key`, and the redundant Android orphan-input fallback is removed so xterm is the single input owner.
- Shell history replay bounded (#331): selecting a Shell session loads a bounded 1 MiB tail instead of replaying the entire multi-megabyte tmux scrollback on xterm's main thread; full history stays available via the explicit "Load full history" action. tmux history limits now apply correctly on both legacy tmux (global default set in the same command queue before pane creation) and tmux 3.7+ (per-pane targeting that never resizes or trims unrelated live panes). Also adds `Server-Timing` and `[TERMINAL-PERF]` timing stages for terminal loads, fixes `scrollToLastNonEmptyLine` double-counting scrollback rows, and keeps live output ordered behind snapshot replays.
### Thanks
- @dignfei for both fixes: the IME punctuation root-cause fix (#327) and the bounded shell history replay with the tmux history-limit correctness work (#331).
## 1.20.0
### Minor Changes
- Response viewer for OpenCode, Gemini, Antigravity and Pi sessions (#326). External CLIs render their own TUIs, so the viewer used to come up empty for them; a new transcript parser (`response-viewer-transcript.ts`) reconstructs the conversation from the pane text instead, and the `?context=full` view now tags every block with a role so prompts render as "You" and agent output as the assistant. The divider normalizer was rewritten as a linear scan after review found catastrophic backtracking on agent-controlled input (minutes of stall on a long dash run), with an equivalence corpus pinning the old accept set.
CLIs installed via nvm or Homebrew are now found when Codeman runs as a service (#329). A shared resolver falls back to a login-shell probe when the direct PATH lookup misses, so systemd and LaunchAgent installs no longer report every CLI as missing. Review hardening on top: a failed resolution is negative-cached with doubling backoff instead of re-spawning a login shell on every request, all probes pass `killSignal: 'SIGKILL'` (interactive bash shrugs off SIGTERM, and a blocking `.bash_profile` could have hung the server indefinitely), the resolvers are inert under vitest again so test suites cannot execute binaries found on the dev box, and the improved not-found guidance is wired into both the session-create errors and the per-CLI status endpoints.
`GET /api/system/repo-status` reports branch, upstream, ahead/behind and remote reachability for git-clone installs (#328). Review hardening: the git network calls moved off the synchronous path onto a single-flight 45s cache (one slow remote could previously freeze the whole server for up to a minute per request), remote URLs and git stderr are credential-redacted before they leave the server, the spawns use the same non-interactive git env as the clone path, and a local-branch upstream no longer parses into garbage.
Auto Copy for the terminal (#325, opt-in, per-device): a finished selection (mouse drag, double or triple click, or a phone long-press) lands on the clipboard by itself, so select-then-copy becomes select. Alongside it, hand-encoded tap reports are now gated on the server-observed `cliMouseTracking` state, so a pane that has fallen back to a plain shell no longer receives `[<0;88;20M` junk on tap.
The Ralph loop no longer stops polling after two ticks (#330): the reschedule guard read a stale timer handle that the timer callback never cleared, so the loop silently died while its status stayed `running`. The handle is now nulled as the callback's first statement, and a regression test pins the bug.
The red "needs you" tab alert clears when a dialog is answered in the terminal instead of surviving until the end of the turn: the post-hook re-capture could erase the parsed dialog options that the staleness sweep relies on (`applyCapture` is now add-only for options), and a delayed staleness pass now runs while a page is open. The unreachable `copyTerminal()` was removed, closing out #322.
### Thanks
- @aakhter contributed the external-CLI response viewer (#326), the repo-status endpoint (#328), the login-shell CLI resolution (#329) and the Ralph reschedule fix (#330)
- @rounakdatta reported the mobile copy gap (#322) closed out in this release
## 1.19.7
### Patch Changes
- Mobile catches up: links open from a tap, terminal text can be selected and copied, long prompts stay visible while you type. Plus Files panel search, a bundled Nerd Font symbols fallback, and a per-device terminal font setting.
- **Terminal and chat links work on phones** (#321): tapping a URL or file path in terminal output now opens it (new tab, file preview, or log viewer), resolved through the same provider desktop hover uses, so tap and click can never disagree about what is a link. Dialog rows and the composer keep their existing meaning. Response-viewer links open in a new tab with `rel="noopener noreferrer"` instead of navigating the dashboard away. Wrapped links open whole: the logical-line reconstruction now stitches hard wraps through the indent their continuation carries, which also fixes desktop hover-click truncating wrapped URLs.
- **Terminal text can be copied on touch devices** (#321): long-press selects the token under the finger, drag or tap the other end to extend, and a small bar offers Copy, Line (the whole logical line, wraps included) and dismiss. Copy works on plain-HTTP installs too. Three guards keep the keyboard down and the selection alive through the browser's own long-press handling.
- **A long prompt stays visible on phones** (#321): the local-echo overlay grows upward once it would run past the last visible row (a prompt taller than the screen keeps its tail, where the cursor is), and the keyboard-driven padding shrink can no longer reclaim the space the fixed toolbar and accessory bar stand in.
- **Files panel search** (#324): `GET /api/sessions/:id/files?q=...` answers a flat match list (name or path substring, `*`/`?` globs), recursing past non-matching directories with its own match cap on top of the existing bounds; without `q` the response is byte-identical to before. Glob queries are matched without regex so a pathological pattern cannot stall the server.
- **Nerd Font prompt glyphs out of the box, custom terminal font** (#320): a bundled icons-only Symbols Nerd Font Mono fallback renders powerlevel10k/starship/oh-my-posh glyphs on every device with no font install, and App Settings gains a per-device terminal font family that is prepended to the built-in stack.
### Thanks
Three contributor PRs in one release: thanks to @rounakdatta (#321), @aakhter (#324) and @comzine (#320).
- 8a54b33: Clear every production-reachable npm advisory, and fix a service-worker caching regression the upgrade exposed.
`npm audit` reported 20 advisories, but 16 were devDependencies-only (Remotion, Puppeteer, postcss, the eslint/tsx toolchain) and never reached anyone installing the package. Four reached production and are now resolved:
- **`@fastify/static` 9.1.3 to 10.1.3** — GHSA-8pvw-jcv7-9cmj, authorization bypass via non-canonical URL paths. The advisory covers `<=10.1.1`, so the entire 9.x line is affected and the fix only exists on 10.x.
- **`find-my-way` 9.6.0 to 9.8.0** — GHSA-c96f-x56v-gq3h (HTTP/2 DDoS). Not exploitable here since Codeman does not enable HTTP/2, fixed anyway.
- **`fast-uri` 3.1.2 to 3.1.5** — GHSA-v2hh-gcrm-f6hx, host confusion via a literal backslash authority delimiter.
- **`brace-expansion` to 5.0.9 / 1.1.18** — GHSA-3jxr-9vmj-r5cp, exponential-time expansion DoS.
The last three were transitive and only needed a lockfile re-resolve; no `overrides` were added.
The `@fastify/static` major changes the `setHeaders` callback's first argument from a Node `ServerResponse` to a `FastifyReply`, which required two fixes:
- `res.setHeader()` became `reply.header()`. A v9-style body throws `TypeError: res.setHeader is not a function` from inside the plugin on every static request.
- **That change also flips precedence, silently.** The callback used to write to the raw response and be overwritten by the route's staged reply headers; it now writes to the reply and wins instead. That handed `/sw.js` a year of `immutable` in place of the `no-cache, no-store` its route sets, which would pin a service worker on every client with no server-side way to recover. A route that already set `Cache-Control` now keeps it.
`ws` also appears in `npm audit` but production is already on 8.21.0, outside the vulnerable range; the only affected copy is bundled under `@remotion/renderer` and is dev-only.
Adds `test/static-cache-headers.test.ts`, which drives a real server and covers the caching contract that had no test at all, and moves the floors in `test/dependency-security.test.ts` up to the patched versions.
## 1.19.6
### Patch Changes
+28 -21
View File
File diff suppressed because one or more lines are too long
+19 -15
View File
@@ -5,7 +5,7 @@
<h2 align="center">Mission control for AI coding agents</h2>
<p align="center">
<em>Claude Code &bull; OpenCode &bull; Codex &bull; Antigravity &bull; Gemini &bull; Pi &bull; Terminal - One Dashboard &bull; Any Device</em>
<em>Claude Code &bull; OpenCode &bull; Codex &bull; Antigravity &bull; Gemini &bull; Pi &bull; Grok &bull; Terminal - One Dashboard &bull; Any Device</em>
</p>
<p align="center">
@@ -27,7 +27,7 @@
<img src="docs/images/subagent-demo-20260724.gif" alt="Codeman — parallel subagent visualization" width="900">
</p>
**Codeman** is a self-hosted mission control for AI coding agents. It spawns Claude Code, OpenCode, Codex, Antigravity, Gemini, or Pi inside persistent tmux sessions, streams the real terminal to any browser, and keeps agents productive after you walk away: it re-prompts on idle, resumes when a usage limit resets, runs scheduled jobs, and shows every background agent working in real time.
**Codeman** is a self-hosted mission control for AI coding agents. It spawns Claude Code, OpenCode, Codex, Antigravity, Gemini, Pi, or Grok inside persistent tmux sessions, streams the real terminal to any browser, and keeps agents productive after you walk away: it re-prompts on idle, resumes when a usage limit resets, runs scheduled jobs, and shows every background agent working in real time.
Get started in one line (macOS & Linux, Windows via WSL):
@@ -42,7 +42,7 @@ codeman web
The installer asks before every system change, and re-running the same line updates in place. Full details: [Quick Start - Installation](#quick-start---installation).
- **One dashboard, six CLIs** - run [Claude Code, OpenCode, Codex, Antigravity, Gemini, or Pi](#more-features) per session (plus plain shell), locally, [in Docker](#isolated-docker-sessions), or [over SSH](#remote-ssh-sessions)
- **One dashboard, seven CLIs** - run [Claude Code, OpenCode, Codex, Antigravity, Gemini, Pi, or Grok](#more-features) per session (plus plain shell), locally, [in Docker](#isolated-docker-sessions), or [over SSH](#remote-ssh-sessions)
- **Truly phone-friendly** - a [touch-optimized terminal](#mobile-optimized-web-ui) with instant local echo, QR login, swipe navigation, and push notifications
- **Runs while you sleep** - [idle detection + respawn cycling](#respawn-controller) and auto-resume when a subscription limit resets, for 24+ hour unattended runs
- **See your agents think** - [live floating windows](#live-agent-visualization) for every subagent and teammate, with real-time transcripts
@@ -68,7 +68,7 @@ This installs Node.js and tmux if missing, clones Codeman to `~/.codeman/app`, a
- **Re-run to update.** The same one-liner updates a finished install in place: local changes in `~/.codeman/app` are stashed (never discarded), and a running service is restarted and verified. If a first install was interrupted, re-running resumes the full setup instead. `install.sh update` and `install.sh uninstall` also exist.
- **CI / headless:** without a terminal attached, steps that would change your system abort with instructions instead of running silently. Set `CODEMAN_NONINTERACTIVE=1` to approve them for automation.
You'll need at least one AI coding CLI installed — [Claude Code](https://docs.anthropic.com/en/docs/claude-code), [OpenCode](https://opencode.ai), [Codex](https://developers.openai.com/codex/cli), [Antigravity](https://antigravity.google), [Gemini CLI](https://github.com/google-gemini/gemini-cli), or [Pi](https://pi.dev) (any combination works; Gemini CLI is enterprise-only since Google's consumer cutover, and Antigravity is its successor). The installer detects whichever of the six is present; if none is found, it offers to install Claude Code or OpenCode, or you can skip and install one yourself later. After install:
You'll need at least one AI coding CLI installed — [Claude Code](https://docs.anthropic.com/en/docs/claude-code), [OpenCode](https://opencode.ai), [Codex](https://developers.openai.com/codex/cli), [Antigravity](https://antigravity.google), [Gemini CLI](https://github.com/google-gemini/gemini-cli), [Pi](https://pi.dev), or [Grok Build](https://github.com/xai-org/grok-build) (any combination works; Gemini CLI is enterprise-only since Google's consumer cutover, and Antigravity is its successor). The installer detects whichever of the seven is present; if none is found, it offers to install Claude Code or OpenCode, or you can skip and install one yourself later. After install:
```bash
codeman web
@@ -171,7 +171,7 @@ launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.codeman.web.plist
wsl bash -c "curl -fsSL https://getcodeman.com/install | bash"
```
Codeman requires tmux, so Windows users need [WSL](https://learn.microsoft.com/en-us/windows/wsl/install). If you don't have WSL yet: run `wsl --install` in an admin PowerShell, reboot, open Ubuntu, then install your preferred AI coding CLI inside WSL ([Claude Code](https://docs.anthropic.com/en/docs/claude-code), [OpenCode](https://opencode.ai), [Codex](https://developers.openai.com/codex/cli), [Antigravity](https://antigravity.google), [Gemini CLI](https://github.com/google-gemini/gemini-cli), or [Pi](https://pi.dev)). After installing, `http://localhost:3000` is accessible from your Windows browser.
Codeman requires tmux, so Windows users need [WSL](https://learn.microsoft.com/en-us/windows/wsl/install). If you don't have WSL yet: run `wsl --install` in an admin PowerShell, reboot, open Ubuntu, then install your preferred AI coding CLI inside WSL ([Claude Code](https://docs.anthropic.com/en/docs/claude-code), [OpenCode](https://opencode.ai), [Codex](https://developers.openai.com/codex/cli), [Antigravity](https://antigravity.google), [Gemini CLI](https://github.com/google-gemini/gemini-cli), [Pi](https://pi.dev), or [Grok Build](https://github.com/xai-org/grok-build)). After installing, `http://localhost:3000` is accessible from your Windows browser.
</details>
@@ -253,7 +253,7 @@ Click **+ New Session** (or **Quick Start**). A session is one AI CLI running in
| Field | What it does |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| **Working directory / case** | The folder the agent operates in. A "case" is just a named working dir Codeman remembers. **Add Case** creates one from scratch, links an existing folder, or clones a GitHub repo straight into one (**Clone Repo**). |
| **CLI / run mode** | `Claude` (default), `OpenCode`, `Codex`, `Antigravity`, `Gemini`, `Pi`, or `Terminal` (plain shell). |
| **CLI / run mode** | `Claude` (default), `OpenCode`, `Codex`, `Antigravity`, `Gemini`, `Pi`, `Grok`, or `Terminal` (plain shell). |
| **Model** | Per-session model (App Settings → Models → New Claude sessions). A soft default — `/model` still works in-session. |
| **Effort / Ultracode** | Reasoning effort (`low`–`max`) or `ultracode` for dynamic multi-agent workflows. Switchable anytime with `/effort`. |
@@ -285,7 +285,7 @@ Hit start — Codeman spawns the CLI via a real PTY and streams it to your brows
- **Phone/tablet** — the UI is fully touch-optimized; scan the desktop **QR code** to log in without typing a password.
- **Outside your network** — `./scripts/tunnel.sh start` opens a Cloudflare tunnel (set `CODEMAN_PASSWORD` first).
- **SSH** — the `sc` chooser attaches to any session from a terminal (`sc` interactive, `sc 2` quick-attach, `sc -l` list).
- **SSH** — `codeman tui` is a full-screen dashboard in the terminal (`codeman tui --list` to list, `codeman tui 2` to attach straight to one).
### 7. Operate & maintain
@@ -437,7 +437,7 @@ PTY Output → 16ms Server Batch → DEC 2026 Wrap → SSE → Client rAF → xt
- **Background daemon & service install** — `codeman web -d` runs the server detached with a pidfile, `~/.codeman/web.log`, and verified startup (it polls the server until it answers, so a port clash never reads as success); `codeman service install` writes a systemd user unit (Linux) or LaunchAgent (macOS) with your shell's PATH baked in, so an nvm or Homebrew `node`, `tmux` and `claude` are actually found. Secrets are never written into unit files
- **Self-update** — git-clone installs under systemd/launchd update in place from **App Settings → System → Updates**: it detects the latest release, auto-stashes a dirty tree, and streams build progress across the service restart (npm installs report as non-updatable)
- **Clone a GitHub repo as a case** — paste a repository URL into **Add Case → Clone Repo** and Codeman clones it into `~/codeman-cases/<name>` and registers it as a normal case, ready to run an agent in. It preflights the URL while you type (tells you whether it can be cloned anonymously and offers the repo's real branches and tags for the optional branch/tag field), fills the case name in from the URL, and lets you pick which CLI the Run button should use. Public repositories over `https://`; Codeman never collects or stores credentials
- **Multi-CLI** — run **Claude Code**, **OpenCode**, **Codex**, **Antigravity**, **Gemini**, or **Pi** per session; env-var prefixes auto-gate (`CLAUDE_CODE_*` vs `OPENCODE_*` vs `CODEX_*` vs `ANTIGRAVITY_*` vs `GEMINI_*`/`GOOGLE_*` vs `PI_*`). See [`docs/opencode-integration.md`](docs/opencode-integration.md) and [`docs/pi-integration.md`](docs/pi-integration.md)
- **Multi-CLI** — run **Claude Code**, **OpenCode**, **Codex**, **Antigravity**, **Gemini**, **Pi**, or **Grok** per session; env-var prefixes auto-gate (`CLAUDE_CODE_*` vs `OPENCODE_*` vs `CODEX_*` vs `ANTIGRAVITY_*` vs `GEMINI_*`/`GOOGLE_*` vs `PI_*` vs `GROK_*`/`XAI_*`). See [`docs/opencode-integration.md`](docs/opencode-integration.md), [`docs/pi-integration.md`](docs/pi-integration.md) and [`docs/grok-integration.md`](docs/grok-integration.md)
- **Docker sessions** — run a case inside an isolated, hardened container. One checkbox on **Create New** spins up a container with sensible defaults and starts the agent inside it; multiple sessions share one per-case container; export a container + its workspace to a portable `.tar.gz` to move it to another machine. See [`docs/docker-cases.md`](docs/docker-cases.md)
- **Remote SSH sessions** — point a case at another machine and run the agent there inside a durable remote tmux: survives SSH drops, auto-reconnects, and can discover + attach sessions already running on the host. See [`docs/remote-sessions.md`](docs/remote-sessions.md)
- **Effort & Ultracode** — set a per-session default effort (`low`–`max`) or enable **ultracode** (dynamic multi-agent workflows). Soft defaults only — switchable anytime with `/effort` in-session. Extended-thinking budget is configurable too
@@ -658,17 +658,19 @@ These run for **every** request — before auth, even on the default no-password
---
## SSH Alternative (`sc`)
## Terminal UI (`codeman tui`)
If you prefer SSH (Termius, Blink, etc.), the `sc` command is a thumb-friendly session chooser:
A full-screen dashboard for your sessions, in the terminal. Same states as the web UI, because it is a client of the same server:
```bash
sc # Interactive chooser
sc 2 # Quick attach to session 2
sc -l # List sessions
codeman tui # the dashboard
codeman tui --list # numbered session list, then exit (scriptable)
codeman tui 2 # attach straight to session 2 of that list
```
Single-digit selection (1-9), color-coded status, token counts, auto-refresh. Detach with `Ctrl+A D`.
Sessions are grouped **NEEDS YOU → WORKING → IDLE → RECENT**, longest-waiting first. `↑↓`/`j`/`k` select, `1`-`9` and `[`/`]` switch between sessions, `Enter` attaches into the tmux pane (**`F1`** to come back). Inside a pane the bar across the top keeps the session strip visible and `Alt+1`-`Alt+9` switch without leaving. `y`/`n`/digit answer a pending permission dialog right from the list, `p` sends a one-line prompt, `n` starts a session and opens straight into it, `x` kills one (`y` confirms), `/` searches, `g` shows the away digest, `?` is help, `q` quits. Below 72 columns it drops the preview pane and becomes a single-column list, so it stays usable in Termius on a phone. With no server running it still starts in attach-only degraded mode.
The web UI remains the primary surface; see **[docs/tui.md](docs/tui.md)** for the full guide.
---
@@ -893,7 +895,9 @@ codeman session start -d /path/to/repo # (s) start a session
codeman session list # list sessions
codeman session logs <id> # tail output
codeman task add "fix the failing test" # (t) queue a task
codeman attach <path> # attach a Claude hook context
codeman attach <path> # show an attachment card for a local file
codeman tui --list # numbered session list (plain text when piped)
codeman tui 3 # attach to session 3 of that list
```
### Hooks (events flowing _back_ to Codeman)
+6 -20
View File
@@ -5,7 +5,7 @@
<h2 align="center">AI 编程智能体的任务控制中心</h2>
<p align="center">
<em>Claude Code &bull; OpenCode &bull; Codex &bull; Antigravity &bull; Gemini &bull; Pi &bull; 终端 —— 统一仪表盘 &bull; 任意设备</em>
<em>Claude Code &bull; OpenCode &bull; Codex &bull; Antigravity &bull; Gemini &bull; Pi &bull; Grok &bull; 终端 —— 统一仪表盘 &bull; 任意设备</em>
</p>
<p align="center">
@@ -58,7 +58,7 @@ curl -fsSL https://getcodeman.com/install | bash
- **重跑即更新。** 再次运行同一条命令即可原地更新已完成的安装:`~/.codeman/app` 中的本地改动会被 stash(绝不丢弃),运行中的服务会自动重启并校验。若首次安装中途失败,重跑会继续完成完整的安装流程。也可以使用 `install.sh update` 与 `install.sh uninstall`。
- **CI / 无终端环境:** 没有终端时,涉及系统改动的步骤会带着说明中止,而不是静默执行;在自动化场景设置 `CODEMAN_NONINTERACTIVE=1` 即可批准这些步骤。
你至少需要安装一个 AI 编程 CLI —— [Claude Code](https://docs.anthropic.com/en/docs/claude-code)、[OpenCode](https://opencode.ai)、[Codex](https://developers.openai.com/codex/cli)、[Antigravity](https://antigravity.google)、[Gemini CLI](https://github.com/google-gemini/gemini-cli) 或 [Pi](https://pi.dev)(任意组合均可;自 Google 面向消费者停售后,Gemini CLI 仅限企业版,Antigravity 是其继任者)。安装器会自动检测这六个中已安装的任意一个;若一个都没有,会提供安装 Claude Code 或 OpenCode 的选项,也可以选择跳过、稍后自行安装。安装完成后:
你至少需要安装一个 AI 编程 CLI —— [Claude Code](https://docs.anthropic.com/en/docs/claude-code)、[OpenCode](https://opencode.ai)、[Codex](https://developers.openai.com/codex/cli)、[Antigravity](https://antigravity.google)、[Gemini CLI](https://github.com/google-gemini/gemini-cli)、[Pi](https://pi.dev) 或 [Grok Build](https://github.com/xai-org/grok-build)(任意组合均可;自 Google 面向消费者停售后,Gemini CLI 仅限企业版,Antigravity 是其继任者)。安装器会自动检测这七个中已安装的任意一个;若一个都没有,会提供安装 Claude Code 或 OpenCode 的选项,也可以选择跳过、稍后自行安装。安装完成后:
```bash
codeman web
@@ -141,7 +141,7 @@ launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.codeman.web.plist
wsl bash -c "curl -fsSL https://getcodeman.com/install | bash"
```
Codeman 依赖 tmux,因此 Windows 用户需要 [WSL](https://learn.microsoft.com/en-us/windows/wsl/install)。如果还没装 WSL:在管理员 PowerShell 中运行 `wsl --install`,重启,打开 Ubuntu,然后在 WSL 内安装你偏好的 AI 编程 CLI([Claude Code](https://docs.anthropic.com/en/docs/claude-code)、[OpenCode](https://opencode.ai)、[Codex](https://developers.openai.com/codex/cli)、[Antigravity](https://antigravity.google)、[Gemini CLI](https://github.com/google-gemini/gemini-cli) 或 [Pi](https://pi.dev))。安装完成后,即可从 Windows 浏览器访问 `http://localhost:3000`。
Codeman 依赖 tmux,因此 Windows 用户需要 [WSL](https://learn.microsoft.com/en-us/windows/wsl/install)。如果还没装 WSL:在管理员 PowerShell 中运行 `wsl --install`,重启,打开 Ubuntu,然后在 WSL 内安装你偏好的 AI 编程 CLI([Claude Code](https://docs.anthropic.com/en/docs/claude-code)、[OpenCode](https://opencode.ai)、[Codex](https://developers.openai.com/codex/cli)、[Antigravity](https://antigravity.google)、[Gemini CLI](https://github.com/google-gemini/gemini-cli)、[Pi](https://pi.dev) 或 [Grok Build](https://github.com/xai-org/grok-build))。安装完成后,即可从 Windows 浏览器访问 `http://localhost:3000`。
</details>
@@ -221,7 +221,7 @@ codeman web -H 0.0.0.0 # 绑定局域网 —— 必须设置 CODEMAN_
| 字段 | 作用 |
| ---------------------- | ------------------------------------------------------------------------------------------- |
| **工作目录 / case** | 智能体操作的文件夹。「case」就是一个 Codeman 记住的命名工作目录。 |
| **CLI / 运行模式** | `Claude`(默认)、`OpenCode`、`Codex`、`Antigravity`、`Gemini`、`Pi` 或 `Terminal`(普通 shell)。 |
| **CLI / 运行模式** | `Claude`(默认)、`OpenCode`、`Codex`、`Antigravity`、`Gemini`、`Pi`、`Grok` 或 `Terminal`(普通 shell)。 |
| **模型** | 每会话模型(App Settings → Claude Model)。软默认值 —— 会话内 `/model` 依然有效。 |
| **Effort / Ultracode** | 推理力度(`low`–`max`),或用 `ultracode` 开启动态多智能体工作流。随时可用 `/effort` 切换。 |
@@ -253,7 +253,7 @@ codeman web -H 0.0.0.0 # 绑定局域网 —— 必须设置 CODEMAN_
- **手机/平板** —— UI 完全触控优化;扫描桌面上的**二维码**即可免密码登录。
- **网络之外** —— `./scripts/tunnel.sh start` 打开一条 Cloudflare 隧道(先设置 `CODEMAN_PASSWORD`)。
- **SSH** —— `sc` 选择器可从终端附着任意会话(`sc` 交互式,`sc 2` 快速附着,`sc -l` 列表)。
- **SSH** —— `codeman tui` 是终端里的全屏会话面板(`codeman tui --list` 列出,`codeman tui 2` 直接附着到某个会话)。
### 7. 运维与维护
@@ -394,7 +394,7 @@ PTY 输出 → 16ms 服务端批处理 → DEC 2026 包裹 → SSE → 客户端
## 更多特性
- **自更新** —— systemd/launchd 管理下的 git-clone 安装可在 **App Settings → Updates** 中原地更新:它会检测最新发行版,自动暂存(stash)脏工作树,并在服务重启期间流式展示构建进度(npm 安装会被报告为不可更新)
- **多 CLI** —— 每个会话可选 **Claude Code**、**OpenCode**、**Codex**、**Antigravity**、**Gemini** 或 **Pi**;环境变量前缀自动隔离(`CLAUDE_CODE_*`、`OPENCODE_*`、`CODEX_*`、`ANTIGRAVITY_*`、`PI_*` 与 `GEMINI_*`/`GOOGLE_*`)。详见 [`docs/opencode-integration.md`](docs/opencode-integration.md) 与 [`docs/pi-integration.md`](docs/pi-integration.md)
- **多 CLI** —— 每个会话可选 **Claude Code**、**OpenCode**、**Codex**、**Antigravity**、**Gemini**、**Pi** 或 **Grok**;环境变量前缀自动隔离(`CLAUDE_CODE_*`、`OPENCODE_*`、`CODEX_*`、`ANTIGRAVITY_*`、`PI_*`、`GROK_*`/`XAI_*` 与 `GEMINI_*`/`GOOGLE_*`)。详见 [`docs/opencode-integration.md`](docs/opencode-integration.md)、[`docs/pi-integration.md`](docs/pi-integration.md) 与 [`docs/grok-integration.md`](docs/grok-integration.md)
- **Docker 会话** —— 在隔离且加固的容器中运行案例。**Create New** 上勾选一个复选框即可用合理的默认值启动容器并在其中启动智能体;同一案例的多个会话共享一个容器;可将容器连同工作区导出为可移植的 `.tar.gz`,迁移到另一台机器。详见 [`docs/docker-cases.md`](docs/docker-cases.md)
- **远程 SSH 会话**:把案例指向另一台机器,让智能体在那里一个持久的远程 tmux 中运行:SSH 断连不中断任务、自动重连,还能发现并附着主机上已在运行的会话。详见 [`docs/remote-sessions.md`](docs/remote-sessions.md)
- **Effort 与 Ultracode** —— 设置每会话的默认 effort(`low`–`max`),或启用 **ultracode**(动态多智能体工作流)。这些都只是软默认值 —— 会话中可随时用 `/effort` 切换。扩展思考预算也可配置
@@ -615,20 +615,6 @@ Codeman 默认用 `--dangerously-skip-permissions` 启动会话,因此 Web UI
---
## SSH 替代方案(`sc`)
如果你更喜欢 SSH(Termius、Blink 等),`sc` 命令是一个便于拇指操作的会话选择器:
```bash
sc # 交互式选择器
sc 2 # 快速附着到会话 2
sc -l # 列出会话
```
单数字选择(1–9)、颜色编码的状态、token 计数、自动刷新。用 `Ctrl+A D` 分离。
---
## 键盘快捷键
> Ctrl 绑定在 macOS 上也接受 Cmd。
+3
View File
@@ -19,6 +19,9 @@
* why these are a runnable suite (`npm run test:browser`) rather than skipped.
*/
export const BROWSER_TEST_GLOBS = [
'test/tab-rail-resize.browser.test.ts',
'test/session-sidebar-ux.browser.test.ts',
'test/session-options-responsive.browser.test.ts',
'test/inline-rename.test.ts',
'test/opencode-resize.test.ts',
'test/webgl-fallback.test.ts',
+20 -2
View File
@@ -51,6 +51,23 @@ RUN npm install -g --ignore-scripts @earendil-works/pi-coding-agent \
&& npm cache clean --force \
&& pi --version
# Grok Build (`grok`, xAI) is NOT on npm: a standalone ~160MB Rust binary through
# xAI's installer, which targets $HOME/.grok/bin with no --dir override. At build
# time that is root's home and unreachable by the `agent` user, so copy the binary
# into /usr/local/bin and drop root's ~/.grok in the same layer so the image does
# not carry the download twice. The staging cp -T is what makes this survive the
# installer's own behavior EITHER way: newer installers already symlink
# /usr/local/bin/grok -> /root/.grok/bin/grok, and a direct `cp -L` onto that
# symlink fails with "same file" (2026-08-24 rebuild), while removing the link
# first and copying fresh works for both old and new installers.
RUN curl -fsSL https://x.ai/cli/install.sh | bash \
&& cp -L /root/.grok/bin/grok /usr/local/bin/grok.real \
&& rm -f /usr/local/bin/grok \
&& mv /usr/local/bin/grok.real /usr/local/bin/grok \
&& chmod 755 /usr/local/bin/grok \
&& rm -rf /root/.grok /root/.local/bin/grok /root/.local/bin/agent \
&& grok --version
# `agent` user (gid 0) with an arbitrary-uid-writable HOME. The uid is
# auto-assigned (node:22-slim already occupies uid 1000 with its `node` user); at
# runtime Codeman overrides with `--user <hostUid>:0` on Linux, so the baked uid
@@ -68,11 +85,12 @@ ENV HOME=/home/agent
# transcript/rollout dirs (`.claude/projects`, `.codex/sessions`) are bind-mounted from
# the host. (gemini/gcloud/opencode are whole seed-copies and need no pre-created dir;
# Antigravity nests its state inside `.gemini/antigravity-cli`, so it rides that seed.)
# `.pi/agent` IS pre-created: pi is seeded per-FILE (auth/settings/trust/models), and a
# `.pi/agent` and `.grok` ARE pre-created: both are seeded per-FILE (pi:
# auth/settings/trust/models; grok: auth.json/config.toml/pager.toml), and a
# per-file seed copy, unlike a whole-dir one, does not create its parent directory.
RUN useradd -g 0 -m -d /home/agent -s /bin/bash agent \
&& mkdir -p /home/agent/.npm /home/agent/.cache /home/agent/.config /home/agent/.codeman \
/home/agent/.claude/projects /home/agent/.codex/sessions /home/agent/.pi/agent \
/home/agent/.claude/projects /home/agent/.codex/sessions /home/agent/.pi/agent /home/agent/.grok \
&& chgrp -R 0 /home/agent \
&& chmod -R g=u /home/agent
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -91,7 +91,7 @@ These map 1:1 to `CronJobSchema` (`src/web/schemas.ts`) and the `CronJob` type
| Field | Required | Values / limits | Notes |
| -------------------------- | ----------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `name` | ✅ | 1–200 chars | Display name; also used as the created session's name. |
| `agentType` | ✅ | `claude` \| `shell` \| `opencode` \| `codex` \| `gemini` \| `antigravity` \| `pi` | Reuses Codeman's `SessionMode`. `shell` = a plain terminal. ⚠️ A `pi` job's readiness poll looks for `❯`/a token count, neither of which pi prints, so it burns the poll budget and then sends the prompt anyway (slower start, still works). |
| `agentType` | ✅ | `claude` \| `shell` \| `opencode` \| `codex` \| `gemini` \| `antigravity` \| `pi` \| `grok` | Reuses Codeman's `SessionMode`. `shell` = a plain terminal. ⚠️ A `pi` or `grok` job's readiness poll looks for `❯`/a token count, which neither CLI prints, so it burns the poll budget and then sends the prompt anyway (slower start, still works). |
| `workingDir` | ✅ | valid path (allowlist-validated) | Validated at **create/update** (must exist, be a directory, and not resolve into a blocked tree — `/etc`, `/root`, `/proc`, `/sys`, `/dev`, or `/` itself) and again **at fire time**. |
| `launchCommand` | — | ≤ 2000 chars, single line | `shell` mode only: sent as the **first input line** once the shell is up, before the prompt. Ignored for other agent types. |
| `promptMode` | ✅ | `inline_text` \| `prompt_file_path` | See §5. |
+4 -4
View File
@@ -2,7 +2,7 @@
Run a case inside an **isolated Docker container** instead of directly on the host. Any number of Codeman sessions can share one container (it is scoped to the case, not the session), so a whole project lives in a sandbox with its own network, resource caps, and filesystem, and you can **export the container to move it to another machine**.
Docker mode is a **location overlay on cases**, the direct analog of [remote SSH cases](./remote-hosts.md): where a remote case runs a local tmux pane doing `ssh host` into a durable remote tmux server, a docker case runs a local tmux pane doing `docker exec -it` into a durable **in-container** tmux server. It is not a separate `SessionMode`, so `claude` / `shell` / `opencode` / `codex` / `gemini` / `antigravity` / `pi` all work inside the container.
Docker mode is a **location overlay on cases**, the direct analog of [remote SSH cases](./remote-hosts.md): where a remote case runs a local tmux pane doing `ssh host` into a durable remote tmux server, a docker case runs a local tmux pane doing `docker exec -it` into a durable **in-container** tmux server. It is not a separate `SessionMode`, so `claude` / `shell` / `opencode` / `codex` / `gemini` / `antigravity` / `pi` / `grok` all work inside the container.
## One-time setup: build the base image
@@ -25,12 +25,12 @@ A zero exit code only proves the layers ran, not that the toolchain works. Verif
```bash
docker run --rm codeman/agent:base bash -lc \
'for c in claude codex gemini opencode agy pi; do printf "%-9s " $c; $c --version 2>&1 | head -1; done'
'for c in claude codex gemini opencode agy pi grok; do printf "%-9s " $c; $c --version 2>&1 | head -1; done'
```
Antigravity (`agy`) is the one CLI not installed from npm (Google ships a standalone binary), so it has its own Dockerfile step and adds roughly 190MB; a full image lands near 1.6GB. Pi also gets its own step, because upstream documents installing it with `--ignore-scripts` and that flag must not silently change how the other four npm CLIs install.
Antigravity (`agy`) and Grok (`grok`) are the two CLIs not installed from npm (Google and xAI ship standalone binaries), so each has its own Dockerfile step, adding roughly 190MB and 160MB respectively. Pi also gets its own step, because upstream documents installing it with `--ignore-scripts` and that flag must not silently change how the other npm CLIs install.
Pi's credentials are seeded per-FILE rather than as a whole directory (`auth.json`, `settings.json`, `trust.json`, `models.json`, `models-store.json` out of `~/.pi/agent`), because that directory also holds `sessions/`, `extensions/`, `skills/` and the installed package trees — gigabytes on an active host. Consequence: in-container pi sessions are invisible host-side, so `pi -c` inside a Docker case only sees that container's own history. See [`pi-integration.md`](./pi-integration.md).
Pi's credentials are seeded per-FILE rather than as a whole directory (`auth.json`, `settings.json`, `trust.json`, `models.json`, `models-store.json` out of `~/.pi/agent`), because that directory also holds `sessions/`, `extensions/`, `skills/` and the installed package trees — gigabytes on an active host. Consequence: in-container pi sessions are invisible host-side, so `pi -c` inside a Docker case only sees that container's own history. See [`pi-integration.md`](./pi-integration.md). Grok is seeded per-file for the same reason (`auth.json`, `config.toml`, `pager.toml` out of `~/.grok`, which also holds `sessions/`, `memory/` and the ~160MB binary under `downloads/`), with the same consequence for `grok -c`. See [`grok-integration.md`](./grok-integration.md).
## Quickest path: one-click "Run in Docker"
+106
View File
@@ -0,0 +1,106 @@
# Grok Build (xAI) integration plan
> **Status**: Executed. This document records the plan, the decision behind each wiring
> point, and what was and was not verified. The user-facing guide is
> [`grok-integration.md`](./grok-integration.md); the per-decision invariants live in
> [`architecture-invariants.md#external-cli-modes-opencode-codex-gemini-antigravity-pi-grok`](./architecture-invariants.md#external-cli-modes-opencode-codex-gemini-antigravity-pi-grok).
> Template: the pi integration (`c5b5963`, [`pi-integration-plan.md`](./pi-integration-plan.md)),
> which was itself calibrated against the four follow-up commits the antigravity
> integration needed. All of grok's facts below were verified against **grok 1.0.5**
> (`grok 1.0.5 (5115b46bc9)`), installed live during the work.
## 1. What Grok Build is
[xai-org/grok-build](https://github.com/xai-org/grok-build) is xAI's coding agent: a
Rust fullscreen-TUI binary named `grok`, installed by
`curl -fsSL https://x.ai/cli/install.sh | bash` into `~/.grok/bin` (with symlinks into
`~/.local/bin`; the installer also ships an `agent` alias). Config lives in
`~/.grok/config.toml`, TUI appearance in `~/.grok/pager.toml`, credentials in
`~/.grok/auth.json` (0600), sessions under `~/.grok/sessions/`. Auth is browser OAuth
on first launch, `grok login --device-auth` for SSH boxes, or `XAI_API_KEY` for
headless use. It has Claude-style permission modes (`default`/`acceptEdits`/`auto`/
`dontAsk`/`bypassPermissions`/`plan`), allow/deny rules, hooks, MCP, subagents, and a
headless `-p` mode.
## 2. Shape decisions (why grok is wired the way it is)
Grok is a seventh run mode, alongside Claude Code, shell, OpenCode, Codex, Gemini,
Antigravity and Pi. Never a location overlay, never a web tab. Its wiring mixes two
existing shapes:
| Question | Decision | Why |
| --- | --- | --- |
| Permission bypass | `GrokConfig.alwaysApprove` -> `--always-approve` | Grok's real flag (verified via `--help`): "Auto-approve all tool executions", i.e. its `bypassPermissions` mode. Config-level deny rules still apply on top. The Run button sends `true`, matching `runAntigravity()` and Claude's own `--dangerously-skip-permissions` default: Codeman sessions exist for autonomous work. |
| Multi-user clamp branch | only-if-sent (codex/antigravity branch) | A bare `grok` spawn is grok's own ask-mode default, which is already safe, so the clamp only needs to force a SENT `alwaysApprove` off. Contrast pi, whose absent default is an answerable prompt and therefore needs the materialize branch. Cron needs nothing for grok for the same reason (`clampCronExternalCliConfigs`). |
| Alt-screen strip | OUT of `isAltScreenStripMode()` | Grok is a fullscreen alternate-screen TUI with mouse support (its own scrollback pane, `pager.toml [terminal] alt_screen`), i.e. the opencode case, not the Ink repaint case. It falls through to the narrow tmux-attach strip like opencode/antigravity/pi. |
| Resolver | version probe, like pi | `grok` has npm squatters (the unrelated `@vibe-kit/grok-cli` installs a `grok` bin). Candidates must pass `grok --version`; `GROK_VERSION_REGEX` is exported and shared with the dependency registry so doctor and run mode cannot disagree. The probe cannot tell two version-printing `grok`s apart, so `GET /api/grok/status` surfaces path AND version. Search dirs: `~/.grok/bin` first (installer target), then `~/.local/bin`, `/usr/local/bin`, `~/bin`. |
| Env allowlist | `GROK_*` + `XAI_*` prefixes | `GROK_*` covers grok's documented inputs (`GROK_HOME`, `GROK_CONFIG`/`GROK_CONFIG_PATH`, `GROK_MEMORY`, `GROK_WORKFLOWS`, `GROK_SANDBOX`, `GROK_OIDC_*`, `GROK_AUTH_PROVIDER_COMMAND`). `XAI_*` is xAI's vendor namespace and carries `XAI_API_KEY`, grok's documented headless auth var: the same narrow-vendor-namespace reasoning that admitted `GOOGLE_*` for gemini. Foreign provider keys stay out, as always. |
| Resume | `--resume <id>` / `--continue`, id-regexed | Grok's `--resume` also matches session TITLES (arbitrary user strings, case-insensitive). The `^[a-zA-Z0-9._-]+$` regex doubles as the no-titles rule, so nothing free-form can reach the `bash -c` spawn line. A valid explicit id wins over `-c`, mirroring pi. |
| Local echo | `'buffer'` via the `_updateLocalEchoState` fallthrough | UNMEASURED against an authenticated session (see §4). If grok's composer turns out per-keystroke reactive like codex's, the fallback is one `'off'` branch; teaching `PredictiveEchoAddon` grok's composer row is the larger follow-up. |
| Truecolor | `COLORTERM=truecolor` + `unset NO_COLOR` | Rust TUI with themes; joins the codex/gemini/antigravity/pi list in `buildEnvExports()` and `buildMuxAttachEnv()`. |
| Docker credentials | per-file seed: `auth.json`, `config.toml`, `pager.toml` | `~/.grok` also holds `sessions/`, `memory/`, `completions/`, `docs/` and the ~160MB binary under `downloads/`; a whole-dir seed would copy all of it on every container start. Same trade-off as pi: in-container sessions are invisible host-side, so `grok -c` in a Docker case sees only that container's history. |
| Docker install | own Dockerfile step | Not an npm package. xAI's installer has no `--dir` override, so the step copies `/root/.grok/bin/grok` (through the symlink, `cp -L`) into `/usr/local/bin` and removes root's `~/.grok` in the same layer. |
| Remote SSH | `exec "$SHELL" -i -l -c 'grok'` | sshd's remote-command PATH does not include `~/.grok/bin`; same login-shell fix as every other agent CLI. |
| What is NOT wired | `--permission-mode`, `--allow`/`--deny`, `-p` headless, `--worktree`, `--sandbox`, `--reasoning-effort`, `-s/--session-id`, `--fork-session`, `--agent`, `--output-format` | Follow-ups. The flag surface is kept minimal on purpose; grok is pre-1.0-style fast-moving and every flag added is a flag validated forever. |
## 3. Touch points (the checklist)
Backend: `types/session.ts` (SessionMode + GrokConfig + SessionState), `utils/grok-cli-resolver.ts` (new)
+ barrel, `tmux-manager.ts` (`buildGrokCommand`, dispatch, resume flag, PATH export, truecolor,
availability error, plumbing), `session.ts` (external-mode gate, label, config plumbing,
tmux-required error, attach env), `mux-interface.ts`, `schemas.ts` (prefixes, `GrokConfigSchema`,
both mode enums, remote command overrides, cron agentType), `session-routes.ts` (clamp + both
create paths), `system-routes.ts` (`GET /api/grok/status`), `server.ts` (availability inject +
mux restore), `docker-hosts.ts`, `remote-hosts.ts`, `config/dependency-registry.ts`,
`cron/cron-service.ts` (comment), `response-viewer-transcript.ts`, `tui/tui-client.ts` + `tui-app.ts`.
Frontend: `index.html` (welcome button, run-mode entry, cron option, clone Brain option),
`session-ui.js` (`runGrok()`, dispatch, availability, "Run GK" label, external-CLI gates,
runMode setter), `app.js` (label, `gk` tab badge, kill-menu), `settings-ui.js`,
`mobile-overview.js`, `home-sessions.js`, `panels-ui.js`, `i18n.js`, `styles.css` +
`mobile.css` (charcoal monochrome identity; the non-og skin block and the mobile
`!important` pair are both load-bearing, see the pi plan's §2.9 cascade trap).
Meta: `docker/agent.Dockerfile`, `install.sh`, `package.json` keyword, changeset,
`skills/codeman/reference/*`, CLAUDE.md, READMEs, `architecture-invariants.md`,
`remote-sessions.md`, `security-architecture.md`, `docker-cases.md`, `cron-guide.md`.
Tests: `test/grok-mode.test.ts` + `test/grok-cli-resolver.test.ts` (new);
`external-cli-bypass-clamp`, `system-routes`, `render-index-html`, `run-mode-ui`,
`mobile-overview`, `local-echo-codex-gating` (extended).
## 4. Verification performed
On this box, with grok 1.0.5 really installed and an isolated
`CODEMAN_INSTANCE=grokwt` server (own data dir, own tmux socket, port 5077):
1. `npm test` (the CI gate): green, 5900+ tests. `typecheck`, `lint`, `format:check`,
`check:frontend-syntax`, `check:public-assets`, `check:lockfile`: green.
2. `GET /api/grok/status` -> `{available: true, path: "/home/arkon/.local/bin", version: "1.0.5"}`
through the real resolver and probe.
3. `POST /api/quick-start {mode: "grok", grokConfig: {alwaysApprove: true}}` -> session
created, tmux pane spawned, real spawn line verified to end in `grok --always-approve`,
and the actual grok TUI rendered its OAuth device-approval screen in the pane
(unauthenticated box, so sign-in is exactly where a first run lands).
4. `grokConfig` persisted into the instance's `state.json`.
5. Session deleted by exact id; instance data dir and throwaway case removed.
**Not verified (honest gaps, all requiring an xAI account or more hardware):**
an authenticated conversation end to end; the local-echo buffer policy against grok's
real composer (§2); scrollback/repaint behavior of the fullscreen TUI under the narrow
strip during a long session; a Docker case with `mode: 'grok'` (needs a `--no-cache`
agent-image rebuild); a remote-SSH grok case; cron readiness degradation (expected:
same slow-start-then-send as pi, documented in `cron-guide.md`).
## 5. Follow-ups
- Idle/completion signal: grok has a hooks system (user-guide `10-hooks.md`); a hook
POSTing to `/api/hook-event` could give grok sessions real idle detection instead of
output-stabilization. Highest-value follow-up, same slot as pi's `agent_settled` idea.
- Response viewer: sessions are ACP JSONL under `~/.grok/sessions/<encoded-cwd>/<id>/updates.jsonl`;
`grok -p ... --output-format json | jq -r '.sessionId'` exists for correlation.
- Permission-mode picker (`--permission-mode`, `--allow`/`--deny`) in Session Options.
- Measure the local-echo policy and the fullscreen-TUI scrollback behavior against an
authenticated session; pin the result in `local-echo-codex-gating` the way pi did.
- `grok doctor` is a built-in terminal-support check worth pointing users at when a
pane renders oddly.
+133
View File
@@ -0,0 +1,133 @@
# Grok Build (xAI) sessions
Codeman can drive [Grok Build](https://github.com/xai-org/grok-build) (xAI's `grok`
CLI, the agent behind docs.x.ai/build) as a session backend, alongside Claude Code,
OpenCode, Codex, Gemini, Antigravity and Pi. `grok` is a seventh **run mode**: its own
PTY, its own tmux session, its own tab identity (monochrome charcoal, `gk` badge). It
is not a location overlay like Docker or remote-SSH cases, and it is not a web tab.
The design rationale behind each decision below lives in
[`grok-integration-plan.md`](./grok-integration-plan.md). Everything here was verified
against grok 1.0.5.
## Install
```bash
curl -fsSL https://x.ai/cli/install.sh | bash
```
The installer places the binary in `~/.grok/bin` and symlinks it into `~/.local/bin`
(it also installs an `agent` alias Codeman ignores). `grok update` self-updates.
Codeman resolves the binary via the server PATH and then the usual install locations,
`~/.grok/bin` first. **`grok` is a name with known squatters** (the unrelated
`@vibe-kit/grok-cli` npm package also installs a `grok` bin), so like `pi` the
resolver does not trust a PATH hit on its own: it runs `grok --version` once and
requires version-shaped output (`grok 1.0.5 (5115b46bc9)`). Check what it resolved:
```bash
curl -s localhost:3000/api/grok/status | jq
# { "available": true, "path": "/home/you/.grok/bin", "version": "1.0.5" }
```
The endpoint carries `version` on top of the sibling `/api/*/status` shape precisely
so a misresolution is visible rather than presenting as "the mode just doesn't work".
## Authenticate
- **Browser OAuth (default)**: the first `grok` run opens a sign-in flow; in a
Codeman pane you get the device-code screen with a URL to open elsewhere.
Credentials land in `~/.grok/auth.json` (0600) and refresh automatically.
- **Device code**: `grok login --device-auth`, made for SSH boxes and headless hosts.
- **API key**: `export XAI_API_KEY="xai-..."` (console.x.ai). Used as a fallback when
no session token exists. As a per-session Codeman `envOverride` it flows through
socket-scoped `tmux setenv`, never the spawn command line.
- **Enterprise OIDC**: `GROK_OIDC_ISSUER` / `GROK_OIDC_CLIENT_ID`.
## What Codeman wires up
`GrokConfig` (per session, persisted in `state.json`, round-trips through respawn):
| Field | Flag | Notes |
| ----------------- | --------------------------- | --------------------------------------------------------------------- |
| `model` | `--model <v>` | e.g. `grok-4.5`, or a custom `[model.<name>]` from `config.toml` |
| `alwaysApprove` | `--always-approve` | Grok's `bypassPermissions` mode; deny rules still apply on top |
| `continueSession` | `--continue` | Most recent session for the working directory; skipped when resuming |
| `resumeSessionId` | `--resume <v>` | Ids only, never titles (grok's own `--resume` also matches titles) |
Every value is regex-validated and **dropped** (not escaped) if it fails, because the
result is interpolated into the pane's `bash -c "..."` command.
The Run button sends `grokConfig: { alwaysApprove: true }`, the same product decision
as Claude's `--dangerously-skip-permissions` default and Antigravity's
`--dangerously-skip-permissions`: Codeman sessions exist for autonomous work. Keep
hard limits as `deny` rules in `~/.grok/config.toml` (they apply in every mode), and
in **multi-user mode** a non-granted owner's `alwaysApprove` is forced off
server-side; a bare `grok` spawn is grok's own ask-mode default.
Env overrides: the `GROK_*` prefix (`GROK_HOME`, `GROK_CONFIG`, `GROK_MEMORY`,
`GROK_WORKFLOWS`, `GROK_SANDBOX`, `GROK_OIDC_*`, ...) plus the `XAI_*` vendor
namespace (`XAI_API_KEY`) are allowlisted. Foreign provider keys are not, as ever.
## What Codeman deliberately does NOT wire up
- **`--permission-mode`, `--allow`/`--deny`.** The boolean covers the autonomous
case; the full rule surface is a follow-up with UI.
- **`-p`/headless, `--output-format`, `--json-schema`.** Codeman drives the TUI.
- **`--worktree`, `--sandbox`, `--reasoning-effort`, `-s/--session-id`,
`--fork-session`, `--agent`/`--agents`.** Tracked as follow-ups in the plan doc.
## Terminal behavior
Grok renders a **fullscreen alternate-screen TUI** (scrollback pane + prompt, mouse
supported). Under Codeman it runs inside tmux like every external CLI, so the
fullscreen rendering stays inside the pane and the browser terminal shows tmux's
repaints; grok stays out of the alt-screen strip list on purpose (the opencode case,
not the Ink case). If a pane renders oddly, `grok doctor` checks terminal, color and
input support without starting a session, and `~/.grok/pager.toml` can force
`alt_screen = "inline"`.
On touch devices grok currently gets the buffered local-echo overlay like Claude,
Gemini, OpenCode and Pi. This is the fallthrough default and has not been measured
against an authenticated grok composer; if grok turns out per-keystroke reactive the
way codex was (issues #218/#219/#220/#222), the fix is the `'off'` branch in
`_updateLocalEchoState` (terminal-ui.js).
## Docker cases
The agent image installs grok in its own Dockerfile step (not npm; xAI's installer
targets `$HOME/.grok/bin` with no `--dir` override, so the binary is copied to
`/usr/local/bin`). Rebuild with the mandatory `--no-cache`:
```bash
node scripts/build-agent-image.mjs --no-cache
```
Credentials are **seeded**, not shared: `auth.json`, `config.toml` and `pager.toml`
are copied into the container's own `~/.grok`, so an in-container grok never writes
refreshed OAuth tokens back to the host and `docker commit` exports stay secret-free.
Only those three files, because `~/.grok` also holds `sessions/`, `memory/` and the
~160MB binary under `downloads/`. Trade-off, same as pi: in-container sessions are
invisible host-side, so `grok -c` inside a Docker case only sees that container's own
history.
## Remote SSH cases
`grok` mode is routed through an interactive login shell
(`exec "$SHELL" -i -l -c 'grok'`), because sshd's remote-command PATH does not include
`~/.grok/bin`. Per-session config and `envOverrides` do not cross ssh and are rejected
rather than silently ignored; use the per-host command override instead. For auth on
the remote host, `grok login --device-auth` exists for exactly this.
## Known gaps
- **No idle/completion hook yet.** Idle detection falls back to output-stabilization
like the other external CLIs. Grok has a hooks system, so a Codeman hook POSTing to
`/api/hook-event` is the highest-value follow-up.
- **No response viewer.** Grok writes ACP JSONL sessions under
`~/.grok/sessions/<encoded-cwd>/<session-id>/updates.jsonl`; nothing reads them yet.
- **Cron jobs mis-detect readiness.** The readiness poll looks for `❯` or a token
count, neither of which grok prints, so a grok cron job burns its poll budget and
then sends the prompt anyway. It works; it is just slower to start.
- **Ralph, respawn heuristics, token/CLI-info parsing and the `❯` readiness probe are
off** for grok, as for every external CLI.
+1 -1
View File
@@ -139,7 +139,7 @@ set -g extended-keys-format csi-u
Codeman's browser input path sends `\r` for submit, so basic use works
unconfigured — what degrades is newline-in-editor, mostly when you attach to the
pane directly (`sc`).
pane directly (`codeman tui`).
⚠️ Upstream notes the setting may need a full `tmux kill-server` to take effect.
**Never run `tmux kill-server` on Codeman's socket** — it would kill every live
+2 -2
View File
@@ -1,7 +1,7 @@
# Remote Sessions (SSH)
Codeman can run a session's agent on a **remote host over SSH** instead of the
local machine. The agent (Claude, OpenCode, Codex, Antigravity, Gemini, Pi, or a plain shell)
local machine. The agent (Claude, OpenCode, Codex, Antigravity, Gemini, Pi, Grok, or a plain shell)
runs inside a `tmux` server **on the remote host**, so it survives the SSH
connection dropping; Codeman attaches to it the same way it attaches to a local
managed session.
@@ -30,7 +30,7 @@ Types live in `src/types/session.ts`; persistence in `src/remote-hosts.ts`.
| `RemoteHost` (extends `RemoteSshOptions`) | A saved host: `id`, `label`, `host`, `username`, `port?`, `commands?` (per-mode launch command override). |
| `RemoteCase` | A working directory on a host: `name`, `type: 'remote'`, `hostId`, `remotePath`. |
| `SessionRemote` (extends `RemoteSshOptions`) | The resolved bundle stamped onto a live session: host coordinates + `remotePath` + `commands`, plus **`owned?`** and **`remoteSessionName?`** (COD-105 — see [Ownership](#ownership-launched-vs-discovered-and-attached-cod-105)). Built by `toSessionRemote(host, case)` (sets `owned: true`) for the launch path, or `toAttachedSessionRemote(host, name, path)` (sets `owned: false`) for the attach path. Both copy the advanced SSH options through so every connection is identical. |
| `RemoteCommandMode` | `Extract<SessionMode, 'shell' \| 'claude' \| 'opencode' \| 'codex' \| 'gemini' \| 'antigravity' \| 'pi'>` — the modes that can run remotely. |
| `RemoteCommandMode` | `Extract<SessionMode, 'shell' \| 'claude' \| 'opencode' \| 'codex' \| 'gemini' \| 'antigravity' \| 'pi' \| 'grok'>` — the modes that can run remotely. |
| `RemoteSessionInfo` (COD-105) | One discovered remote tmux session: `name` (always `codeman-*`), `attached` (a client is connected), `created` (epoch s), `windows`. Returned by `listRemoteCodemanSessions()`. |
Persistence is two flat JSON arrays in the instance data dir:
+1 -1
View File
@@ -489,7 +489,7 @@ production layout (`~/.codeman`, `-L codeman`, port 3000).
Docker cases (1.4.0) run a session inside a per‑case container instead of on the host. The security posture:
- **Hardened create flags, always** — `--cap-drop ALL`, `--security-opt no-new-privileges`, `--pids-limit` (fork‑bomb guard), `--memory` == `--memory-swap` (a real OOM cap), `--init`, and non‑root: `--user <hostUid>:0` on Linux (host uid → workspace files stay host‑owned; GID 0 keeps `$HOME` writable), `--userns=keep-id` on rootless Podman. **Never** `--privileged`, and **never** the docker socket — the pure builder in `docker-hosts.ts` cannot emit them and the schema cannot represent them.
- **Credentials never enter an image** — the convenient default bind‑mounts host cred dirs (`~/.claude`, `~/.codex`, `~/.gemini` — which also carries Antigravity's `antigravity-cli/` state — `~/.config/{gcloud,opencode}`, and five seeded files from `~/.pi/agent`) read‑write. Bind mounts are physically excluded from `docker commit`, so exported images are secret‑free. API‑key CLIs get their key as an exec‑time NAME‑ONLY `--env OPENAI_API_KEY` (no `=value`, no `ps` leak, never committed); a create‑time `-e` for a secret is never used. The **sealed** profile (`mountCredentials:false` + `network:none`) drops the host mounts; full‑image export is then refused (an in‑container login would ride the committed layer) unless a pre‑commit scrub is opted into.
- **Credentials never enter an image** — the convenient default bind‑mounts host cred dirs (`~/.claude`, `~/.codex`, `~/.gemini` — which also carries Antigravity's `antigravity-cli/` state — `~/.config/{gcloud,opencode}`, five seeded files from `~/.pi/agent`, and three from `~/.grok`) read‑write. Bind mounts are physically excluded from `docker commit`, so exported images are secret‑free. API‑key CLIs get their key as an exec‑time NAME‑ONLY `--env OPENAI_API_KEY` (no `=value`, no `ps` leak, never committed); a create‑time `-e` for a secret is never used. The **sealed** profile (`mountCredentials:false` + `network:none`) drops the host mounts; full‑image export is then refused (an in‑container login would ride the committed layer) unless a pre‑commit scrub is opted into.
- **Blast radius — accept it explicitly** — the convenient profile mounts an arbitrary host workspace RW plus the host credential dirs RW into a network‑enabled container, so container‑run agent code can read/modify those host trees and reach the network at once. Still a net improvement over today's on‑host `--dangerously-skip-permissions` execution; use the sealed profile for genuinely untrusted work.
- **Import is untrusted‑bundle‑safe** — `/api/docker-cases/import` validates the manifest + per‑member SHA‑256 before extraction, rejects absolute / `..` tar members (traversal guard), and re‑tags the loaded image into a quarantined namespace so it can never overwrite `codeman/agent:base` or a pre‑existing tag.
- **Host guard & the bridge‑hooks listener** — in‑container hook callbacks carry `Host: host.docker.internal` / `host.containers.internal`; both are on the always‑on host‑header allowlist (`DOCKER_HOST_GATEWAY_ALIASES`) and resolve to the host only from inside a container netns, so they are not a browser DNS‑rebinding surface. On a loopback‑only server, in‑container hooks are opt‑in via `CODEMAN_DOCKER_BRIDGE_HOOKS=1`, which binds a SECOND listener on the docker bridge gateway serving **only** the hook endpoints (every other path → `403`) into the same hook‑secret‑gated pipeline. The bridge is host‑internal (containers + host), not the LAN, so it does not widen network exposure; the hook secret is bind‑mounted read‑only and referenced by path.
+219
View File
@@ -0,0 +1,219 @@
# Codeman TUI Rework Plan
Status: **phases 0-2 implemented** on `feat/tui`; phases 3-4 remain follow-ups. The user guide is [`docs/tui.md`](tui.md); this document stays the design record.
- Phase 0: `src/cli-style.ts` (palette, glyphs, `heading`/`kv`/`table`/`spinner`/`confirm`) plus the mechanical fixes of §5, and `test/cli-commands.test.ts` now derives its inventory from the real commander `program` instead of parsing a fixture.
- Phases 1-2: `src/tui/`. `tui-app.ts` (main loop, attach handoff, verbs) and `tui-client.ts` (API, SSE, degraded enumeration) are the only IO; `tui-model`, `tui-layout`, `tui-render`, `tui-keys`, `tui-ansi`, `tui-composer`, `tui-approvals`, `tui-digest`, `tui-sse` and `tui-types` are pure and unit-tested, with an E2E suite driving the real binary under node-pty.
- Deferred with the rest of phase 3: `r` (resume a RECENT row) is not wired up, so the help overlay does not advertise it.
- Not started: phase 3 (mouse, `--pick` popup switcher, opt-in attach status line, OSC 9) and phase 4 (retiring the bash choosers).
The goal: replace Codeman's scattered terminal surfaces with one first-class TUI, `codeman tui`, that gives SSH/terminal users the same at-a-glance awareness the web UI gives browsers. The reference point is herdr (herdr.dev), the trending Rust "agent multiplexer" whose defining feature is a live agent-state sidebar. Codeman can match and beat that sidebar in the terminal because the states herdr infers from screen-scraping heuristics are states our server already computes from hooks, pane probing, and the approvals inbox.
---
## 1. What we have today (inventory)
Three disconnected surfaces, three visual idioms, two data sources:
| Surface | What it is | Data source | Idiom |
| --- | --- | --- | --- |
| `codeman` CLI (`src/cli.ts`, 1214 lines) | commander + chalk, ~20 commands | HTTP API + state files | `✓`/`✗` line-per-fact, no interactivity |
| `sc` (`scripts/tmux-chooser.sh`, 663 lines) | bash number-menu chooser, mobile-tuned (44 cols) | `tmux -L codeman` + `state.json` via jq | 256-color, numbered, full repaint per key |
| `scripts/tmux-manager.sh` (529 lines) | bash cursor TUI with kill/info | `mux-sessions.json` (and writes it back) | 8-color, box-drawn, arrow keys |
Weaknesses found in the audit (file:line refs verified 2026-08-16):
1. **No interactive picker in the Node CLI at all.** Every `session stop`, `task status`, `session logs` requires a pasted UUID prefix. There is no `codeman attach <session>`; `codeman attach` is actually the attachment-card command (and `README.md:895` describes it wrongly).
2. **`sc` cannot reach sessions 10+ interactively**: entries are numbered globally (`tmux-chooser.sh:343`) but input accepts a single `[1-9]` keypress (`:487-493`). Page 2 shows items 8-14 that mostly cannot be selected.
3. **No cursor/selection concept in `sc`** (`BG_SEL` at `:90` is dead code); arrows only page.
4. The two bash tools can disagree about which sessions exist (different data files), and only `sc` is on PATH.
5. **Zero live feedback anywhere**: `codeman web -d` and `service install` block silently up to 30s (`daemon-control.ts:395-412`); no spinner exists in the codebase.
6. Styling drift: `doctor` is the only table and is deliberately monochrome with a colorize hook nobody wired up (`dependency-report.ts:5-7`); `codeman web` prints its "running at" line twice (colored `cli.ts:934`, plain `server.ts:2366`); the server's security warning is colorless `console.warn` while the CLI's version of the same warning is yellow; `tmux-manager.sh`'s header box is visibly misaligned; `padEnd(14)` overflows on "Antigravity CLI".
7. Bash TUIs emit raw escapes unconditionally (no TTY/NO_COLOR gate); `install.sh` and `postinstall.js` do it right.
8. Detach hint inconsistency: chooser says Ctrl+B D, `README.md:671` says Ctrl+A D.
9. Inside an attached session there is **no chrome at all**: Codeman turns the tmux status bar off (`tmux-manager.ts:1978`), so an SSH user in a pane has no session identity, no state, no way back to a picker except detach.
10. `test/cli-commands.test.ts` asserts against a hand-written fixture, not the real `program`, and that fixture already lists a `tui` command that does not exist (`:57-61`). The name is pre-approved by our own test file.
## 2. Research: how herdr does it
herdr (github.com/herdrdev/herdr, ~30k stars, single Rust binary, pre-1.0) is a background terminal multiplexer "your coding agents live on". What matters for us:
- **The agent-state sidebar is the product.** Every pane is classified live as `working` / `blocked` / `done` / `idle` and grouped in a sidebar, so you see who needs you without switching tabs. Reviews unanimously call this "the killer feature tmux can't match".
- **Detection is heuristic-first**: process-name matching + screen-manifest TOML rules parsing the visible frame; optional per-agent "integration install" adds lifecycle hooks over JSON-RPC on a unix socket for accurate states. Claude Code there is on the heuristic path and reviewers note blocked-state lag.
- **Model**: workspaces → tabs → panes, tmux-style prefix keys (Ctrl+B V split, arrows navigate, D detach), mouse-first (click select, drag resize, right-click menus, touch over SSH), adapts to narrow widths.
- **Agent-shaped API**: socket API with `pane read` (visible/recent/detection), `send-text`/`send-keys`/`run`, `agent start|prompt|wait|explain`, `pane wait-output` with regex, plugins placed as overlay/split/tab/popup.
- **Persistence**: sessions survive disconnects, reattach from any terminal / SSH.
- Weaknesses reviewers cite: pre-1.0 churn, bus factor 1, no session resurrection, rendering lag with many panes.
What is striking is how much of herdr Codeman already has, server-side: our hooks give exact `permission_prompt`/`stop`/`idle_prompt` events (herdr's "integration" path, but installed by default), `_confirmIdle()` does the screen-probe fallback, the approvals inbox parses the actual dialog options, and the agent skill + wait primitives are our socket API. What we lack is purely the presentation layer in the terminal.
Prior art for the architecture we want: **agent-deck** (Bubble Tea + tmux) proves the "TUI list + attach into tmux" model works great: session list with live glyphs (● ◐ ○ ✕), Enter attaches into a tmux pane, status polling, groups, fuzzy search. We take the shape, not the code.
Licensing note: herdr is reported variously as Apache-2.0/AGPL-3.0. Irrelevant either way: we copy concepts, never code.
### What we take / what we skip
Take: the four-state sidebar as the organizing principle; grouping by "needs you first"; narrow-width adaptation; mouse support; tmux-familiar keys; the "attention at a glance" framing.
Skip: being a multiplexer. tmux already backs every Codeman session and is a hard dependency; herdr had to build pane management because it owns terminals, we do not. Also skip (for now): plugin marketplace, split layouts, pane drag. Our TUI is a **dashboard + switchboard over tmux**, not a tmux replacement.
## 3. Design: `codeman tui`
One command, one full-screen client of the existing HTTP/SSE API.
**Positioning (owner decision, 2026-08-16): the web UI remains THE primary surface.** The TUI is strictly additive, for users who want a terminal workflow (SSH, Termius, tmux die-hards). Bare `codeman` keeps printing help; nothing existing changes behavior. The `sc` bash chooser also stays untouched for now; flipping its alias to `codeman tui` is deferred to a follow-up release once the TUI has mileage.
### Layout (≥100 cols)
```
codeman tnode · v1.19.0 · 6 sessions · 5h ▂▂▅ 32% wk 61% ? help q quit
────────────────────────────────────────────────────────────────────────────────────────────
NEEDS YOU ──────────────────────────┐ ┌ w4-api-refactor ── claude · ~/dev/api ────────────
▶ 1 w4-api-refactor ⚠ approval 2m │ │ ✻ Actualizing… (2m 14s · ↓ 12.3k tokens)
2 w6-docs ✋ waiting 11m │ │
│ │ ⚠ Claude requests: Bash(git push origin main)
WORKING ────────────────────────────┤ │ 1. Yes 2. Yes, don't ask again 3. No
3 w1-codeman ✻ 17m 45.2k │ │
4 w2-gallery ✻ 3m 8.1k │ │ [y] approve [n] deny [Enter] attach
IDLE ───────────────────────────────┤ │
5 w3-promo ○ 2h │ │ …live tail of the selected session's
RECENT ─────────────────────────────┤ │ terminal (ANSI colors preserved),
· api-hotfix ✔ done Fri │ │ updating while you browse the list…
────────────────────────────────────────────────────────────────────────────────────────────
↑↓ select · ⏎ attach · 1-9 jump · y/n answer · p prompt · n new · x kill · / search · g digest
```
- **Header**: hostname/instance, server version, session count, plan-usage chip (same telemetry that feeds the web chip, when available). Degrades gracefully when the server is down (see §3.6).
- **Sidebar**: sessions grouped `NEEDS YOU` → `WORKING` → `IDLE` → `RECENT` (past sessions from the unified list, resumable). Within groups, reuse the activity ordering already built for the home screens in PR #303 (blocked first, running longest, quiet newest); that logic is pure and shared.
- **Preview pane**: live tail of the selected session, SGR colors preserved, cursor-movement stripped. When the selected session has a pending approval, the parsed dialog is rendered as a card above the tail with one-key answer bindings.
- **Footer**: contextual keymap (changes when a dialog/confirm is active).
### States and vocabulary
Exactly the web's language so the two surfaces read the same:
| Group | Glyph | Color | Source |
| --- | --- | --- | --- |
| NEEDS YOU (question/permission) | `⚠` | red, blinking row | approvals inbox / `permission_prompt` |
| NEEDS YOU (waiting for input) | `✋` | yellow | `idle_prompt` / waiting classification |
| WORKING | `✻` animating through `· ✢ ✳ ∗ ✻ ✽` at 2Hz | green | working classification (the same glyph family Claude itself draws, a deliberate nod) |
| IDLE | `○` | muted | idle |
| RECENT / done | `✔` | muted green | unified list history rows |
Nerd-font/glyph fallback exactly like `sc` does today (`[!] [w] [*] [-] [ok]` when the terminal is not known-capable), plus full NO_COLOR / `tput colors` degradation (8-color and mono renderings are designed, not accidental).
### Keymap
- `↑/↓` or `j/k` select · `Enter` attach · `1-9` jump-attach (parity with `sc`, but now the cursor covers 10+)
- `y`/`n` (or the digit keys) answer the selected session's pending approval right from the dashboard, via `POST /api/approvals/:id/answer`. The server already re-captures the pane and 409s if the dialog is gone, so this is safe by construction.
- `p` send a one-line prompt to the selected session without attaching (`POST /input` with `\r`, the composer opens in the footer)
- `n` new session (case picker → mode picker, drives `POST /api/quick-start`) · `x` kill with typed confirm (never bulk; refuses the session hosting the TUI itself, like tmux-manager.sh does)
- `/` fuzzy search across sessions/history/attachments (`GET /api/search`) · `g` away digest (`GET /api/away-digest`) rendered as a panel
- `r` resume selected RECENT row (unified list `resume-session` flow) · `?` help overlay · `q` quit
- Mouse (phase 3): SGR mouse reporting, click selects, wheel scrolls list/preview, click on footer keys triggers them. Works over SSH, same as herdr's touch story.
### Responsive behavior
The `sc` design constraint survives: below ~72 cols (Termius, iPhone portrait) the preview pane drops and the TUI is a single-column list with two-line rows, nearly identical to today's `sc` but with a cursor, live states, and the answer/prompt/new/kill verbs. The layout switch is width-driven at draw time, no mode flag.
### Attach model
Enter suspends the TUI (restore main screen + cooked mode), then hands the terminal to `tmux -L <socket> attach-session -t <name>` with `stdio: inherit`. On tmux exit/detach, the TUI resumes and refreshes. Full fidelity (mouse, paste, colors) is tmux's, we never proxy bytes.
- Inside tmux already: same socket → `switch-client -t`; different socket → warn about nesting and offer detach-first. `$TMUX` + `CODEMAN_MUX` detection.
- **Return path**: a tmux binding installed for codeman sessions (opt-in) runs `codeman tui --pick` inside `tmux display-popup -E`, a minimal picker-only mode (list + jump, no preview) so switching sessions from inside a pane is one keystroke, fzf-style.
- Optional per-attach chrome (opt-in setting, default off since `status off` at `tmux-manager.ts:1978` is deliberate): a minimal codeman-styled tmux status line showing `name · state · alert`, set on attach, restored on detach.
### Notifications
While the TUI is open and a session flips to NEEDS YOU: flash the row, ring BEL, and optionally emit OSC 9 (desktop notification in kitty/WezTerm/iTerm2, and it traverses SSH). This is the herdr sidebar promise delivered even when the terminal is backgrounded.
### Degraded mode (server down)
`sc` works without the server today and the TUI must too: when no server answers, enumerate `tmux -L codeman list-sessions` + read `state.json` (read-only), show a "server not running" header line, and offer attach only (no states, no approvals). This keeps the "web server crashed, get me to my sessions" path alive.
## 4. Architecture
### A client of the server, not a second brain
Everything live comes from the API the web UI already uses:
| Need | Endpoint |
| --- | --- |
| Session list + history | `GET /api/sessions/unified` |
| Live updates | SSE `GET /api/events` (heartbeat `sse:heartbeat` already exists; fall back to 2s polling) |
| Pending approvals + parsed options | `GET /api/approvals`, answer via `POST /api/approvals/:id/answer` |
| Preview tail | `GET /api/sessions/:id/terminal?tail=N` (throttled to the selected session only) |
| Prompt send | `POST /api/sessions/:id/input` (single line + `\r`, per the composer contract) |
| New session | `POST /api/quick-start` (routes remote/docker cases correctly) |
| Search | `GET /api/search` |
| Away digest | `GET /api/away-digest` |
| Plan usage chip | latest status-telemetry snapshot (`plan-usage-latest`) |
Server discovery and auth reuse what exists: instance config from `src/config/instance.ts` (`CODEMAN_INSTANCE`, `CODEMAN_PORT`), the probe logic from `daemon-control.ts`, credentials from `~/.codeman/.env` (the established `codeman attach` pattern), self-signed HTTPS accepted for loopback probes (the hooks-on-HTTPS lesson). Multi-user scoping comes free: the API only returns what the authenticated user owns.
### Renderer: hand-rolled, zero new dependencies (decision)
Options considered:
- **Ink (React for CLIs)**: what Claude Code uses. Pros: layout engine, ecosystem. Cons: pulls React into a CLI that today ships only commander+chalk; rerender model fights the two things we care most about (a raw-ANSI preview region and 2Hz glyph animation without flicker); version-pins React for every `npm i -g aicodeman`.
- **blessed/neo-blessed**: unmaintained, skip.
- **Hand-rolled screen core** (recommended): this repo hand-rolls ANSI everywhere already and has the expertise (regex-patterns, stripAnsi, the xterm work). The core is small and boring: alt screen + raw mode + cursor-home full-frame repaint from an off-screen string buffer, throttled to state changes and the 2Hz animation tick, wrapped in DECSET 2026 (synchronized output) where supported so repaints are atomic in modern terminals (tmux, kitty, WezTerm, iTerm2). No diffing needed at these frame rates.
The one genuinely tricky pure function: SGR-aware line clipping for the preview (keep colors, strip cursor movement/OSC/DECSET, clip to width while carrying SGR state, reset at EOL). That is a pure module with exhaustive unit tests, and it is exactly the kind of function Ink would not have given us anyway.
### Module layout
```
src/tui/
tui-app.ts entry + main loop + attach handoff (IO)
tui-client.ts API + SSE client, degraded-mode enumeration (IO)
tui-model.ts pure: state store, grouping, ordering (reuses PR #303 helpers)
tui-layout.ts pure: responsive layout math, row building
tui-render.ts pure: model+layout -> frame string (palette, glyphs, fallbacks)
tui-keys.ts pure: byte stream -> key/mouse events (incl. SGR mouse decode)
tui-ansi.ts pure: SGR-aware clip/filter for the preview
```
Pure modules unit-test with no TTY. `cli.ts` gains one thin `tui` command registration (and `--list`/`<n>` fast paths for `sc -l` / `sc 2` parity, which must stay fast: they short-circuit before any screen setup).
## 5. CLI-wide polish (the rest of "make it much nicer")
A shared style kit, `src/cli-style.ts`: one palette (mirroring the web's status colors), one glyph set with fallback, `heading()`, `kv()`, `table()` (width-aware, fixes the Antigravity overflow), `spinner()` (finally: the 30s silent daemon/service waits get a live line), `confirm()` (used by `reset --force`'s missing prompt and `x` in the TUI). Then the mechanical fixes from §1: colorize `doctor` through the hook that already exists for it, dedupe the `codeman web` startup line, colorize the server's security warning, fix the README `codeman attach` description and the Ctrl+B/Ctrl+A detach drift, TTY/NO_COLOR gates everywhere.
## 6. Phasing
| Phase | Contents | Size |
| --- | --- | --- |
| 0 | `cli-style.ts` + mechanical fixes (§5), real CLI tests (retire the fixture parser in `test/cli-commands.test.ts`) | S |
| 1 | `codeman tui` core: list + states via SSE, cursor + 1-9, attach/return loop, kill w/ confirm, new session, narrow mode, degraded mode, `sc` alias flip + `--list`/`<n>` parity | M/L |
| 2 | Preview pane (SGR clip), approvals answering, prompt composer, search, digest, resume, plan-usage header | M |
| 3 | Mouse support, `--pick` popup switcher + tmux binding, opt-in attach status line, BEL/OSC 9 notifications | M |
| 4 | Retire `tmux-chooser.sh`/fold `tmux-manager.sh` (keep as thin wrappers for one release), docs/README/wiki, screenshots for promo | S |
Phases 0-1 are the useful minimum; 2 is where it beats herdr's sidebar (answering approvals from the dashboard); 3 is delight.
## 7. Testing
- Pure modules (`tui-model/layout/render/keys/ansi`): plain vitest, frame snapshots as stripped strings plus targeted ANSI assertions.
- Interactive E2E: spawn the built TUI under `node-pty` (already a dependency), feed keys, assert on captured frames; the vitest tmux mock (`IS_TEST_MODE`) keeps attach paths inert. Port rules per CLAUDE.md (3150+, `app.inject()` where possible by testing `tui-client` against injected routes).
- Manual: Termius/iPhone portrait (the 44-col case), tmux nesting, server-down mode, NO_COLOR, non-nerd-font terminal.
## 8. Invariants this plan respects
- tmux socket and data dir always via instance config (`dataPath()`, `-L codeman`); a beta instance TUI sees only its own world.
- Never bulk kill, always confirm, never touch another session implicitly, refuse killing the session the TUI runs in (w1/w2/w3 are sacred).
- Input is single-line with `\r`, via the server (never raw tmux send-keys from the TUI while the server owns the session).
- Approvals answering goes through the server's re-capture + 409 path, never blind keystrokes.
- `status off` on panes stays the default; any chrome is opt-in.
- No new runtime dependencies; the npm package stays light.
## 9. Decisions (resolved 2026-08-16)
1. **Bare `codeman` does NOT open the TUI** (owner decision): the web UI is the main thing, the TUI is additional. `codeman tui` only.
2. **`sc` stays the bash chooser for now**; the alias flip is a follow-up once the TUI has mileage. `codeman tui --list` / `codeman tui <n>` provide the same fast paths for people who want to switch.
3. Opt-in tmux status line: deferred to phase 3 along with the `--pick` popup switcher.
4. Preview tail goes over the API (auth/multi-user/remote-consistent); previews are simply unavailable in degraded server-down mode.
5. Name is `codeman tui` (the test fixture historically expected it).
Initial PR scope: phases 0-2. Phase 3 (mouse, popup switcher, status line, OSC 9) and phase 4 (bash chooser retirement) are follow-ups.
+278
View File
@@ -0,0 +1,278 @@
# Terminal UI (`codeman tui`)
`codeman tui` is a full-screen dashboard for your Codeman sessions, in the terminal.
It shows every session grouped by whether it needs you, lets you answer a permission
dialog or send a prompt without switching anywhere, and puts you inside a session's
tmux pane with one keystroke.
It is **additional, not a replacement**: the web UI stays the primary surface and
gets every feature first. The TUI exists for the terminal workflow (SSH, Termius,
a tmux window you keep open all day), and it is a *client* of the running server,
so the two surfaces can never disagree about what a session is doing. It is also
not a multiplexer: tmux still owns every pane, and attaching hands the terminal to
tmux rather than proxying bytes.
## Starting it
```bash
codeman tui # the dashboard
codeman tui --list # print the numbered session list and exit
codeman tui 2 # attach straight to session 2 of that list
```
The two fast paths are the scriptable ones.
Neither sets up a screen, so both are as quick as the one API call they make, and
`--list` prints plain text when piped, so it composes with `grep`/`awk`.
What it needs:
| Needs | What you get |
| --- | --- |
| **Full features** | A running Codeman server (states, approvals, preview, prompts, search, digest). The TUI finds it the way `codeman attach` does: `CODEMAN_API_URL`, else loopback on `CODEMAN_PORT` for this `CODEMAN_INSTANCE`. The self-signed certificate an `--https` install generates is accepted, as it is everywhere else in the CLI. |
| **Server down** | It still starts, in **degraded mode**: sessions are enumerated straight from `tmux -L codeman` plus a read-only peek at `state.json`, and attach is the only verb. See [Troubleshooting](#troubleshooting). |
| **A terminal** | `codeman tui` refuses to run when stdin/stdout are not a TTY, and says to use `--list` instead. A cron job or a pipe therefore fails loudly rather than emitting escape codes into a log. |
## What it looks like
A real frame at 100x30 (`NO_COLOR`, trailing blank rows trimmed). The selected
session has a pending permission dialog, so the preview pane leads with the card:
```
codeman ⚠ 2 tnode · v1.19.0 · 5 sessions · 5h 32% · wk 61% ? help q quit
NEEDS YOU ─────────────────────────│ w4-api-refactor · claude · /home/you/dev/api · blocked
1 w6-docs ✋ 11m│ ⚠ requests: Bash(git push origin main)
▶ 2 w4-api-refactor ⚠ 2m│ 1. Yes
WORKING ───────────────────────────│ 2. Yes, and do not ask again
3 w1-codeman ∗ 1h│ 3. No, tell Claude what to do
4 w2-gallery ∗ 15m│ y approve · n deny · digit chooses
IDLE ──────────────────────────────│
5 w3-promo shell ○ 2h│ > refactor the api routes onto the shared port interface
RECENT ────────────────────────────│
6 api-hotfix ✔ 3d│ Read src/web/ports/session-port.ts (48 lines)
│ Read src/api/routes.ts (312 lines)
│ Edit src/api/routes.ts
│ 1 -import { SessionManager } from "../session-manager.js";
│ 2 +import type { SessionPort } from "../web/ports/session-
│
│ Bash(npm run typecheck)
│ └ tsc --noEmit: no errors
│
│ ✻ Actualizing… (2m 14s · ↓ 12.3k tokens)
↑↓ select · ⏎ attach · y approve · n deny · 1-9 option · p prompt · x kill · / search · g digest ·
```
- **Header**: the machine, the server version, how many sessions are live, and the
plan-usage chip (the same statusLine telemetry that feeds the web chip, when the
server has a snapshot). A `⚠ n` badge counts pending approvals.
- **Sidebar**: every session, grouped and numbered.
- **Preview**: a live tail of the selected session, its own colors preserved, with
the parsed dialog card on top when that session is blocked.
- **Footer**: only the keys that work right now. `n` reads `n new` normally and
`n deny` when the selected session has a dialog, because it cannot be both.
The same world through `--list`:
```
1 waiting w6-docs /home/you/dev/docs
2 blocked w4-api-refactor /home/you/dev/api
3 working w1-codeman /home/you/dev/codeman
4 working w2-gallery /home/you/dev/gallery
5 idle w3-promo /home/you/dev/promo
6 done api-hotfix /home/you/dev/api
```
The numbers are the same on both surfaces, so `codeman tui --list` then
`codeman tui 4` is one thought.
## The four groups
Groups are always in this order, and a session is in exactly one of them:
| Group | Glyph | Means | Comes from |
| --- | --- | --- | --- |
| **NEEDS YOU** | `⚠` | A permission or question dialog is blocking the agent | The approvals inbox (`permission_prompt` hooks, with the on-screen options parsed) |
| | `✋` | Waiting for your next instruction, or errored | `idle_prompt`, or an errored session (equally something only a human clears) |
| **WORKING** | `✻` animating | A turn is running | The same working classification the web dashboard uses |
| **IDLE** | `○` | Live, but sitting there | |
| **RECENT** | `✔` | A past session from the unified list | History rows, no live pane |
Ordering inside a group is "the one that has waited longest, first": blocked
sessions sort by how long the dialog has been up, working sessions by when their
turn started (the pane's last Enter, since a working pane repaints every second
and would otherwise always look freshly started), and quiet ones by last activity.
That is the ordering the web home screens already use.
The cursor sticks to a **session**, not a row number, so a session that jumps to
NEEDS YOU does not drag your selection with it. The number beside each row is what
`1-9` and `codeman tui <n>` mean, and it is renumbered on every re-sort.
When a new dialog appears, the terminal bell rings once, for that dialog only: the
same item announced twice does not ring twice.
## Keymap
| Key | Does |
| --- | --- |
| `↑` `↓` or `j` `k` | Move the cursor. PageUp/PageDown jump five rows. |
| `Enter` | Attach to the selected session (see [Attaching](#attaching)) |
| `1`-`9` | Jump to that row and attach. When a dialog is on screen, a digit answers it instead (see below). |
| `y` | Approve the selected session's dialog |
| `n` | Deny it, or **start a new session** when there is no dialog |
| `p` | Send one line to the selected session without attaching |
| `x` | Kill the selected session; `y` confirms, any other key cancels |
| `/` | Search sessions, events and files |
| `g` | Away digest: what happened while you were gone |
| `?` | Help overlay |
| `Esc` | Close whatever overlay is open |
| `q` or `Ctrl+C` | Quit, restoring the screen you started with |
Inside the `p` composer and the `/` query: `←` `→` `Home` `End` `Delete`
`Backspace` plus `Ctrl+A` / `Ctrl+E` / `Ctrl+U` / `Ctrl+W`, `Enter` to send or open,
`Esc` (or `Ctrl+C`) to cancel. In the kill confirmation you retype the session name;
anything else cancels. In the `n` pickers, type to filter, `Enter` chooses.
Verbs that need the server (`y`/`n`/`p`/`x`/`/`/`g`) say so in degraded mode
instead of failing silently; `Enter` and `1-9` keep working.
### `p` sends exactly one line
The composer is a single line by design, ending in a carriage return: that is the
input contract every Codeman path follows, because multi-line text breaks the
agent's own composer. Pasted newlines become spaces rather than being rejected, so
a paste cannot silently run a different command than the one you read.
## Answering approvals
This is the thing the terminal could not do before. Select a blocked session and:
- `y` approves.
- `n` picks the parsed "No" option, or sends Esc when the dialog did not parse one.
- A digit picks that numbered option, **but only a digit the dialog actually
offers**. A digit with no matching option falls through to the list's own
jump-and-attach binding, so it can never be typed at whatever has focus.
The answer goes through `POST /api/approvals/:id/answer`, which **re-captures the
pane before it types anything**. If the dialog is no longer on screen (you answered
it in tmux a moment ago, or the agent moved on), the server refuses with a 409 and
the TUI says `that dialog is no longer on screen` rather than pressing a key into a
live composer. The answer is scoped to the options the server parsed off the actual
frame, never to a guess.
An idle prompt (`✋`) is not a dialog: there is nothing to approve, so `p` is the
reply path and the footer says `p reply` instead of `p prompt`.
## Attaching
`Enter` suspends the dashboard (main screen back, cooked mode back) and hands the
terminal to tmux with `stdio: inherit`. Colors, mouse and paste are tmux's, at full
fidelity.
**Press `F1` to come back.** One key, no modifier to hold or release, nothing to
type in a particular order. tmux's own way out is a chord — press the prefix, let
go, then a letter — and beta testing showed that is genuinely hard to convey: the
bar first named the wrong letter (tmux binds lowercase `d` to `detach-client` and
capital `D` to `choose-client`), and once corrected it still failed for anyone who
kept Ctrl held, because that sends `Ctrl+D`, which tmux leaves unbound. So the TUI
claims `F1` in tmux's prefix-less key table for the length of the attach and gives
it back afterwards. The chord still works; it is simply not what you are told to
press.
You do not have to remember any of it. For as long as the attach lasts the pane
wears a bar across the top:
```
1 w3-codeman-… 2 w4-codeman-… 3 testcase … alt+1-9 switch · F1 back to the codeman dashboard
```
That is the **session strip**: the other sessions stay visible from inside a pane,
numbered exactly as the dashboard numbers them, with the one you are in inverted.
`Alt+1`..`Alt+9` switch between them without going back to the dashboard first. With
more sessions than fit, the strip shows a window around the current one and marks
each cut end with `…`; the way-out hint is measured first and always keeps its space.
Codeman keeps the status bar off on its panes (the web UI carries that information
around the terminal instead), so the TUI turns it on for the attach and puts it back
exactly as it was on detach, along with each window's size. Every session the strip
can switch to is dressed and sized the same way, so switching is instant and lands
in a pane that already fills your terminal.
Detaching leaves the agent running; typing `exit` or pressing `Ctrl+D` would end it,
which is the difference the bar exists to make obvious. If an agent does exit, its
pane stays as a corpse: the TUI refuses to attach to a dead pane and offers `r` to
resume the conversation in a fresh one instead.
Three cases:
| Where you are | What happens |
| --- | --- |
| Not in tmux | `tmux -L codeman attach-session` |
| Already in tmux on Codeman's socket | `switch-client`, so you do not nest |
| In tmux on a **different** socket | Refused, with an explanation: detach from that tmux first, then run `codeman tui` again |
A direct-PTY session has no pane to attach to, and says so.
**`Enter` on a RECENT row resumes that conversation** instead: there is no pane to
attach to, so the TUI creates a new claude session carrying the old transcript
(`resumeSessionId`, exactly what the web UI's "Resume Conversation" list does), in
the directory it originally ran in and under its old name, then attaches to it. It
is claude-only, and a row with no working directory or no conversation id says why
rather than resuming something else.
`x` never bulk-kills: it kills one session, only after you retype its name, never a
history row, and never the session the TUI itself is running in.
## Over SSH, and on a phone
The TUI is an ordinary terminal program with no local dependencies beyond tmux, so
`ssh box` then `codeman tui` works exactly like running it locally. There is no
separate remote mode.
Below 72 columns (Termius, an iPhone in portrait) the preview pane is dropped and
rows take two lines each, keeping the cursor, the live states and the
answer/prompt/kill verbs. The switch is
width-driven at draw time, so unfolding a foldable or resizing a window re-lays out
immediately; there is no mode flag to set.
## Troubleshooting
**"The Codeman server rejected these credentials."** The server has
`CODEMAN_PASSWORD` set. Export `CODEMAN_PASSWORD` (and `CODEMAN_USERNAME` if it is
not `admin`), or put them in the data dir's `.env` (`~/.codeman/.env`), which is
where `codeman attach` already reads them from.
**`server not running: attach only`** in a yellow banner. Nothing answered on the
expected port, so the TUI fell back to enumerating tmux. You get names and attach;
you do not get states, approvals or previews, because those only exist on the
server. Start the server (`codeman web -d`, or `systemctl --user start codeman-web`)
and the banner clears on its own: the TUI keeps re-probing.
**It found the wrong server, or none.** Discovery is instance-scoped. A beta
instance (`CODEMAN_INSTANCE=beta`) has its own data dir *and* its own tmux socket,
so its TUI sees only its own sessions. Set `CODEMAN_PORT` or `CODEMAN_API_URL`
explicitly when you run more than one.
**"this terminal is already inside tmux on socket ..."** You are in a tmux session
on a socket that is not Codeman's, so attaching would nest two multiplexers whose
prefix keys collide. Detach from that tmux and run `codeman tui` from outside.
**Boxes and glyphs render as garbage.** The TUI picks a glyph tier from the
environment: no `TERM` (or `dumb`), or a non-UTF-8 locale, gets the ASCII set
(`[!] [w] [*] [-]`, `+`/`-`/`|` frames). Force it either way with
`CODEMAN_TUI_GLYPHS=ascii|unicode|nerd`.
**Colors.** Standard `NO_COLOR` / `FORCE_COLOR` handling (chalk's, the same as the
rest of the CLI). Under `NO_COLOR` the frame is cursor addressing and text only,
and the preview's own colors are stripped too, so a session's output cannot repaint
the dashboard.
**It refuses to open at all**, saying it needs an interactive terminal. stdout or
stdin is not a TTY. That is the guard: use `codeman tui --list`.
## Related
- [`docs/tui-plan.md`](tui-plan.md): the design record. Why hand-rolled ANSI, why a
client and not a second brain, and what is deliberately deferred.
- [`docs/approvals-inbox-plan.md`](approvals-inbox-plan.md): where the parsed
dialogs and the answer endpoint come from.
- [`docs/remote-sessions.md`](remote-sessions.md): remote-SSH cases, which the TUI
lists like any other session.
+1 -1
View File
@@ -88,7 +88,7 @@ would. That indirection buys:
- **Real scrollback.** History is held by tmux, so reconnecting replays what happened while
you were gone instead of starting from blank.
- **Attach from anywhere else.** The same session is reachable from a terminal over SSH
with the `sc` chooser, or plain `tmux -L codeman attach`.
with `codeman tui`, or plain `tmux -L codeman attach`.
- **Secrets off the command line.** Environment overrides are injected with socket-scoped
`tmux setenv` rather than being visible in the spawn command.
+4 -2
View File
@@ -73,8 +73,10 @@ features are Claude-only; [Agent CLIs](Agent-CLIs) lists exactly which.
### Can I attach to a session from a terminal instead of the browser?
Yes. `sc` is an interactive chooser (`sc 2` attaches directly, `sc -l` lists), or use tmux
directly on the `codeman` socket. Detach with `Ctrl+A D`.
Yes. `codeman tui` is a full-screen dashboard of your sessions, with the same
NEEDS YOU / WORKING / IDLE grouping the web UI uses. `codeman tui --list` prints the
numbered list and exits, and `codeman tui 2` attaches straight to session 2. `Enter`
attaches, `F1` comes back. You can also use tmux directly on the `codeman` socket.
## Running unattended
+1 -1
View File
@@ -119,7 +119,7 @@ Shell and external CLI sessions accept `idle`, `working`, and `exit`.
## SSE
`GET /api/events` is the live event stream. 155 event names, kept in sync between server and
`GET /api/events` is the live event stream. 156 event names, kept in sync between server and
client with a test that fails on drift.
The heartbeat is a **named** `sse:heartbeat` event rather than an SSE comment, because
+20
View File
@@ -88,6 +88,22 @@ looks exactly like a dead button.
On phones this button replaces the desktop's **Run Shell** control; starting a shell moved
into the Run dropdown.
## Tapping, links and copying
- **Tap a link** in terminal output and it opens in a new tab. Same for a link in an agent's
answer in the response viewer — it opens a tab rather than navigating the dashboard away,
which on a phone would unload the whole session view.
- **Tap a file path** an agent printed and the file-preview overlay opens; a log path opens the
log viewer. Works in scrolled-up transcript too.
- A tap on the prose *beside* a link still places the cursor as usual, and a tap on a dialog's
numbered choice still answers the dialog even when the row contains a path — the dialog wins,
because on a phone it is the only interaction that matters.
- **Long-press to select text**, then drag, or tap the other end to extend the selection — no
hairline handles to grab. A small bar offers **Copy**, **Line** (the whole logical line,
wrapped rows included) and dismiss. Copy works on plain-HTTP installs too, where the browser
clipboard API is unavailable.
- A swipe is never mistaken for a long-press, and the keyboard stays down while you select.
## Scrolling and the keyboard
- The terminal and toolbar shift up when the keyboard opens, tracked through the browser's
@@ -97,6 +113,10 @@ into the Run dropdown.
keeps focus so you can place the caret.
- A scroll is never mistaken for a tap: travel is measured from the start of the gesture, and
multi-touch never counts.
- **A long prompt stays visible.** Once what you are typing wraps past the last visible row it
grows upward over the transcript instead of sliding under the keyboard, so the end of the
sentence — where the cursor is — is always on screen. A prompt taller than the visible strip
shows its tail.
## Voice
+9 -6
View File
@@ -179,16 +179,19 @@ the same IP, which matters because all tunnel traffic arrives from one loopback
## Terminal alternatives
You do not have to use a browser. `sc` is a thumb-friendly session chooser for SSH clients
like Termius or Blink:
You do not have to use a browser. `codeman tui` is a full-screen session dashboard that
works well in SSH clients like Termius or Blink:
```bash
sc # interactive chooser
sc 2 # attach to session 2
sc -l # list
codeman tui # the dashboard
codeman tui 2 # attach straight to session 2
codeman tui --list # numbered list, then exit
```
Detach with `Ctrl+A D`. The sessions are the same ones the dashboard shows.
`Enter` attaches into the pane and `F1` comes back. Under 72 columns it drops the preview
and becomes a single-column list, so it stays usable on a phone. The sessions are the same
ones the dashboard shows. See [docs/tui.md](https://github.com/Ark0N/Codeman/blob/master/docs/tui.md)
for the full guide.
## Common problems
+1
View File
@@ -45,6 +45,7 @@ supervised by systemd or launchd; npm installs report as non-updatable. See
| CJK Input | Off | IME composition through a dedicated text field. |
| Extended Keyboard Bar | Per device | Which accessory bar phones get. Shell sessions override it while they are active. |
| Wheel Scrolls Local History | Off | Keeps the wheel on the local buffer instead of forwarding it to the CLI. |
| Auto Copy Selection | Off | Copies highlighted terminal text to the clipboard the moment you finish selecting it. Ctrl+C still copies on demand. |
| WebGL Renderer | On | With a GPU-stall watchdog that falls back to DOM rendering. |
| Gesture Control | Off | Camera hand tracking. Also needs `CODEMAN_GESTURE=1` on the server. |
+4 -2
View File
@@ -133,8 +133,10 @@ TUIs render correctly.
Worth knowing:
- **Scrollback.** The first time you open a session, Codeman pulls the entire tmux
scrollback, not just the recent tail. Scrolling to the very top pulls again on demand.
- **Scrollback.** Agent/TUI sessions pull their entire tmux scrollback on first open.
Shell sessions open from a bounded recent tail so a large transcript cannot stall tab
switching; press **Load full history** to pull the rest explicitly. Ordinary Shell scrolling
stays within the bounded browser buffer so dragging upward remains responsive.
- **Wheel and touch scrolling** are forwarded into Claude's own transcript on recent Claude
versions, so the wheel scrolls the conversation rather than the terminal. `Shift+Wheel` is
always local scrollback. Other CLIs scroll locally.
+79 -24
View File
@@ -125,6 +125,14 @@ PI_SEARCH_PATHS=(
"$HOME/bin/pi"
)
# Grok CLI search paths (from src/utils/grok-cli-resolver.ts)
GROK_SEARCH_PATHS=(
"$HOME/.grok/bin/grok"
"$HOME/.local/bin/grok"
"/usr/local/bin/grok"
"$HOME/bin/grok"
)
# Antigravity CLI search paths (from src/utils/antigravity-cli-resolver.ts)
ANTIGRAVITY_SEARCH_PATHS=(
"$HOME/.local/bin/agy"
@@ -569,6 +577,37 @@ get_pi_path() {
done
}
# `grok` has known squatters too (the unrelated @vibe-kit/grok-cli), so the
# server-side resolver additionally probes `grok --version`. Detection here only
# feeds the "you have no AI CLI" hint, so a plain executable test is enough.
check_grok() {
if command -v grok &>/dev/null; then
return 0
fi
for path in "${GROK_SEARCH_PATHS[@]}"; do
if [[ -x "$path" ]]; then
return 0
fi
done
return 1
}
get_grok_path() {
if command -v grok &>/dev/null; then
command -v grok
return
fi
for path in "${GROK_SEARCH_PATHS[@]}"; do
if [[ -x "$path" ]]; then
echo "$path"
return
fi
done
}
check_cloudflared() {
# Check ~/.local/bin first (matches tunnel-manager.ts resolution order)
if [[ -x "$HOME/.local/bin/cloudflared" ]]; then
@@ -1072,21 +1111,28 @@ add_to_path() {
success "Added to $profile"
}
setup_sc_alias() {
# The `sc` bash chooser was retired in favour of `codeman tui`, which reaches
# sessions 10+, carries the server's real states and leaves an attach with one
# key. Older installers wrote this alias, so take it back out.
#
# Marker-owned on purpose: it matches the exact line WE wrote, so a user's own
# `alias sc=` for something entirely different is never touched. The rewrite
# goes through `cat >` rather than `mv` so the profile keeps its own mode and
# ownership.
remove_sc_alias() {
local profile
profile=$(detect_shell_profile)
[[ -f "$profile" ]] || return 0
grep -qE "^alias sc='tmux-chooser'\$" "$profile" 2>/dev/null || return 0
# Check if alias already exists
if [[ -f "$profile" ]] && grep -qE "^alias sc=" "$profile" 2>/dev/null; then
info "Alias 'sc' already configured in $profile"
return 0
local tmp
tmp=$(mktemp 2>/dev/null) || return 0
if sed -e "/^alias sc='tmux-chooser'\$/d" \
-e '/^# Codeman tmux session shortcut$/d' "$profile" > "$tmp" 2>/dev/null; then
cat "$tmp" > "$profile"
info "Removed the retired 'sc' alias from $profile (use: codeman tui)"
fi
echo "" >> "$profile"
echo "# Codeman tmux session shortcut" >> "$profile"
echo "alias sc='tmux-chooser'" >> "$profile"
info "Added 'sc' alias for tmux-chooser"
rm -f "$tmp"
}
# ============================================================================
@@ -2076,6 +2122,7 @@ main() {
local has_gemini=false
local has_antigravity=false
local has_pi=false
local has_grok=false
info "Checking AI CLI tools..."
if check_claude; then
@@ -2102,17 +2149,21 @@ main() {
has_pi=true
success "Pi CLI found at $(get_pi_path)"
fi
if check_grok; then
has_grok=true
success "Grok CLI found at $(get_grok_path)"
fi
if [[ "$has_claude" == "false" && "$has_opencode" == "false" && "$has_codex" == "false" && "$has_gemini" == "false" && "$has_antigravity" == "false" && "$has_pi" == "false" ]]; then
if [[ "$has_claude" == "false" && "$has_opencode" == "false" && "$has_codex" == "false" && "$has_gemini" == "false" && "$has_antigravity" == "false" && "$has_pi" == "false" && "$has_grok" == "false" ]]; then
echo ""
warn "No AI CLI found. Codeman needs at least one: Claude Code, OpenCode, Codex, Antigravity, Gemini, or Pi."
warn "No AI CLI found. Codeman needs at least one: Claude Code, OpenCode, Codex, Antigravity, Gemini, Pi, or Grok."
headless_guard "install an AI CLI (curl | bash from its vendor)"
echo ""
echo -e " ${BOLD}Which AI CLI would you like to install?${NC}"
echo -e " ${CYAN}1)${NC} Claude Code (Anthropic)"
echo -e " ${CYAN}2)${NC} OpenCode (open-source)"
echo -e " ${CYAN}3)${NC} Both"
echo -e " ${CYAN}4)${NC} Skip (I'll install one myself, e.g. Codex, Antigravity or Pi)"
echo -e " ${CYAN}4)${NC} Skip (I'll install one myself, e.g. Codex, Antigravity, Pi or Grok)"
echo ""
local cli_choice=""
@@ -2160,6 +2211,7 @@ main() {
info "Install one later, e.g.: npm install -g @openai/codex (Codex)"
info " or: curl -fsSL https://antigravity.google/cli/install.sh | bash (Antigravity)"
info " or: npm install -g --ignore-scripts @earendil-works/pi-coding-agent (Pi)"
info " or: curl -fsSL https://x.ai/cli/install.sh | bash (Grok)"
elif [[ "$has_claude" == "false" ]] && [[ "$has_opencode" == "false" ]]; then
die "The selected AI CLI failed to install. Install one manually and re-run the installer."
fi
@@ -2243,13 +2295,14 @@ main() {
ln -sf "$INSTALL_DIR/dist/index.js" "$symlink_dir/codeman"
info "Created symlink: $symlink_dir/codeman"
# Install tmux-chooser as 'tmux-chooser' command
if [[ -f "$INSTALL_DIR/scripts/tmux-chooser.sh" ]]; then
ln -sf "$INSTALL_DIR/scripts/tmux-chooser.sh" "$symlink_dir/tmux-chooser"
info "Created symlink: $symlink_dir/tmux-chooser"
# Add 'sc' alias for quick access
setup_sc_alias
# tmux-chooser/`sc` is retired; `codeman tui` replaces it. Sweep up what
# an older installer left behind, so an update does not leave a symlink
# pointing at a script this version no longer ships.
if [[ -L "$symlink_dir/tmux-chooser" ]]; then
rm -f "$symlink_dir/tmux-chooser"
info "Removed the retired tmux-chooser symlink (use: codeman tui)"
fi
remove_sc_alias
# Add ~/.local/bin to PATH if not already there
if [[ ":$PATH:" != *":$symlink_dir:"* ]]; then
@@ -2450,22 +2503,23 @@ main() {
echo -e " ${BOLD}Mobile Access (Termius/SSH):${NC}"
echo ""
echo -e " ${CYAN}sc${NC} # Interactive tmux session chooser"
echo -e " ${CYAN}sc 2${NC} # Quick attach to session 2"
echo -e " ${CYAN}sc -h${NC} # Help"
echo -e " ${CYAN}codeman tui${NC} # Full-screen session dashboard"
echo -e " ${CYAN}codeman tui 2${NC} # Attach straight to session 2"
echo -e " ${CYAN}codeman tui -l${NC} # Numbered list, then exit"
echo ""
echo -e " ${BOLD}Documentation:${NC}"
echo -e " https://github.com/Ark0N/Codeman"
echo ""
if ! check_claude && ! check_opencode && ! check_codex && ! check_gemini && ! check_antigravity && ! check_pi; then
if ! check_claude && ! check_opencode && ! check_codex && ! check_gemini && ! check_antigravity && ! check_pi && ! check_grok; then
echo -e " ${YELLOW}${BOLD}Reminder:${NC} Install at least one AI CLI to start using Codeman:"
echo -e " ${CYAN}curl -fsSL https://claude.ai/install.sh | bash${NC} # Claude Code"
echo -e " ${CYAN}curl -fsSL https://opencode.ai/install | bash${NC} # OpenCode"
echo -e " ${CYAN}npm install -g @openai/codex${NC} # Codex"
echo -e " ${CYAN}curl -fsSL https://antigravity.google/cli/install.sh | bash${NC} # Antigravity"
echo -e " ${CYAN}npm install -g --ignore-scripts @earendil-works/pi-coding-agent${NC} # Pi"
echo -e " ${CYAN}curl -fsSL https://x.ai/cli/install.sh | bash${NC} # Grok"
echo ""
fi
@@ -2620,6 +2674,7 @@ uninstall() {
rm -f "$symlink_dir/tmux-chooser"
success "Removed symlink: $symlink_dir/tmux-chooser"
fi
remove_sc_alias
# Remove install directory
if [[ -d "$INSTALL_DIR" ]]; then
+46 -29
View File
@@ -1,12 +1,12 @@
{
"name": "aicodeman",
"version": "1.19.6",
"version": "1.22.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "aicodeman",
"version": "1.19.6",
"version": "1.22.0",
"hasInstallScript": true,
"license": "MIT",
"workspaces": [
@@ -17,7 +17,7 @@
"@fastify/compress": "^8.3.1",
"@fastify/cookie": "^11.0.2",
"@fastify/multipart": "^10.0.0",
"@fastify/static": "^9.1.3",
"@fastify/static": "^10.1.3",
"@fastify/websocket": "^11.2.0",
"@xterm/addon-fit": "^0.11.0",
"@xterm/addon-serialize": "^0.14.0",
@@ -1454,9 +1454,9 @@
}
},
"node_modules/@fastify/static": {
"version": "9.1.3",
"resolved": "https://registry.npmjs.org/@fastify/static/-/static-9.1.3.tgz",
"integrity": "sha512-aXrYtsiryLhRxRNaxNqsn7FUISeb7rB9q4eHUPIot5aeQBLNahnz1m6thzm7JWC1poSGXS9XrX8DvuMivp2hkQ==",
"version": "10.1.3",
"resolved": "https://registry.npmjs.org/@fastify/static/-/static-10.1.3.tgz",
"integrity": "sha512-W6jqajYS974XjPjB5hQWoxPM8NKM4+p8YmQT6G5IbCa4uhdWSVadZUv75siy1wEA/3ty8RYdpBydfWeu9AqAqQ==",
"funding": [
{
"type": "github",
@@ -1470,13 +1470,30 @@
"license": "MIT",
"dependencies": {
"@fastify/accept-negotiator": "^2.0.0",
"@fastify/error": "^4.0.0",
"@fastify/send": "^4.0.0",
"content-disposition": "^1.0.1",
"fastify-plugin": "^5.0.0",
"content-disposition": "^2.0.1",
"fastify-plugin": "^6.0.0",
"fastq": "^1.17.1",
"glob": "^13.0.0"
}
},
"node_modules/@fastify/static/node_modules/fastify-plugin": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/fastify-plugin/-/fastify-plugin-6.0.0.tgz",
"integrity": "sha512-fZOty7z3O7vOliF6d8bHE3wiEh1KcNnKEQensSgTk9C1DvN6nRLS++XVd86v33Hw/8u9Un8A1zDrQ8ujcQDHEg==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/fastify"
},
{
"type": "opencollective",
"url": "https://opencollective.com/fastify"
}
],
"license": "MIT"
},
"node_modules/@fastify/websocket": {
"version": "11.2.0",
"resolved": "https://registry.npmjs.org/@fastify/websocket/-/websocket-11.2.0.tgz",
@@ -4136,16 +4153,16 @@
}
},
"node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": {
"version": "5.0.6",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.6.tgz",
"integrity": "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==",
"version": "5.0.9",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz",
"integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==",
"dev": true,
"license": "MIT",
"dependencies": {
"balanced-match": "^4.0.2"
},
"engines": {
"node": "18 || 20 || >=22"
"node": "20 || >=22"
}
},
"node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": {
@@ -5078,9 +5095,9 @@
"license": "MIT"
},
"node_modules/brace-expansion": {
"version": "1.1.15",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.15.tgz",
"integrity": "sha512-EwOCDEex4quD37XhqM3omwtMoJjr//isUZz1JopUNWms+4Z2ViyM/k1YIRePpoVNnQhENnxtFjLaxNHrT7xIUg==",
"version": "1.1.18",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz",
"integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -5431,9 +5448,9 @@
}
},
"node_modules/content-disposition": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz",
"integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==",
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-2.0.1.tgz",
"integrity": "sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog==",
"license": "MIT",
"engines": {
"node": ">=18"
@@ -6552,9 +6569,9 @@
}
},
"node_modules/fast-uri": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.2.tgz",
"integrity": "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==",
"version": "3.1.5",
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.5.tgz",
"integrity": "sha512-gHwA1O9LDIcKunMKhObS/HimwtehO1nPUECKAu5TpKgaO19fcWEl4bliWe1jWxVFvIXztJjjQ4L8XQ1EU9f7Jw==",
"funding": [
{
"type": "github",
@@ -6661,9 +6678,9 @@
}
},
"node_modules/find-my-way": {
"version": "9.6.0",
"resolved": "https://registry.npmjs.org/find-my-way/-/find-my-way-9.6.0.tgz",
"integrity": "sha512-Zf4Xve4RymLl7NgaavNebZ01joJ8MfVerOG43wy7SHLO+r+K0C6d/SE0BiR7AV5V1VOCFlOP7ecdo+I4qmiHrQ==",
"version": "9.8.0",
"resolved": "https://registry.npmjs.org/find-my-way/-/find-my-way-9.8.0.tgz",
"integrity": "sha512-JtyUgATO7qxRp2zKhrmWof74Mqxc1ikbwpwMY97p8ipuTj2QtreA4gK2JNAF6SOqqHnYYkwMUvsgQVi2AJxIyw==",
"license": "MIT",
"dependencies": {
"fast-deep-equal": "^3.1.3",
@@ -6905,15 +6922,15 @@
}
},
"node_modules/glob/node_modules/brace-expansion": {
"version": "5.0.6",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.6.tgz",
"integrity": "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==",
"version": "5.0.9",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz",
"integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==",
"license": "MIT",
"dependencies": {
"balanced-match": "^4.0.2"
},
"engines": {
"node": "18 || 20 || >=22"
"node": "20 || >=22"
}
},
"node_modules/glob/node_modules/minimatch": {
@@ -12344,7 +12361,7 @@
}
},
"packages/xterm-zerolag-input": {
"version": "0.3.0",
"version": "0.3.1",
"license": "MIT",
"devDependencies": {
"@xterm/headless": "^6.0.0",
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "aicodeman",
"version": "1.19.6",
"version": "1.22.0",
"description": "Mission control for AI coding agents - run 20 autonomous agents with real-time monitoring and session persistence",
"type": "module",
"main": "dist/index.js",
@@ -62,6 +62,7 @@
"codex",
"antigravity",
"pi",
"grok",
"gemini-cli",
"ai-agents",
"agent",
@@ -85,7 +86,7 @@
"@fastify/compress": "^8.3.1",
"@fastify/cookie": "^11.0.2",
"@fastify/multipart": "^10.0.0",
"@fastify/static": "^9.1.3",
"@fastify/static": "^10.1.3",
"@fastify/websocket": "^11.2.0",
"@xterm/addon-fit": "^0.11.0",
"@xterm/addon-serialize": "^0.14.0",
+15
View File
@@ -1,5 +1,20 @@
# xterm-zerolag-input
## 0.3.1
### Patch Changes
- Mobile catches up: links open from a tap, terminal text can be selected and copied, long prompts stay visible while you type. Plus Files panel search, a bundled Nerd Font symbols fallback, and a per-device terminal font setting.
- **Terminal and chat links work on phones** (#321): tapping a URL or file path in terminal output now opens it (new tab, file preview, or log viewer), resolved through the same provider desktop hover uses, so tap and click can never disagree about what is a link. Dialog rows and the composer keep their existing meaning. Response-viewer links open in a new tab with `rel="noopener noreferrer"` instead of navigating the dashboard away. Wrapped links open whole: the logical-line reconstruction now stitches hard wraps through the indent their continuation carries, which also fixes desktop hover-click truncating wrapped URLs.
- **Terminal text can be copied on touch devices** (#321): long-press selects the token under the finger, drag or tap the other end to extend, and a small bar offers Copy, Line (the whole logical line, wraps included) and dismiss. Copy works on plain-HTTP installs too. Three guards keep the keyboard down and the selection alive through the browser's own long-press handling.
- **A long prompt stays visible on phones** (#321): the local-echo overlay grows upward once it would run past the last visible row (a prompt taller than the screen keeps its tail, where the cursor is), and the keyboard-driven padding shrink can no longer reclaim the space the fixed toolbar and accessory bar stand in.
- **Files panel search** (#324): `GET /api/sessions/:id/files?q=...` answers a flat match list (name or path substring, `*`/`?` globs), recursing past non-matching directories with its own match cap on top of the existing bounds; without `q` the response is byte-identical to before. Glob queries are matched without regex so a pathological pattern cannot stall the server.
- **Nerd Font prompt glyphs out of the box, custom terminal font** (#320): a bundled icons-only Symbols Nerd Font Mono fallback renders powerlevel10k/starship/oh-my-posh glyphs on every device with no font install, and App Settings gains a per-device terminal font family that is prepended to the built-in stack.
### Thanks
Three contributor PRs in one release: thanks to @rounakdatta (#321), @aakhter (#324) and @comzine (#320).
## 0.3.0
### Minor Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "xterm-zerolag-input",
"version": "0.3.0",
"version": "0.3.1",
"description": "Instant keystroke feedback overlay for xterm.js: Mosh-inspired local echo that removes perceived input latency over SSH, tunnels and other high-RTT connections",
"type": "module",
"main": "dist/index.cjs",
@@ -65,38 +65,71 @@ export function renderOverlay(container: HTMLDivElement, params: RenderParams):
charTop,
charHeight,
promptRow,
totalRows,
font,
showCursor,
cursorColor,
terminal,
} = params;
// Position container at prompt row.
// ── Keep what is being typed ON SCREEN ────────────────────────────
//
// The overlay lays its wrapped lines out DOWNWARD from the prompt row, and
// nothing past the last terminal row is visible. On a phone the strip left
// above the on-screen keyboard is only a handful of rows, so a prompt long
// enough to wrap ran off the bottom and the user was typing blind — the tail
// of their own sentence, the part they are actually looking at, hidden behind
// the keyboard.
//
// So the composer grows UPWARD once it reaches the last row, exactly as a real
// terminal's does: every line div is opaque (see makeLine), so the lines cover
// transcript rows above instead of vanishing under the keyboard below, and the
// newest text stays where the eye is. A prompt taller than the whole viewport
// keeps its TAIL for the same reason.
//
// `startCol` indents only the line that begins at the prompt marker, so it is
// dropped along with that line when the tail is all that fits.
const rows = totalRows && totalRows > 0 ? totalRows : terminal?.rows;
let visibleLines = lines;
let keepsPromptLine = true;
let topRow = promptRow;
if (rows && rows > 0) {
if (lines.length > rows) {
visibleLines = lines.slice(lines.length - rows);
keepsPromptLine = false;
topRow = 0;
} else if (promptRow + lines.length > rows) {
topRow = rows - lines.length;
}
}
topRow = Math.max(0, topRow);
container.style.left = '0px';
container.style.top = promptRow * cellH + 'px';
container.style.top = topRow * cellH + 'px';
// Clear and rebuild (typically 1-3 line divs, negligible cost)
container.innerHTML = '';
const fullWidthPx = totalCols * cellW;
for (let i = 0; i < lines.length; i++) {
const leftPx = i === 0 ? startCol * cellW : 0;
const widthPx = i === 0 ? fullWidthPx - leftPx : fullWidthPx;
for (let i = 0; i < visibleLines.length; i++) {
const indents = i === 0 && keepsPromptLine;
const leftPx = indents ? startCol * cellW : 0;
const widthPx = indents ? fullWidthPx - leftPx : fullWidthPx;
const topPx = i * cellH;
const lineEl = makeLine(lines[i], leftPx, topPx, widthPx, cellH, cellW, charTop, charHeight, font, terminal);
const lineEl = makeLine(visibleLines[i], leftPx, topPx, widthPx, cellH, cellW, charTop, charHeight, font, terminal);
container.appendChild(lineEl);
}
// Block cursor at end of last line (use visual width for CJK support)
if (showCursor) {
const lastLine = lines[lines.length - 1];
const lastLineLeft = lines.length === 1 ? startCol : 0;
const lastLine = visibleLines[visibleLines.length - 1];
const lastLineLeft = visibleLines.length === 1 && keepsPromptLine ? startCol : 0;
const cursorCol = lastLineLeft + stringCellWidth(terminal, lastLine);
if (cursorCol < totalCols) {
const cursor = document.createElement('span');
cursor.style.cssText = 'position:absolute;display:inline-block';
cursor.style.left = cursorCol * cellW + 'px';
cursor.style.top = (lines.length - 1) * cellH + 'px';
cursor.style.top = (visibleLines.length - 1) * cellH + 'px';
cursor.style.width = cellW + 'px';
cursor.style.height = cellH + 'px';
cursor.style.backgroundColor = cursorColor;
@@ -172,6 +172,13 @@ export interface RenderParams {
/** Height of the character rendering area (px). */
charHeight: number;
promptRow: number;
/**
* Visible terminal rows. When given, the overlay is kept ON SCREEN: it grows
* upward instead of running off the bottom edge, and a wrapped prompt taller
* than the viewport keeps its tail. Omit to lay out straight down from
* `promptRow` (the historical behaviour).
*/
totalRows?: number;
font: FontStyle;
showCursor: boolean;
cursorColor: string;
@@ -565,7 +565,10 @@ export class ZerolagInputAddon implements XtermAddon {
// Skip redundant re-renders — include text content to detect
// same-length changes (e.g., setFlushed with different text)
const renderKey = `${displayText}:${startCol}:${activePrompt.row}:${activePrompt.col}:${totalCols}:${this._flushedOffset}`;
// `rows` is part of the key: the layout is clamped to the visible rows
// (see renderOverlay), so a keyboard opening — which changes rows without
// changing the text — must not be skipped as a redundant render.
const renderKey = `${displayText}:${startCol}:${activePrompt.row}:${activePrompt.col}:${totalCols}:${this._terminal.rows}:${this._flushedOffset}`;
if (renderKey === this._lastRenderKey && this._overlay.style.display !== 'none') return;
this._lastRenderKey = renderKey;
@@ -612,6 +615,7 @@ export class ZerolagInputAddon implements XtermAddon {
charTop,
charHeight,
promptRow: activePrompt.row,
totalRows: this._terminal.rows,
font: this._font,
showCursor: this._options.showCursor,
cursorColor,
@@ -418,3 +418,88 @@ describe('stringCellWidth', () => {
expect(stringCellWidth(null, '')).toBe(0);
});
});
describe('renderOverlay — staying on screen (totalRows)', () => {
// A phone with the keyboard up leaves only a handful of terminal rows. The
// overlay lays its wrapped lines out downward from the prompt row, so a long
// prompt used to run off the bottom edge and the user typed blind, with the
// tail of their own sentence behind the keyboard. With totalRows known, the
// composer grows UPWARD instead — the line divs are opaque, so they cover
// transcript above rather than disappearing below.
const linesOf = (n: number) => Array.from({ length: n }, (_, i) => `line${i}`);
const lineDivs = (container: HTMLDivElement) =>
Array.from(container.children).filter((el) => el.tagName === 'DIV') as HTMLDivElement[];
it('lifts the block so its last line lands on the last visible row', () => {
const container = document.createElement('div');
renderOverlay(container, makeParams({ lines: linesOf(5), promptRow: 10, totalRows: 12, cellH: 17 }));
// 10 + 5 would end on row 14 of a 12-row screen; the block starts at 7 instead.
expect(container.style.top).toBe(7 * 17 + 'px');
expect(lineDivs(container)).toHaveLength(5);
});
it('leaves the prompt row alone when the block already fits', () => {
const container = document.createElement('div');
renderOverlay(container, makeParams({ lines: linesOf(3), promptRow: 5, totalRows: 24, cellH: 17 }));
expect(container.style.top).toBe(5 * 17 + 'px');
});
it('keeps the TAIL when the prompt is taller than the whole viewport', () => {
// The end is where the cursor is, and where the user is looking.
const container = document.createElement('div');
renderOverlay(container, makeParams({ lines: linesOf(6), promptRow: 2, totalRows: 3, cellH: 20 }));
const divs = lineDivs(container);
expect(container.style.top).toBe('0px');
expect(divs).toHaveLength(3);
expect(divs.map((d) => d.textContent)).toEqual(['line3', 'line4', 'line5']);
});
it('drops the prompt indent once the prompt line is no longer shown', () => {
// startCol indents only the line that begins at the prompt marker.
const container = document.createElement('div');
renderOverlay(
container,
makeParams({ lines: linesOf(6), promptRow: 2, totalRows: 3, startCol: 5, cellW: 10, totalCols: 80 })
);
const first = lineDivs(container)[0];
expect(first.style.left).toBe('0px');
expect(first.style.width).toBe(80 * 10 + 'px');
});
it('rides the cursor on the last VISIBLE line', () => {
const container = document.createElement('div');
renderOverlay(
container,
makeParams({ lines: ['aaa', 'bbb', 'ccc', 'ddd'], promptRow: 9, totalRows: 3, cellH: 20, cellW: 10, startCol: 4 })
);
const cursor = Array.from(container.children).find((el) => el.tagName === 'SPAN') as HTMLSpanElement;
// Tail is the last 3 lines, so the cursor sits on row 2 (0-based) of the block…
expect(cursor.style.top).toBe(2 * 20 + 'px');
// …at column 3, NOT startCol + 3: the indented prompt line is not shown.
expect(cursor.style.left).toBe(3 * 10 + 'px');
});
it('lays out straight down when totalRows is absent (unchanged behaviour)', () => {
const container = document.createElement('div');
renderOverlay(container, makeParams({ lines: linesOf(9), promptRow: 20, cellH: 17 }));
expect(container.style.top).toBe(20 * 17 + 'px');
expect(lineDivs(container)).toHaveLength(9);
});
it('falls back to the terminal row count when totalRows is not passed', () => {
// The addon passes totalRows, but a stale bundle / third-party caller may not.
const container = document.createElement('div');
renderOverlay(
container,
makeParams({ lines: linesOf(4), promptRow: 8, cellH: 17, terminal: { rows: 10, cols: 80 } as never })
);
expect(container.style.top).toBe(6 * 17 + 'px');
});
});
+2
View File
@@ -86,6 +86,7 @@ run('minify input-cjk.js', 'npx esbuild dist/web/public/input-cjk.js --minify --
run('minify i18n.js', 'npx esbuild dist/web/public/i18n.js --minify --outfile=dist/web/public/i18n.js --allow-overwrite');
run('minify sanitize-html.js', 'npx esbuild dist/web/public/sanitize-html.js --minify --outfile=dist/web/public/sanitize-html.js --allow-overwrite');
run('minify app.js', 'npx esbuild dist/web/public/app.js --minify --outfile=dist/web/public/app.js --allow-overwrite');
run('minify tab-rail-resize.js', 'npx esbuild dist/web/public/tab-rail-resize.js --minify --outfile=dist/web/public/tab-rail-resize.js --allow-overwrite');
run('minify terminal-ui.js', 'npx esbuild dist/web/public/terminal-ui.js --minify --outfile=dist/web/public/terminal-ui.js --allow-overwrite');
run('minify respawn-ui.js', 'npx esbuild dist/web/public/respawn-ui.js --minify --outfile=dist/web/public/respawn-ui.js --allow-overwrite');
run('minify ralph-panel.js', 'npx esbuild dist/web/public/ralph-panel.js --minify --outfile=dist/web/public/ralph-panel.js --allow-overwrite');
@@ -111,6 +112,7 @@ console.log('\n[build] content-hash cache busting');
'input-cjk.js',
'sanitize-html.js',
'app.js',
'tab-rail-resize.js',
'terminal-ui.js',
'respawn-ui.js',
'ralph-panel.js',
-662
View File
@@ -1,662 +0,0 @@
#!/bin/bash
# ============================================================================
# Codeman Sessions - Mobile-friendly Tmux Session Chooser
# Optimized for iPhone/Termius (portrait ~45 chars, landscape ~95 chars)
# ============================================================================
#
# Design principles:
# - Single-digit selection (1-9) for fast thumb typing
# - Compact display, no wasted space
# - Color-coded status for quick scanning
# - Names pulled from Codeman state.json
# - Minimal keystrokes to attach
#
# Usage:
# tmux-chooser # Interactive chooser
# tmux-chooser 1 # Quick attach to session 1
# tmux-chooser -l # List only (non-interactive)
# tmux-chooser -h # Help
#
# Alias: alias sc='tmux-chooser'
# Then: sc (interactive)
# sc 2 (attach session 2)
#
# ============================================================================
set -e
# ============================================================================
# Configuration
# ============================================================================
CODEMAN_STATE="$HOME/.codeman/state.json"
CODEMAN_SESSIONS="$HOME/.codeman/mux-sessions.json"
# Dedicated tmux socket all Codeman sessions live on. MUST match
# DEFAULT_CODEMAN_TMUX_SOCKET / CODEMAN_TMUX_SOCKET in src/tmux-manager.ts —
# otherwise list-sessions would enumerate the user's default tmux server
# (missing the real Codeman sessions, surfacing unrelated ones).
CODEMAN_TMUX_SOCKET="${CODEMAN_TMUX_SOCKET:-codeman}"
TMUX_CMD=(tmux -L "$CODEMAN_TMUX_SOCKET")
# iPhone 17 Pro portrait width (conservative)
MAX_WIDTH=44
MAX_NAME_LEN=28
# Page size for pagination (leave room for header/footer)
PAGE_SIZE=7
# Auto-refresh timeout (seconds) - 0 to disable
AUTO_REFRESH=60
# ============================================================================
# Icon Detection (Nerd Fonts vs ASCII)
# ============================================================================
detect_icons() {
if [[ "$TERM_PROGRAM" == "iTerm"* ]] || \
[[ "$TERM" == "xterm-kitty" ]] || \
[[ -n "$WEZTERM_PANE" ]] || \
[[ "$LC_TERMINAL" == "iTerm2" ]]; then
ICON_SESSION="󰆍"
ICON_ATTACHED="●"
ICON_DETACHED="○"
ICON_UNKNOWN="◌"
else
ICON_SESSION="[T]"
ICON_ATTACHED="*"
ICON_DETACHED="-"
ICON_UNKNOWN="?"
fi
}
detect_icons
# ============================================================================
# Colors - ANSI 256 for better Termius compatibility
# ============================================================================
R='\033[0m' # Reset
B='\033[1m' # Bold
D='\033[2m' # Dim
GREEN='\033[38;5;82m'
YELLOW='\033[38;5;220m'
BLUE='\033[38;5;75m'
CYAN='\033[38;5;87m'
RED='\033[38;5;203m'
GRAY='\033[38;5;245m'
WHITE='\033[38;5;255m'
BG_SEL='\033[48;5;236m'
# ============================================================================
# Utilities
# ============================================================================
truncate() {
local str="$1"
local max="$2"
local len=${#str}
if [ "$len" -le "$max" ]; then
echo "$str"
return
fi
if [[ "$str" == *"/"* ]]; then
echo "..${str: -$((max-2))}"
else
echo "${str:0:$((max-1))}…"
fi
}
find_full_session_id() {
local short_id="$1"
if [ -f "$CODEMAN_STATE" ]; then
local full_id
full_id=$(jq -r --arg short "$short_id" '
.sessions | keys[] | select(startswith($short))
' "$CODEMAN_STATE" 2>/dev/null | head -1)
if [ -n "$full_id" ]; then
echo "$full_id"
return
fi
fi
if [ -f "$CODEMAN_SESSIONS" ]; then
local full_id
full_id=$(jq -r --arg short "$short_id" '
.[] | select(.sessionId | startswith($short)) | .sessionId
' "$CODEMAN_SESSIONS" 2>/dev/null | head -1)
if [ -n "$full_id" ]; then
echo "$full_id"
return
fi
fi
echo "$short_id"
}
get_session_name() {
local session_id="$1"
local name=""
local workdir=""
if [ -f "$CODEMAN_SESSIONS" ]; then
local result
result=$(jq -r --arg id "$session_id" '
.[] | select(.sessionId | startswith($id)) | "\(.name // "")\t\(.workingDir // "")"
' "$CODEMAN_SESSIONS" 2>/dev/null | head -1)
if [ -n "$result" ]; then
name="${result%% *}"
workdir="${result#* }"
fi
fi
if [ -z "$name" ] && [ -f "$CODEMAN_STATE" ]; then
local result
result=$(jq -r --arg id "$session_id" '
.sessions | to_entries[] | select(.key | startswith($id)) | "\(.value.name // "")\t\(.value.workingDir // "")"
' "$CODEMAN_STATE" 2>/dev/null | head -1)
if [ -n "$result" ]; then
name="${result%% *}"
[ -z "$workdir" ] && workdir="${result#* }"
fi
fi
if [ -n "$name" ]; then
echo "$name"
return
fi
if [ -n "$workdir" ]; then
echo "${workdir##*/}"
return
fi
echo "${session_id:0:8}"
}
get_working_dir() {
local session_id="$1"
if [ -f "$CODEMAN_SESSIONS" ]; then
local dir
dir=$(jq -r --arg id "$session_id" '
.[] | select(.sessionId | startswith($id)) | .workingDir // empty
' "$CODEMAN_SESSIONS" 2>/dev/null | head -1)
if [ -n "$dir" ] && [ "$dir" != "null" ]; then
echo "${dir/#$HOME/~}"
return
fi
fi
if [ -f "$CODEMAN_STATE" ]; then
local dir
dir=$(jq -r --arg id "$session_id" '
.sessions | to_entries[] | select(.key | startswith($id)) | .value.workingDir // empty
' "$CODEMAN_STATE" 2>/dev/null | head -1)
if [ -n "$dir" ] && [ "$dir" != "null" ]; then
echo "${dir/#$HOME/~}"
return
fi
fi
echo ""
}
get_tokens() {
local session_id="$1"
if [ -f "$CODEMAN_STATE" ]; then
local tokens
tokens=$(jq -r --arg id "$session_id" '
.sessions | to_entries[] | select(.key | startswith($id)) |
((.value.inputTokens // 0) + (.value.outputTokens // 0))
' "$CODEMAN_STATE" 2>/dev/null | head -1)
if [ -n "$tokens" ] && [ "$tokens" != "null" ] && [ "$tokens" -gt 0 ] 2>/dev/null; then
if [ "$tokens" -gt 1000 ]; then
echo "$((tokens / 1000))k"
else
echo "${tokens}"
fi
return
fi
fi
echo ""
}
get_respawn_status() {
local session_id="$1"
if [ -f "$CODEMAN_SESSIONS" ]; then
local respawn_enabled
respawn_enabled=$(jq -r --arg id "$session_id" '
.[] | select(.sessionId | startswith($id)) | .respawnConfig.enabled // false
' "$CODEMAN_SESSIONS" 2>/dev/null | head -1)
if [ "$respawn_enabled" = "true" ]; then
echo "R"
return
fi
fi
echo ""
}
check_deps() {
if ! command -v jq &>/dev/null; then
echo -e "${YELLOW}Note: Install jq for session names${R}"
echo ""
fi
}
# ============================================================================
# Tmux Session Parser
# ============================================================================
declare -a SESSION_PIDS
declare -a MUX_NAMES
declare -a SESSION_STATES
declare -a SESSION_IDS
declare -a DISPLAY_NAMES
declare -a WORKING_DIRS
declare -a TOKEN_COUNTS
declare -a RESPAWN_STATUS
parse_sessions() {
SESSION_PIDS=()
MUX_NAMES=()
SESSION_STATES=()
SESSION_IDS=()
DISPLAY_NAMES=()
WORKING_DIRS=()
TOKEN_COUNTS=()
RESPAWN_STATUS=()
local i=0
# Parse tmux list-sessions output
while IFS= read -r line; do
local session_name="${line%%:*}"
# Only show codeman sessions
if [[ "$session_name" != codeman-* ]]; then
continue
fi
# Check if attached
local state="Detached"
if [[ "$line" == *"(attached)"* ]]; then
state="Attached"
fi
# Get PID from tmux
local pid
pid=$("${TMUX_CMD[@]}" display-message -t "$session_name" -p '#{pane_pid}' 2>/dev/null || echo "0")
SESSION_PIDS+=("$pid")
MUX_NAMES+=("$session_name")
SESSION_STATES+=("$state")
# Extract session ID from codeman session name
local session_id=""
local cm_regex='^codeman-(.+)$'
if [[ "$session_name" =~ $cm_regex ]]; then
session_id="${BASH_REMATCH[1]}"
fi
SESSION_IDS+=("$session_id")
# Get display name and metadata
if [ -n "$session_id" ]; then
DISPLAY_NAMES+=("$(get_session_name "$session_id")")
WORKING_DIRS+=("$(get_working_dir "$session_id")")
TOKEN_COUNTS+=("$(get_tokens "$session_id")")
RESPAWN_STATUS+=("$(get_respawn_status "$session_id")")
else
DISPLAY_NAMES+=("$session_name")
WORKING_DIRS+=("")
TOKEN_COUNTS+=("")
RESPAWN_STATUS+=("")
fi
i=$((i + 1))
done < <("${TMUX_CMD[@]}" list-sessions 2>/dev/null || true)
}
# ============================================================================
# Display Functions
# ============================================================================
clear_screen() {
printf '\033[2J\033[H'
}
print_header() {
local count=${#SESSION_PIDS[@]}
echo -e "${B}${CYAN}Codeman Sessions${R} ${D}($count)${R}"
echo -e "${D}$(printf '%.0s─' {1..32})${R}"
}
print_entry() {
local idx="$1"
local num=$((idx + 1))
local name="${DISPLAY_NAMES[$idx]}"
local state="${SESSION_STATES[$idx]}"
local dir="${WORKING_DIRS[$idx]}"
local tokens="${TOKEN_COUNTS[$idx]}"
local respawn="${RESPAWN_STATUS[$idx]}"
local name_max=$MAX_NAME_LEN
[ -n "$respawn" ] && name_max=$((name_max - 2))
[ -n "$tokens" ] && name_max=$((name_max - 4))
name=$(truncate "$name" $name_max)
local status_icon status_color
if [[ "$state" == *"Attached"* ]]; then
status_icon="$ICON_ATTACHED"
status_color="$GREEN"
elif [[ "$state" == *"Detached"* ]]; then
status_icon="$ICON_DETACHED"
status_color="$GRAY"
else
status_icon="$ICON_UNKNOWN"
status_color="$YELLOW"
fi
local num_str="${B}${WHITE}${num})${R}"
local name_str="${B}${WHITE}${name}${R}"
local status_str="${status_color}${status_icon}${R}"
local respawn_str=""
if [ -n "$respawn" ]; then
respawn_str=" ${GREEN}${respawn}${R}"
fi
local token_str=""
if [ -n "$tokens" ]; then
token_str=" ${D}${tokens}${R}"
fi
echo -e " ${num_str} ${name_str} ${status_str}${respawn_str}${token_str}"
if [ -n "$dir" ]; then
dir=$(truncate "$dir" $((MAX_NAME_LEN - 2)))
echo -e " ${D}${dir}${R}"
fi
}
print_footer() {
local page="$1"
local total_pages="$2"
echo ""
echo -e "${D}────────────────────────────────${R}"
if [ "$total_pages" -gt 1 ]; then
echo -e " ${D}Page $((page+1))/$total_pages${R} ${GRAY}[${WHITE}n${GRAY}]ext [${WHITE}p${GRAY}]rev${R}"
fi
echo -e " ${GRAY}[${WHITE}1-9${GRAY}]attach [${WHITE}r${GRAY}]efresh [${WHITE}q${GRAY}]uit${R}"
}
print_no_sessions() {
clear_screen
echo -e "${B}${CYAN}Codeman Sessions${R}"
echo -e "${D}$(printf '%.0s─' {1..32})${R}"
echo ""
echo -e " ${YELLOW}No tmux sessions found${R}"
echo ""
echo -e " ${D}Start one with:${R}"
echo -e " ${WHITE}codeman web${R}"
echo ""
echo -e "${D}$(printf '%.0s─' {1..32})${R}"
echo -e " ${GRAY}[${WHITE}r${GRAY}]efresh [${WHITE}q${GRAY}]uit${R}"
}
# ============================================================================
# Main Display Loop
# ============================================================================
current_page=0
render() {
clear_screen
parse_sessions
local count=${#SESSION_PIDS[@]}
if [ "$count" -eq 0 ]; then
print_no_sessions
return
fi
local total_pages=$(( (count + PAGE_SIZE - 1) / PAGE_SIZE ))
if [ "$current_page" -ge "$total_pages" ]; then
current_page=$((total_pages - 1))
fi
if [ "$current_page" -lt 0 ]; then
current_page=0
fi
local start=$((current_page * PAGE_SIZE))
local end=$((start + PAGE_SIZE))
if [ "$end" -gt "$count" ]; then
end=$count
fi
print_header
echo ""
for ((i = start; i < end; i++)); do
print_entry $i
done
print_footer $current_page $total_pages
}
attach_session() {
local idx="$1"
local mux_name="${MUX_NAMES[$idx]}"
if [ -z "$mux_name" ]; then
return 1
fi
clear_screen
echo -e "${GREEN}Attaching to ${B}${DISPLAY_NAMES[$idx]}${R}${GREEN}...${R}"
echo -e "${D}(Ctrl+B D to detach)${R}"
sleep 0.3
"${TMUX_CMD[@]}" attach-session -t "$mux_name"
return 0
}
# ============================================================================
# Input Handler
# ============================================================================
handle_input() {
local key="$1"
local count=${#SESSION_PIDS[@]}
local total_pages=$(( (count + PAGE_SIZE - 1) / PAGE_SIZE ))
case "$key" in
[1-9])
local idx=$((key - 1))
if [ "$idx" -lt "$count" ]; then
attach_session "$idx"
return 0
fi
;;
$'\e')
read -rsn2 -t 0.1 seq 2>/dev/null || true
case "$seq" in
'[A'|'[D')
if [ "$total_pages" -gt 1 ]; then
current_page=$(( (current_page - 1 + total_pages) % total_pages ))
fi
;;
'[B'|'[C')
if [ "$total_pages" -gt 1 ]; then
current_page=$(( (current_page + 1) % total_pages ))
fi
;;
esac
;;
n|N|j|J)
if [ "$total_pages" -gt 1 ]; then
current_page=$(( (current_page + 1) % total_pages ))
fi
;;
p|P|k|K)
if [ "$total_pages" -gt 1 ]; then
current_page=$(( (current_page - 1 + total_pages) % total_pages ))
fi
;;
r|R)
;;
q|Q)
clear_screen
exit 0
;;
'')
if [ "$count" -eq 1 ]; then
attach_session 0
return 0
fi
;;
esac
return 0
}
# ============================================================================
# List Mode
# ============================================================================
list_mode() {
parse_sessions
local count=${#SESSION_PIDS[@]}
if [ "$count" -eq 0 ]; then
echo "No tmux sessions"
exit 0
fi
for ((i = 0; i < count; i++)); do
local num=$((i + 1))
local name="${DISPLAY_NAMES[$i]}"
local state="${SESSION_STATES[$i]}"
local respawn="${RESPAWN_STATUS[$i]}"
local indicator="-"
[[ "$state" == *"Attached"* ]] && indicator="*"
[ -n "$respawn" ] && indicator="${indicator}R"
echo "$num) $name [$indicator]"
done
}
# ============================================================================
# Quick Attach
# ============================================================================
quick_attach() {
local num="$1"
parse_sessions
local count=${#SESSION_PIDS[@]}
local idx=$((num - 1))
if [ "$idx" -lt 0 ] || [ "$idx" -ge "$count" ]; then
echo -e "${RED}Invalid session: $num${R}"
echo "Available: 1-$count"
exit 1
fi
attach_session "$idx"
}
# ============================================================================
# Help
# ============================================================================
show_help() {
cat << 'EOF'
Codeman Sessions - Mobile-friendly Tmux Session Chooser
USAGE:
sc Interactive chooser
sc <number> Quick attach to session N
sc -l List sessions (non-interactive)
sc -h Show this help
INTERACTIVE KEYS:
1-9 Attach to session
n/j/↓ Next page
p/k/↑ Previous page
r Refresh
q Quit
INDICATORS:
* / ● Attached (someone connected)
- / ○ Detached (available)
R Respawn enabled
45k Token count
TIPS:
- Detach from tmux: Ctrl+B D
- Session names from Codeman state
- Optimized for Termius/iPhone
EOF
}
# ============================================================================
# Main
# ============================================================================
main() {
case "${1:-}" in
-h|--help)
show_help
exit 0
;;
-l|--list)
list_mode
exit 0
;;
[1-9]|[1-9][0-9])
quick_attach "$1"
exit $?
;;
esac
check_deps
render
while true; do
local timeout_opt=""
if [ "$AUTO_REFRESH" -gt 0 ]; then
timeout_opt="-t $AUTO_REFRESH"
fi
if read -rsn1 $timeout_opt key 2>/dev/null; then
handle_input "$key"
fi
render
done
}
trap 'clear_screen; exit 0' INT
main "$@"
+12 -11
View File
@@ -237,7 +237,7 @@ minutes, never retry the credential.
flushed slightly *after* the `stop` hook fires, so a read taken the instant the wait
returns is too early (verified live: empty on the first call, full prose seconds later).
It is also `""` before the worker's first completed turn, and permanently `""` for
`shell`, `opencode`, `gemini`, `antigravity` and `pi`, which write no Claude transcript.
`shell`, `opencode`, `gemini`, `antigravity`, `pi` and `grok`, which write no Claude transcript.
**Fix** Poll it, bounded (10 tries, 1 s apart). If it is still empty on a hook-less mode,
that is expected, not a failure: read `terminal?tail=` and strip ANSI instead.
@@ -336,19 +336,20 @@ ESC=$(printf '\033')
`POST /api/v1/quick-start` body (all optional):
`{"caseName":"worker-1","mode":"claude","sessionName":"w9-worker","effort":"high"}`
, `mode` ∈ `claude|shell|opencode|codex|gemini|antigravity|pi`; response is
, `mode` ∈ `claude|shell|opencode|codex|gemini|antigravity|pi|grok`; response is
`.data.{sessionId, caseName, casePath}`. Creates the case directory (a real directory
on the user's disk) if missing, do not retry it in a loop, and remember the name.
⚠️ A `mode` whose CLI is **not installed on the server** fails the spawn with
`OPERATION_FAILED`; it never falls back to claude. Probe first whenever you did not pick
the mode yourself: `GET /api/v1/claude/status`, `GET /api/v1/opencode/status`,
`GET /api/v1/codex/status`, `GET /api/v1/gemini/status`, `GET /api/v1/antigravity/status`
`GET /api/v1/codex/status`, `GET /api/v1/gemini/status`, `GET /api/v1/antigravity/status`, `GET /api/v1/grok/status`
and `GET /api/v1/pi/status` each return `.data.{available, path}` (no session needed).
Pi's also carries `.data.version`, because `pi` is a short generic name that an unrelated
binary on `$PATH` can shadow: the resolver rejects one whose `--version` is not
semver-shaped, so `available:false` there can mean "a different `pi` is in front" rather
than "nothing is installed". `shell` has no CLI to probe.
Pi's and grok's also carry `.data.version`, because `pi` is a short generic name and
`grok` is a name with npm squatters, so an unrelated binary on `$PATH` can shadow either:
the resolver rejects one whose `--version` is not version-shaped, so `available:false`
there can mean "a different `pi`/`grok` is in front" rather than "nothing is installed".
`shell` has no CLI to probe.
⚠️ **Branch on `.success` before reading `.data.sessionId`.** On any failure the field
is absent, `jq -r` prints the literal string `null`, and every later call then targets
@@ -462,10 +463,10 @@ Quirks that will bite you:
session answers with an empty timeline rather than a 404.
- ⚠️ **`active-tools` proves presence, never absence.** It is fed by the BashToolParser,
which reads Claude's rendered `● Bash(…)` lines, and `_processExpensiveParsers`
returns early for every external CLI mode (`session.ts:2136`), so it is permanently
`[]` on `opencode`/`codex`/`gemini`/`antigravity`/`pi`. ⚠️ **`shell` is NOT one of those**
(`isExternalCliMode`, `session.ts:165-167`, lists only those five), so the parser does
run on a shell worker, and `TEXT_COMMAND_PATTERN` (`bash-tool-parser.ts:88`) matches
returns early for every external CLI mode (`session.ts:2261`), so it is permanently
`[]` on `opencode`/`codex`/`gemini`/`antigravity`/`pi`/`grok`. ⚠️ **`shell` is NOT one of those**
(`isExternalCliMode`, `session.ts:174-183`, lists only those six), so the parser does
run on a shell worker, and `TEXT_COMMAND_PATTERN` (`bash-tool-parser.ts:89`) matches
bare `tail|cat|head|less|grep|watch|multitail <path>` lines with no `● Bash(` wrapper:
a shell worker running `cat build.log` really does populate this. In practice it stays
empty for most shell work. It also never sees non-Bash
+2 -2
View File
@@ -56,7 +56,7 @@ own head: the worker enforcing the cap is the one who has to be told about it.
| synchronize on end of turn | HTTP `wait until=stop` (fires for message-initiated turns too, verified live) |
| liveness / death check | HTTP `wait?until=exit` |
| interrupt a running turn (break-glass) | HTTP input, a bare `\x1b` with no `\r` |
| non-claude modes (`shell`/`opencode`/`codex`/`gemini`/`antigravity`/`pi`) | HTTP only (no other CLI has messaging) |
| non-claude modes (`shell`/`opencode`/`codex`/`gemini`/`antigravity`/`pi`/`grok`) | HTTP only (no other CLI has messaging) |
| delete | HTTP, via SKILL.md's `delete_session` guard |
## Availability: probe, never assume
@@ -347,7 +347,7 @@ Without a break-glass, a pair with a bad brief is a token bonfire with no off sw
### Mixed fleets: the pairing matrix
Non-claude workers (`shell`, `opencode`, `codex`, `gemini`, `antigravity`, `pi`) cannot be peers
Non-claude workers (`shell`, `opencode`, `codex`, `gemini`, `antigravity`, `pi`, `grok`) cannot be peers
at all; no other CLI has this feature. Their tasks route over HTTP, and you never mention
messaging in their briefs. The claude half of the fleet can use messaging among itself,
subject to the namespace rule: **messaging works between two sessions that share one
+1 -1
View File
@@ -188,7 +188,7 @@ for _ in $(seq 1 10); do
done
printf '%s\n' "$TXT"
# (.data is {text,timestamp}; text is also "" before the first completed turn and
# always "" for shell/opencode/gemini/antigravity/pi, which have no transcript, use
# always "" for shell/opencode/gemini/antigravity/pi/grok, which have no transcript, use
# the terminal tail there, and here only to diagnose an unsubmitted prompt.)
# 6. clean up: exact id, own list only, through the fail-closed preamble helper
+3 -3
View File
@@ -343,7 +343,7 @@ recovered by submitting it with `{"input":"\r"}`.
⚠️ `stop` and `blocked` fire for `claude` sessions only (they are Claude Code hooks,
and only when the workspace actually has them, see [§5.1](#51-where-to-spawn)). On
`shell`/`opencode`/`codex`/`gemini`/`antigravity`/`pi`, requesting them explicitly is a
`shell`/`opencode`/`codex`/`gemini`/`antigravity`/`pi`/`grok`, requesting them explicitly is a
400, and lifecycle transitions there are coarse (a short shell command may emit **no**
`idle` transition at all, verified live), so synchronize those with markers.
@@ -369,7 +369,7 @@ from the transcript file, which is flushed slightly *after* the `stop` hook fire
single read taken the instant send-and-wait returns comes back `""` even though the
turn finished (verified live: empty on the first call, full text seconds later). `text`
is also `""` before the worker's first completed turn, and always `""` for modes with
no transcript (`shell`, `opencode`, `gemini`, `antigravity`, `pi`; the first four
no transcript (`shell`, `opencode`, `gemini`, `antigravity`, `pi`, `grok`; the first four
verified live, pi from the same source path), which is
why the loop above is bounded rather than open-ended. Fall back to the terminal buffer
there, tail in **bytes** (`textOutput` in `GET .../output` stays empty for interactive
@@ -454,7 +454,7 @@ turn), and both better than diffing terminal samples:
```
⚠️ `active-tools` is parsed out of Claude's own output format, so it is **empty for
`opencode`/`codex`/`gemini`/`antigravity`/`pi`** (those parsers are skipped wholesale) and
`opencode`/`codex`/`gemini`/`antigravity`/`pi`/`grok`** (those parsers are skipped wholesale) and
in practice empty for `shell`. Source-verified, not measured live.
Only if neither helps: sample `terminal?tail=` twice a few seconds apart. A changing
+299
View File
@@ -0,0 +1,299 @@
/**
* @fileoverview One style vocabulary for everything the `codeman` CLI prints:
* palette, glyphs, the small block helpers (heading/rule/kv), width-aware table
* layout, a stderr spinner and a y/N confirm.
*
* Color detection is chalk's alone. It already honors NO_COLOR, FORCE_COLOR,
* TERM=dumb and TTY-ness, and a second detector here would disagree with it on
* some terminal with no way to tell which one was right.
*
* The layout math is pure and exported separately from anything that touches a
* terminal, which is what lets it be unit-tested with no TTY and reused by
* `utils/dependency-report.ts` while that file stays color-free.
*
* @module cli-style
*/
import chalk, { type ChalkInstance } from 'chalk';
import { createInterface } from 'node:readline';
// Direct import, not the `utils` barrel: the barrel pulls in node-pty and every
// CLI resolver, which a style module has no business loading.
import { stripAnsi } from './utils/regex-patterns.js';
// ─────────────────────────────────────────────────────────────────────────────
// Palette and glyphs
// ─────────────────────────────────────────────────────────────────────────────
/** Semantic roles, mirroring the web UI's status language (green fine, yellow waiting, red blocked). */
export const palette = {
ok: chalk.green,
warn: chalk.yellow,
err: chalk.red,
info: chalk.cyan,
muted: chalk.gray,
emph: chalk.bold,
accent: chalk.magenta,
} as const satisfies Record<string, ChalkInstance>;
/** The glyph vocabulary the CLI already used, in one place. */
export const GLYPH = {
ok: '✓',
fail: '✗',
warn: '⚠',
idle: '○',
dot: '●',
arrow: '→',
} as const;
/** Spinner frames (braille, one cell wide in every terminal we support). */
export const SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] as const;
/** What a line is reporting, independent of how it is painted. */
export type Tone = 'ok' | 'warn' | 'err' | 'idle' | 'info';
const TONE_GLYPH: Record<Tone, string> = {
ok: GLYPH.ok,
warn: GLYPH.warn,
err: GLYPH.fail,
idle: GLYPH.idle,
info: GLYPH.dot,
};
const TONE_STYLE: Record<Tone, ChalkInstance> = {
ok: palette.ok,
warn: palette.warn,
err: palette.err,
idle: palette.muted,
info: palette.info,
};
/** Glyph for a tone. Pure, so the mapping is testable without a terminal. */
export function glyphFor(tone: Tone): string {
return TONE_GLYPH[tone];
}
/** Paint text in a tone's color. */
export function tint(tone: Tone, text: string): string {
return TONE_STYLE[tone](text);
}
// ─────────────────────────────────────────────────────────────────────────────
// Blocks
// ─────────────────────────────────────────────────────────────────────────────
/** Section heading. The blank line above it is part of the existing block idiom. */
export function heading(text: string): string {
return `\n${palette.emph(text)}`;
}
/** Horizontal rule under a title. */
export function rule(width = 40): string {
return palette.muted('─'.repeat(Math.max(0, width)));
}
/**
* Indented `Label: value` line. `pad` aligns the values of a block by padding
* the label column (including its colon), for blocks whose labels differ in
* length.
*/
export function kv(label: string, value: string, pad = 0): string {
const key = pad > 0 ? padCell(`${label}:`, pad) : `${label}:`;
return ` ${key} ${value}`;
}
// ─────────────────────────────────────────────────────────────────────────────
// Width-aware layout (pure)
// ─────────────────────────────────────────────────────────────────────────────
/** Printed width of a cell: ANSI sequences take no columns. */
export function displayWidth(text: string): number {
return stripAnsi(text).length;
}
export type CellAlign = 'left' | 'right';
/** Pad to `width` columns, measuring by display width so colored cells still align. */
export function padCell(text: string, width: number, align: CellAlign = 'left'): string {
const fill = ' '.repeat(Math.max(0, width - displayWidth(text)));
return align === 'right' ? `${fill}${text}` : `${text}${fill}`;
}
/**
* Pad AFTER the paint, so the fill stays outside the color run and a trailing
* empty column can be trimmed away instead of ending in a reset sequence with
* invisible spaces before it.
*/
export function padStyled(text: string, width: number, paint: (t: string) => string): string {
return `${paint(text)}${' '.repeat(Math.max(0, width - displayWidth(text)))}`;
}
/** Widest cell per column. Short rows count as empty cells, never as narrower columns. */
export function columnWidths(rows: readonly (readonly string[])[]): number[] {
const widths: number[] = [];
for (const row of rows) {
for (let i = 0; i < row.length; i++) {
widths[i] = Math.max(widths[i] ?? 0, displayWidth(row[i] ?? ''));
}
}
return widths;
}
export interface TableOptions {
/** Per-column alignment; missing entries are left-aligned. */
align?: readonly CellAlign[];
/** Spaces between columns. */
gap?: number;
/** Prefix for every row. */
indent?: string;
}
/**
* Lay rows out in columns sized to their widest cell. The last cell of a row is
* never padded, so no line carries trailing whitespace.
*/
export function layoutTable(rows: readonly (readonly string[])[], options: TableOptions = {}): string[] {
const { align = [], gap = 1, indent = '' } = options;
const widths = columnWidths(rows);
const separator = ' '.repeat(Math.max(0, gap));
return rows.map((row) => {
const cells = row.map((cell, i) => (i === row.length - 1 ? cell : padCell(cell, widths[i], align[i] ?? 'left')));
return `${indent}${cells.join(separator)}`;
});
}
/** `layoutTable()` as one printable block. */
export function table(rows: readonly (readonly string[])[], options: TableOptions = {}): string {
return layoutTable(rows, options).join('\n');
}
// ─────────────────────────────────────────────────────────────────────────────
// Spinner
// ─────────────────────────────────────────────────────────────────────────────
const HIDE_CURSOR = '\x1b[?25l';
const SHOW_CURSOR = '\x1b[?25h';
const CLEAR_LINE = '\x1b[K';
/** The slice of a stream a spinner needs; `process.stderr` satisfies it. */
export interface SpinnerStream {
isTTY?: boolean;
write(chunk: string): unknown;
}
export interface Spinner {
start(): Spinner;
/** Change the text mid-flight. Silent on a non-TTY, which prints once and stops. */
setText(text: string): void;
/** Clear the line, restore the cursor and optionally print a final line. */
stop(finalLine?: string): void;
}
export interface SpinnerOptions {
stream?: SpinnerStream;
intervalMs?: number;
}
/**
* In-place progress line on stderr, for the calls that block for tens of seconds
* (daemon start, service install). Only a TTY gets the animation: piped output
* and journald get the text once, so a log file never fills with `\r` frames.
*/
export function spinner(text: string, options: SpinnerOptions = {}): Spinner {
const stream = options.stream ?? process.stderr;
const intervalMs = options.intervalMs ?? 90;
const animated = Boolean(stream.isTTY);
let label = text;
let frame = 0;
let timer: NodeJS.Timeout | null = null;
let started = false;
let stopped = false;
const restoreCursor = () => {
if (animated) stream.write(SHOW_CURSOR);
};
const render = () => {
stream.write(`\r${palette.info(SPINNER_FRAMES[frame % SPINNER_FRAMES.length])} ${label}${CLEAR_LINE}`);
frame++;
};
const handle: Spinner = {
start() {
if (started || stopped) return handle;
started = true;
if (!animated) {
stream.write(`${label}\n`);
return handle;
}
stream.write(HIDE_CURSOR);
// A hidden cursor left behind by a Ctrl+C outlives the process, so the
// exit hook is not optional.
process.once('exit', restoreCursor);
render();
// Unref'd: a spinner must never be the reason the process stays alive.
timer = setInterval(render, intervalMs);
timer.unref();
return handle;
},
setText(next: string) {
label = next;
if (animated && started && !stopped) render();
},
stop(finalLine?: string) {
if (stopped) return;
stopped = true;
if (timer) {
clearInterval(timer);
timer = null;
}
if (animated && started) {
stream.write(`\r${CLEAR_LINE}`);
restoreCursor();
process.off('exit', restoreCursor);
}
if (finalLine && animated) stream.write(`${finalLine}\n`);
},
};
return handle;
}
/** Run `work` with a spinner up, stopping it however `work` ends. */
export async function withSpinner<T>(text: string, work: () => Promise<T>, options?: SpinnerOptions): Promise<T> {
const handle = spinner(text, options).start();
try {
return await work();
} finally {
handle.stop();
}
}
// ─────────────────────────────────────────────────────────────────────────────
// Confirm
// ─────────────────────────────────────────────────────────────────────────────
/** Is there a human on the other end of both halves of the terminal? */
export function isInteractive(): boolean {
return Boolean(process.stdin.isTTY && process.stdout.isTTY);
}
/**
* y/N prompt. Answers `false` immediately when stdin is not a TTY (a script
* piping into the CLI must never hang on an invisible question), so callers
* that support a `--force` flag can branch on `isInteractive()` to keep printing
* their "pass --force" hint instead.
*/
export async function confirm(question: string): Promise<boolean> {
if (!isInteractive()) return false;
const rl = createInterface({ input: process.stdin, output: process.stdout });
try {
const answer = await new Promise<string>((resolve) => {
rl.once('SIGINT', () => resolve(''));
rl.question(`${question} ${palette.muted('[y/N]')} `, resolve);
});
return /^y(es)?$/i.test(answer.trim());
} finally {
rl.close();
// readline resumes stdin; a still-flowing stdin keeps the process alive.
process.stdin.pause();
}
}
+270 -205
View File
@@ -8,7 +8,6 @@
*/
import { Command } from 'commander';
import chalk from 'chalk';
import { createRequire } from 'module';
import http from 'node:http';
import https from 'node:https';
@@ -26,6 +25,9 @@ import { isSupportedAttachmentExtension } from './attachment-registry.js';
import { daemonStatus, startDaemon, stopDaemon, type WebLaunchOptions } from './daemon-control.js';
import { installService, serviceStatus, uninstallService } from './service-installer.js';
import { isLoopbackBindHost, isUnauthenticatedNetworkAcknowledged } from './web/network-auth-policy.js';
import { confirm, heading, isInteractive, kv, palette, rule, tint, withSpinner, type Tone } from './cli-style.js';
import type { ToolResult } from './utils/dependency-checker.js';
import type { ReportStyle } from './utils/dependency-report.js';
const require = createRequire(import.meta.url);
const pkg = require('../package.json') as { version: string };
@@ -107,14 +109,14 @@ program
.action(async (filePath, options) => {
const extension = String(filePath).split('.').pop()?.toLowerCase() || '';
if (!isAbsolute(filePath) || !isSupportedAttachmentExtension(extension)) {
console.error(chalk.red('✗ attach requires an absolute path to a png, pdf, docx, pptx, md, or txt file'));
console.error(palette.err('✗ attach requires an absolute path to a png, pdf, docx, pptx, md, or txt file'));
process.exit(1);
}
const sessionId = options.session || process.env.CODEMAN_SESSION_ID;
const apiUrl = options.url || process.env.CODEMAN_API_URL || 'https://127.0.0.1:3000';
if (sessionId && (await postAttachment(apiUrl, sessionId, filePath))) {
console.log(chalk.green('✓ Attachment card requested'));
console.log(palette.ok('✓ Attachment card requested'));
return;
}
@@ -174,7 +176,7 @@ export function resolveSkillTargetPath(options: {
function resolveSkillTarget(options: { case?: string }): string {
const resolved = resolveSkillTargetPath(options);
if (resolved.missingCase !== undefined) {
console.error(chalk.red(`✗ Case not found: ${resolved.missingCase}`));
console.error(palette.err(`✗ Case not found: ${resolved.missingCase}`));
process.exit(1);
}
return resolved.target;
@@ -199,9 +201,9 @@ function reportSkillResult(result: AgentSkillApplyResult, target: string): void
};
const message = messages[result];
if (message.ok) {
console.log(chalk.green(`✓ ${message.text}`));
console.log(palette.ok(`✓ ${message.text}`));
} else {
console.error(chalk.red(`✗ ${message.text}`));
console.error(palette.err(`✗ ${message.text}`));
process.exit(1);
}
}
@@ -220,7 +222,7 @@ skillCmd
const target = resolveSkillTarget(options);
reportSkillResult(await installAgentSkillInto(target), target);
} catch (err) {
console.error(chalk.red(`✗ Failed to install agent skill: ${getErrorMessage(err)}`));
console.error(palette.err(`✗ Failed to install agent skill: ${getErrorMessage(err)}`));
process.exit(1);
}
});
@@ -235,7 +237,7 @@ skillCmd
const target = resolveSkillTarget(options);
reportSkillResult(await removeAgentSkillFrom(target), target);
} catch (err) {
console.error(chalk.red(`✗ Failed to remove agent skill: ${getErrorMessage(err)}`));
console.error(palette.err(`✗ Failed to remove agent skill: ${getErrorMessage(err)}`));
process.exit(1);
}
});
@@ -252,11 +254,11 @@ sessionCmd
try {
const manager = getSessionManager();
const session = await manager.createSession(options.dir);
console.log(chalk.green(`✓ Session started: ${session.id}`));
console.log(palette.ok(`✓ Session started: ${session.id}`));
console.log(` Working directory: ${session.workingDir}`);
console.log(` PID: ${session.pid}`);
} catch (err) {
console.error(chalk.red(`✗ Failed to start session: ${getErrorMessage(err)}`));
console.error(palette.err(`✗ Failed to start session: ${getErrorMessage(err)}`));
process.exit(1);
}
});
@@ -268,70 +270,81 @@ sessionCmd
try {
const manager = getSessionManager();
await manager.stopSession(id);
console.log(chalk.green(`✓ Session stopped: ${id}`));
console.log(palette.ok(`✓ Session stopped: ${id}`));
} catch (err) {
console.error(chalk.red(`✗ Failed to stop session: ${getErrorMessage(err)}`));
console.error(palette.err(`✗ Failed to stop session: ${getErrorMessage(err)}`));
process.exit(1);
}
});
/** Session status in the shared vocabulary: idle is fine, busy is working, anything else is a problem. */
function sessionStatusLabel(status: string): string {
if (status === 'idle') return palette.ok('idle');
if (status === 'busy') return palette.warn('busy');
return palette.err(status);
}
/**
* The one session listing. `codeman list` used to be a copy of this that had
* drifted (it lost the stopped and web-server sections), so it now calls the
* same renderer and only opts out of those two sections.
*/
function printSessionList(options: { includeStored: boolean }): void {
const manager = getSessionManager();
const sessions = manager.getAllSessions();
const stored = manager.getStoredSessions();
if (sessions.length === 0 && Object.keys(stored).length === 0) {
console.log(palette.warn('No sessions found'));
return;
}
console.log(heading('Active Sessions:'));
if (sessions.length === 0) {
console.log(' (none)');
} else {
for (const session of sessions) {
console.log(
` ${palette.info(session.id.slice(0, 8))} ${sessionStatusLabel(session.status)} ${session.workingDir}`
);
}
}
if (options.includeStored) {
const stoppedSessions = Object.values(stored).filter((s) => s.status === 'stopped');
if (stoppedSessions.length > 0) {
console.log(heading('Stopped Sessions:'));
for (const session of stoppedSessions) {
const name = session.name ? ` (${session.name})` : '';
console.log(
` ${palette.muted(session.id.slice(0, 8))} ${palette.muted('stopped')}${name} ${session.workingDir}`
);
}
}
// Sessions the web server owns: this process has no PTY for them, so they
// only exist in the shared state file.
const activeSessions = Object.values(stored).filter((s) => s.status !== 'stopped');
if (sessions.length === 0 && activeSessions.length > 0) {
console.log(heading('Active Sessions (from web server):'));
for (const session of activeSessions) {
const name = session.name ? ` (${session.name})` : '';
const mode = session.mode === 'shell' ? palette.muted(' [shell]') : '';
const cost = session.totalCost ? palette.muted(` $${session.totalCost.toFixed(4)}`) : '';
console.log(
` ${palette.info(session.id.slice(0, 8))} ${sessionStatusLabel(session.status)}${name}${mode}${cost} ${session.workingDir}`
);
}
}
}
console.log('');
}
sessionCmd
.command('list')
.alias('ls')
.description('List all sessions')
.action(() => {
const manager = getSessionManager();
const sessions = manager.getAllSessions();
const stored = manager.getStoredSessions();
if (sessions.length === 0 && Object.keys(stored).length === 0) {
console.log(chalk.yellow('No sessions found'));
return;
}
console.log(chalk.bold('\nActive Sessions:'));
if (sessions.length === 0) {
console.log(' (none)');
} else {
for (const session of sessions) {
const status =
session.status === 'idle'
? chalk.green('idle')
: session.status === 'busy'
? chalk.yellow('busy')
: chalk.red(session.status);
console.log(` ${chalk.cyan(session.id.slice(0, 8))} ${status} ${session.workingDir}`);
}
}
const stoppedSessions = Object.values(stored).filter((s) => s.status === 'stopped');
if (stoppedSessions.length > 0) {
console.log(chalk.bold('\nStopped Sessions:'));
for (const session of stoppedSessions) {
const name = session.name ? ` (${session.name})` : '';
console.log(` ${chalk.gray(session.id.slice(0, 8))} ${chalk.gray('stopped')}${name} ${session.workingDir}`);
}
}
// Show active sessions from state (when web server manages them)
const activeSessions = Object.values(stored).filter((s) => s.status !== 'stopped');
if (sessions.length === 0 && activeSessions.length > 0) {
console.log(chalk.bold('\nActive Sessions (from web server):'));
for (const session of activeSessions) {
const status =
session.status === 'idle'
? chalk.green('idle')
: session.status === 'busy'
? chalk.yellow('busy')
: chalk.red(session.status);
const name = session.name ? ` (${session.name})` : '';
const mode = session.mode === 'shell' ? chalk.gray(' [shell]') : '';
const cost = session.totalCost ? chalk.gray(` $${session.totalCost.toFixed(4)}`) : '';
console.log(` ${chalk.cyan(session.id.slice(0, 8))} ${status}${name}${mode}${cost} ${session.workingDir}`);
}
}
console.log('');
});
.action(() => printSessionList({ includeStored: true }));
sessionCmd
.command('logs <id>')
@@ -342,12 +355,12 @@ sessionCmd
const output = options.errors ? manager.getSessionError(id) : manager.getSessionOutput(id);
if (output === null) {
console.log(chalk.yellow(`Session ${id} not found or not active`));
console.log(palette.warn(`Session ${id} not found or not active`));
return;
}
if (output === '') {
console.log(chalk.gray('(no output)'));
console.log(palette.muted('(no output)'));
return;
}
@@ -374,7 +387,7 @@ taskCmd
completionPhrase: options.completion,
timeoutMs: options.timeout ? parseInt(options.timeout, 10) : undefined,
});
console.log(chalk.green(`✓ Task added: ${task.id}`));
console.log(palette.ok(`✓ Task added: ${task.id}`));
console.log(` Prompt: ${prompt.slice(0, 50)}${prompt.length > 50 ? '...' : ''}`);
console.log(` Priority: ${task.priority}`);
});
@@ -393,26 +406,28 @@ taskCmd
}
if (tasks.length === 0) {
console.log(chalk.yellow('No tasks found'));
console.log(palette.warn('No tasks found'));
return;
}
const statusColors = {
pending: chalk.gray,
running: chalk.yellow,
completed: chalk.green,
failed: chalk.red,
pending: palette.muted,
running: palette.warn,
completed: palette.ok,
failed: palette.err,
};
console.log(chalk.bold('\nTasks:'));
console.log(palette.emph('\nTasks:'));
for (const task of tasks) {
const color = statusColors[task.status];
const prompt = task.prompt.slice(0, 40) + (task.prompt.length > 40 ? '...' : '');
console.log(` ${chalk.cyan(task.id.slice(0, 8))} ${color(task.status.padEnd(10))} [${task.priority}] ${prompt}`);
console.log(
` ${palette.info(task.id.slice(0, 8))} ${color(task.status.padEnd(10))} [${task.priority}] ${prompt}`
);
}
const counts = queue.getCount();
console.log(chalk.bold('\nSummary:'));
console.log(palette.emph('\nSummary:'));
console.log(
` Pending: ${counts.pending}, Running: ${counts.running}, Completed: ${counts.completed}, Failed: ${counts.failed}`
);
@@ -427,11 +442,11 @@ taskCmd
const task = queue.getTask(id);
if (!task) {
console.log(chalk.red(`Task ${id} not found`));
console.log(palette.err(`Task ${id} not found`));
return;
}
console.log(chalk.bold('\nTask Details:'));
console.log(palette.emph('\nTask Details:'));
console.log(` ID: ${task.id}`);
console.log(` Status: ${task.status}`);
console.log(` Priority: ${task.priority}`);
@@ -441,10 +456,10 @@ taskCmd
console.log(` Session: ${task.assignedSessionId}`);
}
if (task.error) {
console.log(` Error: ${chalk.red(task.error)}`);
console.log(` Error: ${palette.err(task.error)}`);
}
if (task.output) {
console.log(chalk.bold('\nOutput:'));
console.log(palette.emph('\nOutput:'));
console.log(task.output.slice(0, 500) + (task.output.length > 500 ? '...' : ''));
}
console.log('');
@@ -457,9 +472,9 @@ taskCmd
.action((id) => {
const queue = getTaskQueue();
if (queue.removeTask(id)) {
console.log(chalk.green(`✓ Task removed: ${id}`));
console.log(palette.ok(`✓ Task removed: ${id}`));
} else {
console.log(chalk.red(`Task ${id} not found`));
console.log(palette.err(`Task ${id} not found`));
}
});
@@ -474,13 +489,13 @@ taskCmd
if (options.all) {
count = queue.clearAll();
console.log(chalk.green(`✓ Cleared ${count} tasks`));
console.log(palette.ok(`✓ Cleared ${count} tasks`));
} else if (options.failed) {
count = queue.clearFailed();
console.log(chalk.green(`✓ Cleared ${count} failed tasks`));
console.log(palette.ok(`✓ Cleared ${count} failed tasks`));
} else {
count = queue.clearCompleted();
console.log(chalk.green(`✓ Cleared ${count} completed tasks`));
console.log(palette.ok(`✓ Cleared ${count} completed tasks`));
}
});
@@ -503,38 +518,38 @@ ralphCmd
}
if (loop.isRunning()) {
console.log(chalk.yellow('Ralph loop is already running'));
console.log(palette.warn('Ralph loop is already running'));
return;
}
loop.on('taskAssigned', (taskId, sessionId) => {
console.log(chalk.cyan(`→ Task ${taskId.slice(0, 8)} assigned to session ${sessionId.slice(0, 8)}`));
console.log(palette.info(`→ Task ${taskId.slice(0, 8)} assigned to session ${sessionId.slice(0, 8)}`));
});
loop.on('taskCompleted', (taskId) => {
console.log(chalk.green(`✓ Task ${taskId.slice(0, 8)} completed`));
console.log(palette.ok(`✓ Task ${taskId.slice(0, 8)} completed`));
});
loop.on('taskFailed', (taskId, error) => {
console.log(chalk.red(`✗ Task ${taskId.slice(0, 8)} failed: ${error}`));
console.log(palette.err(`✗ Task ${taskId.slice(0, 8)} failed: ${error}`));
});
loop.on('stopped', () => {
console.log(chalk.yellow('\nRalph loop stopped'));
console.log(palette.warn('\nRalph loop stopped'));
printStats(loop.getStats());
process.exit(0);
});
await loop.start();
console.log(chalk.green('✓ Ralph loop started'));
console.log(palette.ok('✓ Ralph loop started'));
if (options.minHours) {
console.log(` Minimum duration: ${options.minHours} hours`);
}
console.log(chalk.gray(' Press Ctrl+C to stop\n'));
console.log(palette.muted(' Press Ctrl+C to stop\n'));
// Keep process running
process.on('SIGINT', () => {
console.log(chalk.yellow('\nStopping Ralph loop...'));
console.log(palette.warn('\nStopping Ralph loop...'));
loop.stop();
});
});
@@ -545,11 +560,11 @@ ralphCmd
.action(() => {
const loop = getRalphLoop();
if (!loop.isRunning()) {
console.log(chalk.yellow('Ralph loop is not running'));
console.log(palette.warn('Ralph loop is not running'));
return;
}
loop.stop();
console.log(chalk.green('✓ Ralph loop stopped'));
console.log(palette.ok('✓ Ralph loop stopped'));
});
ralphCmd
@@ -562,9 +577,10 @@ ralphCmd
});
function printStats(stats: ReturnType<ReturnType<typeof getRalphLoop>['getStats']>) {
const statusColor = stats.status === 'running' ? chalk.green : stats.status === 'paused' ? chalk.yellow : chalk.gray;
const statusColor =
stats.status === 'running' ? palette.ok : stats.status === 'paused' ? palette.warn : palette.muted;
console.log(chalk.bold('\nRalph Loop Status:'));
console.log(palette.emph('\nRalph Loop Status:'));
console.log(` Status: ${statusColor(stats.status)}`);
console.log(` Elapsed: ${stats.elapsedHours.toFixed(2)} hours`);
if (stats.minDurationMs) {
@@ -574,14 +590,14 @@ function printStats(stats: ReturnType<ReturnType<typeof getRalphLoop>['getStats'
);
}
console.log(chalk.bold('\nTasks:'));
console.log(palette.emph('\nTasks:'));
console.log(` Pending: ${stats.pending}`);
console.log(` Running: ${stats.running}`);
console.log(` Completed: ${stats.completed} (${stats.tasksCompleted} this session)`);
console.log(` Failed: ${stats.failed}`);
console.log(` Generated: ${stats.tasksGenerated}`);
console.log(chalk.bold('\nSessions:'));
console.log(palette.emph('\nSessions:'));
console.log(` Active: ${stats.activeSessions}`);
console.log(` Idle: ${stats.idleSessions}`);
console.log(` Busy: ${stats.busySessions}`);
@@ -695,20 +711,20 @@ program
}
}
console.log(chalk.bold('\nCodeman Status'));
console.log('─'.repeat(40));
console.log(heading('Codeman Status'));
console.log(rule(40));
console.log(chalk.bold('\nWeb Server:'));
console.log(heading('Web Server:'));
if (probe.reachable) {
const version = probe.version ? ` (v${probe.version})` : '';
console.log(` Status: ${chalk.green('running')}${version} at ${probe.url}`);
console.log(kv('Status', `${palette.ok('running')}${version} at ${probe.url}`));
if (probe.authRequired) {
console.log(chalk.gray(' (answers 401: set CODEMAN_PASSWORD/CODEMAN_USERNAME to see session details)'));
console.log(palette.muted(' (answers 401: set CODEMAN_PASSWORD/CODEMAN_USERNAME to see session details)'));
}
} else {
console.log(` Status: ${chalk.red('not reachable')} at ${candidates.join(' or ')}`);
console.log(kv('Status', `${palette.err('not reachable')} at ${candidates.join(' or ')}`));
console.log(
chalk.gray(' (start it with `codeman web`, or check your service: systemctl --user status codeman-web)')
palette.muted(' (start it with `codeman web`, or check your service: systemctl --user status codeman-web)')
);
}
@@ -716,26 +732,26 @@ program
// as such, so the numbers are never silently a different thing.
if (probe.sessions) {
const live = probe.sessions;
console.log(chalk.bold('\nSessions (live, from the server):'));
console.log(` Total: ${live.length}`);
console.log(` Idle: ${live.filter((s) => s.status === 'idle').length}`);
console.log(` Busy: ${live.filter((s) => s.status === 'busy').length}`);
console.log(heading('Sessions (live, from the server):'));
console.log(kv('Total', String(live.length)));
console.log(kv('Idle', String(live.filter((s) => s.status === 'idle').length)));
console.log(kv('Busy', String(live.filter((s) => s.status === 'busy').length)));
} else {
const manager = getSessionManager();
const storedValues = Object.values(manager.getStoredSessions());
console.log(chalk.bold('\nSessions (from saved state):'));
console.log(` Active: ${storedValues.filter((s) => s.status !== 'stopped').length}`);
console.log(` Idle: ${storedValues.filter((s) => s.status === 'idle').length}`);
console.log(` Busy: ${storedValues.filter((s) => s.status === 'busy').length}`);
console.log(heading('Sessions (from saved state):'));
console.log(kv('Active', String(storedValues.filter((s) => s.status !== 'stopped').length)));
console.log(kv('Idle', String(storedValues.filter((s) => s.status === 'idle').length)));
console.log(kv('Busy', String(storedValues.filter((s) => s.status === 'busy').length)));
}
const taskCounts = getTaskQueue().getCount();
console.log(chalk.bold('\nTasks:'));
console.log(` Total: ${taskCounts.total}`);
console.log(` Pending: ${taskCounts.pending}`);
console.log(` Running: ${taskCounts.running}`);
console.log(` Completed: ${taskCounts.completed}`);
console.log(` Failed: ${taskCounts.failed}`);
console.log(heading('Tasks:'));
console.log(kv('Total', String(taskCounts.total)));
console.log(kv('Pending', String(taskCounts.pending)));
console.log(kv('Running', String(taskCounts.running)));
console.log(kv('Completed', String(taskCounts.completed)));
console.log(kv('Failed', String(taskCounts.failed)));
console.log('');
});
@@ -745,9 +761,17 @@ program
.option('-f, --force', 'Skip confirmation')
.action(async (options) => {
if (!options.force) {
console.log(chalk.yellow('This will stop all sessions and clear all state.'));
console.log(chalk.yellow('Use --force to confirm.'));
return;
console.log(palette.warn('This will stop all sessions and clear all state.'));
// Non-interactive callers keep the old refusal: a script piping into the
// CLI must never be able to reset state by hanging on an unseen question.
if (!isInteractive()) {
console.log(palette.warn('Use --force to confirm.'));
return;
}
if (!(await confirm('Reset all Codeman state?'))) {
console.log(palette.muted('○ Cancelled, nothing was changed'));
return;
}
}
const manager = getSessionManager();
@@ -756,7 +780,7 @@ program
await manager.stopAllSessions();
store.reset();
console.log(chalk.green('✓ All state reset'));
console.log(palette.ok('✓ All state reset'));
});
// Shorthand commands at root level
@@ -767,38 +791,45 @@ program
.action(async (options) => {
const manager = getSessionManager();
const session = await manager.createSession(options.dir);
console.log(chalk.green(`✓ Session started: ${session.id}`));
console.log(palette.ok(`✓ Session started: ${session.id}`));
});
program
.command('list')
.alias('ls')
.description('List all sessions (shorthand)')
.action(() => {
const manager = getSessionManager();
const sessions = manager.getAllSessions();
const stored = manager.getStoredSessions();
.description('List active sessions (shorthand; `codeman session list` also shows stopped ones)')
.action(() => printSessionList({ includeStored: false }));
if (sessions.length === 0 && Object.keys(stored).length === 0) {
console.log(chalk.yellow('No sessions found'));
// ============ TUI ============
program
.command('tui')
.argument('[n]', 'attach straight to the nth session of `codeman tui --list`')
.description('Terminal dashboard for your sessions (the web UI remains the primary surface)')
.option('-l, --list', 'Print the numbered session list and exit, instead of opening the dashboard')
.action(async (position: string | undefined, options: { list?: boolean }) => {
// Imported here, not at the top: the dashboard pulls in the whole TUI core,
// and every other command would pay for it at startup.
const { runTui, runTuiAttach, runTuiList } = await import('./tui/tui-app.js');
if (options.list) {
process.exitCode = await runTuiList();
return;
}
console.log(chalk.bold('\nActive Sessions:'));
if (sessions.length === 0) {
console.log(' (none)');
} else {
for (const session of sessions) {
const status =
session.status === 'idle'
? chalk.green('idle')
: session.status === 'busy'
? chalk.yellow('busy')
: chalk.red(session.status);
console.log(` ${chalk.cyan(session.id.slice(0, 8))} ${status} ${session.workingDir}`);
if (position !== undefined) {
const n = Number.parseInt(position, 10);
if (!Number.isSafeInteger(n) || n < 1) {
console.error(palette.err(`"${position}" is not a session number.`));
console.error(`Run ${palette.info('codeman tui --list')} to see them.`);
process.exitCode = 1;
return;
}
process.exitCode = await runTuiAttach(n);
return;
}
console.log('');
// The dashboard owns the terminal until it quits; exiting explicitly keeps a
// stray handle (a socket mid-close) from stranding the user's shell.
process.exit(await runTui());
});
// ============ Web / daemon / service Commands ============
@@ -831,7 +862,7 @@ function toWebLaunchOptions(options: {
}): WebLaunchOptions {
const port = parseInt(options.port, 10);
if (!Number.isInteger(port) || port <= 0 || port > 65535) {
console.error(chalk.red(`✗ Invalid port: ${options.port}`));
console.error(palette.err(`✗ Invalid port: ${options.port}`));
process.exit(1);
}
return {
@@ -852,11 +883,11 @@ function warnIfUnauthenticatedNetwork(launch: WebLaunchOptions): void {
if (isLoopbackBindHost(launch.host)) return;
if (isUnauthenticatedNetworkAcknowledged(launch.allowUnauthenticatedNetwork)) return;
console.log(
chalk.yellow(
palette.warn(
`⚠ Binding ${launch.host} without CODEMAN_PASSWORD: anyone who can reach this port gets terminal control.`
)
);
console.log(chalk.yellow(' Set CODEMAN_PASSWORD, or bind 127.0.0.1 and front it with tailscale serve.'));
console.log(palette.warn(' Set CODEMAN_PASSWORD, or bind 127.0.0.1 and front it with tailscale serve.'));
}
// Web interface command
@@ -872,17 +903,18 @@ webCmd.action(async (options) => {
const launch = toWebLaunchOptions(options);
if (options.stop) {
const result = await stopDaemon(launch);
// stopDaemon waits for the process to actually exit (up to 15s).
const result = await withSpinner('Stopping Codeman...', () => stopDaemon(launch));
if (result.ok && result.reason === 'not-running') {
console.log(chalk.gray(`○ ${result.message}`));
console.log(palette.muted(`○ ${result.message}`));
return;
}
if (result.ok) {
console.log(chalk.green(`✓ ${result.message ?? `Stopped Codeman (pid ${result.pid})`}`));
console.log(chalk.gray(' Your agents keep running in tmux.'));
console.log(palette.ok(`✓ ${result.message ?? `Stopped Codeman (pid ${result.pid})`}`));
console.log(palette.muted(' Your agents keep running in tmux.'));
return;
}
console.error(chalk.red(`✗ ${result.message ?? 'Could not stop the server'}`));
console.error(palette.err(`✗ ${result.message ?? 'Could not stop the server'}`));
process.exit(1);
}
@@ -890,31 +922,33 @@ webCmd.action(async (options) => {
const status = await daemonStatus(launch);
if (status.responding) {
const version = status.version ? ` (v${status.version})` : '';
console.log(chalk.green(`✓ Responding at ${status.url}${version}`));
console.log(palette.ok(`✓ Responding at ${status.url}${version}`));
} else {
console.log(chalk.yellow(`○ Nothing answering at ${status.url}`));
console.log(palette.warn(`○ Nothing answering at ${status.url}`));
}
console.log(` Daemon pid: ${status.running ? chalk.green(String(status.pid)) : chalk.gray('not running')}`);
console.log(chalk.gray(` Pidfile: ${status.pidFile}`));
console.log(chalk.gray(` Log: ${status.logPath}`));
console.log(kv('Daemon pid', status.running ? palette.ok(String(status.pid)) : palette.muted('not running'), 11));
console.log(palette.muted(kv('Pidfile', status.pidFile, 11)));
console.log(palette.muted(kv('Log', status.logPath, 11)));
if (!status.running && status.responding) {
console.log(chalk.gray(' (running, but not started with --daemon: probably a service or a foreground run)'));
console.log(palette.muted(' (running, but not started with --daemon: probably a service or a foreground run)'));
}
return;
}
if (options.daemon) {
warnIfUnauthenticatedNetwork(launch);
console.log(chalk.cyan('Starting Codeman in the background...'));
const result = await startDaemon(launch);
// The start polls /api/status for up to 30s; without this the shell just sits there.
const result = await withSpinner('Starting Codeman in the background, waiting for it to answer...', () =>
startDaemon(launch)
);
if (result.ok) {
console.log(chalk.green(`\n✓ Codeman is running at ${result.url} (pid ${result.pid})`));
console.log(chalk.gray(` Logs: ${result.logPath}`));
console.log(chalk.gray(' Stop it with: codeman web --stop'));
console.log(chalk.gray(' Want it back after a reboot? codeman service install'));
console.log(palette.ok(`\n✓ Codeman is running at ${result.url} (pid ${result.pid})`));
console.log(palette.muted(` Logs: ${result.logPath}`));
console.log(palette.muted(' Stop it with: codeman web --stop'));
console.log(palette.muted(' Want it back after a reboot? codeman service install'));
return;
}
console.error(chalk.red(`\n✗ ${result.message ?? 'Failed to start'}`));
console.error(palette.err(`\n✗ ${result.message ?? 'Failed to start'}`));
process.exit(1);
}
@@ -924,29 +958,29 @@ webCmd.action(async (options) => {
const https = launch.https;
const titleHostname = options.titleHostname;
const allowUnauthenticatedNetwork = launch.allowUnauthenticatedNetwork ?? false;
const protocol = https ? 'https' : 'http';
const displayHost = host === '0.0.0.0' ? 'localhost' : host;
console.log(chalk.cyan(`Starting Codeman web interface on ${displayHost}:${port}${https ? ' (HTTPS)' : ''}...`));
console.log(palette.info(`Starting Codeman web interface on ${displayHost}:${port}${https ? ' (HTTPS)' : ''}...`));
try {
// The server prints its own "running at" line (it also covers the daemon and
// service launch paths), so this one used to be a duplicate of it.
const server = await startWebServer(port, https, false, host, titleHostname, allowUnauthenticatedNetwork);
console.log(chalk.green(`\n✓ Web interface running at ${protocol}://${displayHost}:${port}`));
if (https) {
console.log(chalk.yellow(' Note: Accept the self-signed certificate in your browser on first visit'));
console.log(palette.warn(' Note: Accept the self-signed certificate in your browser on first visit'));
}
console.log(chalk.gray(' Press Ctrl+C to stop\n'));
console.log(palette.muted(' Press Ctrl+C to stop\n'));
// Graceful shutdown handler — flush state and clean up on SIGTERM/SIGINT
let shuttingDown = false;
const shutdown = async (signal: string) => {
if (shuttingDown) return;
shuttingDown = true;
console.log(chalk.yellow(`\n${signal} received, shutting down gracefully...`));
console.log(palette.warn(`\n${signal} received, shutting down gracefully...`));
try {
await server.stop();
} catch (err) {
console.error(chalk.red(`Error during shutdown: ${getErrorMessage(err)}`));
console.error(palette.err(`Error during shutdown: ${getErrorMessage(err)}`));
}
process.exit(0);
};
@@ -954,7 +988,7 @@ webCmd.action(async (options) => {
process.on('SIGINT', () => shutdown('SIGINT'));
process.on('SIGHUP', () => shutdown('SIGHUP'));
} catch (err) {
console.error(chalk.red(`✗ Failed to start web server: ${getErrorMessage(err)}`));
console.error(palette.err(`✗ Failed to start web server: ${getErrorMessage(err)}`));
process.exit(1);
}
});
@@ -970,20 +1004,23 @@ addWebLaunchOptions(
).action(async (options) => {
const launch = toWebLaunchOptions(options);
warnIfUnauthenticatedNetwork(launch);
console.log(chalk.cyan('Installing the Codeman service...'));
const result = await installService(launch);
for (const warning of result.warnings ?? []) console.log(chalk.yellow(`⚠ ${warning}`));
// Install polls the new unit's /api/status for up to 30s before it can honestly
// report success, so the wait needs a visible heartbeat.
const result = await withSpinner('Installing the Codeman service, waiting for it to answer...', () =>
installService(launch)
);
for (const warning of result.warnings ?? []) console.log(palette.warn(`⚠ ${warning}`));
if (!result.ok) {
console.error(chalk.red(`✗ ${result.message}`));
console.error(palette.err(`✗ ${result.message}`));
process.exit(1);
}
console.log(chalk.green(`✓ ${result.message}`));
console.log(chalk.gray(` Unit: ${result.unitPath}`));
console.log(palette.ok(`✓ ${result.message}`));
console.log(palette.muted(` Unit: ${result.unitPath}`));
if (process.env.CODEMAN_PASSWORD) {
console.log(
chalk.yellow(
palette.warn(
' Note: CODEMAN_PASSWORD was NOT copied into the unit file. Add it there yourself if the service needs auth.'
)
);
@@ -996,10 +1033,10 @@ serviceCmd
.action(() => {
const result = uninstallService();
if (!result.ok) {
console.error(chalk.red(`✗ ${result.message}`));
console.error(palette.err(`✗ ${result.message}`));
process.exit(1);
}
console.log(chalk.green(`✓ ${result.message}`));
console.log(palette.ok(`✓ ${result.message}`));
});
addWebLaunchOptions(
@@ -1007,15 +1044,15 @@ addWebLaunchOptions(
).action(async (options) => {
const status = await serviceStatus(toWebLaunchOptions(options));
if (!status.kind) {
console.log(chalk.yellow(`No supported supervisor on ${process.platform}. Use \`codeman web -d\` instead.`));
console.log(palette.warn(`No supported supervisor on ${process.platform}. Use \`codeman web -d\` instead.`));
return;
}
console.log(` Supervisor: ${status.kind} (${status.name})`);
console.log(` Unit file: ${status.installed ? chalk.green(status.unitPath) : chalk.gray('not installed')}`);
console.log(` Loaded: ${status.loaded ? chalk.green('yes') : chalk.gray('no')}`);
console.log(` Unit file: ${status.installed ? palette.ok(status.unitPath) : palette.muted('not installed')}`);
console.log(` Loaded: ${status.loaded ? palette.ok('yes') : palette.muted('no')}`);
const version = status.version ? ` (v${status.version})` : '';
console.log(
` Responding: ${status.responding ? chalk.green(`yes at ${status.url}${version}`) : chalk.gray(`no at ${status.url}`)}`
` Responding: ${status.responding ? palette.ok(`yes at ${status.url}${version}`) : palette.muted(`no at ${status.url}`)}`
);
});
@@ -1085,7 +1122,7 @@ usersCmd
.action(async (name, options) => {
const { createUser, isValidUsername } = await import('./user-store.js');
if (!isValidUsername(name)) {
console.error(chalk.red('✗ Username must be lowercase, start alphanumeric, 2-32 chars ([a-z0-9_-])'));
console.error(palette.err('✗ Username must be lowercase, start alphanumeric, 2-32 chars ([a-z0-9_-])'));
process.exit(1);
}
try {
@@ -1096,18 +1133,18 @@ usersCmd
password = await promptHiddenPassword('New password: ');
const confirm = await promptHiddenPassword('Confirm password: ');
if (password !== confirm) {
console.error(chalk.red('✗ Passwords do not match'));
console.error(palette.err('✗ Passwords do not match'));
process.exit(1);
}
}
if (!password || password.length < 8) {
console.error(chalk.red('✗ Password must be at least 8 characters'));
console.error(palette.err('✗ Password must be at least 8 characters'));
process.exit(1);
}
const user = await createUser({ username: name, role: options.admin ? 'admin' : 'user', password });
console.log(chalk.green(`✓ Created ${user.role} "${user.username}"`));
console.log(palette.ok(`✓ Created ${user.role} "${user.username}"`));
} catch (err) {
console.error(chalk.red(`✗ ${getErrorMessage(err)}`));
console.error(palette.err(`✗ ${getErrorMessage(err)}`));
process.exit(1);
}
});
@@ -1126,14 +1163,14 @@ usersCmd
password = await promptHiddenPassword('New password: ');
const confirm = await promptHiddenPassword('Confirm password: ');
if (password !== confirm) {
console.error(chalk.red('✗ Passwords do not match'));
console.error(palette.err('✗ Passwords do not match'));
process.exit(1);
}
}
await setPassword(name, password, { mustChangePassword: false });
console.log(chalk.green(`✓ Password updated for "${name}"`));
console.log(palette.ok(`✓ Password updated for "${name}"`));
} catch (err) {
console.error(chalk.red(`✗ ${getErrorMessage(err)}`));
console.error(palette.err(`✗ ${getErrorMessage(err)}`));
process.exit(1);
}
});
@@ -1146,17 +1183,17 @@ usersCmd
const { readUsers } = await import('./user-store.js');
const users = await readUsers(true);
if (users.length === 0) {
console.log(chalk.yellow('No users defined (run: codeman users add <name> --admin)'));
console.log(palette.warn('No users defined (run: codeman users add <name> --admin)'));
return;
}
console.log(chalk.bold('\nUsers:'));
console.log(palette.emph('\nUsers:'));
for (const u of users) {
const role = u.role === 'admin' ? chalk.magenta('admin') : chalk.cyan('user ');
const state = u.disabled ? chalk.red('disabled') : chalk.green('enabled ');
const role = u.role === 'admin' ? palette.accent('admin') : palette.info('user ');
const state = u.disabled ? palette.err('disabled') : palette.ok('enabled ');
const flags = [u.mustChangePassword ? 'must-change-pw' : '', u.canBypassPermissions ? 'can-bypass' : '']
.filter(Boolean)
.join(' ');
console.log(` ${role} ${state} ${u.username}${flags ? chalk.gray(` [${flags}]`) : ''}`);
console.log(` ${role} ${state} ${u.username}${flags ? palette.muted(` [${flags}]`) : ''}`);
}
console.log('');
});
@@ -1171,16 +1208,43 @@ usersCmd
await deleteUser(name);
if (options.deleteSpace) {
await deleteUserSpace(name);
console.log(chalk.green(`✓ Deleted user "${name}" and their space`));
console.log(palette.ok(`✓ Deleted user "${name}" and their space`));
} else {
console.log(chalk.green(`✓ Deleted user "${name}" (space left on disk)`));
console.log(palette.ok(`✓ Deleted user "${name}" (space left on disk)`));
}
} catch (err) {
console.error(chalk.red(`✗ ${getErrorMessage(err)}`));
console.error(palette.err(`✗ ${getErrorMessage(err)}`));
process.exit(1);
}
});
/**
* Missing REQUIRED tools are failures; a missing optional one or a skipped check
* is just absence, so it stays muted rather than shouting red at everyone
* without LibreOffice installed.
*/
function dependencyTone(result: ToolResult): Tone {
if (result.status === 'ok') return 'ok';
if (result.status === 'skipped') return 'idle';
return result.required ? 'err' : 'idle';
}
/**
* The colorize hook `dependency-report.ts` was written for. Versions stay in the
* default color (they are data, not a verdict); everything that IS a verdict is
* painted, and the supporting detail is muted so the glyph column reads first.
*/
const DOCTOR_STYLE: ReportStyle = {
title: (text) => palette.emph(text),
heading: (text) => palette.emph(palette.info(text)),
glyph: (result, glyph) => tint(dependencyTone(result), glyph),
label: (text) => text,
status: (result, text) => (result.status === 'ok' ? text : tint(dependencyTone(result), text)),
path: (text) => palette.muted(text),
meta: (text) => palette.muted(text),
summary: (text) => palette.emph(text),
};
program
.command('doctor')
.alias('check-deps')
@@ -1204,9 +1268,10 @@ program
const results = checkAll(registry, host);
if (options.json) {
// Raw JSON, never styled: this output is parsed, not read.
console.log(JSON.stringify(renderJson(results, host.environment), null, 2));
} else {
console.log(renderTable(results, host.environment));
console.log(renderTable(results, host.environment, DOCTOR_STYLE));
}
process.exit(computeExitCode(results));
});
+24
View File
@@ -8,6 +8,7 @@
*/
import { PI_VERSION_REGEX } from '../utils/pi-cli-resolver.js';
import { GROK_VERSION_REGEX } from '../utils/grok-cli-resolver.js';
export type ProbeEnvironment = 'linux' | 'darwin' | 'win32' | 'wsl';
@@ -139,6 +140,29 @@ export const DEPENDENCY_REGISTRY: ToolDependency[] = [
},
],
},
{
id: 'grok',
label: 'Grok CLI',
category: 'core',
required: false,
usedBy: ['Grok sessions'],
// Version match required for the same reason as pi: `grok` has known squatters
// (the unrelated @vibe-kit/grok-cli npm package also installs a `grok` bin), so a
// bare `which grok` hit is not the coding agent. Both sides share
// GROK_VERSION_REGEX, so the doctor and the run mode cannot drift.
resolvers: [
{
match: ALL,
resolver: {
kind: 'path',
bins: ['grok'],
versionArg: '--version',
versionRegex: GROK_VERSION_REGEX,
requireVersionMatch: true,
},
},
],
},
{
id: 'libreoffice',
label: 'LibreOffice',
+15
View File
@@ -40,6 +40,21 @@ const INSTANCE_SUFFIX = CODEMAN_INSTANCE ? `-${CODEMAN_INSTANCE}` : '';
/** Default tmux socket for this instance. `CODEMAN_TMUX_SOCKET` still overrides. */
export const DEFAULT_TMUX_SOCKET = `codeman${INSTANCE_SUFFIX}`;
/** Characters tmux accepts in a `-L` socket name. */
export const SAFE_TMUX_SOCKET_PATTERN = /^[a-zA-Z0-9_.-]+$/;
/**
* This instance's tmux socket: the `CODEMAN_TMUX_SOCKET` override when it is a
* safe name, else the instance default. Every process that runs `tmux -L` has
* to resolve it through here (the server via TmuxManager, the TUI for its
* degraded-mode listing), or a beta instance ends up driving prod's sessions.
*/
export function resolveTmuxSocketName(): string {
const raw = process.env.CODEMAN_TMUX_SOCKET;
if (raw !== undefined && SAFE_TMUX_SOCKET_PATTERN.test(raw)) return raw;
return DEFAULT_TMUX_SOCKET;
}
let _ensured = false;
/**
+2 -1
View File
@@ -8,7 +8,8 @@
* src/web/public/constants.js and deliberately stays at 50k — 100k xterm lines per tab
* is a mobile-memory hazard — so DEFAULT_TERMINAL_SCROLLBACK_LINES stays 50,000 to match.
* The terminalScrollbackLines/terminalBufferMaxBytes/terminalBufferTrimBytes settings keys
* remain schema-validated but inert (a follow-up wires them); only tmuxHistoryLimit is live.
* remain schema-validated but inert (a follow-up wires them); only tmuxHistoryLimit is wired.
* tmux <3.7 applies it to new panes; tmux 3.7+ can also resize live panes.
* All values remain env- and settings-overridable and bounds-clamped via
* resolveTerminalHistoryConfig().
*/
+3 -2
View File
@@ -48,7 +48,8 @@ const delay = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms
* answer "yes" to, which then loads and EXECUTES repo-local `.pi/extensions` TypeScript,
* so `approveProjectTrust: false` (`--no-approve`) is materialized. Omitting `--approve`
* is NOT a clamp.
* Codex and antigravity need nothing here: their absent config already spawns safe.
* Codex, antigravity and grok need nothing here: their absent config already spawns safe
* (grok's bare spawn is its own ask-mode default; --always-approve is only ever sent).
* Granted/admin/single-user get undefined for both, i.e. upstream defaults untouched.
*/
export function clampCronExternalCliConfigs(
@@ -425,7 +426,7 @@ export class CronService {
piConfig,
owner: job.owner,
});
this.deps.addSession(session);
await this.deps.addSession(session);
this.store.incrementSessionsCreated();
this.deps.persistSessionState(session);
await this.deps.setupSessionListeners(session);
+11
View File
@@ -145,6 +145,7 @@ export function defaultDockerCommandForMode(mode: SessionMode): string {
gemini: 'exec gemini',
antigravity: 'exec agy',
pi: 'exec pi',
grok: 'exec grok',
};
return commands[mode as DockerCommandMode] || commands.shell;
}
@@ -614,6 +615,16 @@ const CRED_STORES: CredStorePolicy[] = [
rel: '.pi/agent',
seedFiles: ['auth.json', 'settings.json', 'trust.json', 'models.json', 'models-store.json'],
},
// Grok (xAI) keeps auth + config in `~/.grok`, but that dir ALSO holds
// `sessions/`, `memory/`, `downloads/` (the ~100MB binary itself) and `bin/`,
// so seedWhole would copy all of it into every container start. Seed only what
// grok needs to authenticate and behave consistently. Same trade-off as pi:
// in-container grok sessions are invisible host-side, so `grok -c` inside a
// Docker case only sees that container's own history.
{
rel: '.grok',
seedFiles: ['auth.json', 'config.toml', 'pager.toml'],
},
{ rel: '.config/gcloud', seedWhole: true },
{ rel: '.config/opencode', seedWhole: true },
];
+11 -2
View File
@@ -479,14 +479,23 @@ export function gitNonInteractiveEnv(base: NodeJS.ProcessEnv = process.env): Nod
// ─── Pure: output handling ───────────────────────────────────────────────────
/**
* Redact any `scheme://user:secret@host` credential pair embedded in text — a
* remote URL stored with an inline token, or git stderr echoing such a URL
* back. Shared by the clone error path (`sanitizeGitOutput`) and the
* repository-status card fields (`web/repo-status.ts`).
*/
export function redactGitCredentials(text: string): string {
return text.replace(/([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)[^/@\s]*:[^/@\s]*@/g, '$1***:***@');
}
/**
* Make git's stderr safe to show in the browser: strip ANSI/control bytes,
* redact any `scheme://user:secret@host` that a credential helper echoed back,
* and keep only the tail (the last lines are the ones that say why it failed).
*/
export function sanitizeGitOutput(text: string, maxBytes = MAX_STDERR_BYTES): string {
const redacted = text
.replace(/([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)[^/@\s]*:[^/@\s]*@/g, '$1***:***@')
const redacted = redactGitCredentials(text)
// eslint-disable-next-line no-control-regex -- deliberate: strip C0/C1 and DEL.
.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g, '')
.trim();
+6 -3
View File
@@ -19,6 +19,7 @@ import type {
GeminiConfig,
AntigravityConfig,
PiConfig,
GrokConfig,
SessionRemote,
SessionDocker,
} from './types.js';
@@ -78,13 +79,14 @@ export interface CreateSessionOptions {
geminiConfig?: GeminiConfig;
antigravityConfig?: AntigravityConfig;
piConfig?: PiConfig;
grokConfig?: GrokConfig;
/** When restoring after reboot, resume a previous Claude conversation by its session ID */
resumeSessionId?: string;
/** Extra env vars exported before launching the CLI (e.g., CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS). Ephemeral — not written to disk. */
envOverrides?: Record<string, string>;
/** Claude CLI effort level, injected as a `--settings` soft default (overridable via /effort in-session) */
effort?: EffortLevel;
/** tmux history-limit (scrollback lines) to set for this session. */
/** tmux history-limit (scrollback lines) allocated when this session is created. */
historyLimit?: number;
/** Remote execution metadata for local tmux sessions wrapping SSH */
remote?: SessionRemote;
@@ -110,13 +112,14 @@ export interface RespawnPaneOptions {
geminiConfig?: GeminiConfig;
antigravityConfig?: AntigravityConfig;
piConfig?: PiConfig;
grokConfig?: GrokConfig;
/** Resume a previous Claude conversation when respawning */
resumeSessionId?: string;
/** Extra env vars exported before launching the CLI (preserved across respawns). */
envOverrides?: Record<string, string>;
/** Claude CLI effort level (preserved across respawns, injected via `--settings`) */
effort?: EffortLevel;
/** tmux history-limit (scrollback lines) to set for this session after respawn. */
/** Original tmux history-limit retained for config parity; respawn cannot resize the existing pane. */
historyLimit?: number;
/** Remote execution metadata for local tmux sessions wrapping SSH */
remote?: SessionRemote;
@@ -216,7 +219,7 @@ export interface TerminalMultiplexer extends EventEmitter {
/** Update Ralph enabled state for a session */
updateRalphEnabled(sessionId: string, enabled: boolean): void;
/** Apply a tmux history-limit to all tracked sessions. */
/** Apply history-limit to live panes where tmux supports it, otherwise to future panes. */
setHistoryLimit(limit: number): Promise<void>;
// ========== Discovery ==========
+8 -1
View File
@@ -281,7 +281,14 @@ export class RalphLoop extends EventEmitter {
// Guard: only reschedule if still running AND no timer is pending
// (prevents race where stop() clears timer between our check and setTimeout)
if (this._status === 'running' && this.loopTimer === null) {
this.loopTimer = setTimeout(() => this.runLoop(), this.pollIntervalMs);
// Null the handle when the timer fires, BEFORE re-entering runLoop —
// otherwise the `loopTimer === null` guard above stays false on the
// next pass and the loop stops rescheduling after 2 ticks.
// Mirrors the orchestrator-loop reschedule pattern.
this.loopTimer = setTimeout(() => {
this.loopTimer = null;
this.runLoop();
}, this.pollIntervalMs);
}
});
}
+1
View File
@@ -114,6 +114,7 @@ export function defaultRemoteCommandForMode(mode: SessionMode): string {
gemini: remoteLoginShellCommand('gemini'),
antigravity: remoteLoginShellCommand('agy'),
pi: remoteLoginShellCommand('pi'),
grok: remoteLoginShellCommand('grok'),
};
return commands[mode as RemoteCommandMode] || commands.shell;
}
+96 -7
View File
@@ -51,6 +51,7 @@ import {
type GeminiConfig,
type AntigravityConfig,
type PiConfig,
type GrokConfig,
type SessionRemote,
type SessionDocker,
} from './types.js';
@@ -171,7 +172,14 @@ const NEWLINE_SPLIT_PATTERN = /\r?\n/;
/** True for external-CLI run modes (non-Claude) that use their own TUI and output format. */
export function isExternalCliMode(mode: SessionMode): boolean {
return mode === 'opencode' || mode === 'codex' || mode === 'gemini' || mode === 'antigravity' || mode === 'pi';
return (
mode === 'opencode' ||
mode === 'codex' ||
mode === 'gemini' ||
mode === 'antigravity' ||
mode === 'pi' ||
mode === 'grok'
);
}
function getModeLabel(mode: SessionMode): string {
@@ -186,6 +194,8 @@ function getModeLabel(mode: SessionMode): string {
return 'Antigravity';
case 'pi':
return 'Pi';
case 'grok':
return 'Grok';
case 'shell':
return 'Shell';
case 'claude':
@@ -202,8 +212,9 @@ function getModeLabel(mode: SessionMode): string {
* repaint via cursor positioning, so dropping the alt-screen switch is safe —
* content stays in the normal buffer. Excluded: `shell` (arbitrary programs like
* vim/less/htop legitimately need the alt screen), `opencode` (renders its own
* TUI that may rely on it) and `pi` (below). Keep parity with the replay-side
* strip in session-routes.ts.
* TUI that may rely on it), `pi` (below) and `grok` (a fullscreen alt-screen TUI
* with mouse support, i.e. the opencode case, not the Ink case). Keep parity
* with the replay-side strip in session-routes.ts.
*
* ⚠️ Being excluded here does NOT preserve the alt screen. Every excluded mode
* falls through to isMuxAltScreenOnlyStripMode(), which strips the alt-screen
@@ -415,6 +426,15 @@ export class Session extends EventEmitter {
// sequences split across PTY chunks can't slip past the alt-screen/scrollback
// strip (see _handleTerminalOutput / isAltScreenStripMode)
private _altScreenSeqCarry: string = '';
/**
* Mouse-tracking DECSET modes the CLI currently has ON, as observed while
* STRIPPING them out of the stream below. Kept as a set rather than a boolean
* because a TUI may enable 1002 and later disable 1000 (a mode it never
* enabled); tracking is on while any of them is.
*/
private _cliMouseModes = new Set<number>();
private _cliMouseTracking = false;
private resolvePromise: ((value: { result: string; cost: number }) => void) | null = null;
private rejectPromise: ((reason: Error) => void) | null = null;
private _promptResolved: boolean = false; // Guard against race conditions in runPrompt
@@ -499,6 +519,8 @@ export class Session extends EventEmitter {
private _antigravityConfig: AntigravityConfig | undefined;
// Pi configuration (only for mode === 'pi')
private _piConfig: PiConfig | undefined;
// Grok configuration (only for mode === 'grok')
private _grokConfig: GrokConfig | undefined;
private _resumeSessionId: string | undefined;
// Ephemeral env overrides (e.g., CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS). Exported by tmux
@@ -510,7 +532,7 @@ export class Session extends EventEmitter {
// the CLAUDE_CODE_EFFORT_LEVEL env var, which would hard-lock the session.
private _effort: EffortLevel | undefined;
// tmux history-limit (scrollback lines) applied to this session's pane.
// tmux history-limit (scrollback lines) allocated when this session's pane is created.
private readonly _tmuxHistoryLimit: number;
// Remote execution metadata, present when this session runs over SSH through local tmux.
@@ -594,13 +616,15 @@ export class Session extends EventEmitter {
antigravityConfig?: AntigravityConfig;
/** Pi configuration (only for mode === 'pi') */
piConfig?: PiConfig;
/** Grok configuration (only for mode === 'grok') */
grokConfig?: GrokConfig;
/** Resume a previous Claude conversation (used after server reboot) */
resumeSessionId?: string;
/** Extra env vars exported to the CLI at spawn time (no disk persistence) */
envOverrides?: Record<string, string>;
/** Claude CLI effort level (soft default via --settings, switchable in-session via /effort) */
effort?: EffortLevel;
/** tmux history-limit (scrollback lines) for this session's pane. */
/** tmux history-limit (scrollback lines) allocated when this session's pane is created. */
tmuxHistoryLimit?: number;
/** Restored per-session attachment history. May include server-private external paths. */
attachmentHistory?: SessionAttachmentHistoryItem[];
@@ -703,6 +727,11 @@ export class Session extends EventEmitter {
this._piConfig = config.piConfig;
}
// Apply Grok configuration
if (config.grokConfig) {
this._grokConfig = config.grokConfig;
}
// Apply env overrides (exported at spawn, not persisted to disk).
// Legacy migration: pre-0.7.2 carried effort as the CLAUDE_CODE_EFFORT_LEVEL env var,
// which hard-locks /effort switching. Extract it into _effort (--settings soft default)
@@ -1285,6 +1314,7 @@ export class Session extends EventEmitter {
niceValue: this._niceConfig.niceValue,
color: this._color,
flickerFilterEnabled: this._flickerFilterEnabled,
cliMouseTracking: this._cliMouseTracking || undefined,
cliVersion: this._cliVersion || undefined,
cliModel: this._cliModel || undefined,
cliAccountType: this._cliAccountType || undefined,
@@ -1294,6 +1324,7 @@ export class Session extends EventEmitter {
geminiConfig: this._geminiConfig,
antigravityConfig: this._antigravityConfig,
piConfig: this._piConfig,
grokConfig: this._grokConfig,
resumeSessionId: this._resumeSessionId,
effort: this._effort,
// COD-118: runtime-only — surfaced so the frontend can require explicit user
@@ -1466,7 +1497,11 @@ export class Session extends EventEmitter {
// COD-75: codex/gemini/antigravity/pi get COLORTERM=truecolor — mirrors buildEnvExports()
// in tmux-manager.ts so the attach client and the tmux session agree.
env: buildMuxAttachEnv(
this.mode === 'codex' || this.mode === 'gemini' || this.mode === 'antigravity' || this.mode === 'pi'
this.mode === 'codex' ||
this.mode === 'gemini' ||
this.mode === 'antigravity' ||
this.mode === 'pi' ||
this.mode === 'grok'
),
})
);
@@ -1536,6 +1571,7 @@ export class Session extends EventEmitter {
geminiConfig: this._geminiConfig,
antigravityConfig: this._antigravityConfig,
piConfig: this._piConfig,
grokConfig: this._grokConfig,
resumeSessionId: this._resumeSessionId,
envOverrides: this._envOverrides,
effort: this._effort,
@@ -1546,6 +1582,46 @@ export class Session extends EventEmitter {
};
}
/**
* Remember whether the CLI currently wants to be told about mouse clicks.
*
* The strip in {@link _handleTerminalOutput} is the ONLY place these sequences
* exist. After it, neither the browser nor xterm can ever learn that the CLI
* asked for mouse tracking, so `terminal.modes.mouseTrackingMode` is
* permanently 'none' for a stripped mode. The browser hand-encodes SGR reports
* to compensate (`_sendSyntheticSgrTap` in terminal-ui.js), and with no state
* to consult it had to do that on EVERY click, delivering mouse reports to a
* CLI that never asked for them. Publishing this through `toState()` is what
* lets the browser report a click only when the CLI is listening.
*
* Only the TRACKING modes count. 1005/1006 select an encoding and 1007 is
* alt-scroll; a CLI that picks SGR encoding without turning a tracking mode on
* is not asking about clicks, and counting those would put the stray reports
* straight back.
*
* This must stay in lockstep with the strip regex that calls it: a sequence
* removed from the stream but not recorded here is one the browser can neither
* see nor be told about.
*/
private _recordStrippedMouseMode(seq: string): void {
// eslint-disable-next-line no-control-regex
const match = /\x1b\[\?(\d+)([hl])$/.exec(seq);
if (!match) return;
const mode = Number(match[1]);
if (mode !== 1000 && mode !== 1001 && mode !== 1002 && mode !== 1003) return;
if (match[2] === 'h') this._cliMouseModes.add(mode);
else this._cliMouseModes.delete(mode);
this._syncCliMouseTracking();
}
/** Emit only on a real transition: a TUI re-emitting its enable on every repaint costs nothing. */
private _syncCliMouseTracking(): void {
const active = this._cliMouseModes.size > 0;
if (active === this._cliMouseTracking) return;
this._cliMouseTracking = active;
this.emit('mouseTrackingChanged', active);
}
private _handleTerminalOutput(data: string): void {
// Codex AND Claude Code emit sequences that wipe xterm.js scrollback, plus
// mouse-tracking enables that hijack the scroll wheel so the user can't reach
@@ -1598,7 +1674,10 @@ export class Session extends EventEmitter {
// eslint-disable-next-line no-control-regex
.replace(/\x1b\[3J/g, '')
// eslint-disable-next-line no-control-regex
.replace(/\x1b\[\?(?:1000|1001|1002|1003|1005|1006|1007)[hl]/g, '');
.replace(/\x1b\[\?(?:1000|1001|1002|1003|1005|1006|1007)[hl]/g, (seq) => {
this._recordStrippedMouseMode(seq);
return '';
});
}
}
@@ -1751,6 +1830,7 @@ export class Session extends EventEmitter {
geminiConfig: this._geminiConfig,
antigravityConfig: this._antigravityConfig,
piConfig: this._piConfig,
grokConfig: this._grokConfig,
resumeSessionId: this._resumeSessionId,
envOverrides: this._envOverrides,
effort: this._effort,
@@ -1840,6 +1920,10 @@ export class Session extends EventEmitter {
if (this.mode === 'pi') {
throw new Error('Pi sessions require tmux. Direct PTY fallback is not supported.');
}
// Grok sessions require tmux for XAI_API_KEY / GROK_* injection via setenv
if (this.mode === 'grok') {
throw new Error('Grok sessions require tmux. Direct PTY fallback is not supported.');
}
try {
// Pass --session-id to use the SAME ID as the Codeman session
// This ensures subagents can be directly matched to the correct tab
@@ -2525,6 +2609,11 @@ export class Session extends EventEmitter {
this._messages = [];
this._lineBuffer = '';
this._altScreenSeqCarry = '';
// A restarted pane starts with no mouse mode: the new program has not asked
// for one yet, and carrying the old CLI's state over would report clicks
// into a program that never enabled tracking.
this._cliMouseModes.clear();
this._syncCliMouseTracking();
this._markActivity(true);
}
+60 -14
View File
@@ -40,6 +40,8 @@ import {
} from './types.js';
import { Debouncer, MAX_SESSION_TOKENS } from './utils/index.js';
import { dataPath, CODEMAN_INSTANCE } from './config/instance.js';
import { normalizeSessionOrder } from './session-order.js';
import { validateTabLayout, type TabLayout } from './tab-layout.js';
/** Debounce delay for batching state writes (ms) */
const SAVE_DEBOUNCE_MS = 500;
@@ -281,6 +283,9 @@ export class StateStore {
if (this.state.sessionOrder) {
parts.push(`"sessionOrder":${JSON.stringify(this.state.sessionOrder)}`);
}
if (this.state.tabLayouts !== undefined) {
parts.push(`"tabLayouts":${JSON.stringify(this.state.tabLayouts)}`);
}
return `{${parts.join(',')}}`;
}
@@ -514,22 +519,28 @@ export class StateStore {
*/
cleanupStaleSessions(activeSessionIds: Set<string>): {
count: number;
cleaned: Array<{ id: string; name?: string }>;
cleaned: Array<{ id: string; name?: string; owner?: string }>;
} {
const allSessionIds = Object.keys(this.state.sessions);
const cleaned: Array<{ id: string; name?: string }> = [];
const staleIds = new Set(Object.keys(this.state.sessions).filter((sessionId) => !activeSessionIds.has(sessionId)));
return this.cleanupSessionsByIds(staleIds);
}
for (const sessionId of allSessionIds) {
if (!activeSessionIds.has(sessionId)) {
if (this.state.sessions[sessionId]?.pinned === true) continue; // COD-142: pinned records persist even with no live session
const name = this.state.sessions[sessionId]?.name;
cleaned.push({ id: sessionId, name });
delete this.state.sessions[sessionId];
this.cachedSessionJsons.delete(sessionId);
this.dirtySessions.delete(sessionId);
// Also clean up Ralph state for this session
this.ralphStates.delete(sessionId);
}
/** Deletes only confirmed stale session IDs, retaining records pinned after confirmation. */
cleanupSessionsByIds(sessionIds: ReadonlySet<string>): {
count: number;
cleaned: Array<{ id: string; name?: string; owner?: string }>;
} {
const cleaned: Array<{ id: string; name?: string; owner?: string }> = [];
for (const sessionId of sessionIds) {
const session = this.state.sessions[sessionId];
if (!session || session.pinned === true) continue; // COD-142: pinned records persist even with no live session
cleaned.push({ id: sessionId, name: session.name, owner: session.owner });
delete this.state.sessions[sessionId];
this.cachedSessionJsons.delete(sessionId);
this.dirtySessions.delete(sessionId);
// Also clean up Ralph state for this session
this.ralphStates.delete(sessionId);
}
if (cleaned.length > 0) {
@@ -664,6 +675,41 @@ export class StateStore {
this.save();
}
/** Returns an owner layout, or null before that owner has been migrated. */
getTabLayout(owner: string): TabLayout | null {
const layouts = this.state.tabLayouts;
return layouts && Object.hasOwn(layouts, owner) ? layouts[owner] : null;
}
/** Returns a defensive snapshot of every stored owner layout. */
getTabLayouts(): Record<string, TabLayout> {
return structuredClone(this.state.tabLayouts ?? {});
}
/** Validates and atomically persists one owner layout. */
setTabLayout(owner: string, layout: TabLayout): void {
const validated = validateTabLayout(layout);
this.state.tabLayouts = { ...(this.state.tabLayouts ?? {}), [owner]: validated };
this.save();
}
/** Atomically publishes validated owner layouts and their latest global compatibility projection. */
commitTabLayoutProjection(
layouts: Readonly<Record<string, TabLayout>>,
projectOrder: (latest: readonly string[]) => readonly string[]
): { layouts: Record<string, TabLayout>; sessionOrder: string[] } {
const validated = Object.fromEntries(
Object.entries(layouts).map(([owner, layout]) => [owner, validateTabLayout(layout)])
);
const sessionOrder = normalizeSessionOrder(projectOrder([...(this.state.sessionOrder ?? [])]));
const nextLayouts = { ...(this.state.tabLayouts ?? {}), ...validated };
this.state.tabLayouts = nextLayouts;
this.state.sessionOrder = sessionOrder;
this.save();
return { layouts: structuredClone(validated), sessionOrder: [...sessionOrder] };
}
/** Resets all state to initial values and saves immediately. */
reset(): void {
this.state = createInitialState();
+81
View File
@@ -0,0 +1,81 @@
/**
* @fileoverview Pure compatibility translation between legacy session order and owner tab layouts.
*/
import { mergeSessionOrder, normalizeSessionOrder } from './session-order.js';
import {
normalizeTabLayout,
validateTabLayout,
type TabLayout,
type TabRef,
type TabRefMetadata,
} from './tab-layout.js';
export interface OwnerOrderProjection {
owner: string;
ownedIds: readonly string[];
order: readonly string[];
}
export function applyLegacySessionRank(
input: TabLayout,
requestedOrder: readonly string[],
metadata: readonly TabRefMetadata[]
): TabLayout {
const layout = validateTabLayout(input);
const requestedRank = new Map(normalizeSessionOrder(requestedOrder).map((id, index) => [id, index]));
const sessionMetadata = new Map<string, TabRefMetadata>();
for (const item of metadata) {
if (item.kind !== 'session' || !item.ownerValid || !item.visible || sessionMetadata.has(item.id)) continue;
sessionMetadata.set(item.id, item);
}
const isRanked = (ref: TabRef): boolean =>
ref.kind === 'session' && sessionMetadata.has(ref.id) && requestedRank.has(ref.id);
const prepare = (ref: TabRef): TabRef => {
if (ref.kind !== 'session') return { ...ref };
const item = sessionMetadata.get(ref.id);
const ownerValidParent = item?.parentSessionId && sessionMetadata.has(item.parentSessionId);
return ownerValidParent ? { ...ref, placement: 'manual' } : { ...ref };
};
const rankContainer = (refs: readonly TabRef[]): TabRef[] => {
const ranked = refs
.filter(isRanked)
.map(prepare)
.sort((a, b) => requestedRank.get(a.id)! - requestedRank.get(b.id)!);
let rankedIndex = 0;
return refs.map((ref) => (isRanked(ref) ? ranked[rankedIndex++] : { ...ref }));
};
const transformed: TabLayout = {
...layout,
groups: layout.groups.map((group) => ({ ...group, refs: rankContainer(group.refs) })),
ungrouped: rankContainer(layout.ungrouped),
};
return normalizeTabLayout(transformed, metadata);
}
export function recomposeGlobalSessionOrder(
current: readonly string[],
projections: readonly OwnerOrderProjection[],
preferred?: readonly string[]
): string[] {
let result = mergeSessionOrder([...(preferred ?? current)], [...current]);
for (const projection of projections) {
const ownedIds = normalizeSessionOrder(projection.ownedIds);
const owned = new Set(ownedIds);
const canonical = normalizeSessionOrder(projection.order).filter((id) => owned.has(id));
const canonicalSet = new Set(canonical);
for (const id of ownedIds) {
if (canonicalSet.has(id)) continue;
canonicalSet.add(id);
canonical.push(id);
}
let canonicalIndex = 0;
const recomposed = result.map((id) => (owned.has(id) ? canonical[canonicalIndex++] : id));
recomposed.push(...canonical.slice(canonicalIndex));
result = normalizeSessionOrder(recomposed);
}
return result;
}
+144
View File
@@ -0,0 +1,144 @@
/**
* @fileoverview Owner-scoped tab-layout persistence and legacy migration primitives.
*
* This module is deliberately independent of routes and runtime managers. Callers
* provide persisted/live session facts plus saved webviews in server-store order.
*/
import { normalizeTabLayout, type TabLayout, type TabRef, type TabRefMetadata } from './tab-layout.js';
export const SINGLE_USER_LAYOUT_OWNER = '@single';
export interface TabLayoutSessionRecord {
id: string;
owner?: string;
createdAt: number;
parentSessionId?: string;
}
export interface TabLayoutWebviewRecord {
id: string;
owner?: string;
}
export interface TabLayoutMigrationInput {
owner: string;
layouts?: Readonly<Record<string, TabLayout>>;
sessionOrder?: readonly string[];
persistedSessions: readonly TabLayoutSessionRecord[];
liveSessions: readonly TabLayoutSessionRecord[];
/** Saved webviews in authoritative server-store order. */
webviews: readonly TabLayoutWebviewRecord[];
/** Required only when creating a layout, making migration deterministic in tests. */
updatedAt?: string;
}
export interface TabLayoutMigrationResult {
layout: TabLayout;
layouts: Record<string, TabLayout>;
created: boolean;
}
/** Resolve the persistence key without accepting an owner key from a client. */
export function ownerLayoutKey(username?: string): string {
return username || SINGLE_USER_LAYOUT_OWNER;
}
function recordOwner(record: { owner?: string }): string {
return record.owner ?? SINGLE_USER_LAYOUT_OWNER;
}
function compareSessions(a: TabLayoutSessionRecord, b: TabLayoutSessionRecord): number {
return a.createdAt - b.createdAt || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
}
function collectSessions(input: TabLayoutMigrationInput): Map<string, TabLayoutSessionRecord> {
const sessions = new Map<string, TabLayoutSessionRecord>();
for (const record of input.persistedSessions) sessions.set(record.id, { ...record });
// A matching live record is authoritative as a whole. In particular, absent
// optional owner/parent fields mean single-user ownership and root lineage;
// retaining those fields from a stale persisted copy changes their semantics.
for (const record of input.liveSessions) sessions.set(record.id, { ...record });
return sessions;
}
function buildMetadata(
input: TabLayoutMigrationInput,
sessions: ReadonlyMap<string, TabLayoutSessionRecord>
): TabRefMetadata[] {
const ownerSessions = [...sessions.values()]
.filter((record) => recordOwner(record) === input.owner)
.sort(compareSessions);
const sessionOrder = new Map(ownerSessions.map((record, index) => [record.id, index]));
const metadata: TabRefMetadata[] = [...sessions.values()].map((record) => ({
kind: 'session',
id: record.id,
ownerValid: recordOwner(record) === input.owner,
visible: true,
order: sessionOrder.get(record.id) ?? record.createdAt,
parentSessionId: record.parentSessionId,
}));
const webviewOffset = ownerSessions.length;
input.webviews.forEach((record, index) => {
metadata.push({
kind: 'webview',
id: record.id,
ownerValid: recordOwner(record) === input.owner,
visible: true,
order: webviewOffset + index,
});
});
return metadata;
}
/**
* Normalize an existing owner layout, or idempotently migrate legacy flat order.
* Unknown stored refs remain unknown to metadata and are therefore preserved.
* No input object is mutated; validation/capacity failure is atomic.
*/
export function normalizeOrMigrateOwnerTabLayout(input: TabLayoutMigrationInput): TabLayoutMigrationResult {
const sessions = collectSessions(input);
const metadata = buildMetadata(input, sessions);
const existing = input.layouts && Object.hasOwn(input.layouts, input.owner) ? input.layouts[input.owner] : undefined;
if (existing) {
const layout = normalizeTabLayout(existing, metadata);
return { layout, layouts: { ...(input.layouts ?? {}), [input.owner]: layout }, created: false };
}
const ownerSessions = [...sessions.values()].filter((record) => recordOwner(record) === input.owner);
const ownerSessionById = new Map(ownerSessions.map((record) => [record.id, record]));
const liveOwnerIds = new Set(
input.liveSessions.filter((record) => recordOwner(record) === input.owner).map((record) => record.id)
);
const seen = new Set<string>();
const orderedSessions: TabLayoutSessionRecord[] = [];
for (const id of input.sessionOrder ?? []) {
const record = ownerSessionById.get(id);
if (!record || seen.has(id)) continue;
seen.add(id);
orderedSessions.push(record);
}
for (const record of ownerSessions.filter((item) => !seen.has(item.id)).sort(compareSessions)) {
seen.add(record.id);
orderedSessions.push(record);
}
const refs: TabRef[] = orderedSessions.map((record) => {
const manual = record.parentSessionId !== undefined && liveOwnerIds.has(record.parentSessionId);
return manual ? { kind: 'session', id: record.id, placement: 'manual' } : { kind: 'session', id: record.id };
});
for (const webview of input.webviews) {
if (recordOwner(webview) === input.owner) refs.push({ kind: 'webview', id: webview.id });
}
const layout = normalizeTabLayout(
{
version: 0,
groups: [],
ungrouped: refs,
updatedAt: input.updatedAt ?? new Date().toISOString(),
},
metadata
);
return { layout, layouts: { ...(input.layouts ?? {}), [input.owner]: layout }, created: true };
}
+678
View File
@@ -0,0 +1,678 @@
/**
* @fileoverview Owner-scoped authoritative tab-layout coordination.
*
* This is the single mutation boundary between the pure layout model, persisted
* state, live sessions, saved webviews, and SSE. Lifecycle callers describe one
* completed server action; this service performs at most one versioned write.
*/
import type { StateStore } from './state-store.js';
import { mergeSessionOrder, normalizeSessionOrder } from './session-order.js';
import { applyLegacySessionRank, recomposeGlobalSessionOrder } from './tab-layout-legacy-order.js';
import {
flattenOwnerSessionOrder,
materializeOrphans,
normalizeTabLayout,
TabLayoutValidationError,
validateTabLayout,
type TabLayout,
type TabRef,
type TabRefMetadata,
} from './tab-layout.js';
import {
normalizeOrMigrateOwnerTabLayout,
SINGLE_USER_LAYOUT_OWNER,
type TabLayoutSessionRecord,
type TabLayoutWebviewRecord,
} from './tab-layout-persistence.js';
import { SseEvent } from './web/sse-events.js';
export interface TabLayoutSessionLike {
id: string;
owner?: string;
createdAt: number;
parentSessionId?: string;
}
interface TabLayoutServiceDeps {
store: Pick<
StateStore,
'getTabLayout' | 'getTabLayouts' | 'getSessions' | 'getSessionOrder' | 'commitTabLayoutProjection'
>;
sessions: ReadonlyMap<string, TabLayoutSessionLike>;
readWebviews(): Promise<readonly TabLayoutWebviewRecord[]>;
broadcast(event: string, data: unknown): void;
broadcastSessionOrder(change: SessionOrderProjectionChange): void;
now?: () => string;
}
export type TabLayoutPutResult = { status: 'updated'; layout: TabLayout } | { status: 'conflict'; layout: TabLayout };
export interface LegacyOrderActor {
owner: string;
isAdmin: boolean;
}
export interface SessionOrderProjectionChange {
changedOwnerOrders: Record<string, string[]>;
globalOrder: string[];
globalChanged: boolean;
}
export interface LegacyOrderPutResult extends SessionOrderProjectionChange {
order: string[];
}
export interface RemovedTabLayoutSession {
id: string;
owner?: string;
}
interface PreparedOwnerLayout {
current: TabLayout | null;
authoritative: TabLayout;
metadata: TabRefMetadata[];
needsReconciliationCommit: boolean;
}
interface OwnerProjectionPublication {
owner: string;
previous: TabLayout | null;
next: TabLayout;
metadata: readonly TabRefMetadata[];
excludedSessionIds?: ReadonlySet<string>;
}
interface PreparedOrderProjection {
owner: string;
previousOrder: string[];
authoritativeBeforeIds: string[];
excludedIds: string[];
currentIds: string[];
order: string[];
}
const ownerOf = (record: { owner?: string }): string => record.owner ?? SINGLE_USER_LAYOUT_OWNER;
const refKey = (ref: Pick<TabRef, 'kind' | 'id'>): string => `${ref.kind}\u0000${ref.id}`;
const sameLayout = (a: TabLayout, b: TabLayout): boolean => JSON.stringify(a) === JSON.stringify(b);
const sameOrder = (a: readonly string[], b: readonly string[]): boolean =>
a.length === b.length && a.every((id, index) => id === b[index]);
export class TabLayoutService {
private restorationState: 'pending' | 'complete' | 'failed' | 'skipped' = 'pending';
private readonly ownerQueues = new Map<string, Promise<void>>();
constructor(private readonly deps: TabLayoutServiceDeps) {}
private async withOwner<T>(owner: string, task: () => Promise<T>): Promise<T> {
const previous = this.ownerQueues.get(owner) ?? Promise.resolve();
const run = previous.catch(() => undefined).then(task);
const tail = run.then(
() => undefined,
() => undefined
);
this.ownerQueues.set(owner, tail);
try {
return await run;
} finally {
if (this.ownerQueues.get(owner) === tail) this.ownerQueues.delete(owner);
}
}
/** Acquire multiple owner queues in stable order so overlapping bulk cleanups cannot deadlock. */
private async withOwners<T>(owners: readonly string[], task: () => Promise<T>, index = 0): Promise<T> {
if (index >= owners.length) return task();
return this.withOwner(owners[index], () => this.withOwners(owners, task, index + 1));
}
markRestorationComplete(): void {
this.restorationState = 'complete';
}
markRestorationFailed(): void {
this.restorationState = 'failed';
}
markRestorationSkipped(): void {
this.restorationState = 'skipped';
}
assertDeletionReady(): void {
if (this.restorationState === 'complete' || this.restorationState === 'skipped') return;
throw new Error(`Tab layout restoration is ${this.restorationState}; destructive deletion is unavailable`);
}
/** Repair/migrate every owner visible after startup restoration. */
async reconcileAfterRestoration(): Promise<void> {
if (this.restorationState !== 'complete') return;
const { persisted, live } = this.sessionRecords();
const webviews = await this.deps.readWebviews();
const owners = new Set<string>();
for (const record of [...persisted, ...live, ...webviews]) owners.add(ownerOf(record));
for (const owner of owners) await this.get(owner);
}
private sessionRecords(): { persisted: TabLayoutSessionRecord[]; live: TabLayoutSessionRecord[] } {
const persisted = Object.entries(this.deps.store.getSessions()).map(([id, record]) => ({
id,
owner: record.owner,
createdAt: record.createdAt,
parentSessionId: record.parentSessionId,
}));
const live = [...this.deps.sessions.values()].map((record) => ({
id: record.id,
owner: record.owner,
createdAt: record.createdAt,
parentSessionId: record.parentSessionId,
}));
return { persisted, live };
}
private async facts(owner: string): Promise<{
persisted: TabLayoutSessionRecord[];
live: TabLayoutSessionRecord[];
webviews: readonly TabLayoutWebviewRecord[];
metadata: TabRefMetadata[];
}> {
const { persisted, live } = this.sessionRecords();
const webviews = await this.deps.readWebviews();
const sessions = new Map<string, TabLayoutSessionRecord>();
for (const record of persisted) sessions.set(record.id, record);
for (const record of live) sessions.set(record.id, record);
const ownedSessions = [...sessions.values()]
.filter((record) => ownerOf(record) === owner)
.sort((a, b) => a.createdAt - b.createdAt || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
const sessionOrder = new Map(ownedSessions.map((record, index) => [record.id, index]));
const metadata: TabRefMetadata[] = [...sessions.values()].map((record) => ({
kind: 'session',
id: record.id,
ownerValid: ownerOf(record) === owner,
visible: true,
order: sessionOrder.get(record.id) ?? record.createdAt,
parentSessionId: record.parentSessionId,
}));
const offset = ownedSessions.length;
webviews.forEach((record, index) =>
metadata.push({
kind: 'webview',
id: record.id,
ownerValid: ownerOf(record) === owner,
visible: true,
order: offset + index,
})
);
return { persisted, live, webviews, metadata };
}
private prepareCommit(base: TabLayout, next: TabLayout): TabLayout {
return validateTabLayout({
...next,
version: base.version + 1,
updatedAt: (this.deps.now ?? (() => new Date().toISOString()))(),
});
}
private prepareOrderProjection(item: OwnerProjectionPublication): PreparedOrderProjection {
const excluded = item.excludedSessionIds ?? new Set<string>();
const authoritativeBeforeIds = item.metadata
.filter((fact) => fact.kind === 'session' && fact.ownerValid && fact.visible)
.map((fact) => fact.id);
const facts = authoritativeBeforeIds.filter((id) => !excluded.has(id));
const visible = new Set(facts);
const rawPrevious = item.previous ? flattenOwnerSessionOrder(item.previous) : [];
const rawNext = flattenOwnerSessionOrder(item.next);
const previousOrder = rawPrevious.filter((id) => visible.has(id) || excluded.has(id));
const order = rawNext.filter((id) => visible.has(id) && !excluded.has(id));
const excludedIds = normalizeSessionOrder([...excluded]);
return {
owner: item.owner,
previousOrder,
authoritativeBeforeIds: normalizeSessionOrder([...authoritativeBeforeIds, ...excluded]),
excludedIds,
currentIds: normalizeSessionOrder([...order, ...facts]),
order,
};
}
private projectOrder(
latest: readonly string[],
projections: readonly PreparedOrderProjection[],
preferred?: readonly string[]
): string[] {
const before = normalizeSessionOrder(latest);
const removed = new Set(
projections.flatMap((projection) => projection.excludedIds.filter((id) => !projection.currentIds.includes(id)))
);
return recomposeGlobalSessionOrder(
before.filter((id) => !removed.has(id)),
projections.map((projection) => ({
owner: projection.owner,
ownedIds: projection.currentIds,
order: projection.order,
})),
preferred
);
}
private publish(
layouts: Readonly<Record<string, TabLayout>>,
publications: readonly OwnerProjectionPublication[],
preferred?: readonly string[]
): SessionOrderProjectionChange {
const projections = publications.map((item) => this.prepareOrderProjection(item));
let beforeOrder: string[] = [];
const accepted = this.deps.store.commitTabLayoutProjection(layouts, (latest) => {
beforeOrder = normalizeSessionOrder(latest);
return this.projectOrder(beforeOrder, projections, preferred);
});
const changedEntries: Array<[string, string[]]> = [];
for (const projection of projections) {
const beforeIds = new Set(projection.authoritativeBeforeIds);
const currentIds = new Set(projection.currentIds);
const persistedBefore = beforeOrder.filter((id) => beforeIds.has(id));
const persistedAfter = accepted.sessionOrder.filter((id) => currentIds.has(id));
const layoutOrderChanged = !sameOrder(projection.previousOrder, projection.order);
const persistedOwnerSliceChanged = !sameOrder(persistedBefore, persistedAfter);
if (layoutOrderChanged || persistedOwnerSliceChanged) {
changedEntries.push([projection.owner, persistedAfter]);
}
}
const change: SessionOrderProjectionChange = {
changedOwnerOrders: Object.fromEntries(changedEntries),
globalOrder: [...accepted.sessionOrder],
globalChanged: !sameOrder(beforeOrder, accepted.sessionOrder),
};
for (const [owner, layout] of Object.entries(accepted.layouts)) {
this.deps.broadcast(SseEvent.TabLayoutChanged, { owner, version: layout.version });
}
if (changedEntries.length > 0 || change.globalChanged) this.deps.broadcastSessionOrder(change);
return change;
}
private commit(
owner: string,
base: TabLayout,
next: TabLayout,
metadata: readonly TabRefMetadata[],
previous: TabLayout | null = base.version < 0 ? null : base
): TabLayout {
const stored = this.prepareCommit(base, next);
this.publish({ [owner]: stored }, [{ owner, previous, next: stored, metadata }]);
return stored;
}
private async prepareUnlocked(owner: string): Promise<PreparedOwnerLayout> {
const facts = await this.facts(owner);
const current = this.deps.store.getTabLayout(owner);
const authoritative = normalizeOrMigrateOwnerTabLayout({
owner,
layouts: current ? { [owner]: current } : undefined,
sessionOrder: this.deps.store.getSessionOrder(),
persistedSessions: facts.persisted,
liveSessions: facts.live,
webviews: facts.webviews,
updatedAt: (this.deps.now ?? (() => new Date().toISOString()))(),
}).layout;
return {
current,
authoritative,
metadata: facts.metadata,
needsReconciliationCommit: !current || !sameLayout(current, authoritative),
};
}
private async getUnlocked(owner: string): Promise<TabLayout> {
const prepared = await this.prepareUnlocked(owner);
if (!prepared.needsReconciliationCommit) {
const publication = {
owner,
previous: prepared.current,
next: prepared.authoritative,
metadata: prepared.metadata,
};
const latest = this.deps.store.getSessionOrder();
const projected = this.projectOrder(latest, [this.prepareOrderProjection(publication)]);
if (!sameOrder(normalizeSessionOrder(latest), projected)) this.publish({}, [publication]);
return prepared.authoritative;
}
const base = prepared.current ?? { ...prepared.authoritative, version: -1 };
return this.commit(owner, base, prepared.authoritative, prepared.metadata);
}
async get(owner: string): Promise<TabLayout> {
return this.withOwner(owner, () => this.getUnlocked(owner));
}
async put(owner: string, desired: unknown, baseVersion: number): Promise<TabLayoutPutResult> {
return this.withOwner(owner, async () => {
const prepared = await this.prepareUnlocked(owner);
if (baseVersion !== prepared.authoritative.version) return { status: 'conflict', layout: prepared.authoritative };
const validated = validateTabLayout(desired);
const owned = new Set(prepared.metadata.filter((item) => item.ownerValid && item.visible).map(refKey));
const refs = [...validated.groups.flatMap((group) => group.refs), ...validated.ungrouped];
const invalid = refs.find((ref) => !owned.has(refKey(ref)));
if (invalid)
throw new TabLayoutValidationError(`ref is not owned by layout owner: ${invalid.kind}:${invalid.id}`);
const normalized = normalizeTabLayout(
{ ...validated, version: prepared.authoritative.version },
prepared.metadata
);
return {
status: 'updated',
layout: this.commit(owner, prepared.authoritative, normalized, prepared.metadata, prepared.current),
};
});
}
async putLegacyOrder(actor: LegacyOrderActor, requested: readonly string[]): Promise<LegacyOrderPutResult> {
return actor.isAdmin ? this.putAdminLegacyOrder(requested) : this.putOwnerLegacyOrder(actor.owner, requested);
}
private async putOwnerLegacyOrder(owner: string, requested: readonly string[]): Promise<LegacyOrderPutResult> {
return this.withOwner(owner, async () => {
const prepared = await this.prepareUnlocked(owner);
const normalized = normalizeSessionOrder(requested);
const visible = new Set(
prepared.metadata
.filter((item) => item.kind === 'session' && item.ownerValid && item.visible)
.map((item) => item.id)
);
// Unknown or foreign ids are DROPPED, never a 400: the browser debounces
// its reorder push (and swallows errors), so a session deleted inside
// that window would otherwise cost the user the whole reorder — and the
// endpoint sits on the stable /api/v1 surface, where the pre-layout
// server merged leniently. Same philosophy as resolveParentSessionId.
const requestedVisible = normalized.filter((id) => visible.has(id));
const currentKnown = flattenOwnerSessionOrder(prepared.authoritative).filter((id) => visible.has(id));
const effective = mergeSessionOrder(requestedVisible, currentKnown);
const ranked = applyLegacySessionRank(prepared.authoritative, effective, prepared.metadata);
const needsLayout = prepared.needsReconciliationCommit || !sameLayout(prepared.authoritative, ranked);
const base = prepared.current ?? { ...prepared.authoritative, version: -1 };
const next = needsLayout ? this.prepareCommit(base, ranked) : prepared.authoritative;
const change = this.publish(needsLayout ? { [owner]: next } : {}, [
{ owner, previous: prepared.current, next, metadata: prepared.metadata },
]);
return { order: flattenOwnerSessionOrder(next).filter((id) => visible.has(id)), ...change };
});
}
private async putAdminLegacyOrder(requested: readonly string[]): Promise<LegacyOrderPutResult> {
const discoverOwners = (): string[] => {
const owners = new Set(Object.keys(this.deps.store.getTabLayouts()));
const { persisted, live } = this.sessionRecords();
for (const record of [...persisted, ...live]) owners.add(ownerOf(record));
return [...owners].sort();
};
for (;;) {
const owners = discoverOwners();
const result = await this.withOwners(owners, async (): Promise<LegacyOrderPutResult | null> => {
if (!sameOrder(owners, discoverOwners())) return null;
const normalized = normalizeSessionOrder(requested);
const knownOwners = new Map<string, string>();
const { persisted, live } = this.sessionRecords();
for (const record of persisted) knownOwners.set(record.id, ownerOf(record));
for (const record of live) knownOwners.set(record.id, ownerOf(record));
// Unknown ids are DROPPED, never a 400 — see putOwnerLegacyOrder. In
// single-user mode every request is the synthetic admin, so this path
// IS the one the browser's debounced (error-swallowing) push hits.
const known = normalized.filter((id) => knownOwners.has(id));
const publications: OwnerProjectionPublication[] = [];
const updates: Record<string, TabLayout> = Object.create(null) as Record<string, TabLayout>;
for (const owner of owners) {
const prepared = await this.prepareUnlocked(owner);
const visible = new Set(
prepared.metadata
.filter((item) => item.kind === 'session' && item.ownerValid && item.visible)
.map((item) => item.id)
);
const requestedOwner = known.filter((id) => visible.has(id));
const currentKnown = flattenOwnerSessionOrder(prepared.authoritative).filter((id) => visible.has(id));
const effective = mergeSessionOrder(requestedOwner, currentKnown);
const ranked = applyLegacySessionRank(prepared.authoritative, effective, prepared.metadata);
const needsLayout = prepared.needsReconciliationCommit || !sameLayout(prepared.authoritative, ranked);
const base = prepared.current ?? { ...prepared.authoritative, version: -1 };
const next = needsLayout ? this.prepareCommit(base, ranked) : prepared.authoritative;
if (needsLayout) updates[owner] = next;
publications.push({ owner, previous: prepared.current, next, metadata: prepared.metadata });
}
const change = this.publish(updates, publications, known);
return { order: [...change.globalOrder], ...change };
});
if (result) return result;
}
}
/** Reconcile one completed session creation into one versioned mutation. */
async sessionCreated(owner: string): Promise<TabLayout> {
return this.get(owner);
}
/** Reconcile one completed saved-webview creation into one versioned mutation. */
async webviewCreated(owner: string): Promise<TabLayout> {
return this.get(owner);
}
async sessionsRemoved(removed: readonly RemovedTabLayoutSession[]): Promise<void> {
if (this.restorationState !== 'complete' || removed.length === 0) return;
const byOwner = new Map<string, string[]>();
for (const item of removed) {
const owner = ownerOf(item);
const ids = byOwner.get(owner) ?? [];
ids.push(item.id);
byOwner.set(owner, ids);
}
const owners = [...byOwner.keys()].sort();
await this.withOwners(owners, async () => {
const publications: OwnerProjectionPublication[] = [];
const updates: Record<string, TabLayout> = Object.create(null) as Record<string, TabLayout>;
for (const owner of owners) {
const ids = byOwner.get(owner) ?? [];
const prepared = await this.prepareUnlocked(owner);
const current = prepared.current;
// Normalize and prune together so stale cleanup, orphan materialization,
// and missing-ref repair remain one versioned server mutation.
const next = normalizeTabLayout(
materializeOrphans(prepared.authoritative, ids, prepared.metadata),
prepared.metadata
);
const stored = current && !sameLayout(current, next) ? this.prepareCommit(current, next) : null;
if (stored) updates[owner] = stored;
publications.push({
owner,
previous: current,
next: stored ?? next,
metadata: prepared.metadata,
excludedSessionIds: new Set(ids),
});
}
if (publications.length > 0) this.publish(updates, publications);
});
}
/**
* Hold the owner mutation lock across an irreversible session deletion.
* All failure-prone normalization happens before `action`; the prepared layout
* commits only after the resource cleanup finishes.
*/
async runSessionDeletion<T>(removed: readonly RemovedTabLayoutSession[], action: () => Promise<T>): Promise<T> {
// A failed restoration must not lock the user out of explicitly closing a
// tab for the rest of the process lifetime: degrade to best-effort deletion
// without layout coordination. Only the AUTOMATED stale sweep stays
// fail-closed on 'failed' (runStaleSessionCleanup), because that one picks
// its victims itself from state a failed restore may have left incomplete.
if (this.restorationState === 'failed') return action();
this.assertDeletionReady();
if (this.restorationState === 'skipped' || removed.length === 0) return action();
const owners = new Set(removed.map(ownerOf));
if (owners.size !== 1) throw new Error('A session deletion transaction must contain exactly one owner');
const owner = owners.values().next().value as string;
const ids = removed.map((item) => item.id);
return this.withOwner(owner, async () => {
const prepared = await this.prepareUnlocked(owner);
const current = prepared.current;
// Prepare while the soon-to-be-deleted sessions are still known, so
// direct children can be materialized before their parent ref is removed.
const next = materializeOrphans(prepared.authoritative, ids, prepared.metadata);
const stored = current && !sameLayout(current, next) ? this.prepareCommit(current, next) : null;
const result = await action();
this.publish(stored ? { [owner]: stored } : {}, [
{
owner,
previous: current,
next: stored ?? next,
metadata: prepared.metadata,
excludedSessionIds: new Set(ids),
},
]);
return result;
});
}
/**
* Prepare every affected owner layout before bulk stale-state deletion.
* The StateStore action remains synchronous in production, so the candidate
* snapshot cannot change between successful preparation and resource removal.
*/
async runStaleSessionCleanup<T>(
activeSessionIds: ReadonlySet<string>,
action: (ids: ReadonlySet<string>) => T | Promise<T>
): Promise<T> {
this.assertDeletionReady();
const candidates = Object.entries(this.deps.store.getSessions())
.filter(([id, record]) => !activeSessionIds.has(id) && record.pinned !== true)
.map(([id, record]) => ({ id, owner: record.owner }));
if (this.restorationState === 'skipped') return action(new Set(candidates.map((item) => item.id)));
if (candidates.length === 0) return action(new Set());
const byOwner = new Map<string, string[]>();
for (const item of candidates) {
const owner = ownerOf(item);
const ids = byOwner.get(owner) ?? [];
ids.push(item.id);
byOwner.set(owner, ids);
}
const owners = [...byOwner.keys()].sort();
return this.withOwners(owners, async () => {
const webviews = await this.deps.readWebviews();
const persistedState = this.deps.store.getSessions();
const persisted = Object.entries(persistedState).map(([id, record]) => ({
id,
owner: record.owner,
createdAt: record.createdAt,
parentSessionId: record.parentSessionId,
}));
const liveIds = new Set(this.deps.sessions.keys());
const confirmed = candidates.filter((candidate) => {
const record = persistedState[candidate.id];
return (
record !== undefined &&
ownerOf(record) === ownerOf(candidate) &&
record.pinned !== true &&
!activeSessionIds.has(candidate.id) &&
!liveIds.has(candidate.id)
);
});
const confirmedByOwner = new Map<string, string[]>();
for (const item of confirmed) {
const owner = ownerOf(item);
const ids = confirmedByOwner.get(owner) ?? [];
ids.push(item.id);
confirmedByOwner.set(owner, ids);
}
const prepared: Array<{
owner: string;
current: TabLayout | null;
next: TabLayout;
stored: TabLayout | null;
metadata: TabRefMetadata[];
excludedSessionIds: ReadonlySet<string>;
}> = [];
for (const owner of owners) {
const ids = confirmedByOwner.get(owner) ?? [];
if (ids.length === 0) continue;
const current = this.deps.store.getTabLayout(owner);
const sessions = new Map<string, TabLayoutSessionRecord>();
for (const record of persisted) sessions.set(record.id, record);
for (const record of this.deps.sessions.values()) sessions.set(record.id, record);
const ownedSessions = [...sessions.values()]
.filter((record) => ownerOf(record) === owner)
.sort((a, b) => a.createdAt - b.createdAt || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
const sessionOrder = new Map(ownedSessions.map((record, index) => [record.id, index]));
const metadata: TabRefMetadata[] = [...sessions.values()].map((record) => ({
kind: 'session',
id: record.id,
ownerValid: ownerOf(record) === owner,
visible: true,
order: sessionOrder.get(record.id) ?? record.createdAt,
parentSessionId: record.parentSessionId,
}));
const offset = ownedSessions.length;
webviews.forEach((record, index) =>
metadata.push({
kind: 'webview',
id: record.id,
ownerValid: ownerOf(record) === owner,
visible: true,
order: offset + index,
})
);
const authoritative = normalizeOrMigrateOwnerTabLayout({
owner,
layouts: current ? { [owner]: current } : undefined,
sessionOrder: this.deps.store.getSessionOrder(),
persistedSessions: persisted,
liveSessions: [...this.deps.sessions.values()],
webviews,
updatedAt: (this.deps.now ?? (() => new Date().toISOString()))(),
}).layout;
const next = materializeOrphans(authoritative, ids, metadata);
prepared.push({
owner,
current,
next,
stored: current && !sameLayout(current, next) ? this.prepareCommit(current, next) : null,
metadata,
excludedSessionIds: new Set(ids),
});
}
const result = await action(new Set(confirmed.map((item) => item.id)));
if (prepared.length > 0) {
this.publish(
Object.fromEntries(prepared.filter((item) => item.stored).map((item) => [item.owner, item.stored!])),
prepared.map((item) => ({
owner: item.owner,
previous: item.current,
next: item.stored ?? item.next,
metadata: item.metadata,
excludedSessionIds: item.excludedSessionIds,
}))
);
}
return result;
});
}
async webviewDeleted(owner: string, id: string): Promise<void> {
// Same explicit-user-action escape hatch as runSessionDeletion: a failed
// restore skips layout coordination instead of failing the delete.
if (this.restorationState === 'failed') return;
this.assertDeletionReady();
if (this.restorationState === 'skipped') return;
await this.withOwner(owner, async () => {
const current = this.deps.store.getTabLayout(owner);
if (!current) return;
const strip = (refs: readonly TabRef[]): TabRef[] =>
refs.filter((ref) => ref.kind !== 'webview' || ref.id !== id).map((ref) => ({ ...ref }));
const stripped: TabLayout = {
...current,
groups: current.groups.map((group) => ({ ...group, refs: strip(group.refs) })),
ungrouped: strip(current.ungrouped),
};
const { metadata } = await this.facts(owner);
const next = normalizeTabLayout(stripped, metadata);
if (!sameLayout(current, next)) this.commit(owner, current, next, metadata);
});
}
}
+547
View File
@@ -0,0 +1,547 @@
/**
* @fileoverview Framework-independent tab layout model.
*
* Callers provide owner-scoped session/webview metadata. This module deliberately
* has no dependency on session runtime, persistence, routes, or browser state.
*/
export const MAX_TAB_GROUPS = 32;
export const MAX_TAB_GROUP_NAME_LENGTH = 60;
export const MAX_TAB_REFS = 512;
export type TabRefKind = 'session' | 'webview';
export interface TabRef {
kind: TabRefKind;
id: string;
placement?: 'manual';
}
export interface TabGroup {
id: string;
name: string;
refs: TabRef[];
}
export interface TabLayout {
version: number;
groups: TabGroup[];
ungrouped: TabRef[];
updatedAt: string;
}
/** Owner and lineage facts supplied by the server or browser integration. */
export interface TabRefMetadata {
kind: TabRefKind;
id: string;
/** False for missing, foreign-owned, or otherwise invalid refs. */
ownerValid: boolean;
/** False when the owner is not permitted to see/store this ref. */
visible: boolean;
/** Stable creation/sibling order. Ties fall back to kind and id. */
order: number;
/** Session-only lineage hint. Ignored for webviews. */
parentSessionId?: string;
}
export interface TabMoveTarget {
/** Null denotes the real ungrouped container. */
groupId: string | null;
/** Zero-based insertion index after removing the moved block. */
index: number;
}
export interface CreateTabGroupInput {
id: string;
name: string;
index?: number;
}
export interface VisibleTabProjectionOptions {
liveSessionIds: ReadonlySet<string>;
openWebviewIds: ReadonlySet<string>;
collapsedGroupIds?: ReadonlySet<string>;
highlighted?: TabRef;
}
export class TabLayoutValidationError extends Error {
constructor(message: string) {
super(message);
this.name = 'TabLayoutValidationError';
}
}
const keyOf = (ref: Pick<TabRef, 'kind' | 'id'>): string => `${ref.kind}\u0000${ref.id}`;
function assertRecord(value: unknown, label: string): asserts value is Record<string, unknown> {
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
throw new TabLayoutValidationError(`${label} must be an object`);
}
}
function parseNonEmptyString(value: unknown, label: string): string {
if (typeof value !== 'string' || value.length === 0) {
throw new TabLayoutValidationError(`${label} must be a non-empty string`);
}
return value;
}
function parseName(value: unknown, label: string): string {
if (typeof value !== 'string') throw new TabLayoutValidationError(`${label} must be a string`);
const trimmed = value.trim();
if (trimmed.length === 0 || trimmed.length > MAX_TAB_GROUP_NAME_LENGTH) {
throw new TabLayoutValidationError(`${label} must be 1-${MAX_TAB_GROUP_NAME_LENGTH} trimmed characters`);
}
return trimmed;
}
function parseRef(value: unknown, label: string): TabRef {
assertRecord(value, label);
if (value.kind !== 'session' && value.kind !== 'webview') {
throw new TabLayoutValidationError(`${label}.kind must be session or webview`);
}
const id = parseNonEmptyString(value.id, `${label}.id`);
if (value.placement !== undefined && value.placement !== 'manual') {
throw new TabLayoutValidationError(`${label}.placement must be manual when present`);
}
return value.placement === 'manual' ? { kind: value.kind, id, placement: 'manual' } : { kind: value.kind, id };
}
function parseTabLayout(input: unknown, repairDuplicates: boolean): TabLayout {
assertRecord(input, 'layout');
if (!Number.isSafeInteger(input.version) || (input.version as number) < 0) {
throw new TabLayoutValidationError('layout.version must be a non-negative safe integer');
}
if (!Array.isArray(input.groups)) throw new TabLayoutValidationError('layout.groups must be an array');
if (input.groups.length > MAX_TAB_GROUPS) {
throw new TabLayoutValidationError(`layout.groups cannot exceed ${MAX_TAB_GROUPS}`);
}
if (!Array.isArray(input.ungrouped)) throw new TabLayoutValidationError('layout.ungrouped must be an array');
const updatedAt = parseNonEmptyString(input.updatedAt, 'layout.updatedAt');
const groupIds = new Set<string>();
const refKeys = new Set<string>();
let refCount = input.ungrouped.length;
const parseStoredRef = (entry: unknown, label: string): TabRef => {
const ref = parseRef(entry, label);
const key = keyOf(ref);
if (!repairDuplicates && refKeys.has(key)) {
throw new TabLayoutValidationError(`duplicate ref: ${ref.kind}:${ref.id}`);
}
refKeys.add(key);
return ref;
};
const groups = input.groups.map((rawGroup, groupIndex): TabGroup => {
const label = `layout.groups[${groupIndex}]`;
assertRecord(rawGroup, label);
const id = parseNonEmptyString(rawGroup.id, `${label}.id`);
if (groupIds.has(id)) throw new TabLayoutValidationError(`duplicate group id: ${id}`);
groupIds.add(id);
if (!Array.isArray(rawGroup.refs)) throw new TabLayoutValidationError(`${label}.refs must be an array`);
refCount += rawGroup.refs.length;
return {
id,
name: parseName(rawGroup.name, `${label}.name`),
refs: rawGroup.refs.map((entry, refIndex) => parseStoredRef(entry, `${label}.refs[${refIndex}]`)),
};
});
if (refCount > MAX_TAB_REFS) {
throw new TabLayoutValidationError(`layout cannot contain more than ${MAX_TAB_REFS} refs`);
}
return {
version: input.version as number,
groups,
ungrouped: input.ungrouped.map((entry, index) => parseStoredRef(entry, `layout.ungrouped[${index}]`)),
updatedAt,
};
}
/** Validate and defensively clone a layout. Group names are normalized by trimming. */
export function validateTabLayout(input: unknown): TabLayout {
return parseTabLayout(input, false);
}
function validMetadata(metadata: readonly TabRefMetadata[]): TabRefMetadata[] {
const byKey = new Map<string, TabRefMetadata>();
for (const item of metadata) {
if ((item.kind !== 'session' && item.kind !== 'webview') || typeof item.id !== 'string' || item.id.length === 0) {
throw new TabLayoutValidationError('metadata contains an invalid ref identity');
}
if (!Number.isFinite(item.order)) throw new TabLayoutValidationError(`metadata order is invalid for ${item.id}`);
if (!item.ownerValid || !item.visible) continue;
const key = keyOf(item);
if (!byKey.has(key)) byKey.set(key, { ...item });
}
const compareText = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);
const result = [...byKey.values()].sort(
(a, b) => a.order - b.order || compareText(a.kind, b.kind) || compareText(a.id, b.id)
);
if (result.length > MAX_TAB_REFS) {
throw new TabLayoutValidationError(`owner layout cannot exceed ${MAX_TAB_REFS} refs`);
}
return result;
}
interface LocatedRef {
ref: TabRef;
container: string | null;
position: number;
}
function locations(layout: TabLayout): LocatedRef[] {
const result: LocatedRef[] = [];
let position = 0;
for (const group of layout.groups) {
for (const ref of group.refs) result.push({ ref, container: group.id, position: position++ });
}
for (const ref of layout.ungrouped) result.push({ ref, container: null, position: position++ });
return result;
}
function withContainers(layout: TabLayout, refsByContainer: ReadonlyMap<string | null, TabRef[]>): TabLayout {
return {
...layout,
groups: layout.groups.map((group) => ({ ...group, refs: [...(refsByContainer.get(group.id) ?? [])] })),
ungrouped: [...(refsByContainer.get(null) ?? [])],
};
}
/**
* Reconcile a layout against owner-valid metadata and session lineage.
* First stored occurrence wins; missing valid refs append to ungrouped.
*/
export function normalizeTabLayout(input: TabLayout, metadata: readonly TabRefMetadata[]): TabLayout {
const layout = parseTabLayout(input, true);
const valid = validMetadata(metadata);
const metadataByKey = new Map(valid.map((item) => [keyOf(item), item]));
const knownMetadataKeys = new Set(metadata.map((item) => keyOf(item)));
const seen = new Set<string>();
const dedupedByContainer = new Map<string | null, TabRef[]>();
for (const group of layout.groups) dedupedByContainer.set(group.id, []);
dedupedByContainer.set(null, []);
for (const located of locations(layout)) {
const key = keyOf(located.ref);
// Missing metadata is unknown rather than invalid (for example, during
// restoration). Preserve it until an explicit invalid/deletion fact arrives.
if ((knownMetadataKeys.has(key) && !metadataByKey.has(key)) || seen.has(key)) continue;
seen.add(key);
dedupedByContainer.get(located.container)!.push({ ...located.ref });
}
for (const item of valid) {
const key = keyOf(item);
if (seen.has(key)) continue;
seen.add(key);
dedupedByContainer.get(null)!.push({ kind: item.kind, id: item.id });
}
if (seen.size > MAX_TAB_REFS) {
throw new TabLayoutValidationError(`normalized layout cannot exceed ${MAX_TAB_REFS} refs`);
}
let working = withContainers(layout, dedupedByContainer);
const located = locations(working);
const refByKey = new Map(located.map((item) => [keyOf(item.ref), item.ref]));
const sessionById = new Map(valid.filter((item) => item.kind === 'session').map((item) => [item.id, item]));
const manualCycleEdges = new Set<string>();
const state = new Map<string, 'visiting' | 'done'>();
const visit = (id: string): void => {
if (state.get(id) === 'done') return;
state.set(id, 'visiting');
const item = sessionById.get(id);
const stored = refByKey.get(keyOf({ kind: 'session', id }));
if (item?.parentSessionId && stored?.placement !== 'manual') {
const parent = sessionById.get(item.parentSessionId);
const parentStored = refByKey.get(keyOf({ kind: 'session', id: item.parentSessionId }));
if (parent && parentStored) {
if (state.get(parent.id) === 'visiting') manualCycleEdges.add(id);
else visit(parent.id);
}
}
state.set(id, 'done');
};
for (const item of located)
if (item.ref.kind === 'session' && state.get(item.ref.id) === undefined) visit(item.ref.id);
if (manualCycleEdges.size > 0) {
working = {
...working,
groups: working.groups.map((group) => ({
...group,
refs: group.refs.map((ref) =>
ref.kind === 'session' && manualCycleEdges.has(ref.id) ? { ...ref, placement: 'manual' } : ref
),
})),
ungrouped: working.ungrouped.map((ref) =>
ref.kind === 'session' && manualCycleEdges.has(ref.id) ? { ...ref, placement: 'manual' } : ref
),
};
}
const ordered = locations(working);
const updatedRefByKey = new Map(ordered.map((item) => [keyOf(item.ref), item.ref]));
const parentOf = new Map<string, string>();
const children = new Map<string, string[]>();
for (const item of ordered) {
if (item.ref.kind !== 'session' || item.ref.placement === 'manual') continue;
const info = sessionById.get(item.ref.id);
const parentId = info?.parentSessionId;
if (!parentId || !sessionById.has(parentId) || !updatedRefByKey.has(keyOf({ kind: 'session', id: parentId })))
continue;
parentOf.set(item.ref.id, parentId);
const siblings = children.get(parentId) ?? [];
siblings.push(item.ref.id);
children.set(parentId, siblings);
}
const emitted = new Set<string>();
const output = new Map<string | null, TabRef[]>();
for (const group of working.groups) output.set(group.id, []);
output.set(null, []);
const emitSubtree = (root: TabRef, container: string | null): void => {
const rootKey = keyOf(root);
if (emitted.has(rootKey)) return;
emitted.add(rootKey);
output.get(container)!.push({ ...root });
if (root.kind !== 'session') return;
for (const childId of children.get(root.id) ?? []) {
const child = updatedRefByKey.get(keyOf({ kind: 'session', id: childId }));
if (child) emitSubtree(child, container);
}
};
for (const item of ordered) {
if (item.ref.kind === 'session' && parentOf.has(item.ref.id)) continue;
emitSubtree(item.ref, item.container);
}
return withContainers(working, output);
}
function cloneForEdit(input: TabLayout): TabLayout {
return validateTabLayout(input);
}
function boundedIndex(index: number, length: number, label: string): number {
if (!Number.isSafeInteger(index) || index < 0 || index > length) {
throw new TabLayoutValidationError(`${label} index must be between 0 and ${length}`);
}
return index;
}
export function createGroup(input: TabLayout, group: CreateTabGroupInput): TabLayout {
const layout = cloneForEdit(input);
if (layout.groups.length >= MAX_TAB_GROUPS)
throw new TabLayoutValidationError(`cannot exceed ${MAX_TAB_GROUPS} groups`);
const id = parseNonEmptyString(group.id, 'group.id');
if (layout.groups.some((entry) => entry.id === id)) throw new TabLayoutValidationError(`duplicate group id: ${id}`);
const index = boundedIndex(group.index ?? layout.groups.length, layout.groups.length, 'group');
const groups = [...layout.groups];
groups.splice(index, 0, { id, name: parseName(group.name, 'group.name'), refs: [] });
return { ...layout, groups };
}
export function renameGroup(input: TabLayout, groupId: string, name: string): TabLayout {
const layout = cloneForEdit(input);
if (!layout.groups.some((group) => group.id === groupId))
throw new TabLayoutValidationError(`unknown group: ${groupId}`);
return {
...layout,
groups: layout.groups.map((group) =>
group.id === groupId ? { ...group, name: parseName(name, 'group.name') } : group
),
};
}
export function deleteGroup(input: TabLayout, groupId: string): TabLayout {
const layout = cloneForEdit(input);
const group = layout.groups.find((entry) => entry.id === groupId);
if (!group) throw new TabLayoutValidationError(`unknown group: ${groupId}`);
return {
...layout,
groups: layout.groups.filter((entry) => entry.id !== groupId),
ungrouped: [...layout.ungrouped, ...group.refs.map((ref) => ({ ...ref }))],
};
}
export function reorderGroup(input: TabLayout, groupId: string, index: number): TabLayout {
const layout = cloneForEdit(input);
const from = layout.groups.findIndex((group) => group.id === groupId);
if (from < 0) throw new TabLayoutValidationError(`unknown group: ${groupId}`);
const groups = [...layout.groups];
const [group] = groups.splice(from, 1);
groups.splice(boundedIndex(index, groups.length, 'group'), 0, group);
return { ...layout, groups };
}
function mapRef(input: TabLayout, target: TabRef, transform: (ref: TabRef) => TabRef): TabLayout {
const layout = cloneForEdit(input);
let found = false;
const apply = (ref: TabRef): TabRef => {
if (keyOf(ref) !== keyOf(target)) return ref;
found = true;
return transform(ref);
};
const result = {
...layout,
groups: layout.groups.map((group) => ({ ...group, refs: group.refs.map(apply) })),
ungrouped: layout.ungrouped.map(apply),
};
if (!found) throw new TabLayoutValidationError(`unknown ref: ${target.kind}:${target.id}`);
return result;
}
export function setManualPlacement(input: TabLayout, target: TabRef, manual: boolean): TabLayout {
if (!manual) {
throw new TabLayoutValidationError('manual placement can only be cleared through followParent');
}
return mapRef(input, target, (ref) => ({ ...ref, placement: 'manual' }));
}
export function followParent(input: TabLayout, target: TabRef, metadata: readonly TabRefMetadata[]): TabLayout {
const normalized = normalizeTabLayout(input, metadata);
if (target.kind !== 'session') {
throw new TabLayoutValidationError('only a session ref can follow a parent');
}
const valid = validMetadata(metadata);
const targetMetadata = valid.find((item) => item.kind === 'session' && item.id === target.id);
if (!targetMetadata?.parentSessionId) {
throw new TabLayoutValidationError(`session has no owner-valid parent: ${target.id}`);
}
const parentMetadata = valid.find((item) => item.kind === 'session' && item.id === targetMetadata.parentSessionId);
if (!parentMetadata) {
throw new TabLayoutValidationError(`session parent is not owner-valid: ${targetMetadata.parentSessionId}`);
}
const storedKeys = new Set(locations(normalized).map((item) => keyOf(item.ref)));
if (!storedKeys.has(keyOf(target))) {
throw new TabLayoutValidationError(`unknown ref: ${target.kind}:${target.id}`);
}
const parentRef: TabRef = { kind: 'session', id: targetMetadata.parentSessionId };
if (!storedKeys.has(keyOf(parentRef))) {
throw new TabLayoutValidationError(`session parent is not represented: ${targetMetadata.parentSessionId}`);
}
const cleared = mapRef(normalized, target, (ref) => ({ kind: ref.kind, id: ref.id }));
return normalizeTabLayout(cleared, metadata);
}
function descendantKeys(root: TabRef, layout: TabLayout, metadata: readonly TabRefMetadata[]): Set<string> {
const valid = validMetadata(metadata);
const stored = new Map(locations(layout).map((item) => [keyOf(item.ref), item.ref]));
const children = new Map<string, string[]>();
for (const item of valid) {
if (item.kind !== 'session' || !item.parentSessionId) continue;
const child = stored.get(keyOf(item));
if (!child || child.placement === 'manual' || !stored.has(keyOf({ kind: 'session', id: item.parentSessionId })))
continue;
const siblings = children.get(item.parentSessionId) ?? [];
siblings.push(item.id);
children.set(item.parentSessionId, siblings);
}
const result = new Set<string>();
const add = (ref: TabRef): void => {
const key = keyOf(ref);
if (result.has(key)) return;
result.add(key);
if (ref.kind !== 'session') return;
for (const childId of children.get(ref.id) ?? []) add({ kind: 'session', id: childId });
};
add(root);
return result;
}
export function moveRef(
input: TabLayout,
target: TabRef,
destination: TabMoveTarget,
metadata: readonly TabRefMetadata[]
): TabLayout {
let layout = normalizeTabLayout(input, metadata);
const targetKey = keyOf(target);
if (!locations(layout).some((item) => keyOf(item.ref) === targetKey)) {
throw new TabLayoutValidationError(`unknown ref: ${target.kind}:${target.id}`);
}
if (destination.groupId !== null && !layout.groups.some((group) => group.id === destination.groupId)) {
throw new TabLayoutValidationError(`unknown group: ${destination.groupId}`);
}
const blockKeys = descendantKeys(target, layout, metadata);
const block = locations(layout)
.filter((item) => blockKeys.has(keyOf(item.ref)))
.map((item) => ({ ...item.ref }));
const metadataItem = validMetadata(metadata).find((item) => keyOf(item) === targetKey);
if (target.kind === 'session' && metadataItem?.parentSessionId) block[0] = { ...block[0], placement: 'manual' };
const remaining = new Map<string | null, TabRef[]>();
for (const group of layout.groups)
remaining.set(
group.id,
group.refs.filter((ref) => !blockKeys.has(keyOf(ref)))
);
remaining.set(
null,
layout.ungrouped.filter((ref) => !blockKeys.has(keyOf(ref)))
);
const destinationRefs = remaining.get(destination.groupId)!;
const index = boundedIndex(destination.index, destinationRefs.length, 'destination');
destinationRefs.splice(index, 0, ...block);
layout = withContainers(layout, remaining);
return normalizeTabLayout(layout, metadata);
}
/**
* Remove explicitly deleted session parents and pin their direct inherited
* children at their current stored positions so a later reused ID cannot adopt them.
*/
export function materializeOrphans(
input: TabLayout,
removedParentIds: readonly string[],
metadata: readonly TabRefMetadata[]
): TabLayout {
const layout = cloneForEdit(input);
const removed = new Set(removedParentIds);
const directChildren = new Set(
validMetadata(metadata)
.filter((item) => item.kind === 'session' && item.parentSessionId && removed.has(item.parentSessionId))
.map((item) => item.id)
);
const transform = (refs: readonly TabRef[]): TabRef[] =>
refs
.filter((ref) => ref.kind !== 'session' || !removed.has(ref.id))
.map((ref) =>
ref.kind === 'session' && directChildren.has(ref.id) && ref.placement !== 'manual'
? { ...ref, placement: 'manual' }
: { ...ref }
);
return {
...layout,
groups: layout.groups.map((group) => ({ ...group, refs: transform(group.refs) })),
ungrouped: transform(layout.ungrouped),
};
}
/** Session-only compatibility order; collapse and webviews do not affect it. */
export function flattenOwnerSessionOrder(input: TabLayout): string[] {
return locations(validateTabLayout(input))
.map((item) => item.ref)
.filter((ref): ref is TabRef & { kind: 'session' } => ref.kind === 'session')
.map((ref) => ref.id);
}
/** Locally renderable order used by tab painting and Alt-number consumers. */
export function flattenVisibleRefs(input: TabLayout, options: VisibleTabProjectionOptions): TabRef[] {
const layout = validateTabLayout(input);
const collapsed = options.collapsedGroupIds ?? new Set<string>();
const renderable = (ref: TabRef): boolean =>
ref.kind === 'session' ? options.liveSessionIds.has(ref.id) : options.openWebviewIds.has(ref.id);
const highlightedKey = options.highlighted ? keyOf(options.highlighted) : undefined;
const result: TabRef[] = [];
for (const group of layout.groups) {
for (const ref of group.refs) {
if (!renderable(ref)) continue;
if (collapsed.has(group.id) && keyOf(ref) !== highlightedKey) continue;
result.push({ ...ref });
}
}
for (const ref of layout.ungrouped) if (renderable(ref)) result.push({ ...ref });
return result;
}
+140 -50
View File
@@ -31,7 +31,13 @@ import { existsSync, readFileSync, mkdirSync } from 'node:fs';
import { writeFile, rename } from 'node:fs/promises';
import { dirname } from 'node:path';
import { homedir } from 'node:os';
import { dataPath, DEFAULT_TMUX_SOCKET, CODEMAN_INSTANCE } from './config/instance.js';
import {
dataPath,
DEFAULT_TMUX_SOCKET,
CODEMAN_INSTANCE,
SAFE_TMUX_SOCKET_PATTERN,
resolveTmuxSocketName,
} from './config/instance.js';
import {
ProcessStats,
PersistedRespawnConfig,
@@ -46,6 +52,7 @@ import {
type GeminiConfig,
type AntigravityConfig,
type PiConfig,
type GrokConfig,
type SessionRemote,
type SessionDocker,
type DockerCommandMode,
@@ -75,11 +82,19 @@ import {
SAFE_PATH_PATTERN,
findClaudeDir,
getClaudeCliVersion,
getClaudeNotFoundMessage,
resolveOpenCodeDir,
getOpenCodeNotFoundMessage,
resolveCodexDir,
getCodexNotFoundMessage,
resolveGeminiDir,
getGeminiNotFoundMessage,
resolveAntigravityDir,
getAntigravityNotFoundMessage,
resolvePiDir,
getPiNotFoundMessage,
resolveGrokDir,
getGrokNotFoundMessage,
resolveLocalShell,
loginShellArgs,
} from './utils/index.js';
@@ -194,9 +209,6 @@ const SAFE_PANE_TARGET_PATTERN = /^(%\d+|\d+)$/;
* `codeman` for prod, `codeman-beta` on the beta branch). */
const DEFAULT_CODEMAN_TMUX_SOCKET = DEFAULT_TMUX_SOCKET;
/** Regex to validate tmux socket names passed to `tmux -L`. */
const SAFE_TMUX_SOCKET_PATTERN = /^[a-zA-Z0-9_.-]+$/;
/**
* Separator used in `tmux list-panes -F` output between session name and pid.
*
@@ -591,9 +603,8 @@ function resolveConfiguredTmuxSocket(): string {
const raw = process.env.CODEMAN_TMUX_SOCKET ?? DEFAULT_CODEMAN_TMUX_SOCKET;
if (!SAFE_TMUX_SOCKET_PATTERN.test(raw)) {
console.warn(`[TmuxManager] Ignoring invalid CODEMAN_TMUX_SOCKET: ${JSON.stringify(raw)}`);
return DEFAULT_CODEMAN_TMUX_SOCKET;
}
return raw;
return resolveTmuxSocketName();
}
/** Build the `tmux -L <socket>` command prefix. Socket name is shell-escaped. */
@@ -794,6 +805,47 @@ function buildPiCommand(config?: PiConfig): string {
return parts.join(' ');
}
/**
* Build the Grok Build CLI (xAI `grok`) command with appropriate flags.
*
* The bypass switch is `--always-approve` ("auto-approve all tool executions",
* grok's `bypassPermissions` permission mode; config-level deny rules still
* apply on top). Absent config spawns bare `grok`, i.e. grok's own default
* ask-mode, which is why the multi-user clamp only needs the only-if-sent
* branch for grok. Flag surface verified against grok 1.0.5.
*
* `XAI_API_KEY` is deliberately never wired as a flag: secrets flow through
* socket-scoped `tmux setenv` (envOverrides), never the spawn command line.
*
* Like the sibling builders, every user value is regex-allowlisted and silently
* DROPPED on failure: the result is interpolated into a `bash -c "..."` string.
*/
function buildGrokCommand(config?: GrokConfig): string {
const parts = ['grok'];
if (config?.alwaysApprove) {
parts.push('--always-approve');
}
if (config?.model) {
const safeModel = /^[a-zA-Z0-9._\-/]+$/.test(config.model) ? config.model : undefined;
if (safeModel) parts.push('--model', safeModel);
}
// --resume and -c conflict; a valid explicit session id wins. Ids only:
// grok's --resume also accepts session TITLES, which are arbitrary user
// strings, so the id regex doubles as the no-titles rule here.
const safeSessionId =
config?.resumeSessionId && /^[a-zA-Z0-9._-]+$/.test(config.resumeSessionId) ? config.resumeSessionId : undefined;
if (safeSessionId) {
parts.push('--resume', safeSessionId);
} else if (config?.continueSession) {
parts.push('--continue');
}
return parts.join(' ');
}
/**
* Build the spawn command for any session mode.
* Shared by createSession() and respawnPane() to avoid duplication.
@@ -837,6 +889,7 @@ export function buildSpawnCommand(options: {
geminiConfig?: GeminiConfig;
antigravityConfig?: AntigravityConfig;
piConfig?: PiConfig;
grokConfig?: GrokConfig;
resumeSessionId?: string;
effort?: EffortLevel;
/** Codeman session name, passed to claude as `--name` (version-gated, sanitized; local spawns only). */
@@ -886,6 +939,9 @@ export function buildSpawnCommand(options: {
if (options.mode === 'pi') {
return buildPiCommand(options.piConfig);
}
if (options.mode === 'grok') {
return buildGrokCommand(options.grokConfig);
}
// #208: NOT the literal '$SHELL'. This string is embedded in the `bash -c "…"`
// argument of the respawn-pane line, which execSync runs through `/bin/sh -c`,
// so a `$SHELL` here is expanded by the SERVER process's shell against the
@@ -1101,6 +1157,8 @@ function appendResumeFlag(modeCommand: string, mode: SessionMode, resumeId: stri
return `${modeCommand} --conversation ${resumeId}`;
case 'pi':
return `${modeCommand} --session ${resumeId}`;
case 'grok':
return `${modeCommand} --resume ${resumeId}`;
default:
return modeCommand; // shell / opencode: no resume
}
@@ -1562,6 +1620,8 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
private reconnectGuard: Set<string> = new Set();
private trueColorConfigured = false;
/** tmux 3.7+ can resize pane history after creation; older releases cannot. */
private liveHistoryResizeSupported: boolean | null = null;
constructor() {
super();
@@ -1580,6 +1640,26 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
return tmuxCommand(this.tmuxSocket);
}
private supportsLiveHistoryResize(): boolean {
if (this.liveHistoryResizeSupported !== null) return this.liveHistoryResizeSupported;
try {
const output = execSync(`${this.tmux()} -V`, {
encoding: 'utf8',
timeout: EXEC_TIMEOUT_MS,
stdio: ['ignore', 'pipe', 'ignore'],
});
const match = output.match(/(?:^|\D)(\d+)\.(\d+)/);
const major = match ? Number(match[1]) : 0;
const minor = match ? Number(match[2]) : 0;
this.liveHistoryResizeSupported = major > 3 || (major === 3 && minor >= 7);
} catch {
// Unknown versions take the legacy path required by tmux <3.7.
this.liveHistoryResizeSupported = false;
}
return this.liveHistoryResizeSupported;
}
// Load saved sessions from disk (NEVER called in test mode)
private loadSessions(): void {
if (IS_TEST_MODE) return;
@@ -1669,10 +1749,12 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
const exports = [
'export LANG=en_US.UTF-8',
'export LC_ALL=en_US.UTF-8',
mode === 'codex' || mode === 'gemini' || mode === 'antigravity' || mode === 'pi'
mode === 'codex' || mode === 'gemini' || mode === 'antigravity' || mode === 'pi' || mode === 'grok'
? 'export COLORTERM=truecolor'
: 'unset COLORTERM',
...(mode === 'codex' || mode === 'gemini' || mode === 'antigravity' || mode === 'pi' ? ['unset NO_COLOR'] : []),
...(mode === 'codex' || mode === 'gemini' || mode === 'antigravity' || mode === 'pi' || mode === 'grok'
? ['unset NO_COLOR']
: []),
// Stamp each Codex pane with a unique originator so the response-viewer
// can locate THIS pane's rollout exactly — codex writes the value into
// session_meta.originator of every rollout it creates. Without it,
@@ -1767,6 +1849,10 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
const dir = resolvePiDir();
return { pathExport: dir ? `export PATH="${dir}:$PATH" && ` : '', dir };
}
if (mode === 'grok') {
const dir = resolveGrokDir();
return { pathExport: dir ? `export PATH="${dir}:$PATH" && ` : '', dir };
}
return { pathExport: '', dir: null };
}
@@ -1816,6 +1902,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
geminiConfig,
antigravityConfig,
piConfig,
grokConfig,
resumeSessionId,
envOverrides,
effort,
@@ -1853,29 +1940,31 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
return session;
}
// Resolve CLI binary directory based on mode
// Resolve CLI binary directory based on mode. The not-found messages come
// from the resolvers (formatCliNotFoundMessage) so the error names WHERE it
// looked — server PATH, login shell, checked directories — instead of just
// asserting the CLI is missing (the classic systemd/launchd PATH trap).
const { pathExport, dir: cliDir } = this.buildPathExport(mode);
if (mode === 'claude' && !cliDir) {
throw new Error('Claude CLI not found. Install it with: curl -fsSL https://claude.ai/install.sh | bash');
throw new Error(getClaudeNotFoundMessage());
}
if (mode === 'opencode' && !cliDir) {
throw new Error('OpenCode CLI not found. Install with: curl -fsSL https://opencode.ai/install | bash');
throw new Error(getOpenCodeNotFoundMessage());
}
if (mode === 'codex' && !cliDir) {
throw new Error('Codex CLI not found. Install with: npm install -g @openai/codex');
throw new Error(getCodexNotFoundMessage());
}
if (mode === 'gemini' && !cliDir) {
throw new Error('Gemini CLI not found. Install with: npm install -g @google/gemini-cli');
throw new Error(getGeminiNotFoundMessage());
}
if (mode === 'antigravity' && !cliDir) {
throw new Error(
'Antigravity CLI not found. Install with: curl -fsSL https://antigravity.google/cli/install.sh | bash'
);
throw new Error(getAntigravityNotFoundMessage());
}
if (mode === 'pi' && !cliDir) {
throw new Error(
'Pi CLI not found. Install with: npm install -g --ignore-scripts @earendil-works/pi-coding-agent'
);
throw new Error(getPiNotFoundMessage());
}
if (mode === 'grok' && !cliDir) {
throw new Error(getGrokNotFoundMessage());
}
const envExportsStr = this.buildEnvExports(sessionId, muxName, mode).join(' && ');
@@ -1891,6 +1980,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
geminiConfig,
antigravityConfig,
piConfig,
grokConfig,
resumeSessionId,
effort,
sessionName: name,
@@ -1921,7 +2011,16 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
// launched in TMUX_LAUNCH_CWD (/tmp) rather than the real workingDir: a FUSE/rclone
// mount that isn't ready yet makes `getcwd` fail and breaks the spawn (see #110). The
// pane cd's into workingDir below via respawn-pane.
execSync(`${this.tmux()} new-session -ds "${muxName}" -c ${TMUX_LAUNCH_CWD}`, {
// tmux <3.7 allocates history only at pane creation, so its global default
// must be set immediately BEFORE new-session. tmux 3.7+ can resize a pane
// after creation; target only the new session there because changing the
// global option can resize (and when lowered, trim) unrelated live panes.
const safeHistoryLimit =
Number.isSafeInteger(historyLimit) && historyLimit > 0 ? Math.trunc(historyLimit) : DEFAULT_TMUX_HISTORY_LIMIT;
const createSessionCommand = this.supportsLiveHistoryResize()
? `${this.tmux()} new-session -ds "${muxName}" -c ${TMUX_LAUNCH_CWD} \\; set-option -t "${muxName}" history-limit ${safeHistoryLimit}`
: `${this.tmux()} set-option -g history-limit ${safeHistoryLimit} \\; new-session -ds "${muxName}" -c ${TMUX_LAUNCH_CWD} \\; set-option -t "${muxName}" history-limit ${safeHistoryLimit}`;
execSync(createSessionCommand, {
cwd: TMUX_LAUNCH_CWD,
timeout: EXEC_TIMEOUT_MS,
stdio: 'ignore',
@@ -1986,16 +2085,6 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
.catch(() => {
/* Already set globally as fallback */
}),
// Raise tmux scrollback from its 2000-line default so re-attach preserves
// more context. Intentionally exceeds the xterm-side DEFAULT_SCROLLBACK (50k
// in constants.js), which stays lower to protect browser/mobile memory.
execAsync(`${this.tmux()} set-option -t "${muxName}" history-limit ${historyLimit}`, {
timeout: EXEC_TIMEOUT_MS,
})
.then(() => {})
.catch(() => {
/* Non-critical — falls back to tmux default */
}),
];
// Enable 24-bit true color passthrough — server-wide, set once per lifetime
@@ -2116,10 +2205,10 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
geminiConfig,
antigravityConfig,
piConfig,
grokConfig,
resumeSessionId,
envOverrides,
effort,
historyLimit = DEFAULT_TMUX_HISTORY_LIMIT,
remote,
docker,
name,
@@ -2130,16 +2219,6 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
if (!isValidMuxName(muxName) || !isValidPath(workingDir)) return null;
// Re-apply the configured tmux history-limit after respawn (kept in sync
// with the live setting via setHistoryLimit()).
if (!IS_TEST_MODE) {
await execAsync(`${this.tmux()} set-option -t ${shellescape(muxName)} history-limit ${historyLimit}`, {
timeout: EXEC_TIMEOUT_MS,
}).catch(() => {
/* Non-critical — keeps existing tmux history-limit */
});
}
// Resolve CLI binary directory based on mode
const { pathExport } = this.buildPathExport(mode);
@@ -2156,6 +2235,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
geminiConfig,
antigravityConfig,
piConfig,
grokConfig,
resumeSessionId,
effort,
sessionName: name,
@@ -2998,9 +3078,9 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
}
/**
* Apply a tmux history-limit to all tracked sessions (e.g. when the user
* changes the terminal-history setting). Invalid limits fall back to the
* default. Best-effort per session.
* Apply a tmux history limit. tmux 3.7+ safely targets tracked live sessions;
* older releases can only change the global default for future panes. Invalid
* limits fall back to the default.
*/
async setHistoryLimit(limit: number): Promise<void> {
const safeLimit = Number.isSafeInteger(limit) && limit > 0 ? Math.trunc(limit) : DEFAULT_TMUX_HISTORY_LIMIT;
@@ -3009,12 +3089,22 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
return;
}
const updates = Array.from(this.sessions.values()).map((session) =>
execAsync(`${this.tmux()} set-option -t ${shellescape(session.muxName)} history-limit ${safeLimit}`, {
timeout: EXEC_TIMEOUT_MS,
})
);
await Promise.allSettled(updates);
if (this.supportsLiveHistoryResize()) {
const updates = Array.from(this.sessions.values()).map((session) =>
execAsync(`${this.tmux()} set-option -t ${shellescape(session.muxName)} history-limit ${safeLimit}`, {
timeout: EXEC_TIMEOUT_MS,
})
);
await Promise.allSettled(updates);
return;
}
await execAsync(`${this.tmux()} set-option -g history-limit ${safeLimit}`, {
timeout: EXEC_TIMEOUT_MS,
}).catch(() => {
// No tmux server yet is fine: legacy createSession sets the same default
// immediately before it creates the first pane.
});
}
/**
+598
View File
@@ -0,0 +1,598 @@
/**
* @fileoverview Pure ANSI helpers for the TUI preview pane.
*
* The preview shows the tail of a session's raw terminal stream, which is
* xterm-bound bytes: SGR colors, cursor jumps, OSC titles, DECSET modes and
* carriage-return repaints. This is NOT a terminal emulator. It reconstructs a
* readable, color-preserving tail: SGR survives, everything else that steers a
* cursor is dropped, and a `\r` is honored as "back to column 0" so a spinner
* that repaints its line 200 times contributes one line instead of 200.
*
* CURSOR ADDRESSING (`ESC [ r ; c H`) is honored too, and it has to be: an Ink
* TUI like Claude Code repaints by ROW and emits almost no newlines, so
* dropping those sequences collapses a whole screen into one unreadable line
* (measured against a live pane, 2026-08-16). A jump to column 1 starts a new
* display line, a jump within a row moves the write position, which is the same
* reading `normalizeCapturedFrame` in `web/approval-inbox.ts` takes of the same
* kind of frame.
*
* Two approximations are deliberate, because the alternative is an emulator:
* a carriage-return overwrite counts CODE POINTS, not display columns (so a
* repaint over CJK text can land one cell off), and tab stops are counted the
* same way. Neither can corrupt output, they only shift a repaint's alignment.
* Absolute ROW numbers are ignored as well: rows arrive in the order they are
* painted, which for a tail is the order worth reading.
*
* @module tui/tui-ansi
*/
const ESC = 0x1b;
const BEL = 0x07;
const ST_C1 = 0x9c;
const DEL = 0x7f;
/** SGR reset, appended by `clipStyledLine` so a clipped line cannot bleed. */
export const SGR_RESET = '\x1b[0m';
const TAB_WIDTH = 8;
/** Cap on remembered SGR sequences per cell, so a pathological stream cannot grow one unboundedly. */
const MAX_ACTIVE_SGR = 32;
/** Ceiling on a display line's cells: a stream may address column 99999, a terminal has none. */
const MAX_LINE_CELLS = 1000;
// ─────────────────────────────────────────────────────────────────────────────
// Escape-sequence scanning
// ─────────────────────────────────────────────────────────────────────────────
interface EscapeScan {
/** Index just past the sequence; `text.length` for a truncated one. */
next: number;
/** The sequence itself, only when it is SGR (`CSI ... m`) and therefore kept. */
sgr?: string;
/** 1-based column of a cursor-position sequence (`CSI r ; c H` or `f`). */
column?: number;
/** 1-based row of that same sequence. Row 1 means a repaint is starting. */
row?: number;
}
/** The row and column a `CSI r ; c H` addresses. Both parameters default to 1. */
function cursorPosition(params: string): { row: number; column: number } {
const parts = params.split(';');
const read = (index: number): number => {
const value = Number.parseInt(parts[index] ?? '', 10);
return Number.isSafeInteger(value) && value > 0 ? value : 1;
};
return { row: read(0), column: read(1) };
}
/** Scan a CSI body starting at `from` (params, then intermediates, then a final byte). */
function readCsi(text: string, start: number, from: number, keepSgr: boolean): EscapeScan {
let j = from;
while (j < text.length && text.charCodeAt(j) >= 0x30 && text.charCodeAt(j) <= 0x3f) j++;
while (j < text.length && text.charCodeAt(j) >= 0x20 && text.charCodeAt(j) <= 0x2f) j++;
if (j >= text.length) return { next: text.length };
const next = j + 1;
if (keepSgr && text[j] === 'm') return { next, sgr: text.slice(start, next) };
if (keepSgr && (text[j] === 'H' || text[j] === 'f')) {
return { next, ...cursorPosition(text.slice(from, j)) };
}
return { next };
}
/** Scan an OSC/DCS/PM/APC body: everything up to BEL, C1 ST or `ESC \`. */
function readStringSequence(text: string, from: number): number {
let j = from;
while (j < text.length) {
const code = text.charCodeAt(j);
if (code === BEL || code === ST_C1) return j + 1;
if (code === ESC && text[j + 1] === '\\') return j + 2;
j++;
}
return text.length;
}
/** Scan the escape sequence starting at `i` (which must be an ESC). */
function readEscape(text: string, i: number): EscapeScan {
const second = text[i + 1];
if (second === undefined) return { next: text.length };
if (second === '[') return readCsi(text, i, i + 2, true);
if (second === ']' || second === 'P' || second === 'X' || second === '^' || second === '_') {
return { next: readStringSequence(text, i + 2) };
}
// Charset / character-set selection: one more byte belongs to the sequence.
if (second === '(' || second === ')' || second === '*' || second === '+' || second === '#' || second === '%') {
return { next: Math.min(text.length, i + 3) };
}
return { next: i + 2 };
}
/** Scan a single-byte C1 control at `i` (0x80-0x9f). */
function readC1(text: string, i: number): number {
const code = text.charCodeAt(i);
if (code === 0x9b) return readCsi(text, i, i + 1, false).next;
if (code === 0x90 || code === 0x9d || code === 0x9e || code === 0x9f) return readStringSequence(text, i + 1);
return i + 1;
}
function isC1(code: number): boolean {
return code >= 0x80 && code <= 0x9f;
}
/** `CSI 0 m`, `CSI m` and `CSI 0;0 m` all mean "back to plain". */
function isSgrReset(seq: string): boolean {
const params = seq.slice(2, -1);
return params === '' || /^0(?:;0)*$/.test(params);
}
/**
* Fold one SGR sequence into the active set. Sequences accumulate in arrival
* order (a later color simply wins when replayed), a reset clears them, and a
* repeat moves rather than duplicates.
*/
function applySgr(active: string[], seq: string): string[] {
if (isSgrReset(seq)) return [];
const next = active.filter((s) => s !== seq);
next.push(seq);
return next.length > MAX_ACTIVE_SGR ? next.slice(-MAX_ACTIVE_SGR) : next;
}
// ─────────────────────────────────────────────────────────────────────────────
// Display width
// ─────────────────────────────────────────────────────────────────────────────
/**
* Combining marks, variation selectors and other zero-advance code points.
* Pragmatic, not exhaustive: enough that accents and emoji modifiers do not
* inflate a measured width.
*/
const ZERO_WIDTH_RANGES: ReadonlyArray<readonly [number, number]> = [
[0x0300, 0x036f],
[0x0483, 0x0489],
[0x0591, 0x05bd],
[0x05bf, 0x05bf],
[0x0610, 0x061a],
[0x064b, 0x065f],
[0x0670, 0x0670],
[0x06d6, 0x06dc],
[0x0e31, 0x0e31],
[0x0e34, 0x0e3a],
[0x0e47, 0x0e4e],
[0x200b, 0x200f],
[0x2028, 0x202e],
[0x2060, 0x2064],
[0x20d0, 0x20f0],
[0xfe00, 0xfe0f],
[0xfe20, 0xfe2f],
[0xfeff, 0xfeff],
];
/**
* East Asian Wide + Fullwidth, plus the standalone code points UAX #11 marks
* Wide because they are emoji-presentation by default. This repo ships a zh-CN
* locale, so CJK correctness is the point; exhaustive Unicode is not required,
* but the scattered BMP entries below are not optional either: `✋` (U+270B) is
* one of them and it is a glyph this TUI draws in every waiting row, so getting
* it wrong mis-pads a column on every frame.
*/
const WIDE_RANGES: ReadonlyArray<readonly [number, number]> = [
[0x1100, 0x115f],
[0x231a, 0x231b],
[0x23e9, 0x23ec],
[0x23f0, 0x23f0],
[0x23f3, 0x23f3],
[0x25fd, 0x25fe],
[0x2614, 0x2615],
[0x2648, 0x2653],
[0x267f, 0x267f],
[0x2693, 0x2693],
[0x26a1, 0x26a1],
[0x26aa, 0x26ab],
[0x26bd, 0x26be],
[0x26c4, 0x26c5],
[0x26ce, 0x26ce],
[0x26d4, 0x26d4],
[0x26ea, 0x26ea],
[0x26f2, 0x26f3],
[0x26f5, 0x26f5],
[0x26fa, 0x26fa],
[0x26fd, 0x26fd],
[0x2705, 0x2705],
[0x270a, 0x270b],
[0x2728, 0x2728],
[0x274c, 0x274c],
[0x274e, 0x274e],
[0x2753, 0x2755],
[0x2757, 0x2757],
[0x2795, 0x2797],
[0x27b0, 0x27b0],
[0x27bf, 0x27bf],
[0x2b1b, 0x2b1c],
[0x2b50, 0x2b50],
[0x2b55, 0x2b55],
[0x2e80, 0x303e],
[0x3041, 0x33ff],
[0x3400, 0x4dbf],
[0x4e00, 0x9fff],
[0xa000, 0xa4cf],
[0xa960, 0xa97f],
[0xac00, 0xd7a3],
[0xf900, 0xfaff],
[0xfe10, 0xfe19],
[0xfe30, 0xfe6f],
[0xff00, 0xff60],
[0xffe0, 0xffe6],
[0x1f004, 0x1f004],
[0x1f0cf, 0x1f0cf],
[0x1f18e, 0x1f18e],
[0x1f191, 0x1f19a],
[0x1f200, 0x1f320],
[0x1f32d, 0x1f335],
[0x1f337, 0x1f37c],
[0x1f37e, 0x1f393],
[0x1f3a0, 0x1f3ca],
[0x1f3cf, 0x1f3d3],
[0x1f3e0, 0x1f3f0],
[0x1f3f4, 0x1f3f4],
[0x1f3f8, 0x1f43e],
[0x1f440, 0x1f440],
[0x1f442, 0x1f4fc],
[0x1f4ff, 0x1f53d],
[0x1f54b, 0x1f54e],
[0x1f550, 0x1f567],
[0x1f57a, 0x1f57a],
[0x1f595, 0x1f596],
[0x1f5a4, 0x1f5a4],
[0x1f5fb, 0x1f64f],
[0x1f680, 0x1f6c5],
[0x1f6cc, 0x1f6cc],
[0x1f6d0, 0x1f6d2],
[0x1f6eb, 0x1f6ec],
[0x1f6f4, 0x1f6fc],
[0x1f7e0, 0x1f7eb],
[0x1f90c, 0x1f93a],
[0x1f93c, 0x1f945],
[0x1f947, 0x1f9ff],
[0x1fa70, 0x1faff],
[0x20000, 0x2fffd],
[0x30000, 0x3fffd],
];
function inRanges(cp: number, ranges: ReadonlyArray<readonly [number, number]>): boolean {
for (const [lo, hi] of ranges) {
if (cp < lo) return false;
if (cp <= hi) return true;
}
return false;
}
/** Columns one code point advances the cursor by: 0, 1 or 2. */
export function charWidth(codePoint: number): number {
if (codePoint < 0x20 || (codePoint >= DEL && codePoint <= 0x9f)) return 0;
if (inRanges(codePoint, ZERO_WIDTH_RANGES)) return 0;
if (inRanges(codePoint, WIDE_RANGES)) return 2;
return 1;
}
/** Display width of a string: escape sequences take no columns, CJK takes two. */
export function visibleWidth(text: string): number {
let width = 0;
let i = 0;
while (i < text.length) {
const code = text.charCodeAt(i);
if (code === ESC) {
i = readEscape(text, i).next;
continue;
}
if (isC1(code)) {
i = readC1(text, i);
continue;
}
if (code < 0x20 || code === DEL) {
i++;
continue;
}
const cp = text.codePointAt(i) as number;
i += cp > 0xffff ? 2 : 1;
width += charWidth(cp);
}
return width;
}
// ─────────────────────────────────────────────────────────────────────────────
// Raw stream to display lines
// ─────────────────────────────────────────────────────────────────────────────
/** One printed code point (plus any combining marks) and the SGR state under it. */
interface Cell {
text: string;
sgr: string;
}
/**
* Replay cells into a string, emitting an SGR change only where the state
* actually changes and closing the line so it is self-contained.
*/
function renderCells(cells: Cell[]): string {
let out = '';
let active = '';
for (const cell of cells) {
if (cell.sgr !== active) {
if (active !== '') out += SGR_RESET;
out += cell.sgr;
active = cell.sgr;
}
out += cell.text;
}
if (active !== '') out += SGR_RESET;
return out;
}
/**
* Turn a raw terminal stream into display lines: SGR preserved, every other
* escape sequence dropped, `\r` treated as a return to column 0 (the following
* text overwrites what is there), tabs expanded, other control characters
* dropped.
*
* Splitting matches `String.split('\n')`, so `''` yields `['']` and a trailing
* newline yields a trailing empty line.
*/
/**
* Glyphs a CLI draws as chrome that a plain terminal font very often has no
* coverage for, and the ASCII that means the same thing.
*
* ⚠️ This is NOT a substitute for the glyph TIER. The tier answers "can this
* terminal do Unicode at all", which is a locale question, and it says yes for
* exactly the terminals this table exists for: a beta tester's font rendered
* `·`, `─`, `│` and `▶` perfectly while drawing claude's `❯` prompt and its
* `⏵⏵` mode marker as empty boxes. Coverage is per-glyph and undetectable from
* here, so the rare ones are folded and the common ones are left alone.
*
* Kept deliberately SHORT. Every entry is a glyph seen rendering as tofu in a
* real terminal, not a guess, and each maps to the arrow it already looks like.
*/
const PREVIEW_GLYPH_FOLD: ReadonlyMap<string, string> = new Map([
['\u276F', '>'], // ❯ heavy right-pointing angle quotation mark (claude, starship, zsh prompts)
['\u276E', '<'], // ❮
['\u23F5', '>'], // ⏵ black medium right-pointing triangle (claude's bypass-permissions marker)
['\u23F4', '<'], // ⏴
['\u23F6', '^'], // ⏶
['\u23F7', 'v'], // ⏷
['\u2771', '>'], // ❱
['\u2770', '<'], // ❰
// claude's own working/done spinner cycles through these, and they are the
// same sparse-Dingbats class as `❯`: the animated line is exactly where a
// reader looks, so tofu there is the most visible kind.
['\u2722', '*'], // ✢
['\u2733', '*'], // ✳
['\u2217', '*'], // ∗
['\u273B', '*'], // ✻
['\u273D', '*'], // ✽
['\u2734', '*'], // ✴
['\u26A0', '!'], // ⚠ Misc Symbols, and emoji-presentation on many terminals
]);
/**
* Replace preview glyphs a plain font is likely to draw as an empty box.
*
* Applied to ANOTHER program's output on its way into the preview pane, never
* to the TUI's own chrome, and skipped at the `nerd` tier where the user has
* declared a font that can draw anything.
*/
export function foldPreviewGlyphs(line: string): string {
let out = '';
for (const char of line) out += PREVIEW_GLYPH_FOLD.get(char) ?? char;
return out;
}
export function toDisplayLines(raw: string): string[] {
const lines: string[] = [];
let cells: Cell[] = [];
let col = 0;
let active: string[] = [];
let sgr = '';
const endLine = (): void => {
lines.push(renderCells(cells));
cells = [];
col = 0;
};
/**
* Park the write position at a column, padding the gap so the cell array
* never grows a hole (a hole would crash the replay, and a stream can address
* any column it likes).
*/
const moveTo = (column: number): void => {
const target = Math.min(column, MAX_LINE_CELLS);
while (cells.length < target) cells.push({ text: ' ', sgr: '' });
col = target;
};
const write = (text: string, width: number): void => {
if (width === 0) {
// A combining mark belongs to the character it follows, never to a cell
// of its own: keeping them together is what stops a clip from severing
// an accent from its base letter.
if (col > 0) cells[col - 1].text += text;
return;
}
cells[col] = { text, sgr };
col++;
};
let i = 0;
while (i < raw.length) {
const code = raw.charCodeAt(i);
if (code === ESC) {
const scan = readEscape(raw, i);
if (scan.sgr !== undefined) {
active = applySgr(active, scan.sgr);
sgr = active.join('');
} else if (scan.row === 1 && scan.column === 1) {
// ⚠️ A HOME is a full-screen app announcing that it is repainting from
// the top, and everything already on screen is about to be overwritten
// in place. This replay is line-based and cannot overwrite, so the
// faithful equivalent is to start over — without it every repaint was
// APPENDED, and a claude pane's tail carried fifty stacked copies of
// the same frame. The preview then showed the last N lines, which on a
// tall terminal spanned two of them (reported from the beta as the
// overview showing the session twice).
lines.length = 0;
cells = [];
col = 0;
} else if (scan.column !== undefined) {
// Column 1 is a fresh row, which is the only thing a repainting TUI
// gives us to split lines on.
if (scan.column <= 1) endLine();
else moveTo(scan.column - 1);
}
i = scan.next;
continue;
}
if (isC1(code)) {
i = readC1(raw, i);
continue;
}
if (code === 0x0a) {
endLine();
i++;
continue;
}
if (code === 0x0d) {
col = 0;
i++;
continue;
}
if (code === 0x09) {
const stop = TAB_WIDTH - (col % TAB_WIDTH);
for (let n = 0; n < stop; n++) write(' ', 1);
i++;
continue;
}
if (code < 0x20 || code === DEL) {
i++;
continue;
}
const cp = raw.codePointAt(i) as number;
const text = String.fromCodePoint(cp);
i += text.length;
write(text, charWidth(cp));
}
endLine();
return lines;
}
/**
* The parameter bytes plus final byte of a CSI sequence whose `ESC [` was cut
* off. Requires at least one parameter byte, so ordinary text starting with a
* letter is never mistaken for one.
*/
const SEVERED_CSI = /^[0-9;?:<>=]+[A-Za-z]/;
/**
* Drop the remains of an escape sequence a byte-sliced tail begins in the
* middle of.
*
* `GET /api/sessions/:id/terminal?tail=N` cuts the buffer at a byte offset, so
* a tail can start inside `ESC [ 12 ; 1 H` and hand the parser `;1H` as text,
* which is exactly what it then prints (observed against a live Claude pane).
* Only the severed head is dropped, never a whole line.
*/
export function dropSeveredEscape(raw: string): string {
return raw.replace(SEVERED_CSI, '');
}
/**
* Drop every escape sequence, keeping the visible text. Needed because the
* preview carries the session's OWN colors: under NO_COLOR the frame must not
* smuggle them back in.
*/
export function stripStyles(text: string): string {
let out = '';
let i = 0;
while (i < text.length) {
const code = text.charCodeAt(i);
if (code === ESC) {
i = readEscape(text, i).next;
continue;
}
if (isC1(code)) {
i = readC1(text, i);
continue;
}
if (code < 0x20 || code === DEL) {
i++;
continue;
}
const cp = text.codePointAt(i) as number;
const size = cp > 0xffff ? 2 : 1;
out += text.slice(i, i + size);
i += size;
}
return out;
}
// ─────────────────────────────────────────────────────────────────────────────
// Clipping and padding
// ─────────────────────────────────────────────────────────────────────────────
/**
* Clip a line that carries SGR to `width` display columns, keeping the styling
* that is active up to the clip point and closing it with a reset. Never splits
* a code point, a combining sequence or an escape sequence, and never emits
* half of a double-width character (the cell is dropped instead).
*/
export function clipStyledLine(line: string, width: number): string {
if (width <= 0) return '';
let out = '';
let used = 0;
let active: string[] = [];
// Styles are emitted lazily, right before the character that wears them, so a
// sequence sitting exactly on the clip boundary is not carried into a line it
// no longer styles.
let emitted = '';
let i = 0;
while (i < line.length) {
const code = line.charCodeAt(i);
if (code === ESC) {
const scan = readEscape(line, i);
if (scan.sgr !== undefined) active = applySgr(active, scan.sgr);
i = scan.next;
continue;
}
if (isC1(code)) {
i = readC1(line, i);
continue;
}
if (code < 0x20 || code === DEL) {
i++;
continue;
}
const cp = line.codePointAt(i) as number;
const w = charWidth(cp);
if (used + w > width) break;
const style = active.join('');
if (style !== emitted) {
if (emitted !== '') out += SGR_RESET;
out += style;
emitted = style;
}
out += String.fromCodePoint(cp);
used += w;
i += cp > 0xffff ? 2 : 1;
}
return emitted !== '' ? out + SGR_RESET : out;
}
/**
* Pad or clip to exactly `width` display columns. A clip that lands on a
* double-width boundary leaves one column short, so the pad runs after it.
*/
export function padDisplay(text: string, width: number): string {
if (width <= 0) return '';
const w = visibleWidth(text);
if (w === width) return text;
if (w < width) return text + ' '.repeat(width - w);
const clipped = clipStyledLine(text, width);
return clipped + ' '.repeat(Math.max(0, width - visibleWidth(clipped)));
}
+2696
View File
File diff suppressed because it is too large Load Diff
+137
View File
@@ -0,0 +1,137 @@
/**
* @fileoverview Pure reading of an approvals-inbox item: what the card says,
* which keys are live for it, and which of them just appeared.
*
* This is the half of "answer the dialog from the dashboard" that can be stated
* as a function of the item. The IO half (`POST /api/approvals/:id/answer`)
* lives in `tui-client.ts`, and the server re-captures the pane before it aims
* any keystroke, so a card that went stale is refused rather than mis-answered.
*
* The key matrix is deliberately narrow, because the alternative is typing a
* digit into whatever now has focus:
*
* | kind | y | n | 1-9 |
* | ---------- | ------------ | ---------------------- | ------------------------- |
* | permission | approve | the parsed "No" option, | only digits the server |
* | question | approve | else Esc | actually parsed off screen |
* | idle | not a dialog: `p` (the composer) is the reply path |
*
* A digit that is not among the parsed options returns null, which is what lets
* the caller fall back to the list's own 1-9 jump instead of sending a keystroke
* the dialog has no answer for.
*
* PURE: no IO, no timers, no `process.*`.
*
* @module tui/tui-approvals
*/
import type { ApprovalItem, ApprovalOption } from '../web/approval-inbox.js';
import type { TuiApprovalAnswer } from './tui-client.js';
/** Card severity, in the same red/yellow vocabulary the web inbox uses. */
export type TuiApprovalTone = 'err' | 'warn';
export interface TuiApprovalCard {
tone: TuiApprovalTone;
/** One line: what is being asked. */
title: string;
/** Extra context, one entry per line, already trimmed. May be empty. */
detail: string[];
/** Numbered choices parsed off the pane, empty when the frame did not parse. */
options: ApprovalOption[];
/** What the user can press right now, in words. */
hint: string;
}
/** Longest single line the card contributes before the renderer clips it. */
const MAX_CARD_TEXT = 400;
function clean(text: string | undefined): string {
return (text ?? '').replace(/\s+/g, ' ').trim().slice(0, MAX_CARD_TEXT);
}
export function approvalTone(item: ApprovalItem): TuiApprovalTone {
return item.kind === 'idle' ? 'warn' : 'err';
}
/**
* What the card says. Permission prompts lead with the tool (that is the whole
* question), questions lead with their message, and an idle prompt says what it
* is, since there is nothing to approve.
*/
export function approvalCard(item: ApprovalItem): TuiApprovalCard {
const options = item.options ?? [];
const message = clean(item.message);
const summary = clean(item.toolSummary) || clean(item.toolName);
if (item.kind === 'idle') {
return {
tone: 'warn',
title: message || 'waiting for your reply',
detail: [],
options: [],
hint: 'p to reply',
};
}
const title =
item.kind === 'permission'
? `requests: ${summary || 'permission'}`
: message || `question: ${summary || 'Claude is asking'}`;
const detail: string[] = [];
if (item.kind === 'permission' && message && message !== summary) detail.push(message);
return {
tone: 'err',
title,
detail,
options,
hint: options.length > 0 ? 'y approve · n deny · digit chooses' : 'y approve · n deny',
};
}
/**
* The parsed option that means "no". Claude renders it as `3. No, tell Claude
* what to do (esc)`, and answering with its digit is the same keystroke the
* dialog itself is waiting for; without a parsed one the answer route's `deny`
* sends Esc, which every dialog understands.
*/
export function approvalDenyOption(item: ApprovalItem): number | null {
const match = (item.options ?? []).find((option) => /^no\b/i.test(option.label));
return match ? match.n : null;
}
/**
* The answer one key produces, or null when that key means nothing here (so the
* caller can let its normal binding through).
*/
export function approvalAnswerForKey(item: ApprovalItem, key: string): TuiApprovalAnswer | null {
// An idle prompt has no dialog on screen: a digit or a `1` would land in the
// composer as text. The card points at `p` instead.
if (item.kind === 'idle') return null;
if (key === 'y') return { action: 'approve' };
if (key === 'n') {
const deny = approvalDenyOption(item);
return deny === null ? { action: 'deny' } : { action: 'option', option: deny };
}
if (key >= '1' && key <= '9') {
const option = Number.parseInt(key, 10);
return (item.options ?? []).some((entry) => entry.n === option) ? { action: 'option', option } : null;
}
return null;
}
/**
* Ids in `items` that `seen` has not recorded. The bell rings for these and for
* nothing else, which is what keeps a repaint (or a refetch that returns the
* same pending item) silent.
*
* Answered ids stay in `seen` on purpose: the inbox restores an item under its
* ORIGINAL id when a write fails, and re-ringing for a prompt the user already
* heard about is worse than missing one.
*/
export function newApprovalIds(seen: ReadonlySet<string>, items: readonly ApprovalItem[]): string[] {
const fresh: string[] = [];
for (const item of items) if (!seen.has(item.id) && !fresh.includes(item.id)) fresh.push(item.id);
return fresh;
}
File diff suppressed because it is too large Load Diff
+205
View File
@@ -0,0 +1,205 @@
/**
* @fileoverview Pure single-line editor behind the TUI's prompt composer (`p`)
* and search query (`/`).
*
* Text is held as CODE POINTS rather than a string, because every operation
* here is index-based and a cursor that can land inside a surrogate pair
* eventually deletes half an emoji. Combining marks are their own entries: they
* are zero-width, so they neither move the cursor's column nor cost a cell, and
* backspace peeling one off a base letter is what a terminal editor does.
*
* Scrolling is derived, never remembered implicitly: `composerScroll()` takes
* the width and returns the state whose window holds the cursor, which is what
* keeps "what the footer shows" a function of the state plus the terminal width
* rather than of the order the user pressed keys in.
*
* PURE: no IO, no timers, no `process.*`. Enter and Escape are reported as
* `submit`/`cancel` rather than acted on, since only the caller knows whether
* Enter means "send this prompt" or "open the highlighted search result".
*
* @module tui/tui-composer
*/
import { charWidth } from './tui-ansi.js';
import type { TuiInputEvent } from './tui-keys.js';
export interface TuiComposerState {
/** Code points. `chars.join('')` is the text. */
readonly chars: readonly string[];
/** 0..chars.length. The cursor sits BEFORE `chars[cursor]`. */
readonly cursor: number;
/** First visible code point, as `composerScroll()` last resolved it. */
readonly scroll: number;
}
export function createComposer(text = ''): TuiComposerState {
const chars = [...text];
return { chars, cursor: chars.length, scroll: 0 };
}
export function composerText(state: TuiComposerState): string {
return state.chars.join('');
}
function withChars(chars: readonly string[], cursor: number, scroll: number): TuiComposerState {
const clampedCursor = Math.min(Math.max(0, cursor), chars.length);
return { chars, cursor: clampedCursor, scroll: Math.min(Math.max(0, scroll), chars.length) };
}
/** Insert typed text at the cursor. Newlines are stripped: this is one line. */
export function composerInsert(state: TuiComposerState, value: string): TuiComposerState {
const inserted = [...value.replace(/[\r\n]+/g, ' ')];
if (inserted.length === 0) return state;
const chars = [...state.chars.slice(0, state.cursor), ...inserted, ...state.chars.slice(state.cursor)];
return withChars(chars, state.cursor + inserted.length, state.scroll);
}
/** Delete the code point before the cursor. */
export function composerBackspace(state: TuiComposerState): TuiComposerState {
if (state.cursor === 0) return state;
const chars = [...state.chars.slice(0, state.cursor - 1), ...state.chars.slice(state.cursor)];
return withChars(chars, state.cursor - 1, state.scroll);
}
/** Delete the code point under the cursor (the Delete key). */
export function composerDelete(state: TuiComposerState): TuiComposerState {
if (state.cursor >= state.chars.length) return state;
const chars = [...state.chars.slice(0, state.cursor), ...state.chars.slice(state.cursor + 1)];
return withChars(chars, state.cursor, state.scroll);
}
/** Delete back to the start of the word before the cursor (Ctrl+W). */
export function composerDeleteWord(state: TuiComposerState): TuiComposerState {
let start = state.cursor;
while (start > 0 && state.chars[start - 1] === ' ') start--;
while (start > 0 && state.chars[start - 1] !== ' ') start--;
if (start === state.cursor) return state;
const chars = [...state.chars.slice(0, start), ...state.chars.slice(state.cursor)];
return withChars(chars, start, state.scroll);
}
export function composerMove(state: TuiComposerState, delta: number): TuiComposerState {
const cursor = Math.min(Math.max(0, state.cursor + Math.trunc(delta)), state.chars.length);
return cursor === state.cursor ? state : withChars(state.chars, cursor, state.scroll);
}
export function composerHome(state: TuiComposerState): TuiComposerState {
return state.cursor === 0 ? state : withChars(state.chars, 0, state.scroll);
}
export function composerEnd(state: TuiComposerState): TuiComposerState {
return state.cursor === state.chars.length ? state : withChars(state.chars, state.chars.length, state.scroll);
}
export function composerClear(state: TuiComposerState): TuiComposerState {
return state.chars.length === 0 ? state : { chars: [], cursor: 0, scroll: 0 };
}
/** Display columns of `chars[from..to)`. */
function widthOf(chars: readonly string[], from: number, to: number): number {
let width = 0;
for (let i = from; i < to; i++) width += charWidth(chars[i].codePointAt(0) ?? 0);
return width;
}
/**
* Resolve `scroll` so the cursor is inside a window `width` columns wide,
* scrolling the minimum needed. One column is reserved for the cursor itself,
* so a cursor at the end of the text still has a cell to sit in instead of
* hanging one past the edge where the terminal would wrap it.
*/
export function composerScroll(state: TuiComposerState, width: number): TuiComposerState {
const usable = Math.max(0, Math.trunc(width) - 1);
let scroll = Math.min(Math.max(0, state.scroll), state.cursor);
while (scroll < state.cursor && widthOf(state.chars, scroll, state.cursor) > usable) scroll++;
return scroll === state.scroll ? state : { chars: state.chars, cursor: state.cursor, scroll };
}
export interface TuiComposerWindow {
/** The visible slice of the text. */
text: string;
/** Cursor offset in display columns from the start of `text`. */
cursorColumn: number;
/** Resolved first visible code point (may differ from `state.scroll`). */
scroll: number;
}
/**
* The slice the footer draws plus where the terminal cursor belongs. The scroll
* is resolved here too, so a renderer that never writes state back still shows
* the cursor.
*/
export function composerWindow(state: TuiComposerState, width: number): TuiComposerWindow {
const columns = Math.max(1, Math.trunc(width));
const scrolled = composerScroll(state, columns);
const { chars, cursor, scroll } = scrolled;
let used = 0;
let end = scroll;
while (end < chars.length) {
const next = charWidth(chars[end].codePointAt(0) ?? 0);
if (used + next > columns) break;
used += next;
end++;
}
return {
text: chars.slice(scroll, Math.max(end, cursor)).join(''),
cursorColumn: widthOf(chars, scroll, cursor),
scroll,
};
}
export type TuiComposerStep =
| { kind: 'edit'; state: TuiComposerState }
| { kind: 'submit'; text: string }
| { kind: 'cancel' }
| { kind: 'ignore' };
/**
* One keystroke. Enter and Escape are REPORTED rather than applied: `p` sends
* the line while `/` opens the highlighted result, and only the caller knows
* which.
*/
export function composerStep(state: TuiComposerState, event: TuiInputEvent): TuiComposerStep {
switch (event.type) {
case 'char':
return { kind: 'edit', state: composerInsert(state, event.value) };
case 'backspace':
return { kind: 'edit', state: composerBackspace(state) };
case 'enter':
return { kind: 'submit', text: composerText(state) };
case 'escape':
return { kind: 'cancel' };
case 'key':
switch (event.name) {
case 'left':
return { kind: 'edit', state: composerMove(state, -1) };
case 'right':
return { kind: 'edit', state: composerMove(state, 1) };
case 'home':
return { kind: 'edit', state: composerHome(state) };
case 'end':
return { kind: 'edit', state: composerEnd(state) };
case 'delete':
return { kind: 'edit', state: composerDelete(state) };
default:
return { kind: 'ignore' };
}
case 'ctrl':
switch (event.key) {
case 'c':
return { kind: 'cancel' };
case 'a':
return { kind: 'edit', state: composerHome(state) };
case 'e':
return { kind: 'edit', state: composerEnd(state) };
case 'u':
return { kind: 'edit', state: composerClear(state) };
case 'w':
return { kind: 'edit', state: composerDeleteWord(state) };
default:
return { kind: 'ignore' };
}
default:
return { kind: 'ignore' };
}
}
+90
View File
@@ -0,0 +1,90 @@
/**
* @fileoverview Pure formatting of `GET /api/away-digest` into the lines the
* `g` overlay scrolls.
*
* The digest answers "what happened while I was away", so it is read top-down
* and never studied: every entry is one line (age, session, what happened), a
* long section is capped with a "… n more" tail rather than allowed to push the
* next section off screen, and the counts that matter live in the first line
* where they are visible without scrolling at all.
*
* PURE: no IO, no clock of its own (the caller passes `now`), no `process.*`.
*
* @module tui/tui-digest
*/
import { formatElapsed, formatTokens } from './tui-render.js';
import type { AwayDigestItem, AwayDigestResponse, AwayDigestSectionName } from '../web/away-digest.js';
/** Entries per section before the tail takes over. */
export const DIGEST_SECTION_LIMIT = 6;
const SECTION_ORDER: ReadonlyArray<readonly [AwayDigestSectionName, string]> = [
['needsAttention', 'NEEDS ATTENTION'],
['completed', 'COMPLETED'],
['stillRunning', 'STILL RUNNING'],
['idle', 'IDLE'],
['informational', 'INFO'],
];
const RANGE_WORDS: Record<string, string> = {
'since-last-visit': 'since your last visit',
'1h': 'the last hour',
today: 'today',
'24h': 'the last 24 hours',
custom: 'the selected window',
};
export interface TuiDigestOptions {
now: number;
sectionLimit?: number;
}
function ageColumn(item: AwayDigestItem, now: number): string {
const age = item.timestamp > 0 ? formatElapsed(now - item.timestamp) : '';
return age.padEnd(4);
}
function itemLine(item: AwayDigestItem, now: number): string {
const who = item.sessionName ?? item.sessionId?.slice(0, 8) ?? '';
const what = [item.title, item.detail].filter((part) => part && part.trim() !== '').join(' · ');
return ` ${ageColumn(item, now)} ${[who, what].filter((part) => part !== '').join(' ')}`.replace(/\s+$/, '');
}
/**
* The digest as display lines. The first line is the summary, then one block
* per non-empty section, then the token totals when the range had any.
*/
export function formatAwayDigest(digest: AwayDigestResponse, options: TuiDigestOptions): string[] {
const limit = Math.max(1, Math.trunc(options.sectionLimit ?? DIGEST_SECTION_LIMIT));
const { totals } = digest;
const lines: string[] = [
[
RANGE_WORDS[digest.range.range] ?? 'recently',
`${totals.sessionsCreated} started`,
`${totals.sessionsExited} exited`,
`${totals.activeSessions} running`,
].join(' · '),
];
let entries = 0;
for (const [key, label] of SECTION_ORDER) {
const items = digest.sections[key] ?? [];
if (items.length === 0) continue;
entries += items.length;
lines.push('', `${label} (${items.length})`);
for (const item of items.slice(0, limit)) lines.push(itemLine(item, options.now));
if (items.length > limit) lines.push(` … ${items.length - limit} more`);
}
if (entries === 0) lines.push('', 'nothing happened while you were away');
const tokens = [
formatTokens(totals.inputTokens ?? 0) ? `${formatTokens(totals.inputTokens ?? 0)} in` : '',
formatTokens(totals.outputTokens ?? 0) ? `${formatTokens(totals.outputTokens ?? 0)} out` : '',
typeof totals.estimatedCost === 'number' && totals.estimatedCost > 0 ? `$${totals.estimatedCost.toFixed(2)}` : '',
].filter((part) => part !== '');
if (tokens.length > 0) lines.push('', `tokens: ${tokens.join(' · ')}`);
return lines;
}
+240
View File
@@ -0,0 +1,240 @@
/**
* @fileoverview Pure byte-stream to input-event parser for raw-mode stdin.
*
* Stateful (a sequence can arrive split across reads, and a UTF-8 character can
* be split mid-code-point) but pure: it owns a byte buffer and nothing else, no
* stdin, no timers. The one timing decision a terminal forces on us stays with
* the caller: a lone ESC is indistinguishable from the start of an arrow key
* until something either follows it or does not, so the parser HOLDS a trailing
* ESC and the caller calls `flush()` after ~30ms of silence to turn it into an
* Escape event.
*
* Unknown sequences are swallowed rather than leaked as text: a stray
* `CSI 200~` must never end up typed into a prompt composer.
*
* @module tui/tui-keys
*/
/** Keys with a name rather than a character. */
export type TuiNamedKey =
| 'up'
| 'down'
| 'left'
| 'right'
| 'home'
| 'end'
| 'pageup'
| 'pagedown'
| 'delete'
| 'insert';
export type TuiMouseKind = 'press' | 'release' | 'wheel-up' | 'wheel-down';
/** Discriminated union, exhaustive-switch friendly (see `utils/assertNever`). */
export type TuiInputEvent =
| { type: 'char'; value: string }
| { type: 'enter' }
| { type: 'tab' }
| { type: 'backspace' }
| { type: 'escape' }
| { type: 'ctrl'; key: string }
| { type: 'alt'; value: string }
| { type: 'key'; name: TuiNamedKey }
| { type: 'mouse'; kind: TuiMouseKind; x: number; y: number; button: number };
export interface TuiKeyParser {
/** Decode a chunk. Incomplete tails are held for the next call. */
feed(chunk: Buffer | string): TuiInputEvent[];
/** Resolve a held ESC (the caller's disambiguation timer fired). */
flush(): TuiInputEvent[];
/** Bytes currently held back. Exposed for the ESC timer and for tests. */
pending(): number;
}
/**
* An unterminated sequence longer than this is not a sequence: the held bytes
* are dropped whole, so a garbage burst can neither wedge the parser nor leak
* its bytes into a prompt as typed characters.
*/
const MAX_PENDING_BYTES = 64;
/** Bytes in a UTF-8 sequence given its lead byte; 0 for a byte that cannot lead one. */
function utf8SequenceLength(lead: number): number {
if (lead < 0x80) return 1;
if (lead >= 0xc2 && lead <= 0xdf) return 2;
if (lead >= 0xe0 && lead <= 0xef) return 3;
if (lead >= 0xf0 && lead <= 0xf4) return 4;
return 0;
}
const CSI_FINAL_KEYS: Record<string, TuiNamedKey> = {
A: 'up',
B: 'down',
C: 'right',
D: 'left',
H: 'home',
F: 'end',
};
/** `CSI <n> ~` keys, by their first numeric parameter. */
const CSI_TILDE_KEYS: Record<number, TuiNamedKey> = {
1: 'home',
2: 'insert',
3: 'delete',
4: 'end',
5: 'pageup',
6: 'pagedown',
7: 'home',
8: 'end',
};
/** Result of trying to parse one sequence off the front of the buffer. */
type ParseStep = { consumed: number; events: TuiInputEvent[] } | 'incomplete';
const NOTHING: TuiInputEvent[] = [];
export function createKeyParser(): TuiKeyParser {
let buf: Buffer = Buffer.alloc(0);
/** Parse the CSI/SS3 sequence that starts at buf[0] === ESC. */
const parseEscape = (): ParseStep => {
if (buf.length < 2) return 'incomplete';
const second = buf[1];
// SS3 (`ESC O <final>`): the arrows/Home/End of application-cursor mode.
if (second === 0x4f) {
if (buf.length < 3) return 'incomplete';
const name = CSI_FINAL_KEYS[String.fromCharCode(buf[2])];
return { consumed: 3, events: name ? [{ type: 'key', name }] : NOTHING };
}
// ESC followed by a printable character IN THE SAME READ is Alt+that key:
// that is how every terminal sends a meta chord. A lone Esc cannot look
// like this, because a buffer holding only ESC returns 'incomplete' above
// and is flushed as `escape` when the read ends, which is the standard way
// to tell the two apart without a timer.
//
// ⚠️ Three characters are deliberately NOT treated as Alt chords, because
// the terminal uses them to introduce sequences and a chord is
// indistinguishable from one: `[` (CSI) and `O` (SS3) would swallow every
// arrow key, and `]` (OSC) would swallow a terminal's colour-query reply.
// Alt+[ and Alt+] therefore cannot exist in a terminal at all, which is why
// the list binds bare `[` and `]` for the same job.
if (second !== 0x5b) {
if (second >= 0x20 && second <= 0x7e && second !== 0x4f && second !== 0x5d) {
return { consumed: 2, events: [{ type: 'alt', value: String.fromCharCode(second) }] };
}
return { consumed: 1, events: [{ type: 'escape' }] };
}
let j = 2;
while (j < buf.length && buf[j] >= 0x30 && buf[j] <= 0x3f) j++;
while (j < buf.length && buf[j] >= 0x20 && buf[j] <= 0x2f) j++;
if (j >= buf.length) return 'incomplete';
const final = String.fromCharCode(buf[j]);
const params = buf.subarray(2, j).toString('latin1');
const consumed = j + 1;
// X10 mouse (`CSI M` + 3 raw bytes): swallowed, but its payload bytes must
// be consumed or they would surface as typed characters.
if (params === '' && final === 'M') {
if (buf.length < consumed + 3) return 'incomplete';
return { consumed: consumed + 3, events: NOTHING };
}
if (params.startsWith('<') && (final === 'M' || final === 'm')) {
return { consumed, events: parseSgrMouse(params.slice(1), final) };
}
if (final === '~') {
const name = CSI_TILDE_KEYS[Number.parseInt(params, 10)];
return { consumed, events: name ? [{ type: 'key', name }] : NOTHING };
}
// Modified arrows (`CSI 1;5A`) carry the same final byte; the modifier is
// dropped rather than exposed, since nothing in the keymap wants it yet.
const named = CSI_FINAL_KEYS[final];
return { consumed, events: named ? [{ type: 'key', name: named }] : NOTHING };
};
const parseSgrMouse = (params: string, final: string): TuiInputEvent[] => {
const parts = params.split(';');
if (parts.length < 3) return NOTHING;
const button = Number.parseInt(parts[0], 10);
const x = Number.parseInt(parts[1], 10);
const y = Number.parseInt(parts[2], 10);
if (!Number.isFinite(button) || !Number.isFinite(x) || !Number.isFinite(y)) return NOTHING;
if (button >= 64) {
// 64 = wheel up, 65 = wheel down (the low bit is the direction).
const kind: TuiMouseKind = (button & 1) === 1 ? 'wheel-down' : 'wheel-up';
return [{ type: 'mouse', kind, x, y, button }];
}
// Motion reports (bit 32) would fire on every pixel of a drag; nothing in
// the keymap consumes them, so they are swallowed here rather than upstream.
if ((button & 32) === 32) return NOTHING;
return [{ type: 'mouse', kind: final === 'M' ? 'press' : 'release', x, y, button }];
};
/** Parse one non-escape byte (or one UTF-8 character) off the front. */
const parseByte = (): ParseStep => {
const b = buf[0];
// LF counts as Enter because some terminals send it for Return; the cost is
// that Ctrl+J is not bindable, which no key in the plan's keymap wants.
if (b === 0x0d || b === 0x0a) return { consumed: 1, events: [{ type: 'enter' }] };
if (b === 0x09) return { consumed: 1, events: [{ type: 'tab' }] };
if (b === 0x7f || b === 0x08) return { consumed: 1, events: [{ type: 'backspace' }] };
if (b === 0x00) return { consumed: 1, events: [{ type: 'ctrl', key: '@' }] };
if (b >= 0x01 && b <= 0x1a) {
return { consumed: 1, events: [{ type: 'ctrl', key: String.fromCharCode(b + 0x60) }] };
}
if (b >= 0x1c && b <= 0x1f) {
return { consumed: 1, events: [{ type: 'ctrl', key: String.fromCharCode(b + 0x40) }] };
}
const length = utf8SequenceLength(b);
if (length === 0) return { consumed: 1, events: NOTHING };
if (buf.length < length) return 'incomplete';
const value = buf.subarray(0, length).toString('utf8');
// A lead byte followed by junk decodes to U+FFFD; that is corruption on the
// wire, not something to type into a composer. Only the bad lead byte is
// dropped, so whatever valid input followed it still decodes.
if (value.includes('�')) return { consumed: 1, events: NOTHING };
return { consumed: length, events: [{ type: 'char', value }] };
};
/** Drain the buffer, stopping at the first incomplete sequence. */
const drain = (events: TuiInputEvent[]): void => {
while (buf.length > 0) {
const step = buf[0] === 0x1b ? parseEscape() : parseByte();
if (step === 'incomplete') {
if (buf.length > MAX_PENDING_BYTES) buf = Buffer.alloc(0);
return;
}
for (const event of step.events) events.push(event);
buf = buf.subarray(step.consumed);
}
};
return {
feed(chunk: Buffer | string): TuiInputEvent[] {
const bytes = typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : chunk;
buf = buf.length === 0 ? Buffer.from(bytes) : Buffer.concat([buf, bytes]);
const events: TuiInputEvent[] = [];
drain(events);
return events;
},
flush(): TuiInputEvent[] {
const events: TuiInputEvent[] = [];
if (buf.length > 0 && buf[0] === 0x1b) {
events.push({ type: 'escape' });
buf = buf.subarray(1);
drain(events);
}
return events;
},
pending(): number {
return buf.length;
},
};
}
+137
View File
@@ -0,0 +1,137 @@
/**
* @fileoverview Pure responsive layout math for the TUI frame.
*
* One rule decides the shape: below 72 columns (Termius, iPhone portrait) the
* preview pane is gone and rows take two lines, which is the constraint the
* `sc` chooser was built around and the reason it is still usable on a phone.
* Above it, a clamped sidebar carries the session list and the preview takes
* the rest.
*
* Rectangles are 1-based (row 1, column 1 is the top-left cell) because that is
* what `ESC [ <row>;<col> H` takes, and every region is clamped to a
* non-negative size so a 5x5 terminal degrades instead of producing negative
* widths that would crash the renderer.
*
* @module tui/tui-layout
*/
import type { TuiConnectionStatus } from './tui-types.js';
/** Width at which the preview pane is dropped and rows become two lines. */
export const NARROW_BREAKPOINT = 72;
/** Sidebar clamp: narrower than this and a session name stops being readable. */
export const SIDEBAR_MIN_WIDTH = 34;
/** Sidebar clamp: wider than this is wasted on a list of short names. */
export const SIDEBAR_MAX_WIDTH = 44;
/** A preview thinner than this shows nothing useful, so the layout goes narrow instead. */
export const PREVIEW_MIN_WIDTH = 24;
/** Share of the width the sidebar aims for between the clamps. */
const SIDEBAR_RATIO = 0.36;
export interface TuiRect {
/** 1-based terminal row of the first line. */
row: number;
/** 1-based terminal column of the first cell. */
col: number;
width: number;
height: number;
}
export interface TuiLayoutOptions {
/**
* Reserve one line under the header for the connection banner. The caller
* decides with `needsBanner(model.connection)`, so layout stays pure math.
*/
banner?: boolean;
}
export interface TuiLayout {
cols: number;
rows: number;
/** No preview pane, two-line rows. */
narrow: boolean;
/** Terminal lines one session row occupies. */
rowHeight: 1 | 2;
header: TuiRect;
/** Connection banner, when the caller asked for one and there was room. */
banner: TuiRect | null;
/** Everything between header and footer, banner included. */
body: TuiRect;
/** The session list. */
list: TuiRect;
/** The one-column rule between list and preview; null in narrow mode. */
divider: TuiRect | null;
/** The preview pane; null in narrow mode. */
preview: TuiRect | null;
footer: TuiRect;
}
/** Which connection states get a banner line under the header. */
export function needsBanner(connection: TuiConnectionStatus): boolean {
return connection !== 'connected';
}
function clamp(value: number, min: number, max: number): number {
return Math.min(max, Math.max(min, value));
}
/**
* Rectangles for one frame at `cols` x `rows`.
*
* The header always exists; the footer appears from 2 rows up; the body is
* whatever is left, which may legitimately be zero lines high.
*/
export function computeLayout(cols: number, rows: number, options: TuiLayoutOptions = {}): TuiLayout {
const width = Math.max(1, Math.floor(cols) || 1);
const height = Math.max(1, Math.floor(rows) || 1);
const headerHeight = 1;
const footerHeight = height >= 2 ? 1 : 0;
const bodyHeight = Math.max(0, height - headerHeight - footerHeight);
const bodyRow = headerHeight + 1;
const header: TuiRect = { row: 1, col: 1, width, height: headerHeight };
const footer: TuiRect = { row: height, col: 1, width, height: footerHeight };
const body: TuiRect = { row: bodyRow, col: 1, width, height: bodyHeight };
const bannerHeight = options.banner === true && bodyHeight > 0 ? 1 : 0;
const banner: TuiRect | null = bannerHeight > 0 ? { row: bodyRow, col: 1, width, height: 1 } : null;
const contentRow = bodyRow + bannerHeight;
const contentHeight = Math.max(0, bodyHeight - bannerHeight);
const sidebarTarget = Math.floor(width * SIDEBAR_RATIO);
const sidebarWidth = clamp(sidebarTarget, SIDEBAR_MIN_WIDTH, SIDEBAR_MAX_WIDTH);
const previewWidth = width - sidebarWidth - 1;
const narrow = width < NARROW_BREAKPOINT || previewWidth < PREVIEW_MIN_WIDTH;
if (narrow) {
return {
cols: width,
rows: height,
narrow: true,
rowHeight: 2,
header,
banner,
body,
list: { row: contentRow, col: 1, width, height: contentHeight },
divider: null,
preview: null,
footer,
};
}
return {
cols: width,
rows: height,
narrow: false,
rowHeight: 1,
header,
banner,
body,
list: { row: contentRow, col: 1, width: sidebarWidth, height: contentHeight },
divider: { row: contentRow, col: sidebarWidth + 1, width: 1, height: contentHeight },
preview: { row: contentRow, col: sidebarWidth + 2, width: previewWidth, height: contentHeight },
footer,
};
}
+562
View File
@@ -0,0 +1,562 @@
/**
* @fileoverview Pure state, classification and grouping for the TUI dashboard.
*
* Classification speaks the web UI's language on purpose (red blocked, yellow
* waiting, green working, muted idle), because a user who has both surfaces
* open must never have to translate between them. The inputs are the ones the
* server already computes: a unified-list row and, when the session is blocked,
* the approvals-inbox item that blocks it. Nothing here screen-scrapes.
*
* Selection is tracked by session id, never by row index: rows re-sort under
* the cursor constantly (a session starts working, an approval lands), and an
* index-tracked cursor would silently move the selection to a different
* session between two keystrokes.
*
* PURE: no IO, no timers, no `process.*`. The store mutates its own state and
* nothing else.
*
* @module tui/tui-model
*/
import type { SearchResultGroup, SearchSourceType } from '../types/search.js';
import type { ApprovalItem } from '../web/approval-inbox.js';
import type {
TuiConfirmState,
TuiConnectionStatus,
TuiDigestState,
TuiGroup,
TuiGroupKey,
TuiHeaderInfo,
TuiMessage,
TuiPickerState,
TuiPreview,
TuiPromptState,
TuiRenderModel,
TuiRow,
TuiSearchEntry,
TuiSearchState,
TuiSessionRow,
TuiSessionState,
TuiUiMode,
} from './tui-types.js';
/** How many history rows the RECENT group shows before it stops being a dashboard. */
export const DEFAULT_RECENT_LIMIT = 8;
export const GROUP_ORDER: readonly TuiGroupKey[] = ['needs-you', 'working', 'idle', 'recent'];
export const GROUP_LABELS: Record<TuiGroupKey, string> = {
'needs-you': 'NEEDS YOU',
working: 'WORKING',
idle: 'IDLE',
recent: 'RECENT',
};
const STATE_GROUP: Record<TuiSessionState, TuiGroupKey> = {
'blocked-question': 'needs-you',
'blocked-permission': 'needs-you',
waiting: 'needs-you',
working: 'working',
idle: 'idle',
recent: 'recent',
};
/** A row is live when the unified merge saw it in the in-memory session map. */
export function isLiveRow(session: TuiSessionRow): boolean {
return Array.isArray(session.sources) && session.sources.includes('live');
}
/**
* Classify one row.
*
* Order matters and mirrors `_mobileOverviewState()` in the web UI: a pending
* prompt outranks everything (it is literally blocking the agent), and it
* outranks a stale `busy` status because the hook is the newer signal. An
* errored session has no state of its own here and joins the waiting tier,
* since it is equally something only a human can clear.
*/
export function classifySession(session: TuiSessionRow, approval?: ApprovalItem): TuiSessionState {
if (!isLiveRow(session)) return 'recent';
if (approval) {
if (approval.kind === 'permission') return 'blocked-permission';
if (approval.kind === 'question') return 'blocked-question';
return 'waiting';
}
if (session.status === 'error') return 'waiting';
if (session.isWorking === true || session.status === 'busy') return 'working';
return 'idle';
}
/**
* Epoch ms the session entered its current state, which is what the intra-group
* ordering sorts on. 0 when nothing usable is known.
*
* A WORKING pane repaints about once a second, so its `lastActivityAt` is
* always "now" and would report every running turn as freshly started; the
* turn's own start is the pane's last Enter.
*/
export function stateSince(state: TuiSessionState, session: TuiSessionRow, approval?: ApprovalItem): number {
if (approval) return approval.createdAt;
if (state === 'working') return session.lastSubmitAt ?? session.createdAt ?? 0;
return session.lastActivityAt ?? session.createdAt ?? 0;
}
/** Classify a batch of rows against the pending approvals, keyed by session id. */
export function buildRows(
sessions: readonly TuiSessionRow[],
approvals: ReadonlyMap<string, ApprovalItem> = new Map()
): TuiRow[] {
return sessions.map((session) => {
const approval = approvals.get(session.sessionId);
const state = classifySession(session, approval);
const row: TuiRow = {
session,
state,
group: STATE_GROUP[state],
since: stateSince(state, session, approval),
};
if (approval) row.approval = approval;
return row;
});
}
function compareIds(a: TuiRow, b: TuiRow): number {
if (a.session.sessionId < b.session.sessionId) return -1;
if (a.session.sessionId > b.session.sessionId) return 1;
return 0;
}
/** Longest first: the oldest anchor wins, and an unknown anchor sorts last. */
function compareLongestFirst(a: TuiRow, b: TuiRow): number {
const left = a.since || Number.MAX_SAFE_INTEGER;
const right = b.since || Number.MAX_SAFE_INTEGER;
return left !== right ? left - right : compareIds(a, b);
}
/** Newest first: the freshest anchor wins, and an unknown anchor sorts last. */
function compareNewestFirst(a: TuiRow, b: TuiRow): number {
const left = a.since || 0;
const right = b.since || 0;
return left !== right ? right - left : compareIds(a, b);
}
export interface GroupOptions {
/** RECENT is a tail, not a list: everything past this is dropped. */
recentLimit?: number;
}
/**
* Split classified rows into the four display groups.
*
* Always returns all four in display order (empty ones included) so callers
* never have to guess the shape; the renderer skips the empty ones.
*
* NEEDS YOU and WORKING are ordered by how long they have been in that state
* (longest first: the thing that has waited longest for you is the thing to
* look at). IDLE and RECENT are ordered by recency, newest first.
*/
export function groupSessions(rows: readonly TuiRow[], options: GroupOptions = {}): TuiGroup[] {
const recentLimit = Math.max(0, Math.floor(options.recentLimit ?? DEFAULT_RECENT_LIMIT));
const buckets: Record<TuiGroupKey, TuiRow[]> = {
'needs-you': [],
working: [],
idle: [],
recent: [],
};
for (const row of rows) buckets[row.group].push(row);
buckets['needs-you'].sort(compareLongestFirst);
buckets.working.sort(compareLongestFirst);
buckets.idle.sort(compareNewestFirst);
buckets.recent.sort(compareNewestFirst);
buckets.recent = buckets.recent.slice(0, recentLimit);
return GROUP_ORDER.map((key) => ({ key, label: GROUP_LABELS[key], rows: buckets[key] }));
}
/** The cursor's list: group headers are chrome, only sessions are selectable. */
export function flattenRows(groups: readonly TuiGroup[]): TuiRow[] {
const rows: TuiRow[] = [];
for (const group of groups) rows.push(...group.rows);
return rows;
}
/**
* Fold an incoming row into a known one. Defined fields win, `undefined` never
* clobbers (a live SSE payload carries no transcript fields, a unified refresh
* carries no token counters), but a non-empty `sources` list REPLACES rather
* than unions: a session that ended must be able to lose its `live` source and
* fall to RECENT.
*/
export function mergeSessionRow(existing: TuiSessionRow, incoming: TuiSessionRow): TuiSessionRow {
const merged: TuiSessionRow = { ...existing };
for (const [key, value] of Object.entries(incoming)) {
if (value === undefined) continue;
(merged as unknown as Record<string, unknown>)[key] = value;
}
merged.sources = incoming.sources?.length ? [...incoming.sources] : [...(existing.sources ?? [])];
return merged;
}
// ─────────────────────────────────────────────────────────────────────────────
// Search results (pure)
// ─────────────────────────────────────────────────────────────────────────────
const SEARCH_GROUP_LABELS: Record<SearchSourceType, string> = {
session: 'SESSIONS',
event: 'EVENTS',
file: 'FILES',
};
/**
* A session snippet opens with the session's own name, which the row already
* shows in its first column (`search-service.ts` builds it as
* `w1-alpha <em dash> /tmp/alpha`, hence the separator in the pattern).
* Dropping the repeat is what keeps a result row from reading as a stutter.
*/
function withoutLabelPrefix(snippet: string, label: string): string {
const rest = snippet.startsWith(label) ? snippet.slice(label.length) : snippet;
return rest === snippet ? snippet : rest.replace(/^\s*(?:[—:-]\s*)?/, '');
}
/**
* Flatten `GET /api/search`'s typed groups into the overlay's lines: a header
* per group, then its results. Only a result row carries a session id, which is
* what the cursor uses to skip headers.
*
* `isLive` decides which rows can hand the dashboard a session: a history hit
* has a session id too, but selecting it would move the cursor to a row that is
* not on the list.
*/
export function buildSearchEntries(
groups: readonly SearchResultGroup[],
isLive: (sessionId: string) => boolean
): TuiSearchEntry[] {
const entries: TuiSearchEntry[] = [];
for (const group of groups) {
if (group.results.length === 0) continue;
entries.push({ kind: 'header', text: SEARCH_GROUP_LABELS[group.type] ?? group.type.toUpperCase() });
for (const result of group.results) {
const live = result.jumpTo.kind === 'session' && isLive(result.sessionId);
const label = result.jumpTo.relativePath ?? result.sessionName ?? result.sessionId.slice(0, 8);
entries.push({
kind: 'result',
text: label,
detail: withoutLabelPrefix(result.snippet, label),
sessionId: result.sessionId,
live,
});
}
}
return entries;
}
/** First selectable row, or -1 when the list is all headers (or empty). */
export function firstSearchIndex(entries: readonly TuiSearchEntry[]): number {
return entries.findIndex((entry) => entry.kind === 'result');
}
/**
* Move the search cursor by `delta` result rows, skipping headers and stopping
* at both ends (wrapping a search result list scrolls past the answer the user
* was reading).
*/
export function moveSearchIndex(entries: readonly TuiSearchEntry[], index: number, delta: number): number {
const step = Math.trunc(delta);
if (step === 0) return index;
const direction = step > 0 ? 1 : -1;
let current = index;
for (let remaining = Math.abs(step); remaining > 0; remaining--) {
let next = current + direction;
while (next >= 0 && next < entries.length && entries[next].kind !== 'result') next += direction;
if (next < 0 || next >= entries.length) break;
current = next;
}
return current;
}
/**
* The dashboard's state. Update methods mutate in place (one store per TUI
* process, no subscribers) and every derived view is recomputed from scratch,
* which keeps "what is on screen" a pure function of the stored facts.
*/
export class TuiModelStore implements TuiRenderModel {
private sessionsById = new Map<string, TuiSessionRow>();
private approvalsBySession = new Map<string, ApprovalItem>();
private _revision = 0;
selectedId: string | null = null;
connection: TuiConnectionStatus = 'connected';
mode: TuiUiMode = 'list';
header: TuiHeaderInfo = {};
preview: TuiPreview | null = null;
message: TuiMessage | null = null;
confirm: TuiConfirmState | null = null;
picker: TuiPickerState | null = null;
prompt: TuiPromptState | null = null;
search: TuiSearchState | null = null;
digest: TuiDigestState | null = null;
recentLimit: number;
constructor(options: GroupOptions = {}) {
this.recentLimit = Math.max(0, Math.floor(options.recentLimit ?? DEFAULT_RECENT_LIMIT));
}
/**
* Bumped by every mutating method. The app layer repaints when this changed
* (plus on resize and on the animation tick), which is what keeps an idle
* dashboard from redrawing itself. Writing a public field directly bypasses
* it, so state changes go through the methods below.
*/
get revision(): number {
return this._revision;
}
private touch(): void {
this._revision++;
}
// ── Data ───────────────────────────────────────────────────────────────────
upsertSession(session: TuiSessionRow): void {
this.mutate(() => {
const existing = this.sessionsById.get(session.sessionId);
this.sessionsById.set(session.sessionId, existing ? mergeSessionRow(existing, session) : { ...session });
});
}
removeSession(sessionId: string): void {
this.mutate(() => {
this.sessionsById.delete(sessionId);
this.approvalsBySession.delete(sessionId);
});
}
/** Full refresh (a `GET /api/sessions/unified` poll): the server is authoritative. */
replaceSessions(sessions: readonly TuiSessionRow[]): void {
this.mutate(() => {
this.sessionsById.clear();
for (const session of sessions) this.sessionsById.set(session.sessionId, { ...session });
});
}
setApprovals(items: readonly ApprovalItem[]): void {
this.mutate(() => {
this.approvalsBySession.clear();
// One active item per session is an inbox invariant; the newest wins if
// that ever stops being true.
for (const item of items) this.approvalsBySession.set(item.sessionId, item);
});
}
sessions(): TuiSessionRow[] {
return [...this.sessionsById.values()];
}
// ── Chrome ─────────────────────────────────────────────────────────────────
setConnection(status: TuiConnectionStatus): void {
if (this.connection === status) return;
this.connection = status;
this.touch();
}
setHeader(header: TuiHeaderInfo): void {
this.header = { ...this.header, ...header };
this.touch();
}
setPreview(preview: TuiPreview | null): void {
this.preview = preview;
this.touch();
}
setMode(mode: TuiUiMode): void {
if (this.mode === mode) return;
this.mode = mode;
this.touch();
}
setMessage(message: TuiMessage | null): void {
this.message = message;
this.mode = message ? 'message' : 'list';
this.touch();
}
/** Show (or clear) the overlay chooser. Setting one takes the keyboard. */
setPicker(picker: TuiPickerState | null): void {
this.picker = picker;
this.mode = picker ? 'new-session' : 'list';
this.touch();
}
/** Open (or close) the one-line prompt composer. Setting one takes the keyboard. */
setPrompt(prompt: TuiPromptState | null): void {
this.prompt = prompt;
this.mode = prompt ? 'prompt' : 'list';
this.touch();
}
/** Replace the composer's editor state, keeping the target session. */
updatePrompt(composer: TuiPromptState['composer']): void {
if (!this.prompt || this.prompt.composer === composer) return;
this.prompt = { ...this.prompt, composer };
this.touch();
}
setSearch(search: TuiSearchState | null): void {
this.search = search;
this.mode = search ? 'search' : 'list';
this.touch();
}
/** Fold a partial update into the open search overlay. No-op when it is closed. */
updateSearch(patch: Partial<TuiSearchState>): void {
if (!this.search) return;
this.search = { ...this.search, ...patch };
this.touch();
}
setDigest(digest: TuiDigestState | null): void {
this.digest = digest;
this.mode = digest ? 'digest' : 'list';
this.touch();
}
/**
* Scroll the digest by `delta` lines. `capacity` is how many lines the box
* shows, so the last page cannot scroll into empty space.
*/
scrollDigest(delta: number, capacity: number): void {
if (!this.digest) return;
const room = Math.max(0, this.digest.lines.length - Math.max(1, Math.trunc(capacity)));
const offset = Math.min(Math.max(0, this.digest.offset + Math.trunc(delta)), room);
if (offset === this.digest.offset) return;
this.digest = { ...this.digest, offset };
this.touch();
}
/**
* Arm the typed-name confirmation for `x` (kill). Whether what the user typed
* AUTHORIZES the kill is `confirmAccepts()` in tui-app, which owns that rule
* for every caller: a second copy here answered the same question differently
* (it refused the id prefix a mux name carries) and nothing consulted it.
*/
beginConfirmKill(row: TuiRow, label: string): void {
this.confirm = {
sessionId: row.session.sessionId,
// ⚠️ Passed in, not derived here. `row.session.name ?? id.slice(0,8)`
// used to compute it, and `??` falls back only on null/undefined: a
// session whose name is the EMPTY STRING (every session the server did
// not name) sailed through it and the dialog read "Kill ?". A destructive
// prompt that cannot say what it is about to destroy is worse than no
// prompt, and it is now one keystroke. The caller passes the same label
// the LIST shows, so the dialog names the row the user is looking at.
name: label,
};
this.mode = 'confirm-kill';
this.touch();
}
/** Drop whatever overlay owns the keyboard and go back to the list. */
closeOverlay(): void {
this.confirm = null;
this.message = null;
this.picker = null;
this.prompt = null;
this.search = null;
this.digest = null;
this.mode = 'list';
this.touch();
}
// ── Derived views ──────────────────────────────────────────────────────────
groups(): TuiGroup[] {
return groupSessions(buildRows(this.sessions(), this.approvalsBySession), { recentLimit: this.recentLimit });
}
rows(): TuiRow[] {
return flattenRows(this.groups());
}
get sessionCount(): number {
let count = 0;
for (const session of this.sessionsById.values()) if (isLiveRow(session)) count++;
return count;
}
// ── Cursor ─────────────────────────────────────────────────────────────────
selectedSession(): TuiRow | null {
if (!this.selectedId) return null;
return this.rows().find((row) => row.session.sessionId === this.selectedId) ?? null;
}
/** Select a session by id. Returns false when it is not on screen. */
select(sessionId: string): boolean {
if (!this.rows().some((row) => row.session.sessionId === sessionId)) return false;
this.moveTo(sessionId);
return true;
}
/** Move by `delta` rows, skipping group headers and wrapping at both ends. */
moveCursor(delta: number): void {
const rows = this.rows();
if (rows.length === 0) {
this.moveTo(null);
return;
}
const current = this.indexOfSelected(rows);
if (current < 0) {
this.moveTo(rows[delta >= 0 ? 0 : rows.length - 1].session.sessionId);
return;
}
const step = Math.trunc(delta);
const next = (((current + step) % rows.length) + rows.length) % rows.length;
this.moveTo(rows[next].session.sessionId);
}
/** The 1-9 jump: `n` is the 1-based position in the flattened list. */
cursorToIndex(n: number): boolean {
const rows = this.rows();
const index = Math.trunc(n) - 1;
if (index < 0 || index >= rows.length) return false;
this.moveTo(rows[index].session.sessionId);
return true;
}
private moveTo(sessionId: string | null): void {
if (this.selectedId === sessionId) return;
this.selectedId = sessionId;
this.touch();
}
private indexOfSelected(rows: readonly TuiRow[] = this.rows()): number {
if (!this.selectedId) return -1;
return rows.findIndex((row) => row.session.sessionId === this.selectedId);
}
/**
* Run a data mutation and keep the cursor sane afterwards: the selected
* session stays selected wherever it moved to, and a session that vanished
* hands the cursor to whatever now occupies its place.
*/
private mutate(apply: () => void): void {
const previousIndex = this.indexOfSelected();
apply();
this.touch();
const rows = this.rows();
if (rows.length === 0) {
this.moveTo(null);
return;
}
if (this.selectedId !== null && rows.some((row) => row.session.sessionId === this.selectedId)) return;
const index = Math.min(Math.max(previousIndex, 0), rows.length - 1);
this.moveTo(rows[index].session.sessionId);
}
}
export function createTuiModel(options: GroupOptions = {}): TuiModelStore {
return new TuiModelStore(options);
}
+921
View File
@@ -0,0 +1,921 @@
/**
* @fileoverview Pure frame renderer: model + layout in, one string out.
*
* The frame is absolute-addressed, one `ESC [ <row>;1 H` per line followed by
* `ESC [ K`, so nothing ever scrolls and a repaint cannot leave debris. The
* caller wraps the result in synchronized-output brackets (DECSET 2026) where
* the terminal supports it; that is an IO decision and stays out of here.
*
* Color is decided by the caller and passed in, never detected here: chalk's
* auto-detection is the right answer for the one-shot CLI (see `cli-style.ts`)
* but it would make a frame non-deterministic, and "same inputs, same string"
* is what makes this module testable. The palette below is the same semantic
* vocabulary chalk gives `cli-style` (ok green, warn yellow, err red, info
* cyan, muted gray, emph bold), written as raw SGR so the mapping is fixed.
*
* With `color: false` the frame contains no escape sequences at all beyond the
* cursor addressing that puts each line in place.
*
* @module tui/tui-render
*/
import { clipStyledLine, padDisplay, stripStyles, visibleWidth } from './tui-ansi.js';
import { approvalCard } from './tui-approvals.js';
import { composerText, composerWindow } from './tui-composer.js';
import type { TuiLayout, TuiRect } from './tui-layout.js';
import type { ApprovalItem } from '../web/approval-inbox.js';
import type { StatusTelemetry } from '../usage-telemetry.js';
import type {
TuiDigestState,
TuiGlyphTier,
TuiGroup,
TuiPickerState,
TuiPromptState,
TuiRenderModel,
TuiRow,
TuiSearchState,
TuiSessionRow,
TuiSessionState,
} from './tui-types.js';
export interface TuiRenderOptions {
/** Emit SGR color. False is NO_COLOR: cursor addressing and nothing else. */
color: boolean;
glyphs: TuiGlyphTier;
/** Animation counter. The WORKING glyph cycles with it. */
tick: number;
/** Wall clock for elapsed times, passed in so a frame is reproducible. */
now: number;
/**
* Footer entries, already labelled, joined here with the separator glyph.
* The app layer passes the keys that actually do something right now (which
* verbs are wired up, whether a server is answering); omitting it falls back
* to the full keymap below.
*/
footerKeys?: readonly string[];
/**
* `[key, what it does]` pairs for the help overlay, same reasoning as
* `footerKeys`: the app layer knows which verbs are wired up. Omitting it
* falls back to the full keymap.
*/
helpKeys?: ReadonlyArray<readonly [string, string]>;
}
// ─────────────────────────────────────────────────────────────────────────────
// Palette and glyphs
// ─────────────────────────────────────────────────────────────────────────────
const SGR = {
reset: '\x1b[0m',
bold: '\x1b[1m',
dim: '\x1b[2m',
inverse: '\x1b[7m',
red: '\x1b[31m',
green: '\x1b[32m',
yellow: '\x1b[33m',
magenta: '\x1b[35m',
cyan: '\x1b[36m',
gray: '\x1b[90m',
} as const;
/**
* One word per state, shared by the preview title and the `--list` output so
* both surfaces call a session the same thing.
*/
export const STATE_WORDS: Record<TuiSessionState, string> = {
'blocked-permission': 'blocked',
'blocked-question': 'blocked',
waiting: 'waiting',
working: 'working',
idle: 'idle',
recent: 'done',
};
const STATE_COLOR: Record<TuiSessionState, string> = {
'blocked-permission': SGR.red,
'blocked-question': SGR.red,
waiting: SGR.yellow,
working: SGR.green,
idle: SGR.gray,
recent: SGR.gray,
};
export interface TuiGlyphSet {
blockedPermission: string;
blockedQuestion: string;
waiting: string;
/** WORKING animates through Claude's own glyph family, a deliberate nod. */
working: readonly string[];
idle: string;
recent: string;
cursor: string;
rule: string;
divider: string;
boxTopLeft: string;
boxTopRight: string;
boxBottomLeft: string;
boxBottomRight: string;
boxHorizontal: string;
boxVertical: string;
enter: string;
updown: string;
separator: string;
ellipsis: string;
}
/**
* ⚠️ Every glyph here must clear TWO bars that are easy to miss, and both were
* failed at once by the first version of this table.
*
* WIDTH: the renderer addresses cells by column, so a glyph the terminal draws
* two cells wide shifts everything after it. `east_asian_width` W or F is
* therefore disqualifying. `✋` (U+270B) was Wide, and being an emoji is also
* why fonts render it at emoji size in the middle of a text row.
*
* COVERAGE: a plain terminal font carries far less than the unicode TIER
* implies. The tier answers "is the locale UTF-8", which says nothing about
* whether a given codepoint has a glyph.
*
* One beta tester's font mapped the blocks like this, and it is the profile to
* design against because it is an ordinary terminal font, not a broken one:
*
* RENDERS Latin-1 (·), Box Drawing (─ │), Block Elements (█ ▛ ▐),
* Geometric Shapes (○ ▶), General Punctuation (…), Arrows
* TOFU Misc Technical (⏎ U+23CE, ⏵ U+23F5), the sparse end of
* Dingbats (❯ U+276F)
*
* So: draw from the blocks on the first line. Dingbats, Miscellaneous
* Technical, Miscellaneous Symbols and anything with emoji presentation are
* out — that class produced three separate "why are there boxes" reports, one
* per glyph, because each was fixed on its own instead of as a class.
*/
const UNICODE_GLYPHS: TuiGlyphSet = {
blockedPermission: '▲',
blockedQuestion: '▲',
waiting: '!',
// Quadrant blocks, which rotate as a spinner and live in the same block as
// the `▛█▐` art claude itself draws — proven to render on the font that
// failed the dingbats this used to use.
working: ['▖', '▘', '▝', '▗'],
idle: '○',
recent: '✔',
cursor: '▶',
rule: '─',
divider: '│',
boxTopLeft: '┌',
boxTopRight: '┐',
boxBottomLeft: '└',
boxBottomRight: '┘',
boxHorizontal: '─',
boxVertical: '│',
enter: '↵',
updown: '↑↓',
separator: '·',
ellipsis: '…',
};
/**
* The lowest tier, for terminals that are not known-capable. Every state token
* is three columns wide so rows still line up, mirroring what `sc` falls back
* to today.
*/
const ASCII_GLYPHS: TuiGlyphSet = {
blockedPermission: '[!]',
blockedQuestion: '[?]',
waiting: '[w]',
working: ['[*]', '[+]', '[x]', '[+]'],
idle: '[-]',
recent: '[v]',
cursor: '>',
rule: '-',
divider: '|',
boxTopLeft: '+',
boxTopRight: '+',
boxBottomLeft: '+',
boxBottomRight: '+',
boxHorizontal: '-',
boxVertical: '|',
enter: 'enter',
updown: 'up/dn',
separator: '-',
ellipsis: '..',
};
/**
* Glyphs for a tier. `nerd` currently renders like `unicode`: the tier exists
* so detection has somewhere to land and a nerd-font-only set has a home,
* without shipping glyphs nobody has reviewed on a real font.
*/
export function glyphsFor(tier: TuiGlyphTier): TuiGlyphSet {
return tier === 'ascii' ? ASCII_GLYPHS : UNICODE_GLYPHS;
}
/**
* Glyph tier from the environment. IO-ish by nature (it reads env), so it takes
* the env as an argument and the app layer calls it once at startup. The
* known-capable list is a TERM allowlist, plus a UTF-8 locale check and an
* explicit override.
*/
export function detectGlyphTier(env: Record<string, string | undefined>): TuiGlyphTier {
const override = env.CODEMAN_TUI_GLYPHS;
if (override === 'ascii' || override === 'unicode' || override === 'nerd') return override;
const term = env.TERM ?? '';
if (term === '' || term === 'dumb') return 'ascii';
const locale = env.LC_ALL || env.LC_CTYPE || env.LANG || '';
if (!/utf-?8/i.test(locale)) return 'ascii';
const termProgram = env.TERM_PROGRAM ?? '';
if (termProgram.startsWith('iTerm') || term === 'xterm-kitty' || env.WEZTERM_PANE || env.LC_TERMINAL === 'iTerm2') {
return 'nerd';
}
return 'unicode';
}
// ─────────────────────────────────────────────────────────────────────────────
// Formatting helpers (pure, exported for tests and for the app layer)
// ─────────────────────────────────────────────────────────────────────────────
/** Compact age: `45s`, `11m`, `2h`, `3d`. Empty when the anchor is unknown. */
export function formatElapsed(ms: number): string {
if (!Number.isFinite(ms) || ms < 0) return '';
const seconds = Math.floor(ms / 1000);
if (seconds < 60) return `${seconds}s`;
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return `${minutes}m`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours}h`;
return `${Math.floor(hours / 24)}d`;
}
function trimTrailingZero(value: string): string {
return value.endsWith('.0') ? value.slice(0, -2) : value;
}
/** Compact token count: `842`, `45.2k`, `1.2M`. Empty when there is nothing to show. */
export function formatTokens(total: number): string {
if (!Number.isFinite(total) || total <= 0) return '';
if (total < 1000) return String(Math.floor(total));
if (total < 1_000_000) return `${trimTrailingZero((total / 1000).toFixed(1))}k`;
return `${trimTrailingZero((total / 1_000_000).toFixed(1))}M`;
}
/**
* The header's plan-usage chip: `5h 32% · wk 61%`, the same two windows the web
* chip shows (the statusline telemetry carries no others). Empty when the
* account reports neither, so the header shows no placeholder for a fact that
* does not exist. The separator is passed in because the header's own comes
* from the glyph tier, and an ASCII terminal must not get a stray `·`.
*/
export function formatPlanUsage(usage: StatusTelemetry | null | undefined, separator = ' · '): string {
if (!usage) return '';
const parts: string[] = [];
if (typeof usage.fiveHour?.usedPercentage === 'number') {
parts.push(`5h ${Math.round(usage.fiveHour.usedPercentage)}%`);
}
if (typeof usage.sevenDay?.usedPercentage === 'number') {
parts.push(`wk ${Math.round(usage.sevenDay.usedPercentage)}%`);
}
return parts.join(separator);
}
/**
* What a row is called. Same rule as the web history rows, including the
* "(no content)" placeholder the transcript reader emits, which is not a title.
*/
export function rowLabel(session: TuiSessionRow): string {
if (session.name) return session.name;
const base = (session.workingDir ?? '').split('/').filter(Boolean).pop();
// ⚠️ A LIVE pane (it has a mux name) is identified by WHERE it runs, never by
// a line scraped out of its transcript. A session created before the user has
// typed anything has no prompt to be named after, so the fallback took
// whatever the CLI happened to print first: a beta tester's new session
// appeared in the list called "Login interrupted", which reads like a failure
// report and was in fact a healthy session. A history row is the opposite
// case, where the prompt IS the identity, so it keeps the old order.
if (session.muxName && base) return base;
const prompt = (session.firstPrompt ?? '').trim();
if (prompt && prompt !== '(no content)') return prompt;
return base || session.sessionId.slice(0, 8);
}
/** Keep the tail of a path: the last segments identify it, the root never does. */
function truncatePathLeft(path: string, width: number, ellipsis: string): string {
if (width <= 0) return '';
if (visibleWidth(path) <= width) return path;
const keep = Math.max(0, width - visibleWidth(ellipsis));
return ellipsis + path.slice(path.length - keep);
}
function tokensOf(session: TuiSessionRow): number {
return (session.inputTokens ?? 0) + (session.outputTokens ?? 0);
}
// ─────────────────────────────────────────────────────────────────────────────
// Painting
// ─────────────────────────────────────────────────────────────────────────────
type Painter = (text: string, code: string) => string;
function painterFor(enabled: boolean): Painter {
return enabled ? (text, code) => (text === '' ? text : `${code}${text}${SGR.reset}`) : (text) => text;
}
function stateGlyph(row: TuiRow, glyphs: TuiGlyphSet, tick: number): string {
switch (row.state) {
case 'blocked-permission':
return glyphs.blockedPermission;
case 'blocked-question':
return glyphs.blockedQuestion;
case 'waiting':
return glyphs.waiting;
case 'working': {
const frames = glyphs.working;
const index = ((Math.trunc(tick) % frames.length) + frames.length) % frames.length;
return frames[index];
}
case 'idle':
return glyphs.idle;
case 'recent':
return glyphs.recent;
}
}
function centered(text: string, width: number): string {
const pad = Math.max(0, Math.floor((width - visibleWidth(text)) / 2));
return padDisplay(`${' '.repeat(pad)}${text}`, width);
}
// ─────────────────────────────────────────────────────────────────────────────
// Rows and groups
// ─────────────────────────────────────────────────────────────────────────────
interface RowContext {
width: number;
/** 1-based position in the flattened list; only 1-9 get a jump digit. */
index: number;
selected: boolean;
twoLine: boolean;
glyphs: TuiGlyphSet;
opts: TuiRenderOptions;
}
function renderRowLines(row: TuiRow, ctx: RowContext): string[] {
// A selected row is one inverse-video block, so its parts are built unpainted:
// an inner reset would punch a hole in the highlight.
const inverse = ctx.selected && ctx.opts.color;
const paint = painterFor(ctx.opts.color && !inverse);
const { session } = row;
const marker = ctx.selected ? padDisplay(ctx.glyphs.cursor, 2) : ' ';
const digit = ctx.index >= 1 && ctx.index <= 9 ? `${ctx.index} ` : ' ';
const glyph = paint(stateGlyph(row, ctx.glyphs, ctx.opts.tick), STATE_COLOR[row.state]);
const elapsed = row.since > 0 ? formatElapsed(ctx.opts.now - row.since) : '';
const tokens = formatTokens(tokensOf(session));
const rightParts = [glyph, paint(elapsed, SGR.gray)];
if (!ctx.twoLine && tokens) rightParts.push(paint(tokens, SGR.gray));
const right = rightParts.filter((part) => part !== '').join(' ');
const mode = session.mode && session.mode !== 'claude' ? session.mode : '';
const nameWidth = Math.max(4, ctx.width - visibleWidth(marker + digit) - visibleWidth(right) - 1);
const label = rowLabel(session);
const name = mode ? `${label} ${paint(mode, SGR.magenta)}` : label;
const first = padDisplay(`${marker}${digit}${padDisplay(name, nameWidth)} ${right}`, ctx.width);
const lines = [first];
if (ctx.twoLine) {
const detail = [truncatePathLeft(session.workingDir ?? '', Math.max(0, ctx.width - 8), ctx.glyphs.ellipsis)];
if (mode) detail.push(mode);
if (tokens) detail.push(tokens);
const text = detail.filter((part) => part !== '').join(` ${ctx.glyphs.separator} `);
lines.push(padDisplay(` ${paint(text, SGR.gray)}`, ctx.width));
}
return inverse ? lines.map((line) => `${SGR.inverse}${line}${SGR.reset}`) : lines;
}
function renderGroupHeader(group: TuiGroup, width: number, glyphs: TuiGlyphSet, opts: TuiRenderOptions): string {
const paint = painterFor(opts.color);
const label = ` ${group.label} `;
const fill = Math.max(0, width - visibleWidth(label));
return padDisplay(`${paint(label, SGR.bold)}${paint(glyphs.rule.repeat(fill), SGR.gray)}`, width);
}
export interface TuiListEntry {
text: string;
/** Set on the lines that belong to a session row, so the window can chase the cursor. */
sessionId?: string;
}
function buildListEntries(model: TuiRenderModel, layout: TuiLayout, opts: TuiRenderOptions): TuiListEntry[] {
const glyphs = glyphsFor(opts.glyphs);
const width = layout.list.width;
const entries: TuiListEntry[] = [];
let index = 0;
for (const group of model.groups()) {
if (group.rows.length === 0) continue;
entries.push({ text: renderGroupHeader(group, width, glyphs, opts) });
for (const row of group.rows) {
index++;
const ctx: RowContext = {
width,
index,
selected: row.session.sessionId === model.selectedId,
twoLine: layout.rowHeight === 2,
glyphs,
opts,
};
for (const text of renderRowLines(row, ctx)) entries.push({ text, sessionId: row.session.sessionId });
}
}
return entries;
}
/**
* First visible entry, scrolling the minimum needed to keep the selected row on
* screen. Deterministic on purpose: the window is derived, never remembered, so
* two identical models render identically.
*/
export function computeListWindow(
entries: readonly TuiListEntry[],
capacity: number,
selectedId: string | null
): number {
if (capacity <= 0 || entries.length <= capacity) return 0;
const maxStart = entries.length - capacity;
if (!selectedId) return 0;
const first = entries.findIndex((entry) => entry.sessionId === selectedId);
if (first < 0) return 0;
let last = first;
while (last + 1 < entries.length && entries[last + 1].sessionId === selectedId) last++;
let start = 0;
if (last >= capacity) start = Math.min(last - capacity + 1, maxStart);
if (first < start) start = first;
return start;
}
// ─────────────────────────────────────────────────────────────────────────────
// Preview
// ─────────────────────────────────────────────────────────────────────────────
/**
* The pending dialog, drawn above the tail: the question, the parsed options
* with their digits, and the keys that answer them. Red for a permission or
* question prompt, yellow for an idle one, the same severity vocabulary the web
* inbox uses.
*/
export function renderApprovalCard(
item: ApprovalItem,
width: number,
glyphs: TuiGlyphSet,
opts: TuiRenderOptions
): string[] {
const paint = painterFor(opts.color);
const card = approvalCard(item);
const color = card.tone === 'err' ? SGR.red : SGR.yellow;
const glyph = card.tone === 'err' ? glyphs.blockedPermission : glyphs.waiting;
const lines: string[] = [];
const push = (text: string, style: string): void => {
lines.push(padDisplay(paint(clipStyledLine(text, width), style), width));
};
push(` ${glyph} ${card.title}`, color);
for (const detail of card.detail) push(` ${detail}`, SGR.gray);
for (const option of card.options) push(` ${option.n}. ${option.label}`, '');
push(` ${card.hint}`, SGR.gray);
return lines;
}
/** The card may take half the pane at most: the tail is why the pane exists. */
function cardCapacity(height: number): number {
return Math.max(0, Math.floor((height - 1) / 2));
}
/**
* `name · mode · dir · state`, with the DIRECTORY absorbing the squeeze: the
* state word is the one fact the pane exists to confirm, so it must survive a
* narrow preview that a full path would push off the end.
*/
function previewTitle(row: TuiRow, width: number, glyphs: TuiGlyphSet): string {
const { session } = row;
const sep = ` ${glyphs.separator} `;
const head = ` ${rowLabel(session)}${sep}${session.mode ?? 'claude'}`;
const tail = `${sep}${STATE_WORDS[row.state]}`;
const dirBudget = width - visibleWidth(head) - visibleWidth(tail) - visibleWidth(sep);
const dir = session.workingDir ? truncatePathLeft(session.workingDir, Math.max(0, dirBudget), glyphs.ellipsis) : '';
return clipStyledLine(dir ? `${head}${sep}${dir}${tail}` : `${head}${tail}`, width);
}
function buildPreviewLines(model: TuiRenderModel, rect: TuiRect, opts: TuiRenderOptions): string[] {
const paint = painterFor(opts.color);
const glyphs = glyphsFor(opts.glyphs);
const lines: string[] = [];
const selected = model.selectedId
? (model
.groups()
.flatMap((group) => group.rows)
.find((row) => row.session.sessionId === model.selectedId) ?? null)
: null;
if (!selected) {
lines.push(padDisplay(paint(' no session selected', SGR.gray), rect.width));
} else {
lines.push(padDisplay(paint(previewTitle(selected, rect.width, glyphs), SGR.bold), rect.width));
}
const budget = cardCapacity(rect.height);
if (selected?.approval && budget > 0) {
for (const line of renderApprovalCard(selected.approval, rect.width, glyphs, opts).slice(0, budget)) {
lines.push(line);
}
if (lines.length < rect.height) lines.push(' '.repeat(rect.width));
}
const body = previewBody(model, selected, rect, opts, rect.height - lines.length);
for (const line of body) lines.push(line);
while (lines.length < rect.height) lines.push(' '.repeat(rect.width));
return lines.slice(0, Math.max(0, rect.height));
}
function previewBody(
model: TuiRenderModel,
selected: TuiRow | null,
rect: TuiRect,
opts: TuiRenderOptions,
capacity: number
): string[] {
const paint = painterFor(opts.color);
if (capacity <= 0) return [];
const hint = (text: string): string[] => [padDisplay(paint(` ${text}`, SGR.gray), rect.width)];
if (!selected) return [];
if (model.connection === 'degraded' || model.connection === 'down') {
return hint('preview unavailable while the server is down');
}
const preview = model.preview;
if (!preview || preview.sessionId !== selected.session.sessionId) return hint('loading preview…');
if (preview.note) return hint(preview.note);
if (preview.error) return hint(preview.error);
const trimmed = [...preview.lines];
while (trimmed.length > 0 && trimmed[trimmed.length - 1].trim() === '') trimmed.pop();
if (trimmed.length === 0) return hint('(no output yet)');
// The tail carries the session's OWN colors, which is the point of the pane,
// but under NO_COLOR they must go too.
return trimmed
.slice(-capacity)
.map((line) => padDisplay(` ${clipStyledLine(opts.color ? line : stripStyles(line), rect.width - 1)}`, rect.width));
}
// ─────────────────────────────────────────────────────────────────────────────
// Chrome
// ─────────────────────────────────────────────────────────────────────────────
/** Sessions with a prompt waiting on a human, which is what the badge counts. */
export function pendingApprovalCount(model: TuiRenderModel): number {
let count = 0;
for (const group of model.groups()) for (const row of group.rows) if (row.approval) count++;
return count;
}
function renderHeaderLine(model: TuiRenderModel, layout: TuiLayout, opts: TuiRenderOptions): string {
const paint = painterFor(opts.color);
const glyphs = glyphsFor(opts.glyphs);
const { hostname, instance, version, planUsage } = model.header;
const facts = [
instance ? `${hostname ?? ''}:${instance}` : (hostname ?? ''),
version ? `v${version}` : '',
`${model.sessionCount} session${model.sessionCount === 1 ? '' : 's'}`,
planUsage ?? '',
].filter((part) => part !== '');
const pending = pendingApprovalCount(model);
const badge = pending > 0 ? `${paint(`${glyphs.blockedPermission} ${pending}`, SGR.red)} ` : '';
const left = ` ${paint('codeman', SGR.bold)} ${badge}${paint(facts.join(` ${glyphs.separator} `), SGR.gray)}`;
const right = paint('? help q quit ', SGR.gray);
const gap = layout.cols - visibleWidth(left) - visibleWidth(right);
if (gap < 1) return padDisplay(left, layout.cols);
return `${left}${' '.repeat(gap)}${right}`;
}
function renderBannerLine(model: TuiRenderModel, layout: TuiLayout, opts: TuiRenderOptions): string {
const paint = painterFor(opts.color);
const glyphs = glyphsFor(opts.glyphs);
const [text, color] =
model.connection === 'degraded'
? ['server not running: attach only', SGR.yellow]
: model.connection === 'reconnecting'
? ['reconnecting to the server…', SGR.yellow]
: ['server unreachable', SGR.red];
return padDisplay(paint(` ${glyphs.blockedPermission} ${text}`, color), layout.cols);
}
const FOOTER_KEYS: Record<string, (glyphs: TuiGlyphSet) => string> = {
list: (g) =>
[
`${g.updown} select`,
`${g.enter} attach`,
'1-9 switch',
'y/n answer',
'p prompt',
'n new',
'x kill',
'/ search',
'g digest',
'? help',
'q quit',
].join(` ${g.separator} `),
help: (g) => `esc ${g.separator} ? close`,
'confirm-kill': (g) => `y kill ${g.separator} any other key cancels`,
message: () => 'esc dismiss',
prompt: (g) => `${g.enter} send ${g.separator} esc cancel`,
search: (g) => `${g.updown} results ${g.separator} ${g.enter} open ${g.separator} esc close`,
digest: (g) => `j/k ${g.separator} ${g.updown} scroll ${g.separator} esc close`,
'new-session': (g) => `${g.updown} select ${g.separator} ${g.enter} choose ${g.separator} esc cancel`,
};
/**
* The composer's prefix. Fixed width on purpose: the terminal cursor is placed
* by column arithmetic (`composerCursorCell`), and a prefix that changed with
* the session name would move the cursor with it.
*/
export const COMPOSER_PREFIX = ' > ';
function renderComposerLine(prompt: TuiPromptState, layout: TuiLayout, opts: TuiRenderOptions): string {
const paint = painterFor(opts.color);
const window = composerWindow(prompt.composer, Math.max(1, layout.cols - visibleWidth(COMPOSER_PREFIX)));
return padDisplay(`${paint(COMPOSER_PREFIX, SGR.cyan)}${window.text}`, layout.cols);
}
/**
* Where the terminal's own cursor belongs, or null when nothing is being typed
* into a single-line editor. The app shows the cursor there and hides it
* otherwise, because a blinking cursor parked in a dashboard reads as a bug.
*/
export function composerCursorCell(model: TuiRenderModel, layout: TuiLayout): { row: number; col: number } | null {
if (model.mode !== 'prompt' || !model.prompt || layout.footer.height <= 0) return null;
const prefix = visibleWidth(COMPOSER_PREFIX);
const window = composerWindow(model.prompt.composer, Math.max(1, layout.cols - prefix));
return { row: layout.footer.row, col: Math.min(layout.cols, prefix + 1 + window.cursorColumn) };
}
function renderFooterLine(model: TuiRenderModel, layout: TuiLayout, opts: TuiRenderOptions): string {
const paint = painterFor(opts.color);
const glyphs = glyphsFor(opts.glyphs);
if (model.mode === 'prompt' && model.prompt) return renderComposerLine(model.prompt, layout, opts);
const text = opts.footerKeys
? opts.footerKeys.join(` ${glyphs.separator} `)
: (FOOTER_KEYS[model.mode] ?? FOOTER_KEYS.list)(glyphs);
return padDisplay(paint(clipStyledLine(` ${text}`, layout.cols), SGR.gray), layout.cols);
}
// ─────────────────────────────────────────────────────────────────────────────
// Overlays
// ─────────────────────────────────────────────────────────────────────────────
interface OverlayContent {
title: string;
lines: string[];
/**
* Floor for the box's inner width. The search and digest panels are lists
* people scan, so they keep a stable width instead of snapping around their
* longest current line.
*/
minWidth?: number;
}
function wrapText(text: string, width: number): string[] {
if (width <= 0) return [];
const out: string[] = [];
let line = '';
for (const word of text.split(/\s+/).filter((part) => part !== '')) {
const candidate = line === '' ? word : `${line} ${word}`;
if (visibleWidth(candidate) > width && line !== '') {
out.push(line);
line = word;
} else {
line = candidate;
}
}
if (line !== '') out.push(line);
return out.length > 0 ? out : [''];
}
function helpLines(glyphs: TuiGlyphSet, custom?: ReadonlyArray<readonly [string, string]>): string[] {
const pairs: ReadonlyArray<readonly [string, string]> = custom ?? [
[`${glyphs.updown} / j k`, 'select'],
[glyphs.enter, 'attach'],
['1-9', 'jump'],
['y / n', 'answer the pending approval'],
['p', 'send a prompt'],
['n', 'new session'],
['x', 'kill (typed confirmation)'],
['/', 'search'],
['g', 'away digest'],
['?', 'this help'],
['q', 'quit'],
];
const keyWidth = Math.max(...pairs.map(([key]) => visibleWidth(key)));
return pairs.map(([key, description]) => `${padDisplay(key, keyWidth)} ${description}`);
}
/** Longest item list a picker overlay shows, however tall the terminal is. */
const PICKER_MAX_ROWS = 10;
/**
* A picker's lines: hint, a window of items around the cursor, then the filter
* echo. Windowed rather than clipped, so the selected item is always visible in
* a long case list.
*/
function pickerLines(picker: TuiPickerState, glyphs: TuiGlyphSet, capacity: number): string[] {
const head: string[] = picker.hint ? [picker.hint, ''] : [];
const tail: string[] = picker.filter === undefined ? [] : ['', `filter: ${picker.filter}_`];
if (picker.items.length === 0) return [...head, '(nothing to choose)', ...tail];
const budget = Math.max(1, Math.min(PICKER_MAX_ROWS, capacity - head.length - tail.length));
const first = Math.max(0, Math.min(picker.index - Math.floor(budget / 2), picker.items.length - budget));
const rows = picker.items.slice(first, first + budget).map((item, i) => {
const marker = first + i === picker.index ? glyphs.cursor : ' '.repeat(visibleWidth(glyphs.cursor));
return `${marker} ${item.label}${item.detail ? ` ${item.detail}` : ''}`;
});
return [...head, ...rows, ...tail];
}
/**
* The `/` overlay: the query with a caret, one status line, then the results.
*
* The caret is a trailing `_` rather than the terminal's own cursor, and that is
* why the search keymap leaves left/right to the result list: a caret that
* cannot move is honest, an invisible one that can is not.
*/
function searchLines(state: TuiSearchState, glyphs: TuiGlyphSet, capacity: number): string[] {
const head = [`${composerText(state.composer)}_`];
if (state.note) head.push(state.note);
head.push('');
const budget = Math.max(1, capacity - head.length);
if (state.entries.length === 0) {
return [...head, state.status === 'searching' ? 'searching…' : '(type to search sessions, events and files)'];
}
const first = Math.max(0, Math.min(state.index - Math.floor(budget / 2), state.entries.length - budget));
const rows = state.entries.slice(first, first + budget).map((entry, i) => {
if (entry.kind === 'header') return entry.text;
const marker = first + i === state.index ? glyphs.cursor : ' '.repeat(visibleWidth(glyphs.cursor));
return `${marker} ${entry.text}${entry.detail ? ` ${entry.detail}` : ''}`;
});
return [...head, ...rows];
}
/** Lines an overlay box can show inside its border, given the body's height. */
function overlayCapacity(height: number): number {
return Math.max(1, height - 2);
}
/**
* How many digest lines fit. Exported because the app scrolls by pages and must
* not scroll the last page into empty space, which needs this exact number.
*/
export function digestCapacity(layout: TuiLayout): number {
return overlayCapacity(layout.body.height);
}
function digestLines(state: TuiDigestState, capacity: number): string[] {
const offset = Math.min(Math.max(0, state.offset), Math.max(0, state.lines.length - 1));
return state.lines.slice(offset, offset + capacity);
}
function overlayContent(
model: TuiRenderModel,
opts: TuiRenderOptions,
width: number,
height: number
): OverlayContent | null {
const glyphs = glyphsFor(opts.glyphs);
const panelWidth = Math.max(20, Math.min(width - 8, 72));
switch (model.mode) {
case 'help':
return { title: 'Keys', lines: helpLines(glyphs, opts.helpKeys) };
case 'search': {
if (!model.search) return null;
return {
title: 'Search',
lines: searchLines(model.search, glyphs, overlayCapacity(height)),
minWidth: panelWidth,
};
}
case 'digest': {
if (!model.digest) return null;
return {
title: model.digest.title,
lines: digestLines(model.digest, overlayCapacity(height)),
minWidth: panelWidth,
};
}
case 'new-session': {
if (!model.picker) return null;
return { title: model.picker.title, lines: pickerLines(model.picker, glyphs, Math.max(1, height - 2)) };
}
case 'confirm-kill': {
if (!model.confirm) return null;
return {
title: 'Kill session',
lines: [`Kill ${model.confirm.name}?`, '', 'press y to kill, any other key cancels'],
};
}
case 'message':
if (!model.message) return null;
return {
title: model.message.tone === 'err' ? 'Error' : model.message.tone === 'warn' ? 'Warning' : 'Notice',
lines: wrapText(model.message.text, Math.max(8, width - 8)),
};
default:
return null;
}
}
/** Paint an overlay box over the body, centered, replacing whole terminal rows. */
function applyOverlay(lines: string[], model: TuiRenderModel, layout: TuiLayout, opts: TuiRenderOptions): void {
const body = layout.body;
if (body.height < 3 || body.width < 12) return;
const content = overlayContent(model, opts, body.width, body.height);
if (!content) return;
const paint = painterFor(opts.color);
const glyphs = glyphsFor(opts.glyphs);
const maxInner = body.width - 4;
const visible = content.lines.slice(0, Math.max(1, body.height - 2));
const inner = Math.min(
maxInner,
Math.max(content.minWidth ?? 0, visibleWidth(content.title) + 2, ...visible.map((line) => visibleWidth(line)))
);
const boxWidth = inner + 4;
const boxHeight = visible.length + 2;
const left = body.col + Math.max(0, Math.floor((body.width - boxWidth) / 2));
const top = body.row + Math.max(0, Math.floor((body.height - boxHeight) / 2));
const titleText = ` ${content.title} `;
const titleFill = Math.max(0, inner + 2 - visibleWidth(titleText));
const boxLines = [
`${glyphs.boxTopLeft}${titleText}${glyphs.boxHorizontal.repeat(titleFill)}${glyphs.boxTopRight}`,
...visible.map((line) => `${glyphs.boxVertical} ${padDisplay(line, inner)} ${glyphs.boxVertical}`),
`${glyphs.boxBottomLeft}${glyphs.boxHorizontal.repeat(inner + 2)}${glyphs.boxBottomRight}`,
];
for (let i = 0; i < boxLines.length; i++) {
const row = top + i - 1;
if (row < 0 || row >= lines.length) continue;
lines[row] = `${' '.repeat(left - 1)}${paint(boxLines[i], SGR.cyan)}`;
}
}
// ─────────────────────────────────────────────────────────────────────────────
// Frame
// ─────────────────────────────────────────────────────────────────────────────
function writeBody(lines: string[], model: TuiRenderModel, layout: TuiLayout, opts: TuiRenderOptions): void {
const { list, preview, divider } = layout;
if (list.height <= 0) return;
const paint = painterFor(opts.color);
const glyphs = glyphsFor(opts.glyphs);
const entries = buildListEntries(model, layout, opts);
if (entries.length === 0) {
const hint = paint('No sessions. n to start one, q to quit.', SGR.gray);
const row = list.row + Math.floor((list.height - 1) / 2);
lines[row - 1] = centered(hint, layout.cols);
return;
}
const start = computeListWindow(entries, list.height, model.selectedId);
const previewLines = preview ? buildPreviewLines(model, preview, opts) : [];
for (let i = 0; i < list.height; i++) {
const left = entries[start + i]?.text ?? ' '.repeat(list.width);
if (!preview || !divider) {
lines[list.row - 1 + i] = left;
continue;
}
const right = previewLines[i] ?? ' '.repeat(preview.width);
lines[list.row - 1 + i] = `${left}${paint(glyphs.divider, SGR.gray)}${right}`;
}
}
/**
* The whole frame as one string: absolute cursor addressing per line, each line
* closed with an erase-to-end so a shorter line cannot leave the previous
* frame's tail behind.
*/
export function renderFrame(model: TuiRenderModel, layout: TuiLayout, opts: TuiRenderOptions): string {
const lines: string[] = new Array<string>(layout.rows).fill('');
lines[0] = renderHeaderLine(model, layout, opts);
if (layout.banner) lines[layout.banner.row - 1] = renderBannerLine(model, layout, opts);
writeBody(lines, model, layout, opts);
if (layout.footer.height > 0) lines[layout.footer.row - 1] = renderFooterLine(model, layout, opts);
applyOverlay(lines, model, layout, opts);
let frame = '';
for (let i = 0; i < lines.length; i++) {
frame += `\x1b[${i + 1};1H${clipStyledLine(lines[i], layout.cols)}\x1b[K`;
}
return frame;
}
+234
View File
@@ -0,0 +1,234 @@
/**
* @fileoverview Pure SSE wire parsing, event classification and reconnect math.
*
* Node has no `EventSource`, so the TUI reads `GET /api/events` as a raw stream
* and decodes the wire format here. Everything in this module is pure: bytes
* (as decoded strings) in, frames out. The socket, the timers and the backoff
* loop live in `tui-client.ts`.
*
* Three wire details this parser exists to get right:
*
* 1. **Frames split across chunk boundaries.** A TCP read can end anywhere,
* including between the `\r` and the `\n` of a CRLF, so a lone trailing
* `\r` is held back rather than treated as a line end.
* 2. **Comments are not frames.** The server appends a `:pppp…` padding line
* after a frame while a Cloudflare tunnel is up (it flushes the proxy
* buffer) and that line carries no blank line after it. Dispatch happens on
* a blank line and on nothing else, so padding cannot split a frame.
* 3. **The keepalive is a NAMED event** (`sse:heartbeat`), because an SSE
* comment is invisible to a browser `EventSource` by spec. We treat ANY
* inbound bytes as liveness, comments included, which is why comments need
* no representation in the returned frames.
*
* @module tui/tui-sse
*/
import {
ApprovalPending,
ApprovalResolved,
ApprovalUpdated,
Heartbeat,
Init,
MuxCreated,
MuxDied,
MuxKilled,
RemoteSessionDropped,
RemoteSessionReconnected,
SessionCliInfo,
SessionCompletion,
SessionCreated,
SessionDeleted,
SessionError,
SessionExit,
SessionIdle,
SessionInteractive,
SessionPinned,
SessionRunning,
SessionStatusTelemetry,
SessionUpdated,
SessionWorking,
} from '../web/sse-events.js';
/** One dispatched SSE frame. `event` defaults to `message` per the spec. */
export interface SseFrame {
event: string;
data: string;
id?: string;
retry?: number;
}
/**
* Ceiling on the unterminated tail the parser will hold. The `init` frame
* carries the whole light state and is legitimately large, so this is not a
* frame-size limit but a guard against a non-SSE endpoint streaming something
* with no line terminators at all.
*/
export const MAX_PENDING_BYTES = 8 * 1024 * 1024;
/** Incremental decoder. One instance per connection; `reset()` on reconnect. */
export class SseFrameParser {
private buffer = '';
private eventName = '';
private dataLines: string[] = [];
private lastId: string | undefined;
private retry: number | undefined;
/** Decode one chunk, returning every frame it completed (possibly none). */
feed(chunk: string): SseFrame[] {
this.buffer += chunk;
const frames: SseFrame[] = [];
let start = 0;
for (let i = 0; i < this.buffer.length; i++) {
const ch = this.buffer[i];
if (ch !== '\n' && ch !== '\r') continue;
// A trailing CR may be the first half of a CRLF the next chunk finishes.
if (ch === '\r' && i === this.buffer.length - 1) break;
const line = this.buffer.slice(start, i);
if (ch === '\r' && this.buffer[i + 1] === '\n') i++;
start = i + 1;
const frame = this.consumeLine(line);
if (frame) frames.push(frame);
}
this.buffer = this.buffer.slice(start);
if (this.buffer.length > MAX_PENDING_BYTES) this.reset();
return frames;
}
/** Drop every partial frame. Called when a connection is torn down. */
reset(): void {
this.buffer = '';
this.eventName = '';
this.dataLines = [];
this.lastId = undefined;
this.retry = undefined;
}
private consumeLine(line: string): SseFrame | null {
if (line === '') return this.dispatch();
if (line.startsWith(':')) return null;
const colon = line.indexOf(':');
const field = colon === -1 ? line : line.slice(0, colon);
let value = colon === -1 ? '' : line.slice(colon + 1);
if (value.startsWith(' ')) value = value.slice(1);
switch (field) {
case 'event':
this.eventName = value;
break;
case 'data':
this.dataLines.push(value);
break;
case 'id':
this.lastId = value;
break;
case 'retry': {
const ms = Number.parseInt(value, 10);
if (Number.isSafeInteger(ms) && ms >= 0) this.retry = ms;
break;
}
default:
break;
}
return null;
}
/**
* A blank line ends a frame. Per the spec an empty data buffer dispatches
* nothing (it still clears the event name), which is what makes a bare
* `event:` line or a stray blank line harmless.
*/
private dispatch(): SseFrame | null {
if (this.dataLines.length === 0) {
this.eventName = '';
return null;
}
const frame: SseFrame = {
event: this.eventName || 'message',
data: this.dataLines.join('\n'),
};
if (this.lastId !== undefined) frame.id = this.lastId;
if (this.retry !== undefined) frame.retry = this.retry;
this.eventName = '';
this.dataLines = [];
return frame;
}
}
/** What the app layer should do with a frame. */
export type SseEventClass = 'init' | 'heartbeat' | 'resync' | 'approval' | 'plan-usage' | 'ignore';
/**
* Events that change WHICH sessions exist or WHAT state they are in.
*
* The TUI never patches a single row from a payload: it re-fetches the unified
* list, which is the only source that also carries history rows, so this set
* only has to answer "is a refetch worth it". `session:terminal` is
* deliberately absent (it is the bulk of the stream and the preview pane pulls
* its own tail), as are the ralph/respawn/subagent/orchestrator families, which
* change nothing the dashboard draws.
*/
const RESYNC_EVENTS: ReadonlySet<string> = new Set<string>([
SessionCreated,
SessionUpdated,
SessionDeleted,
SessionExit,
SessionError,
SessionIdle,
SessionWorking,
SessionCompletion,
SessionInteractive,
SessionRunning,
SessionPinned,
SessionCliInfo,
MuxCreated,
MuxKilled,
MuxDied,
RemoteSessionDropped,
RemoteSessionReconnected,
]);
const APPROVAL_EVENTS: ReadonlySet<string> = new Set<string>([ApprovalPending, ApprovalUpdated, ApprovalResolved]);
/** Which approval event this is, or null when the name is not one. */
export function approvalEventKind(name: string): 'pending' | 'updated' | 'resolved' | null {
if (name === ApprovalPending) return 'pending';
if (name === ApprovalUpdated) return 'updated';
if (name === ApprovalResolved) return 'resolved';
return null;
}
/** Route one event name. Unknown names are ignored, never a resync. */
export function classifySseEvent(name: string): SseEventClass {
if (name === Init) return 'init';
if (name === Heartbeat) return 'heartbeat';
if (APPROVAL_EVENTS.has(name)) return 'approval';
if (name === SessionStatusTelemetry) return 'plan-usage';
if (RESYNC_EVENTS.has(name)) return 'resync';
return 'ignore';
}
/**
* Silence that means the stream is dead even though the socket never errored.
* The server heartbeats every 15s, so three missed beats is the signal.
*/
export const SSE_STALE_TIMEOUT_MS = 45_000;
/** Reconnect delay ceiling. A local server is back in milliseconds, not minutes. */
export const SSE_MAX_BACKOFF_MS = 15_000;
/** First reconnect delay; doubles per consecutive failure up to the ceiling. */
export const SSE_BASE_BACKOFF_MS = 500;
/**
* Delay before reconnect attempt `attempt` (1-based). Deterministic, with no
* jitter on purpose: one client talks to one loopback server, so there is no
* herd to spread out and a reproducible delay is testable.
*/
export function sseBackoffDelay(attempt: number, base = SSE_BASE_BACKOFF_MS, max = SSE_MAX_BACKOFF_MS): number {
const step = Math.max(1, Math.trunc(attempt));
const exponent = Math.min(step - 1, 30);
return Math.min(max, base * 2 ** exponent);
}
+209
View File
@@ -0,0 +1,209 @@
/**
* @fileoverview Shared types for the `codeman tui` pure core.
*
* The TUI is a client of the server, never a second brain: its rows are the
* rows `GET /api/sessions/unified` already returns (`UnifiedSessionItem`) and
* its blocked states are the items `GET /api/approvals` already parsed
* (`ApprovalItem`). Both are imported as TYPES only, so nothing here pulls the
* server, node-pty or the utils barrel into a CLI process.
*
* Everything in `src/tui/*` except `tui-app.ts` / `tui-client.ts` is pure:
* deterministic outputs from inputs, no `process.*`, no timers, no IO.
*
* @module tui/tui-types
*/
import type { UnifiedSessionItem } from '../services/unified-session-service.js';
import type { ApprovalItem } from '../web/approval-inbox.js';
import type { TuiComposerState } from './tui-composer.js';
/**
* A unified-list row plus the few live-only extras the dashboard shows.
*
* The unified list is the spine (it is the only source that carries history
* rows), but it has no token counters and no turn-start stamp, so the client
* merges those from the live session payload (`GET /api/sessions` /
* `session_updated` SSE) when a row is live. History rows simply lack them.
*/
export interface TuiSessionRow extends UnifiedSessionItem {
/**
* Wall-clock ms of the pane's last Enter (`SessionState.lastSubmitAt`). The
* only usable "working since" anchor: a working pane repaints about once a
* second, so its `lastActivityAt` is always "now".
*/
lastSubmitAt?: number;
inputTokens?: number;
outputTokens?: number;
/**
* tmux session name to attach to (`codeman-<first 8 of the id>`).
*
* The unified list does not carry it (no server view merges the mux name into
* a row), so the app layer fills it in from the local tmux enumeration, which
* is also the only thing that proves the pane really exists. A row without one
* cannot be attached: it is either history or a direct-PTY session.
*/
muxName?: string;
}
/**
* Row state, in the web UI's vocabulary so both surfaces read the same.
*
* There is deliberately no `error` member: an errored session is something a
* human has to look at, so it classifies as `waiting` and lands in NEEDS YOU
* rather than growing a fifth color nobody designed.
*/
export type TuiSessionState = 'blocked-question' | 'blocked-permission' | 'waiting' | 'working' | 'idle' | 'recent';
/** The four display groups, in display order. */
export type TuiGroupKey = 'needs-you' | 'working' | 'idle' | 'recent';
/** A classified session: what the cursor moves over and the renderer paints. */
export interface TuiRow {
session: TuiSessionRow;
state: TuiSessionState;
group: TuiGroupKey;
/** The pending prompt that blocks this session, when it has one. */
approval?: ApprovalItem;
/** Epoch ms the session entered `state`; the intra-group sort key. 0 when unknown. */
since: number;
}
export interface TuiGroup {
key: TuiGroupKey;
label: string;
rows: TuiRow[];
}
/** How the client currently sees the server. */
export type TuiConnectionStatus = 'connected' | 'reconnecting' | 'degraded' | 'down';
/** Which overlay (if any) owns the keyboard. */
export type TuiUiMode = 'list' | 'help' | 'confirm-kill' | 'prompt' | 'search' | 'digest' | 'message' | 'new-session';
/**
* Glyph capability tier. Detection is env-driven and therefore lives in a tiny
* function the app layer calls (`detectGlyphTier`); the renderer only ever
* takes the resolved tier as an input.
*/
export type TuiGlyphTier = 'nerd' | 'unicode' | 'ascii';
/** Header facts, all optional: the header degrades to just the product name. */
export interface TuiHeaderInfo {
hostname?: string;
instance?: string;
version?: string;
/** Plan-usage chip text, e.g. `5h 32% · wk 61%`. */
planUsage?: string;
}
/** The selected session's terminal tail, already run through `toDisplayLines()`. */
export interface TuiPreview {
sessionId: string;
/** Display lines, oldest first. */
lines: string[];
/** Set instead of lines when the tail could not be fetched. */
error?: string;
/**
* Set instead of lines when there is nothing to fetch (a history row has no
* live buffer). Distinct from `error`: nothing failed, so it must not read
* like something did.
*/
note?: string;
}
export interface TuiMessage {
text: string;
tone: 'info' | 'warn' | 'err';
}
/** Typed-confirmation state for `x` (kill): the user retypes the session name. */
export interface TuiConfirmState {
sessionId: string;
name: string;
}
export interface TuiPickerItem {
/** What choosing this item means to the caller; never shown. */
id: string;
label: string;
/** Second column, dimmed (a case path, a mode description). */
detail?: string;
}
/**
* A one-column chooser drawn as an overlay (the case and mode pickers behind
* `n`). Items are already filtered: the app owns the unfiltered list, the
* renderer only paints what it is given.
*/
export interface TuiPickerState {
title: string;
items: TuiPickerItem[];
/** Index into `items`; -1 when the list is empty. */
index: number;
/** Current filter text, when the picker filters as you type. */
filter?: string;
/** One line above the list: what is being chosen, or why the list is empty. */
hint?: string;
}
/** The `p` composer: one line aimed at one session. */
export interface TuiPromptState {
sessionId: string;
/** What the session is called on screen, for the footer prefix. */
label: string;
composer: TuiComposerState;
}
/**
* One line of the `/` overlay. Group headers are chrome (the API returns typed
* groups), so only `result` rows are selectable.
*/
export interface TuiSearchEntry {
kind: 'header' | 'result';
text: string;
detail?: string;
sessionId?: string;
/** The row can hand the dashboard a session that is open right now. */
live?: boolean;
}
export interface TuiSearchState {
composer: TuiComposerState;
/** The query `entries` answer. Lags the composer while a search is in flight. */
query: string;
entries: TuiSearchEntry[];
/** Index into `entries`, always a `result` row; -1 when none is selectable. */
index: number;
status: 'idle' | 'searching' | 'done' | 'error';
/** One line under the query: what happened, or why there is nothing. */
note?: string;
}
/** The `g` overlay: pre-formatted lines plus where the window starts. */
export interface TuiDigestState {
title: string;
lines: string[];
offset: number;
}
/**
* What `renderFrame()` reads. The store implements it; a test can hand-build
* one, which is what keeps the renderer testable without the model.
*/
export interface TuiRenderModel {
groups(): TuiGroup[];
readonly selectedId: string | null;
readonly connection: TuiConnectionStatus;
readonly mode: TuiUiMode;
readonly header: TuiHeaderInfo;
readonly preview: TuiPreview | null;
readonly message: TuiMessage | null;
readonly confirm: TuiConfirmState | null;
/** Optional so a test can hand-build a model without one. */
readonly picker?: TuiPickerState | null;
readonly prompt?: TuiPromptState | null;
readonly search?: TuiSearchState | null;
readonly digest?: TuiDigestState | null;
/** Live sessions only (RECENT rows are history, not sessions you have open). */
readonly sessionCount: number;
}
+3
View File
@@ -24,6 +24,7 @@ import type { TaskState } from './task.js';
import type { RalphLoopState } from './ralph.js';
import type { RespawnConfig } from './respawn.js';
import type { CronJob, CronJobRun } from './cron.js';
import type { TabLayout } from '../tab-layout.js';
// ========== Global Stats Types ==========
@@ -118,6 +119,8 @@ export interface AppState {
cronJobRuns?: Record<string, CronJobRun>;
/** Global tab order shared across devices (ordered list of sessionIds) — COD-131 */
sessionOrder?: string[];
/** Owner-scoped authoritative grouped tab layouts. */
tabLayouts?: Record<string, TabLayout>;
}
// ========== Default Configuration ==========
+39 -4
View File
@@ -8,7 +8,7 @@
* - SessionConfig — creation-time config (id, workingDir, createdAt)
* - SessionOutput — captured stdout/stderr/exitCode
* - SessionStatus — 'idle' | 'busy' | 'stopped' | 'error'
* - SessionMode — 'claude' | 'shell' | 'opencode' | 'codex' | 'gemini' | 'antigravity' | 'pi' (which CLI backend)
* - SessionMode — 'claude' | 'shell' | 'opencode' | 'codex' | 'gemini' | 'antigravity' | 'pi' | 'grok' (which CLI backend)
* - ClaudeMode — CLI permission mode ('dangerously-skip-permissions' | 'auto' | 'normal' | 'allowedTools')
* - SessionColor — visual differentiation color
* - OpenCodeConfig — OpenCode-specific settings (model, autoAllowTools, continueSession)
@@ -16,6 +16,7 @@
* - GeminiConfig — Gemini CLI-specific settings (model, approvalMode, resumeSession)
* - AntigravityConfig — Antigravity CLI (agy) settings (model, dangerouslySkipPermissions, resumeConversationId)
* - PiConfig — Pi CLI (pi.dev) settings (model, provider, thinking, resume/continue, project trust)
* - GrokConfig — Grok Build CLI (xAI `grok`) settings (model, alwaysApprove, resume/continue)
*
* Cross-domain relationships:
* - SessionState.respawnConfig embeds RespawnConfig (respawn domain)
@@ -44,11 +45,11 @@ export type SessionStatus = 'idle' | 'busy' | 'stopped' | 'error';
export type ClaudeMode = 'dangerously-skip-permissions' | 'auto' | 'normal' | 'allowedTools';
/** Session mode: which CLI backend a session runs */
export type SessionMode = 'claude' | 'shell' | 'opencode' | 'codex' | 'gemini' | 'antigravity' | 'pi';
export type SessionMode = 'claude' | 'shell' | 'opencode' | 'codex' | 'gemini' | 'antigravity' | 'pi' | 'grok';
export type RemoteCommandMode = Extract<
SessionMode,
'shell' | 'claude' | 'opencode' | 'codex' | 'gemini' | 'antigravity' | 'pi'
'shell' | 'claude' | 'opencode' | 'codex' | 'gemini' | 'antigravity' | 'pi' | 'grok'
>;
/**
@@ -157,7 +158,7 @@ export interface RemoteSessionInfo {
/** Which CLI backends a Docker case can run (same set as remote). */
export type DockerCommandMode = Extract<
SessionMode,
'shell' | 'claude' | 'opencode' | 'codex' | 'gemini' | 'antigravity' | 'pi'
'shell' | 'claude' | 'opencode' | 'codex' | 'gemini' | 'antigravity' | 'pi' | 'grok'
>;
/** Container engine. Docker and Podman differ in the uid/userns + host-gateway alias. */
@@ -363,6 +364,30 @@ export interface PiConfig {
approveProjectTrust?: boolean;
}
/**
* Grok Build CLI (xAI `grok`) session configuration.
*
* Grok has Claude-style permission modes; the bypass switch is `--always-approve`
* ("auto-approve all tool executions", the CLI's `bypassPermissions` mode). Deny
* rules from `~/.grok/config.toml` / project `.grok/config.toml` still apply on
* top of it. Verified against grok 1.0.5.
*/
export interface GrokConfig {
/** Model ID (e.g. "grok-4.5", or a custom `[model.<name>]` from config.toml). Passed via --model. */
model?: string;
/**
* Auto-approve all tool executions (passes --always-approve). Absent = grok's
* own default permission mode (ask). Multi-user: forced off for non-granted
* owners by the only-if-sent clamp branch, like codex/antigravity — the
* absent-config spawn already defaults safe.
*/
alwaysApprove?: boolean;
/** Continue the most recent session for the working directory (-c). Skipped when resumeSessionId is set. */
continueSession?: boolean;
/** Resume a specific session by ID (--resume). Ids only, never titles or paths. */
resumeSessionId?: string;
}
/**
* Configuration for creating a new session
*/
@@ -500,6 +525,14 @@ export interface SessionState {
color?: SessionColor;
/** Flicker filter enabled (buffers output after screen clears) */
flickerFilterEnabled?: boolean;
/**
* True while the CLI in the pane has a mouse-tracking DECSET on, as observed
* by the server on its way out of the stream (those sequences are stripped for
* claude/codex/gemini, so the browser can never see them itself). The browser
* hand-encodes a click report ONLY when this is true; without it, every click
* sent mouse reports to a CLI that never asked for them.
*/
cliMouseTracking?: boolean;
/** Claude Code CLI version (parsed from terminal, e.g., "2.1.27") */
cliVersion?: string;
/** Claude model in use (parsed from terminal, e.g., "Opus 4.5") */
@@ -518,6 +551,8 @@ export interface SessionState {
antigravityConfig?: AntigravityConfig;
/** Pi-specific configuration (only for mode === 'pi') */
piConfig?: PiConfig;
/** Grok-specific configuration (only for mode === 'grok') */
grokConfig?: GrokConfig;
/** Claude conversation session ID to resume after reboot (set by restore script) */
resumeSessionId?: string;
/** Claude CLI effort level (soft default via --settings, switchable in-session via /effort) */
+49
View File
@@ -98,3 +98,52 @@ export interface UpdateCheckResult {
source: 'github-api' | 'git-ls-remote' | 'none';
error?: string;
}
/**
* Role of a remote in the repository-status view.
* - `tracking`: the current branch's `@{upstream}` remote (where `git pull` goes).
* - `upstream`: the canonical project (a remote named `origin`/`upstream` that is
* not the tracking remote).
* - `other`: anything else explicitly requested via `CODEMAN_UPDATE_REMOTES`.
*/
export type RepoRemoteRole = 'tracking' | 'upstream' | 'other';
/** A single incoming commit — present on the remote ref but not in local HEAD. */
export interface RepoIncomingCommit {
/** Abbreviated SHA. */
sha: string;
/** Commit subject (first line). */
subject: string;
}
/** Ahead/behind + incoming summary for local HEAD vs one remote's compare ref. */
export interface RepoRemoteStatus {
/** Remote name, e.g. `origin`, `bitbucket`. */
name: string;
/** Remote URL (best-effort; empty if unresolved). */
url: string;
role: RepoRemoteRole;
/** Ref HEAD is compared against, e.g. `origin/master`, `bitbucket/local`. */
compareRef: string;
/** Commits in local HEAD not on the remote ref (local-only / unpushed). */
ahead: number;
/** Commits on the remote ref not in local HEAD (incoming). */
behind: number;
/** Up to N most recent incoming commits (newest first). */
incoming: RepoIncomingCommit[];
/** Set when this remote could not be fetched/compared. */
error?: string;
}
/** Result of the repository-status check across the configured remotes. */
export interface RepositoryStatusResult {
/** epoch ms of the check. */
checkedAt: number;
/** False when this is not a git install (then `remotes` is empty + `error` set). */
isGit: boolean;
/** Current running version, for display. */
currentVersion: string;
remotes: RepoRemoteStatus[];
/** Top-level error (e.g. not a git install, or no remotes resolved). */
error?: string;
}
+26 -30
View File
@@ -7,22 +7,37 @@
* @module utils/antigravity-cli-resolver
*/
import { execSync } from 'node:child_process';
import { existsSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { join } from 'node:path';
import { homedir } from 'node:os';
import { EXEC_TIMEOUT_MS } from '../config/exec-timeout.js';
import {
createCliExecutableResolver,
formatCliNotFoundMessage,
type CliResolverHost,
} from './cli-executable-resolver.js';
/** Common directories where the Antigravity CLI binary may be installed */
const ANTIGRAVITY_SEARCH_DIRS = [
join(homedir(), '.local', 'bin'),
join(homedir(), '.antigravity', 'bin'),
'/usr/local/bin',
join(homedir(), '.bun', 'bin'),
join(homedir(), '.npm-global', 'bin'),
join(homedir(), 'bin'),
];
/** Cached directory containing the agy binary (empty string = searched but not found) */
let _antigravityDir: string | null = null;
const ANTIGRAVITY_NOT_FOUND =
'Antigravity CLI not found. Install with: curl -fsSL https://antigravity.google/cli/install.sh | bash';
function createAntigravityResolver(host?: CliResolverHost, now?: () => number) {
return createCliExecutableResolver({ binary: 'agy', searchDirs: ANTIGRAVITY_SEARCH_DIRS, now }, host);
}
/** Creates an isolated Antigravity wrapper around an injected resolver host and clock. */
export function createAntigravityResolverForTest(host: CliResolverHost, now?: () => number) {
return createAntigravityResolver(host, now);
}
const antigravityResolver = createAntigravityResolver();
/**
* Finds the directory containing the `agy` binary.
@@ -31,30 +46,7 @@ let _antigravityDir: string | null = null;
* @returns Directory path, or null if not found
*/
export function resolveAntigravityDir(): string | null {
if (_antigravityDir !== null) return _antigravityDir || null;
try {
const result = execSync('which agy', {
encoding: 'utf-8',
timeout: EXEC_TIMEOUT_MS,
}).trim();
if (result && existsSync(result)) {
_antigravityDir = dirname(result);
return _antigravityDir;
}
} catch {
// agy not in PATH, will check common locations
}
for (const dir of ANTIGRAVITY_SEARCH_DIRS) {
if (existsSync(join(dir, 'agy'))) {
_antigravityDir = dir;
return _antigravityDir;
}
}
_antigravityDir = '';
return null;
return antigravityResolver.resolve()?.directory ?? null;
}
/**
@@ -63,3 +55,7 @@ export function resolveAntigravityDir(): string | null {
export function isAntigravityAvailable(): boolean {
return resolveAntigravityDir() !== null;
}
export function getAntigravityNotFoundMessage(): string {
return formatCliNotFoundMessage(ANTIGRAVITY_NOT_FOUND, antigravityResolver.diagnostics());
}
+15 -28
View File
@@ -8,11 +8,11 @@
* @module utils/claude-cli-resolver
*/
import { execSync, execFileSync } from 'node:child_process';
import { existsSync } from 'node:fs';
import { delimiter, dirname, join } from 'node:path';
import { execFileSync } from 'node:child_process';
import { delimiter, join } from 'node:path';
import { homedir } from 'node:os';
import { EXEC_TIMEOUT_MS } from '../config/exec-timeout.js';
import { createCliExecutableResolver, formatCliNotFoundMessage } from './cli-executable-resolver.js';
/** Common directories where the Claude CLI binary may be installed */
const CLAUDE_SEARCH_DIRS = [
@@ -23,8 +23,8 @@ const CLAUDE_SEARCH_DIRS = [
join(homedir(), 'bin'),
];
/** Cached directory containing the claude binary (empty string = searched but not found) */
let _claudeDir: string | null = null;
const claudeResolver = createCliExecutableResolver({ binary: 'claude', searchDirs: CLAUDE_SEARCH_DIRS });
const CLAUDE_NOT_FOUND = 'Claude CLI not found. Install it with: curl -fsSL https://claude.ai/install.sh | bash';
/**
* Returns true if the Claude CLI binary can be located (via `which` or one of
@@ -43,29 +43,11 @@ export function isClaudeAvailable(): boolean {
* @returns Directory path, or null if not found
*/
export function findClaudeDir(): string | null {
if (_claudeDir !== null) return _claudeDir || null;
return claudeResolver.resolve()?.directory ?? null;
}
// Try `which` first (respects current PATH)
try {
const result = execSync('which claude', { encoding: 'utf-8', timeout: EXEC_TIMEOUT_MS }).trim();
if (result && existsSync(result)) {
_claudeDir = dirname(result);
return _claudeDir;
}
} catch {
// Claude not in PATH, will check common locations
}
// Fallback: check common installation directories
for (const dir of CLAUDE_SEARCH_DIRS) {
if (existsSync(join(dir, 'claude'))) {
_claudeDir = dir;
return _claudeDir;
}
}
_claudeDir = ''; // mark as searched, not found
return null;
export function getClaudeNotFoundMessage(): string {
return formatCliNotFoundMessage(CLAUDE_NOT_FOUND, claudeResolver.diagnostics());
}
/**
@@ -99,7 +81,9 @@ export function getAugmentedPath(): string {
const currentPath = process.env.PATH || '';
const claudeDir = findClaudeDir();
if (claudeDir && !currentPath.split(delimiter).includes(claudeDir)) {
if (!claudeDir) return currentPath;
if (!currentPath.split(delimiter).includes(claudeDir)) {
_augmentedPath = `${claudeDir}${delimiter}${currentPath}`;
return _augmentedPath;
}
@@ -193,6 +177,9 @@ function probeClaudeCliVersion(): string | null {
encoding: 'utf-8',
timeout: EXEC_TIMEOUT_MS,
env: { ...process.env, PATH: getAugmentedPath() },
// execFileSync's timeout only SENDS the signal and then keeps waiting; a
// child that ignores SIGTERM would block the server thread permanently.
killSignal: 'SIGKILL',
});
const match = out.match(/(\d+\.\d+\.\d+)/);
return match ? match[1] : null;
+301
View File
@@ -0,0 +1,301 @@
/**
* @fileoverview Shared CLI executable resolution for the per-CLI resolvers.
*
* One lookup chain behind all seven *-cli-resolver modules (claude, opencode,
* codex, gemini, antigravity, pi, grok): the server process PATH first, then the
* CLI's common install directories in order, then — last, because it is the
* only step that spawns anything — an interactive login shell, which is what
* finds nvm/Homebrew/user-npm installs when Codeman runs as a systemd/launchd
* service with a minimal PATH (launchd hands a job `/usr/bin:/bin:/usr/sbin:/sbin`).
*
* Caching is asymmetric, same shape as `resolveClaudeCliVersion` in
* claude-cli-resolver.ts: a successful resolution is cached for the process
* lifetime, a MISS is negative-cached and retried only after a doubling backoff
* (`cliResolveRetryDelayMs`). The callers are request-facing (the per-CLI
* status endpoints in system-routes.ts, the availability gates in
* session-routes.ts, and tmux-manager's spawn path), and the login-shell probe
* is a SYNCHRONOUS spawn bounded by `EXEC_TIMEOUT_MS` — without the negative
* cache, a missing CLI re-ran the whole chain and stalled the event loop for up
* to 5s on every request, forever.
*
* Test hermeticity: under vitest (`process.env.VITEST`) the production host
* short-circuits — IO primitives that were not injected become inert stubs, so
* a suite can never scan the machine's PATH or spawn login shells (the same
* rule as `IS_TEST_MODE` in tmux-manager and the VITEST gate in
* `getClaudeCliVersion`). Tests opt back in through the injection hooks
* (`runCommand`/`isExecutableFile` fakes do no real IO by construction) or, for
* fixtures that need the real filesystem predicate against their own temp
* files, via `allowRealIoUnderVitest`.
*
* @module utils/cli-executable-resolver
*/
import { execFileSync } from 'node:child_process';
import { accessSync, constants, statSync } from 'node:fs';
import { basename, delimiter, dirname, isAbsolute, join } from 'node:path';
import { EXEC_TIMEOUT_MS } from '../config/exec-timeout.js';
import { loginShellArgs, resolveLocalShell } from './shell-resolver.js';
const SAFE_BINARY_NAME = /^[a-z0-9][a-z0-9._-]*$/i;
const LOGIN_SHELL_BEGIN_MARKER = '__CODEMAN_CLI_RESOLVE_BEGIN__';
const LOGIN_SHELL_END_MARKER = '__CODEMAN_CLI_RESOLVE_END__';
/** Maximum rendered length of each bounded diagnostic field, excluding its label. */
const DIAGNOSTIC_FIELD_MAX_LENGTH = 1024;
/** First retry window after a full-chain resolution miss. */
const RESOLVE_RETRY_BASE_MS = 60_000;
/**
* Ceiling for the doubling backoff. Deliberately shorter than the 15min cap on
* the claude version probe: that one is cosmetic, while this gates the Run
* flow, and "installing a CLI while the server is running is picked up without
* a restart" should stay true within minutes.
*/
const RESOLVE_RETRY_MAX_MS = 5 * 60_000;
/**
* How long to wait before re-running the resolution chain after `failures`
* consecutive misses: 1min, 2min, 4min… capped at 5min. Mirrors
* `claudeVersionRetryDelayMs` in claude-cli-resolver.ts. Exported for tests.
*/
export function cliResolveRetryDelayMs(failures: number): number {
if (failures <= 0) return 0;
return Math.min(RESOLVE_RETRY_BASE_MS * 2 ** (failures - 1), RESOLVE_RETRY_MAX_MS);
}
export type CliResolutionSource = 'process-path' | 'common-directory' | 'login-shell';
export interface CliResolutionDiagnostics {
binary: string;
processPath: string;
shellPath: string;
shellArgs: string[];
searchDirs: string[];
}
export interface CliResolverHost {
processPath: string;
shellPath: string;
shellArgs: string[];
findOnProcessPath(binary: string): string | null;
findInLoginShell(binary: string): string | null;
exists(path: string): boolean;
}
export interface CandidateValidation<T> {
accepted: boolean;
metadata?: T;
}
export interface CliResolution<T = undefined> {
binaryPath: string;
directory: string;
source: CliResolutionSource;
metadata?: T;
}
export interface CliExecutableResolver<T = undefined> {
resolve(): CliResolution<T> | null;
diagnostics(): CliResolutionDiagnostics;
}
export interface CliResolverCommandOptions {
encoding: 'utf8';
timeout: number;
stdio: ['ignore', 'pipe', 'ignore'];
killSignal: 'SIGKILL';
}
export type CliResolverCommandRunner = (file: string, args: string[], options: CliResolverCommandOptions) => string;
export interface ProductionCliResolverHostOptions {
processPath?: string;
shellPath?: string;
shellArgs?: string[];
runCommand?: CliResolverCommandRunner;
isExecutableFile?: (path: string) => boolean;
/**
* Test-only escape hatch: keep the REAL IO primitives even under vitest.
* For tests that exercise `isExecutableRegularFile` against their own temp
* fixtures. Such a test must still inject `runCommand` if it can reach the
* login-shell step, or it would spawn a real interactive shell.
*/
allowRealIoUnderVitest?: boolean;
}
function isExecutableRegularFile(path: string): boolean {
try {
if (!statSync(path).isFile()) return false;
accessSync(path, constants.X_OK);
return true;
} catch {
return false;
}
}
function parseLoginShellResult(output: string, binary: string): string | null {
const lines = output.split(/\r?\n/).map((line) => line.trim());
const begin = lines.indexOf(LOGIN_SHELL_BEGIN_MARKER);
if (begin === -1) return null;
const end = lines.indexOf(LOGIN_SHELL_END_MARKER, begin + 1);
if (end === -1) return null;
for (const candidate of lines.slice(begin + 1, end)) {
if (isAbsolute(candidate) && basename(candidate) === binary) return candidate;
}
return null;
}
function loginShellCommand(binary: string): string {
return [
`printf '%s\\n' '${LOGIN_SHELL_BEGIN_MARKER}'`,
`command -v -- ${binary}`,
`printf '%s\\n' '${LOGIN_SHELL_END_MARKER}'`,
].join('; ');
}
export function createProductionCliResolverHost(options: ProductionCliResolverHostOptions = {}): CliResolverHost {
const shellPath = options.shellPath ?? resolveLocalShell();
const shellArgs = options.shellArgs ?? loginShellArgs(shellPath).trim().split(/\s+/).filter(Boolean);
const processPath = options.processPath ?? process.env.PATH ?? '';
// Hermeticity gate (see @fileoverview): under vitest, any IO primitive the
// caller did not inject is replaced by an inert stub. The suites must never
// depend on — or execute — whatever happens to be installed on the machine
// running them, and route tests hitting the per-CLI status endpoints would
// otherwise scan the real PATH and spawn real login shells on CI.
const inert = Boolean(process.env.VITEST) && options.allowRealIoUnderVitest !== true;
const isExecutableFile = options.isExecutableFile ?? (inert ? () => false : isExecutableRegularFile);
const runCommand: CliResolverCommandRunner =
options.runCommand ?? (inert ? () => '' : (file, args, commandOptions) => execFileSync(file, args, commandOptions));
const run = (file: string, args: string[]): string => {
try {
return runCommand(file, args, {
encoding: 'utf8',
timeout: EXEC_TIMEOUT_MS,
stdio: ['ignore', 'pipe', 'ignore'],
// SIGKILL is load-bearing: execFileSync's `timeout` only SENDS the kill
// signal and then keeps waiting for the child to exit. Interactive bash
// ignores SIGTERM (the default), so a login shell stuck in a blocking
// .bash_profile would survive the timeout and block the server forever.
killSignal: 'SIGKILL',
});
} catch {
return '';
}
};
return {
processPath,
shellPath,
shellArgs: [...shellArgs],
findOnProcessPath: (binary) => {
if (!SAFE_BINARY_NAME.test(binary)) return null;
for (const directory of processPath.split(delimiter).filter(Boolean)) {
const candidate = join(directory, binary);
if (isAbsolute(candidate) && isExecutableFile(candidate)) return candidate;
}
return null;
},
findInLoginShell: (binary) => {
if (!SAFE_BINARY_NAME.test(binary)) return null;
const candidate = parseLoginShellResult(run(shellPath, [...shellArgs, '-c', loginShellCommand(binary)]), binary);
return candidate && isExecutableFile(candidate) ? candidate : null;
},
exists: isExecutableFile,
};
}
export function createCliExecutableResolver<T = undefined>(
options: {
binary: string;
searchDirs: string[];
validateCandidate?: (path: string) => CandidateValidation<T>;
/** Clock injection for tests driving the failure backoff. Defaults to `Date.now`. */
now?: () => number;
},
host: CliResolverHost = createProductionCliResolverHost()
): CliExecutableResolver<T> {
if (!SAFE_BINARY_NAME.test(options.binary)) {
throw new Error(`Unsafe CLI binary name: ${options.binary}`);
}
const now = options.now ?? Date.now;
/** Successful resolution, cached for the process lifetime. */
let cached: CliResolution<T> | null = null;
/** Consecutive full-chain misses (drives the retry backoff). */
let failures = 0;
/** Timestamp of the most recent miss. */
let lastFailureAt = 0;
const accept = (path: string | null, source: CliResolutionSource): CliResolution<T> | null => {
if (!path || !isAbsolute(path) || !host.exists(path)) return null;
const validation = options.validateCandidate?.(path) ?? ({ accepted: true } as CandidateValidation<T>);
if (!validation.accepted) return null;
return {
binaryPath: path,
directory: dirname(path),
source,
metadata: validation.metadata,
};
};
return {
resolve() {
if (cached) return cached;
// Negative cache: a miss is remembered and the chain — whose login-shell
// tail is a synchronous 5s-bounded spawn — is not re-run until the
// backoff elapses. Without this, every status poll and Run click against
// a missing CLI froze the event loop for the full probe, forever.
if (failures > 0 && now() - lastFailureAt < cliResolveRetryDelayMs(failures)) return null;
cached = accept(host.findOnProcessPath(options.binary), 'process-path');
if (!cached) {
for (const dir of options.searchDirs) {
cached = accept(join(dir, options.binary), 'common-directory');
if (cached) break;
}
}
if (!cached) {
cached = accept(host.findInLoginShell(options.binary), 'login-shell');
}
if (cached) {
failures = 0;
lastFailureAt = 0;
return cached;
}
failures += 1;
lastFailureAt = now();
return null;
},
diagnostics: () => ({
binary: options.binary,
processPath: host.processPath,
shellPath: host.shellPath,
shellArgs: [...host.shellArgs],
searchDirs: [...options.searchDirs],
}),
};
}
function sanitizeDiagnosticField(value: string, emptyMarker: string): string {
const flattened = Array.from(value, (character) => {
const codePoint = character.codePointAt(0) ?? 0;
const isControl = codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f);
return isControl || codePoint === 0x2028 || codePoint === 0x2029 ? ' ' : character;
})
.join('')
.replace(/ +/g, ' ')
.trim();
if (!flattened) return emptyMarker;
if (flattened.length <= DIAGNOSTIC_FIELD_MAX_LENGTH) return flattened;
return `${flattened.slice(0, DIAGNOSTIC_FIELD_MAX_LENGTH - 1)}…`;
}
export function formatCliNotFoundMessage(base: string, diagnostics: CliResolutionDiagnostics): string {
const processPath = sanitizeDiagnosticField(diagnostics.processPath, '(empty)');
const shell = sanitizeDiagnosticField(
[diagnostics.shellPath, ...diagnostics.shellArgs].filter(Boolean).join(' '),
'(none)'
);
const dirs = sanitizeDiagnosticField(diagnostics.searchDirs.join(', '), '(none)');
return `${base}\nServer PATH: ${processPath}\nLogin shell: ${shell}\nChecked directories: ${dirs}`;
}
+9 -31
View File
@@ -7,11 +7,9 @@
* @module utils/codex-cli-resolver
*/
import { execSync } from 'node:child_process';
import { existsSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { join } from 'node:path';
import { homedir } from 'node:os';
import { EXEC_TIMEOUT_MS } from '../config/exec-timeout.js';
import { createCliExecutableResolver, formatCliNotFoundMessage } from './cli-executable-resolver.js';
/** Common directories where the Codex CLI binary may be installed */
const CODEX_SEARCH_DIRS = [
@@ -23,8 +21,8 @@ const CODEX_SEARCH_DIRS = [
join(homedir(), 'bin'), // User bin
];
/** Cached directory containing the codex binary (empty string = searched but not found) */
let _codexDir: string | null = null;
const codexResolver = createCliExecutableResolver({ binary: 'codex', searchDirs: CODEX_SEARCH_DIRS });
const CODEX_NOT_FOUND = 'Codex CLI not found. Install with: npm install -g @openai/codex';
/**
* Finds the directory containing the `codex` binary.
@@ -34,31 +32,7 @@ let _codexDir: string | null = null;
* @returns Directory path, or null if not found
*/
export function resolveCodexDir(): string | null {
if (_codexDir !== null) return _codexDir || null;
// Try `which` first (respects current PATH)
try {
const result = execSync('which codex', {
encoding: 'utf-8',
timeout: EXEC_TIMEOUT_MS,
}).trim();
if (result && existsSync(result)) {
_codexDir = dirname(result);
return _codexDir;
}
} catch {
// Codex not in PATH, will check common locations
}
for (const dir of CODEX_SEARCH_DIRS) {
if (existsSync(join(dir, 'codex'))) {
_codexDir = dir;
return _codexDir;
}
}
_codexDir = ''; // mark as searched, not found
return null;
return codexResolver.resolve()?.directory ?? null;
}
/**
@@ -67,3 +41,7 @@ export function resolveCodexDir(): string | null {
export function isCodexAvailable(): boolean {
return resolveCodexDir() !== null;
}
export function getCodexNotFoundMessage(): string {
return formatCliNotFoundMessage(CODEX_NOT_FOUND, codexResolver.diagnostics());
}
+53 -10
View File
@@ -1,17 +1,50 @@
/**
* @fileoverview Renders ToolResult[] from the dependency checker into a
* human-readable grouped table or JSON, and computes the process exit code.
* Plain text only (no color) so output is stable and snapshot-friendly; the
* CLI layer may colorize.
* Plain text by default (no color) so output is stable and snapshot-friendly;
* the CLI layer passes a `ReportStyle` to paint it (see `cli.ts`, `doctor`).
*
* Column widths are measured, not hardcoded: "Antigravity CLI" is 15 characters
* and the old `padEnd(14)` pushed its whole row one column right.
*
* @module utils/dependency-report
*/
import { columnWidths, padStyled } from '../cli-style.js';
import type { ProbeEnvironment, ToolCategory } from '../config/dependency-registry.js';
import type { ToolResult, ToolStatus } from './dependency-checker.js';
const CATEGORY_ORDER: ToolCategory[] = ['core', 'office', 'other'];
/**
* Paint hooks for the CLI layer. Every hook is identity by default, so this
* module never decides anything about color and its output stays byte-stable
* for tests.
*/
export interface ReportStyle {
title(text: string): string;
heading(text: string): string;
glyph(result: ToolResult, glyph: string): string;
label(text: string): string;
status(result: ToolResult, text: string): string;
path(text: string): string;
meta(text: string): string;
summary(text: string): string;
}
const identity = (text: string): string => text;
const PLAIN_STYLE: ReportStyle = {
title: identity,
heading: identity,
glyph: (_result, glyph) => glyph,
label: identity,
status: (_result, text) => text,
path: identity,
meta: identity,
summary: identity,
};
function glyph(r: ToolResult): string {
if (r.status === 'ok') return '✓';
if (r.status === 'skipped') return '○';
@@ -33,24 +66,34 @@ export function computeExitCode(results: ToolResult[]): number {
return failed ? 1 : 0;
}
export function renderTable(results: ToolResult[], environment: ProbeEnvironment): string {
const lines: string[] = [`Codeman dependency check — ${environment}`, ''];
export function renderTable(
results: ToolResult[],
environment: ProbeEnvironment,
style: ReportStyle = PLAIN_STYLE
): string {
// Widths are taken across ALL categories so the groups line up with each other.
const [labelWidth, statusWidth] = columnWidths(results.map((r) => [r.label, statusText(r)]));
const lines: string[] = [style.title(`Codeman dependency check — ${environment}`), ''];
for (const category of CATEGORY_ORDER) {
const rows = results.filter((r) => r.category === category);
if (rows.length === 0) continue;
lines.push(category.toUpperCase());
lines.push(style.heading(category.toUpperCase()));
for (const r of rows) {
const detail = r.path ? ` ${r.path}` : '';
lines.push(` ${glyph(r)} ${r.label.padEnd(14)} ${statusText(r).padEnd(22)}${detail}`);
if (r.usedBy.length) lines.push(` used by: ${r.usedBy.join(', ')}`);
if (r.installHint) lines.push(` install: ${r.installHint}`);
const label = padStyled(r.label, labelWidth ?? 0, style.label);
const status = padStyled(statusText(r), statusWidth ?? 0, (text) => style.status(r, text));
const detail = r.path ? ` ${style.path(r.path)}` : '';
lines.push(` ${style.glyph(r, glyph(r))} ${label} ${status}${detail}`.trimEnd());
if (r.usedBy.length) lines.push(style.meta(` used by: ${r.usedBy.join(', ')}`));
if (r.installHint) lines.push(style.meta(` install: ${r.installHint}`));
}
lines.push('');
}
const ok = results.filter((r) => r.status === 'ok').length;
const requiredMissing = results.filter((r) => r.required && r.status !== 'ok' && r.status !== 'skipped').length;
const optionalMissing = results.filter((r) => !r.required && r.status === 'missing').length;
lines.push(`Summary: ${ok} ok · ${requiredMissing} required missing · ${optionalMissing} optional missing`);
lines.push(
style.summary(`Summary: ${ok} ok · ${requiredMissing} required missing · ${optionalMissing} optional missing`)
);
return lines.join('\n');
}
+93
View File
@@ -0,0 +1,93 @@
/**
* @fileoverview Pure file-name/path query matcher for the Files panel search
* (COD-236). Compiles a user query string into a reusable predicate so the
* server-side file walk can prune to matching entries instead of streaming the
* whole tree.
*
* Semantics:
* - Empty / whitespace-only query → `compileFileQuery` returns `null` (the
* caller treats this as "no search", falling back to the full tree). A query
* longer than `MAX_QUERY_LENGTH` compiles to `null` too: no honest filename
* search is that long, and the glob walk below is O(text · pattern).
* - A query containing a glob metachar (`*` or `?`) matches anchored and
* case-insensitively, `*` spanning any run (slashes included) and `?` exactly
* one character; every other character matches literally.
* - Otherwise the query is a plain case-insensitive substring.
* - When the query contains a `/` it matches against the relative path; else it
* matches against the bare entry name.
*
* ⚠️ Globs are matched by `globMatch` below, never by compiling the query into
* a RegExp: `*a*a*a…` translated to `^.*a.*a.*a…$` is a classic backtracking
* blowup, evaluated synchronously against every walked path — a pathological
* query could freeze the event loop for the whole server (the same reason
* `search-service.ts` is regex-free). The two-pointer wildcard walk is
* O(text · pattern) worst case, with both operands short by construction.
*
* No fs / IO — safe to unit-test directly.
*/
export type FileQueryMatcher = (name: string, relativePath: string) => boolean;
// Longer than any honest file search; bounds the O(text · pattern) glob walk.
const MAX_QUERY_LENGTH = 256;
/**
* Anchored glob match, linear-space two-pointer walk (no RegExp — see the
* fileoverview). `pattern` must already be lowercased; `text` is lowercased
* here so one compiled matcher serves many entries.
*/
function globMatch(pattern: string, rawText: string): boolean {
const text = rawText.toLowerCase();
let p = 0;
let t = 0;
let starP = -1;
let starT = -1;
while (t < text.length) {
const pc = p < pattern.length ? pattern[p] : '';
if (pc === '?' || pc === text[t]) {
p++;
t++;
} else if (pc === '*') {
// Remember the star; try matching zero characters first, and on a later
// mismatch re-expand it one character at a time from here.
starP = p++;
starT = t;
} else if (starP !== -1) {
p = starP + 1;
t = ++starT;
} else {
return false;
}
}
while (p < pattern.length && pattern[p] === '*') p++;
return p === pattern.length;
}
/**
* Compile a query string into a matcher predicate, or `null` when the query is
* empty/whitespace or overlong (caller treats null as "no search").
*/
export function compileFileQuery(query: string): FileQueryMatcher | null {
const trimmed = query.trim();
if (trimmed === '' || trimmed.length > MAX_QUERY_LENGTH) return null;
const matchesPath = trimmed.includes('/');
const isGlob = trimmed.includes('*') || trimmed.includes('?');
if (isGlob) {
const pattern = trimmed.toLowerCase();
return (name, relativePath) => globMatch(pattern, matchesPath ? relativePath : name);
}
const needle = trimmed.toLowerCase();
return (name, relativePath) => (matchesPath ? relativePath : name).toLowerCase().includes(needle);
}
/**
* Convenience: compile the query and apply it in one call. Returns false when
* the query compiles to null (empty).
*/
export function matchFileQuery(query: string, name: string, relativePath: string): boolean {
const matcher = compileFileQuery(query);
return matcher ? matcher(name, relativePath) : false;
}
+9 -30
View File
@@ -7,11 +7,9 @@
* @module utils/gemini-cli-resolver
*/
import { execSync } from 'node:child_process';
import { existsSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { join } from 'node:path';
import { homedir } from 'node:os';
import { EXEC_TIMEOUT_MS } from '../config/exec-timeout.js';
import { createCliExecutableResolver, formatCliNotFoundMessage } from './cli-executable-resolver.js';
/** Common directories where the Gemini CLI binary may be installed */
const GEMINI_SEARCH_DIRS = [
@@ -23,8 +21,8 @@ const GEMINI_SEARCH_DIRS = [
join(homedir(), 'bin'),
];
/** Cached directory containing the gemini binary (empty string = searched but not found) */
let _geminiDir: string | null = null;
const geminiResolver = createCliExecutableResolver({ binary: 'gemini', searchDirs: GEMINI_SEARCH_DIRS });
const GEMINI_NOT_FOUND = 'Gemini CLI not found. Install with: npm install -g @google/gemini-cli';
/**
* Finds the directory containing the `gemini` binary.
@@ -33,30 +31,7 @@ let _geminiDir: string | null = null;
* @returns Directory path, or null if not found
*/
export function resolveGeminiDir(): string | null {
if (_geminiDir !== null) return _geminiDir || null;
try {
const result = execSync('which gemini', {
encoding: 'utf-8',
timeout: EXEC_TIMEOUT_MS,
}).trim();
if (result && existsSync(result)) {
_geminiDir = dirname(result);
return _geminiDir;
}
} catch {
// Gemini not in PATH, will check common locations
}
for (const dir of GEMINI_SEARCH_DIRS) {
if (existsSync(join(dir, 'gemini'))) {
_geminiDir = dir;
return _geminiDir;
}
}
_geminiDir = '';
return null;
return geminiResolver.resolve()?.directory ?? null;
}
/**
@@ -65,3 +40,7 @@ export function resolveGeminiDir(): string | null {
export function isGeminiAvailable(): boolean {
return resolveGeminiDir() !== null;
}
export function getGeminiNotFoundMessage(): string {
return formatCliNotFoundMessage(GEMINI_NOT_FOUND, geminiResolver.diagnostics());
}
+151
View File
@@ -0,0 +1,151 @@
/**
* @fileoverview Resolve the Grok Build CLI (`grok`, xAI) binary across common install paths.
*
* Mirrors pi-cli-resolver.ts, version probe included: `grok` is another short
* name with known squatters (the unrelated `@vibe-kit/grok-cli` npm package also
* installs a `grok` bin), so a `which grok` hit is not by itself evidence that
* xAI's coding agent is installed. Every candidate is sanity-probed with
* `grok --version` and required to print a version-shaped string (the real CLI
* prints `grok 1.0.5 (5115b46bc9)`); a binary that fails the probe is treated
* as absent and the rejected path is logged. The probe cannot tell two
* version-printing `grok`s apart, which is why `GET /api/grok/status` surfaces
* path AND version: a misresolution is diagnosable rather than presenting as
* "the mode just doesn't work".
*
* The official installer (`curl -fsSL https://x.ai/cli/install.sh | bash`)
* places the binary in `~/.grok/bin` and symlinks it into `~/.local/bin`, so
* those two head the search list.
*
* @module utils/grok-cli-resolver
*/
import { execFileSync } from 'node:child_process';
import { join } from 'node:path';
import { homedir } from 'node:os';
import { EXEC_TIMEOUT_MS } from '../config/exec-timeout.js';
import {
createCliExecutableResolver,
formatCliNotFoundMessage,
type CliResolverHost,
} from './cli-executable-resolver.js';
/** Common directories where the Grok CLI binary may be installed */
const GROK_SEARCH_DIRS = [
join(homedir(), '.grok', 'bin'),
join(homedir(), '.local', 'bin'),
'/usr/local/bin',
join(homedir(), 'bin'),
];
/**
* A real `grok --version` prints `grok 1.0.5 (5115b46bc9)` (measured, 1.0.5).
*
* Exported and SHARED with the `grok` entry in `config/dependency-registry.ts`,
* so `codeman doctor` and the run mode cannot disagree about what counts as an
* installed grok (the same single-source rule as PI_VERSION_REGEX). Shape is
* dictated by the doctor's `extractVersion()` (first capture group, whole-output
* scan): hence a capturing group and a leading boundary instead of `^`. No `g`
* flag, so there is no shared `lastIndex` to reset.
*/
export const GROK_VERSION_REGEX = /(?:^|\s)(\d+\.\d+\.\d+)/;
const GROK_NOT_FOUND = 'Grok CLI not found. Install with: curl -fsSL https://x.ai/cli/install.sh | bash';
/**
* Run `grok --version` on a candidate path and return the version token when it
* looks like the coding agent. Returns null for anything else: a missing
* binary, a non-zero exit, a hang (timeout), or output with no version-shaped
* token (which is how an unrelated `grok` on PATH gets rejected).
*
* Never runs under vitest: the suites must stay hermetic and must not depend on
* whether the dev box happens to have grok installed, and since `grok` is a
* name with known squatters, this probe would EXECUTE whatever binary of that
* name the machine carries. The shared resolver host is already inert under
* vitest, so this gate is defense in depth for any opted-in host that still
* carries the default probe; tests drive resolution via
* `createGrokResolverForTest`, whose injected probe bypasses it. Pinned by
* test/grok-cli-resolver.test.ts.
*/
function probeGrokVersion(binPath: string): string | null {
if (process.env.VITEST) return null;
try {
const out = execFileSync(binPath, ['--version'], {
encoding: 'utf-8',
timeout: EXEC_TIMEOUT_MS,
stdio: ['ignore', 'pipe', 'ignore'],
// A stuck or hostile `grok` that ignores SIGTERM would survive the timeout
// and block the server (execFileSync keeps waiting after the signal).
killSignal: 'SIGKILL',
}).trim();
const candidate = GROK_VERSION_REGEX.exec(out)?.[1];
if (candidate) return candidate;
console.warn(`[GrokResolver] Ignoring ${binPath}: "grok --version" printed ${JSON.stringify(out.slice(0, 80))}`);
} catch (err) {
console.warn(`[GrokResolver] Ignoring ${binPath}: "grok --version" failed (${(err as Error).message})`);
}
return null;
}
type GrokVersionProbe = (binPath: string) => string | null;
function createGrokResolver(
host?: CliResolverHost,
versionProbe: GrokVersionProbe = probeGrokVersion,
now?: () => number
) {
return createCliExecutableResolver<string>(
{
binary: 'grok',
searchDirs: GROK_SEARCH_DIRS,
validateCandidate: (binPath) => {
const version = versionProbe(binPath);
return version ? { accepted: true, metadata: version } : { accepted: false };
},
now,
},
host
);
}
/**
* Creates an isolated Grok wrapper around an injected host, version probe and
* clock. Omitting `versionProbe` keeps the ambient (VITEST-gated) probe, which
* is exactly what the hermeticity test exercises.
*/
export function createGrokResolverForTest(host: CliResolverHost, versionProbe?: GrokVersionProbe, now?: () => number) {
return createGrokResolver(host, versionProbe ?? probeGrokVersion, now);
}
const grokResolver = createGrokResolver();
/**
* Finds the directory containing a verified `grok` binary.
* Checks the server PATH first, then the common install locations
* (`~/.grok/bin` leading, the official installer's target). Every candidate
* must pass the `grok --version` sanity probe before it is accepted.
*
* @returns Directory path, or null if not found
*/
export function resolveGrokDir(): string | null {
return grokResolver.resolve()?.directory ?? null;
}
/**
* Check if the Grok CLI is available on the system.
*/
export function isGrokAvailable(): boolean {
return resolveGrokDir() !== null;
}
export function getGrokNotFoundMessage(): string {
return formatCliNotFoundMessage(GROK_NOT_FOUND, grokResolver.diagnostics());
}
/**
* Version reported by the resolved `grok` binary, or null when grok is
* unavailable. Surfaced through `GET /api/grok/status` so a misresolution is
* diagnosable from the UI.
*/
export function getGrokCliVersion(): string | null {
return grokResolver.resolve()?.metadata ?? null;
}
+19 -6
View File
@@ -28,10 +28,23 @@ export { stringSimilarity, fuzzyPhraseMatch, todoContentHash } from './string-si
export { assertNever } from './type-safety.js';
export { wrapWithNice } from './nice-wrapper.js';
export { resolveLocalShell, loginShellArgs } from './shell-resolver.js';
export { findClaudeDir, getAugmentedPath, getClaudeCliVersion, getClaudeBinaryPath } from './claude-cli-resolver.js';
export {
findClaudeDir,
getAugmentedPath,
getClaudeCliVersion,
getClaudeBinaryPath,
getClaudeNotFoundMessage,
} from './claude-cli-resolver.js';
export { spawnPtyWithHelperRepair } from './node-pty-repair.js';
export { resolveOpenCodeDir } from './opencode-cli-resolver.js';
export { resolveCodexDir, isCodexAvailable } from './codex-cli-resolver.js';
export { resolveGeminiDir, isGeminiAvailable } from './gemini-cli-resolver.js';
export { resolveAntigravityDir, isAntigravityAvailable } from './antigravity-cli-resolver.js';
export { resolvePiDir, isPiAvailable, getPiCliVersion } from './pi-cli-resolver.js';
export { resolveOpenCodeDir, getOpenCodeNotFoundMessage } from './opencode-cli-resolver.js';
export { resolveCodexDir, isCodexAvailable, getCodexNotFoundMessage } from './codex-cli-resolver.js';
export { resolveGeminiDir, isGeminiAvailable, getGeminiNotFoundMessage } from './gemini-cli-resolver.js';
export {
resolveAntigravityDir,
isAntigravityAvailable,
getAntigravityNotFoundMessage,
} from './antigravity-cli-resolver.js';
export { resolvePiDir, isPiAvailable, getPiCliVersion, getPiNotFoundMessage } from './pi-cli-resolver.js';
export { resolveGrokDir, isGrokAvailable, getGrokCliVersion, getGrokNotFoundMessage } from './grok-cli-resolver.js';
export { compileFileQuery, matchFileQuery } from './file-query.js';
export type { FileQueryMatcher } from './file-query.js';
+9 -32
View File
@@ -7,11 +7,9 @@
* @module utils/opencode-cli-resolver
*/
import { execSync } from 'node:child_process';
import { existsSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { join } from 'node:path';
import { homedir } from 'node:os';
import { EXEC_TIMEOUT_MS } from '../config/exec-timeout.js';
import { createCliExecutableResolver, formatCliNotFoundMessage } from './cli-executable-resolver.js';
/** Common directories where the OpenCode CLI binary may be installed */
const OPENCODE_SEARCH_DIRS = [
@@ -24,8 +22,8 @@ const OPENCODE_SEARCH_DIRS = [
join(homedir(), 'bin'), // User bin
];
/** Cached directory containing the opencode binary (empty string = searched but not found) */
let _openCodeDir: string | null = null;
const openCodeResolver = createCliExecutableResolver({ binary: 'opencode', searchDirs: OPENCODE_SEARCH_DIRS });
const OPENCODE_NOT_FOUND = 'OpenCode CLI not found. Install with: curl -fsSL https://opencode.ai/install | bash';
/**
* Finds the directory containing the `opencode` binary.
@@ -35,32 +33,7 @@ let _openCodeDir: string | null = null;
* @returns Directory path, or null if not found
*/
export function resolveOpenCodeDir(): string | null {
if (_openCodeDir !== null) return _openCodeDir || null;
// Try `which` first (respects current PATH)
try {
const result = execSync('which opencode', {
encoding: 'utf-8',
timeout: EXEC_TIMEOUT_MS,
}).trim();
if (result && existsSync(result)) {
_openCodeDir = dirname(result);
return _openCodeDir;
}
} catch {
// OpenCode not in PATH, will check common locations
}
// Fallback: check common installation directories
for (const dir of OPENCODE_SEARCH_DIRS) {
if (existsSync(join(dir, 'opencode'))) {
_openCodeDir = dir;
return _openCodeDir;
}
}
_openCodeDir = ''; // mark as searched, not found
return null;
return openCodeResolver.resolve()?.directory ?? null;
}
/**
@@ -69,3 +42,7 @@ export function resolveOpenCodeDir(): string | null {
export function isOpenCodeAvailable(): boolean {
return resolveOpenCodeDir() !== null;
}
export function getOpenCodeNotFoundMessage(): string {
return formatCliNotFoundMessage(OPENCODE_NOT_FOUND, openCodeResolver.diagnostics());
}
+53 -53
View File
@@ -15,11 +15,15 @@
* @module utils/pi-cli-resolver
*/
import { execFileSync, execSync } from 'node:child_process';
import { existsSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { execFileSync } from 'node:child_process';
import { join } from 'node:path';
import { homedir } from 'node:os';
import { EXEC_TIMEOUT_MS } from '../config/exec-timeout.js';
import {
createCliExecutableResolver,
formatCliNotFoundMessage,
type CliResolverHost,
} from './cli-executable-resolver.js';
/** Common directories where the Pi CLI binary may be installed */
const PI_SEARCH_DIRS = [
@@ -45,10 +49,7 @@ const PI_SEARCH_DIRS = [
*/
export const PI_VERSION_REGEX = /(?:^|\s)(\d+\.\d+\.\d+)/;
/** Cached directory containing the pi binary (empty string = searched but not found) */
let _piDir: string | null = null;
/** Cached version string reported by the resolved binary (empty string = probed, unusable) */
let _piVersion: string | null = null;
const PI_NOT_FOUND = 'Pi CLI not found. Install with: npm install -g --ignore-scripts @earendil-works/pi-coding-agent';
/**
* Run `pi --version` on a candidate path and return the trimmed version when it
@@ -57,7 +58,12 @@ let _piVersion: string | null = null;
* (which is how an unrelated `pi` on PATH gets rejected).
*
* Never runs under vitest: the suites must stay hermetic and must not depend on
* whether the dev box happens to have pi installed.
* whether the dev box happens to have pi installed — and since `pi` is a short
* GENERIC name, this probe would EXECUTE whatever binary of that name the
* machine carries. The shared resolver host is already inert under vitest, so
* this gate is defense in depth for any opted-in host that still carries the
* default probe; tests drive resolution via `createPiResolverForTest`, whose
* injected probe bypasses it. Pinned by test/pi-cli-resolver.test.ts.
*/
function probePiVersion(binPath: string): string | null {
if (process.env.VITEST) return null;
@@ -66,6 +72,9 @@ function probePiVersion(binPath: string): string | null {
encoding: 'utf-8',
timeout: EXEC_TIMEOUT_MS,
stdio: ['ignore', 'pipe', 'ignore'],
// A stuck or hostile `pi` that ignores SIGTERM would survive the timeout
// and block the server (execFileSync keeps waiting after the signal).
killSignal: 'SIGKILL',
}).trim();
// Upstream prints a bare version today; tolerate a `pi 0.84.1` style prefix too.
const candidate = PI_VERSION_REGEX.exec(out)?.[1];
@@ -77,6 +86,34 @@ function probePiVersion(binPath: string): string | null {
return null;
}
type PiVersionProbe = (binPath: string) => string | null;
function createPiResolver(host?: CliResolverHost, versionProbe: PiVersionProbe = probePiVersion, now?: () => number) {
return createCliExecutableResolver<string>(
{
binary: 'pi',
searchDirs: PI_SEARCH_DIRS,
validateCandidate: (binPath) => {
const version = versionProbe(binPath);
return version ? { accepted: true, metadata: version } : { accepted: false };
},
now,
},
host
);
}
/**
* Creates an isolated Pi wrapper around an injected host, version probe and
* clock. Omitting `versionProbe` keeps the ambient (VITEST-gated) probe, which
* is exactly what the hermeticity test exercises.
*/
export function createPiResolverForTest(host: CliResolverHost, versionProbe?: PiVersionProbe, now?: () => number) {
return createPiResolver(host, versionProbe ?? probePiVersion, now);
}
const piResolver = createPiResolver();
/**
* Finds the directory containing a verified `pi` binary.
* Checks `which pi` first, then falls back to common install locations. Every
@@ -86,46 +123,7 @@ function probePiVersion(binPath: string): string | null {
* @returns Directory path, or null if not found
*/
export function resolvePiDir(): string | null {
if (_piDir !== null) return _piDir || null;
const accept = (binPath: string): string | null => {
// Under vitest the probe never runs, so existence alone decides (keeps the
// suites hermetic and matches how the sibling resolvers behave there).
if (process.env.VITEST) {
_piDir = dirname(binPath);
_piVersion = '';
return _piDir;
}
const version = probePiVersion(binPath);
if (!version) return null;
_piDir = dirname(binPath);
_piVersion = version;
return _piDir;
};
try {
const result = execSync('which pi', {
encoding: 'utf-8',
timeout: EXEC_TIMEOUT_MS,
}).trim();
if (result && existsSync(result)) {
const dir = accept(result);
if (dir) return dir;
}
} catch {
// pi not in PATH, will check common locations
}
for (const dir of PI_SEARCH_DIRS) {
const binPath = join(dir, 'pi');
if (!existsSync(binPath)) continue;
const accepted = accept(binPath);
if (accepted) return accepted;
}
_piDir = '';
_piVersion = '';
return null;
return piResolver.resolve()?.directory ?? null;
}
/**
@@ -135,12 +133,14 @@ export function isPiAvailable(): boolean {
return resolvePiDir() !== null;
}
export function getPiNotFoundMessage(): string {
return formatCliNotFoundMessage(PI_NOT_FOUND, piResolver.diagnostics());
}
/**
* Version reported by the resolved `pi` binary, or null when pi is unavailable
* (or when the probe was skipped, i.e. under vitest). Surfaced through
* `GET /api/pi/status` so a misresolution is diagnosable from the UI.
* Version reported by the resolved `pi` binary, or null when pi is unavailable.
* Surfaced through `GET /api/pi/status` so a misresolution is diagnosable from the UI.
*/
export function getPiCliVersion(): string | null {
resolvePiDir();
return _piVersion || null;
return piResolver.resolve()?.metadata ?? null;
}
+110 -26
View File
@@ -22,14 +22,14 @@
* - Acknowledgement (`acknowledge()`, idle items only) is NOT resolution: the
* item stays pending, it just stops arming the tab alert on every client.
*
* @dependencies utils (stripAnsi)
* @dependencies utils (stripAnsi, CLAUDE_WORKING_LINE_PATTERN)
* @consumedby web/routes/hook-event-routes (notePrompt/resolve), web/routes/approval-routes,
* web/session-listener-wiring (working/exit resolution), web/server (emit callbacks + stop)
*
* @module web/approval-inbox
*/
import { stripAnsi } from '../utils/index.js';
import { stripAnsi, CLAUDE_WORKING_LINE_PATTERN } from '../utils/index.js';
// ─── Types ───────────────────────────────────────────────────────────────────
@@ -106,6 +106,12 @@ const ITEM_TTL_MS = 12 * 60 * 60 * 1000;
* single delayed re-capture picks up the frame the immediate capture missed.
*/
const RECAPTURE_DELAY_MS = 600;
/**
* Delayed staleness pass for the late-hook case (see notePrompt). Comfortably
* clear of RECAPTURE_DELAY_MS so a dialog Ink has not painted yet is never
* mistaken for one that is gone.
*/
const STALE_CHECK_DELAY_MS = 3000;
/** Context kept per item: enough for a dialog plus a few lines above it. */
const MAX_CONTEXT_CHARS = 4000;
const MAX_CONTEXT_LINES = 30;
@@ -195,7 +201,8 @@ export function parseDialogOptions(context: string | undefined): ApprovalOption[
export class ApprovalInbox {
/** Keyed by sessionId; the one-active-item-per-session invariant lives here. */
private items = new Map<string, ApprovalItem>();
private recaptureTimers = new Map<string, ReturnType<typeof setTimeout>>();
/** Post-capture timers per item id (re-capture + the delayed staleness check). */
private itemTimers = new Map<string, ReturnType<typeof setTimeout>[]>();
/** Capture callbacks kept for answer-time re-verification; dropped on remove. */
private captures = new Map<string, () => string | null>();
private seq = 0;
@@ -229,31 +236,55 @@ export class ApprovalInbox {
if (args.capture) this.captures.set(args.sessionId, args.capture);
this.onPending?.(item);
if (args.capture && !this.stopped) {
const timer = setTimeout(() => {
this.recaptureTimers.delete(item.id);
// Only update the item if it is still the live one for the session.
if (this.items.get(args.sessionId)?.id !== item.id) return;
// Pass 1 (600ms): enrich the card with the painted frame.
this.scheduleForItem(item, RECAPTURE_DELAY_MS, () => {
this.applyCapture(item, args.capture);
this.onUpdated?.(item);
}, RECAPTURE_DELAY_MS);
this.recaptureTimers.set(item.id, timer);
});
// Pass 2: the late-hook staleness check. Claude Code fires the
// Notification behind the dialog, so a prompt answered before the hook
// lands creates an item for a dialog that is ALREADY gone: nothing ever
// parsed, so the "options vanished" test can never fire, `stop` may have
// gone by already, and the red alert then outlived reloads until the 12h
// TTL. This pass re-reads the pane and resolves when the frame proves no
// dialog is up. Deliberately LATER than the re-capture, whose whole
// reason for existing is that Ink may not have painted the dialog yet:
// resolving inside that window could clear the alert for a dialog that
// was about to appear.
this.scheduleForItem(item, STALE_CHECK_DELAY_MS, () => {
this.verifyStillAnswerable(item.id);
});
}
return item;
}
/**
* Answer-time guard: re-capture the pane and check the dialog is still on
* screen before keystrokes are sent at it. Only conclusive when the ORIGINAL
* frame parsed options: if a fresh capture then parses none, the dialog is
* gone (answered in the terminal moments ago), so the item resolves and the
* answer must be refused, because the digit would land in whatever now has
* focus. Unparseable-from-the-start items stay answerable (approve/deny
* only), same risk the terminal user already carries.
* screen before keystrokes are sent at it. If the dialog is gone (answered in
* the terminal moments ago) the item resolves and the answer is refused,
* because the digit would land in whatever now has focus.
*
* A fresh frame that parses NO options is conclusive in two cases, and only
* those; anything else stays answerable, so an unreadable capture keeps the
* alert rather than losing a live dialog:
*
* 1. The item HAD parsed options. They cannot vanish while the dialog is up.
* 2. The frame shows Claude actively running a turn. A modal dialog BLOCKS
* the turn, so a working line and a dialog cannot coexist — measured on
* v2.1.237: a live-dialog frame carries neither the `… (13s` timer nor
* even the `esc to interrupt` footer, which the dialog replaces with
* `Enter to select · ↑/↓ to navigate · Esc to cancel`.
*
* Case 2 is what closes the late-hook hole. Claude Code fires the
* Notification behind the dialog, so a prompt answered before the hook lands
* produces an item whose FIRST capture already has no dialog in it — never
* parsed, so case 1 can never fire, and the red alert then outlived even
* `stop` (which had already fired) and survived reloads until the 12h TTL.
*/
verifyStillAnswerable(id: string): boolean {
const item = this.getById(id);
if (!item) return false;
if (item.kind === 'idle' || !item.options) return true;
if (item.kind === 'idle') return true;
const capture = this.captures.get(item.sessionId);
if (!capture) return true;
let raw: string | null = null;
@@ -266,14 +297,39 @@ export class ApprovalInbox {
if (!context) return true;
const options = parseDialogOptions(context);
if (!options) {
this.remove(item, 'resolved_in_terminal');
return false;
if (item.options || CLAUDE_WORKING_LINE_PATTERN.test(context)) {
this.remove(item, 'resolved_in_terminal');
return false;
}
return true; // never parsed and the pane is not visibly working: unreadable, not gone
}
item.context = context;
item.options = options;
return true;
}
/**
* "This session's pane started moving again": re-verify its pending DIALOG
* item against the screen and resolve it if the dialog is gone.
*
* The staleness check itself lived only in `GET /api/approvals`, which
* nothing calls while a page is open (`seedApprovals()` runs on init and
* reconnect), so a dialog answered in the terminal kept its red tab alert for
* the whole rest of the turn. The `working` signal is exactly the moment an
* answer lands, and routing it through `verifyStillAnswerable` is what makes
* it safe to act on for a permission/question item: `working` is heuristic
* and can flap, but it only decides WHEN to look — the pane decides the
* outcome, and an unreadable capture keeps the alert.
*
* Cheap by construction: a Map miss unless a dialog item is actually pending,
* and the item is gone after the first successful resolve.
*/
resolveIfDialogGone(sessionId: string): void {
const item = this.getForSession(sessionId);
if (!item || item.kind === 'idle') return;
this.verifyStillAnswerable(item.id);
}
/** Pending item for a session, TTL-checked. */
getForSession(sessionId: string): ApprovalItem | undefined {
const item = this.items.get(sessionId);
@@ -359,12 +415,27 @@ export class ApprovalInbox {
/** Clear all timers (shutdown/tests). Items become inert; no events fire after this. */
stop(): void {
this.stopped = true;
for (const timer of this.recaptureTimers.values()) clearTimeout(timer);
this.recaptureTimers.clear();
for (const timers of this.itemTimers.values()) for (const timer of timers) clearTimeout(timer);
this.itemTimers.clear();
this.items.clear();
this.captures.clear();
}
/**
* Run `fn` after `delayMs` if the item is still the live one for its session,
* tracking the timer so `remove()`/`stop()` can cancel it.
*/
private scheduleForItem(item: ApprovalItem, delayMs: number, fn: () => void): void {
const timer = setTimeout(() => {
const timers = this.itemTimers.get(item.id)?.filter((t) => t !== timer) ?? [];
if (timers.length > 0) this.itemTimers.set(item.id, timers);
else this.itemTimers.delete(item.id);
if (this.items.get(item.sessionId)?.id !== item.id) return;
fn();
}, delayMs);
this.itemTimers.set(item.id, [...(this.itemTimers.get(item.id) ?? []), timer]);
}
private applyCapture(item: ApprovalItem, capture?: () => string | null): void {
if (!capture) return;
let raw: string | null = null;
@@ -377,17 +448,30 @@ export class ApprovalInbox {
if (!context) return;
item.context = context;
// Idle prompts are not dialogs; never offer digit answers for them.
if (item.kind !== 'idle') item.options = parseDialogOptions(context);
if (item.kind === 'idle') return;
const options = parseDialogOptions(context);
// ⚠️ ADD-ONLY: a re-capture that parses NOTHING must never erase options a
// previous capture found. Claude Code delays the Notification hook behind
// the dialog (measured 6s here, up to ~30s), so the 600ms re-capture very
// often lands AFTER the user has already answered in the terminal, on a
// frame with no dialog in it. Clearing the field there was the whole bug:
// `verifyStillAnswerable` reads a MISSING `options` as "never parsed" and
// keeps such an item answerable by design, so a cleared field made the item
// permanently unsweepable — the red "needs you" alert then survived every
// `GET /api/approvals` and every page reload and only went away on `stop`
// (owner report 2026-08-20: a confirmed question left a tab flowing red for
// ~8 minutes while the turn ran on), and the stale card still accepted an
// answer, typing a bare `1` into a composer with no dialog under it.
// Keeping the parse means a later capture is CONCLUSIVE: options present +
// fresh frame without them == answered in the terminal.
if (options) item.options = options;
}
private remove(item: ApprovalItem, resolution: ApprovalResolution): void {
this.items.delete(item.sessionId);
this.captures.delete(item.sessionId);
const timer = this.recaptureTimers.get(item.id);
if (timer) {
clearTimeout(timer);
this.recaptureTimers.delete(item.id);
}
for (const timer of this.itemTimers.get(item.id) ?? []) clearTimeout(timer);
this.itemTimers.delete(item.id);
if (!this.stopped) {
this.onResolved?.({ id: item.id, sessionId: item.sessionId, kind: item.kind, resolution });
}
+1
View File
@@ -14,3 +14,4 @@ export type { InfraPort, ScheduledRun } from './infra-port.js';
export type { AuthPort } from './auth-port.js';
export type { OrchestratorPort } from './orchestrator-port.js';
export type { CronPort } from './cron-port.js';
export type { TabLayoutPort } from './tab-layout-port.js';
+1 -1
View File
@@ -7,7 +7,7 @@ import type { Session } from '../../session.js';
export interface SessionPort {
readonly sessions: ReadonlyMap<string, Session>;
addSession(session: Session): void;
addSession(session: Session): Promise<void>;
cleanupSession(sessionId: string, killMux?: boolean, reason?: string): Promise<void>;
setupSessionListeners(session: Session): Promise<void>;
persistSessionState(session: Session): void;
+8
View File
@@ -0,0 +1,8 @@
/** @fileoverview Owner-scoped tab-layout capabilities exposed to route modules. */
import type { TabLayoutService } from '../../tab-layout-service.js';
export type { LegacyOrderActor, LegacyOrderPutResult, SessionOrderProjectionChange } from '../../tab-layout-service.js';
export interface TabLayoutPort {
readonly tabLayouts: TabLayoutService;
}
+271 -70
View File
@@ -536,10 +536,10 @@ class CodemanApp {
this._initGeneration = 0; // dedup concurrent handleInit calls
this._initFallbackTimer = null; // fallback timer if SSE init doesn't arrive
this._selectGeneration = 0; // cancel stale selectSession loads
// Sessions whose full tmux scrollback has already been replayed this page load
// (COD-47). Tracked PER SESSION rather than as a single "first load" flag: the
// flag was consumed by whichever session auto-selected at page load, so every
// OTHER tab started life with one visible frame of history (issue #205).
// Non-shell sessions whose full tmux scrollback has already been replayed this
// page load (COD-47). Shells deliberately start from a bounded tail because
// their scrollback can be very large; full history stays available on demand.
// Tracked PER SESSION rather than as a single "first load" flag (issue #205).
this._fullHistoryLoaded = new Set();
// Cooldown per session for the scroll-to-top "load more history" re-pull.
this._fullHistoryRepullAt = new Map(); // Map<sessionId, timestamp>
@@ -919,6 +919,8 @@ class CodemanApp {
// Calls applyTabWrapSettings() itself (it owns tabs-two-rows / tabs-show-folder)
// and then applies the sidebar variant on top — do not call both.
this.applySessionListLayout();
this.applyTabOrientation();
this.initTabRailResize?.();
this.applyMonitorVisibility();
this.applyLineageLineSettings?.();
this._installLineageStripScrollListener?.();
@@ -986,6 +988,11 @@ class CodemanApp {
this.applySkin();
this.applyLocalization();
this.applySessionListLayout();
// A fresh device seeding tabOrientation from the server would otherwise
// show no rail until a resize or a settings save: the boot-time call ran
// before this async load resolved. Must stay AFTER applySessionListLayout
// (same ordering rule as the settings-save path).
this.applyTabOrientation?.();
this.applyMonitorVisibility();
this.applyLineageLineSettings?.();
// ultracodeFloatingWindows syncs from the server (non-display key), but on a
@@ -2053,6 +2060,28 @@ class CodemanApp {
wrap.appendChild(actions);
wrap.appendChild(pre);
});
// Links open in a NEW tab.
//
// marked emits a bare `<a href>` and the sanitizer's allowlist has no
// `target`, so a tap in the chat NAVIGATED THE APP AWAY: on a phone that
// unloads the whole dashboard — SSE, terminal buffers, unsent composer
// text — and the OS back gesture reloads it from scratch, which is what
// "links don't open" reads as on mobile, with no middle-click or
// open-in-new-tab affordance to work around it.
//
// This pass runs AFTER sanitizing, so it is the only source of these two
// attributes: whatever an agent wrote is already gone, and `rel` is set on
// the same element in the same breath, so no page Codeman opens ever gets
// a `window.opener` handle back (reverse tabnabbing).
//
// A fragment link stays in-page, and mailto:/tel: are handed to the OS —
// giving those a target just strands an empty tab.
tmpl.content.querySelectorAll('a[href]').forEach((a) => {
const href = a.getAttribute('href') || '';
if (!href || href.startsWith('#') || /^(?:mailto|tel):/i.test(href)) return;
a.setAttribute('target', '_blank');
a.setAttribute('rel', 'noopener noreferrer');
});
return tmpl.innerHTML;
} catch { /* fall through */ }
}
@@ -2221,9 +2250,11 @@ class CodemanApp {
? 'Antigravity'
: mode === 'pi'
? 'Pi'
: mode === 'opencode'
? 'OpenCode'
: 'Claude';
: mode === 'grok'
? 'Grok'
: mode === 'opencode'
? 'OpenCode'
: 'Claude';
}
async toggleResponseViewer() {
@@ -3734,6 +3765,21 @@ class CodemanApp {
return layout === 'sidebar' || layout === 'sidebar-rich' ? layout : 'header';
}
resolveSessionSidebarFontSize(value) {
const size = Number(value);
// Default 12, matching the sidebar's historical 0.75rem name size: a user
// who never touches the slider must not get silently restyled (14 here
// bumped every existing sidebar install on the rail feature's release).
return Number.isInteger(size) && size >= 11 && size <= 18 ? size : 12;
}
applySessionSidebarFontSize(settings = null) {
const resolvedSettings = settings ?? this.loadAppSettingsFromStorage();
const size = this.resolveSessionSidebarFontSize(resolvedSettings?.sessionSidebarFontSize);
document.documentElement.style.setProperty('--session-sidebar-name-font-size', `${size}px`);
return size;
}
/**
* Reads the APPLIED layout off <html>, not the settings blob: this is called
* per dragover event and per tab in render loops, and getSessionListLayout()
@@ -3745,6 +3791,26 @@ class CodemanApp {
return document.documentElement.dataset.sessionList === 'sidebar';
}
_tabOrientation() {
return document.documentElement.getAttribute('data-tab-orientation') === 'vertical' ? 'vertical' : 'horizontal';
}
/**
* True when the session list renders as a vertical column: the sidebar layout
* OR the vertical tab rail. Axis decisions (drag insertion side, active-tab
* scroll-into-view, floating-window anchors) must use THIS, not
* isSessionSidebarActive() alone — the rail leaves data-session-list at
* 'header', so the sidebar predicate reads a vertical rail as horizontal.
*/
_isVerticalTabList() {
return this.isSessionSidebarActive() || this._tabOrientation() === 'vertical';
}
shouldInlineSessionActions() {
if (this.isSessionSidebarActive()) return !this.isSessionSidebarCollapsed();
return this._tabOrientation() === 'vertical' && !document.documentElement.classList.contains('tab-rail-compact');
}
/**
* True when the sidebar is showing the DETAILED rows: the home screen's
* per-session line ("created 3d ago · working 12m") plus a status pill.
@@ -3837,17 +3903,22 @@ class CodemanApp {
*/
applySessionListLayout() {
const mode = this.getSessionListLayout();
this.applySessionSidebarFontSize();
// 'sidebar' and 'sidebar-rich' are the same column; only row detail differs.
const sidebar = mode === 'sidebar' || mode === 'sidebar-rich';
const collapsed = this.isSessionSidebarCollapsed();
const prevMode = document.documentElement.dataset.sessionList;
const prevDetail = document.documentElement.dataset.sidebarDetail;
const prevCollapsed = document.documentElement.dataset.sidebar;
const tabsEl = document.getElementById('sessionTabs');
const headerHost = document.getElementById('sessionTabsHost');
const sidebarList = document.getElementById('sessionSidebarList');
if (!tabsEl || !headerHost || !sidebarList) return;
const host = sidebar ? sidebarList : headerHost;
const rail = document.getElementById('tabRail');
const railOwnsTabs =
!sidebar && document.documentElement.getAttribute('data-tab-orientation') === 'vertical';
const host = sidebar ? sidebarList : railOwnsTabs && rail ? rail : headerHost;
if (tabsEl.parentElement !== host) host.appendChild(tabsEl);
document.documentElement.dataset.sessionList = sidebar ? 'sidebar' : 'header';
@@ -3856,7 +3927,7 @@ class CodemanApp {
// would let the sidebar CSS style a strip that has nothing to style.
document.documentElement.dataset.sidebarDetail = mode === 'sidebar-rich' ? 'rich' : 'simple';
document.documentElement.dataset.sidebar = collapsed ? 'collapsed' : 'expanded';
tabsEl.setAttribute('aria-orientation', sidebar ? 'vertical' : 'horizontal');
tabsEl.setAttribute('aria-orientation', host === headerHost ? 'horizontal' : 'vertical');
const btn = document.getElementById('sidebarToggleBtn');
if (btn) {
@@ -3909,7 +3980,8 @@ class CodemanApp {
const layoutChanged =
prevMode !== document.documentElement.dataset.sessionList ||
prevDetail !== document.documentElement.dataset.sidebarDetail;
if (layoutChanged && prevTall === this._tallTabsEnabled) {
const collapseChanged = prevCollapsed !== document.documentElement.dataset.sidebar;
if ((layoutChanged || collapseChanged) && prevTall === this._tallTabsEnabled) {
this._fullRenderSessionTabs();
}
// tabs-auto-wrap is measured, not derived from settings — updateTabOverflowMode()
@@ -4213,12 +4285,13 @@ class CodemanApp {
container.querySelector('.session-tab.active');
if (!tab) return;
// Sidebar layout: the list scrolls VERTICALLY in its own scroller, so the
// horizontal computeTabScrollLeft math below would always no-op (scrollLeft
// pinned at 0). With 25+ sessions the active row is routinely below the
// fold; 'nearest' never scrolls when it is already visible, and only the
// list's own scroller moves — the drawer and document stay put.
if (this.isSessionSidebarActive()) {
// Sidebar layout AND the vertical rail: the list scrolls VERTICALLY in its
// own scroller, so the horizontal computeTabScrollLeft math below would
// always no-op (scrollLeft pinned at 0). With 25+ sessions the active row
// is routinely below the fold; 'nearest' never scrolls when it is already
// visible, and only the list's own scroller moves — drawer/rail and
// document stay put.
if (this._isVerticalTabList()) {
tab.scrollIntoView({ block: 'nearest' });
return;
}
@@ -4249,12 +4322,13 @@ class CodemanApp {
/**
* Where a floating window (subagent / ultracode) attaches to its parent tab.
* Header strip: below the tab, connector runs vertically. Sidebar: to the
* RIGHT of the tab, connector runs horizontally — otherwise the window spawns
* on top of the sidebar and its bezier loops backwards underneath it.
* Header strip: below the tab, connector runs vertically. Sidebar AND the
* vertical rail: to the RIGHT of the tab, connector runs horizontally —
* otherwise the window spawns on top of the list and its bezier loops
* backwards underneath it.
*/
_tabAnchor(rect) {
if (this.isSessionSidebarActive()) {
if (this._isVerticalTabList()) {
return {
x: rect.right,
y: rect.top + rect.height / 2,
@@ -4452,9 +4526,17 @@ class CodemanApp {
const nameEl = tab.querySelector('.tab-name');
if (nameEl) {
const _p = parseSessionPrefix(name);
const _label = _p && _p.suffix ? _p.suffix : name;
if (nameEl.textContent !== _label) {
nameEl.textContent = _label;
if (nameEl.dataset.fullName !== name) {
nameEl.replaceChildren();
if (_p && _p.suffix) {
const prefix = document.createElement('span');
prefix.className = 'tab-name-prefix';
prefix.textContent = `${_p.prefix}: `;
nameEl.append(prefix, document.createTextNode(_p.suffix));
} else {
nameEl.textContent = name;
}
nameEl.dataset.fullName = name;
tab.title = _p && _p.suffix
? (session.workingDir ? `${_p.prefix} (${session.workingDir})` : _p.prefix)
: (session.workingDir || '');
@@ -4505,9 +4587,11 @@ class CodemanApp {
// Need to add badge - insert before the action-icon overlay so the
// badge stays a direct child of the tab (outside .tab-actions)
const badgeHtml = this.renderSubagentTabBadge(id, minimizedAgents);
const actionsEl = tab.querySelector('.tab-actions');
const actionsEl = tab.querySelector(':scope > .tab-actions');
if (actionsEl) {
actionsEl.insertAdjacentHTML('beforebegin', badgeHtml);
} else {
tab.insertAdjacentHTML('beforeend', badgeHtml);
}
} else if (minimizedCount === 0 && subagentBadgeEl) {
// Count went to 0 - remove badge
@@ -4537,11 +4621,12 @@ class CodemanApp {
// The full-render path already redraws the connection SVG; this incremental
// one does not, and a badge appearing widens a tab and shifts every tab after
// it, sliding the lineage arcs off their anchors. Only pay for it when there
// is something anchored to tab rects: lineage arcs, or — in sidebar layout,
// where lineage is skipped and the edge count stays 0 — the subagent/
// ultracode connectors, whose rows a badge changes the HEIGHT of. Same
// widening as the strip-scroll listener in session-lineage.js.
if (this._lineageEdgeCount > 0 || this.isSessionSidebarActive()) this.updateConnectionLines();
// is something anchored to tab rects: lineage arcs, or — in a VERTICAL list
// (sidebar, where lineage is skipped and the edge count stays 0, or the
// rail, which can show connectors with zero lineage edges too) — the
// subagent/ultracode connectors, whose rows a badge changes the HEIGHT of.
// Same widening as the strip-scroll listener in session-lineage.js.
if (this._lineageEdgeCount > 0 || this._isVerticalTabList()) this.updateConnectionLines();
this.applySidebarFilter(this._sidebarFilter);
}
@@ -4565,6 +4650,17 @@ class CodemanApp {
const defaults = this.getDefaultSettings();
const manualTwoRows = deviceType === 'desktop' ? (settings.tabTwoRows ?? defaults.tabTwoRows ?? false) : false;
const orientation = window.CodemanTabOverflow?.resolveTabOrientation
? window.CodemanTabOverflow.resolveTabOrientation({
deviceType,
setting: settings.tabOrientation ?? defaults.tabOrientation ?? 'horizontal',
})
: 'horizontal';
if (orientation === 'vertical') {
container.classList.remove('tabs-auto-wrap');
return;
}
if (manualTwoRows || deviceType !== 'desktop') {
container.classList.remove('tabs-auto-wrap');
return;
@@ -4605,6 +4701,7 @@ class CodemanApp {
}
_fullRenderSessionTabs() {
this.closeTabRailActionMenu?.();
if (this._inlineRenameActive) return;
const container = this.$('sessionTabs');
@@ -4682,7 +4779,9 @@ class CodemanApp {
// JUST the description on the tab; the generated w<n>-<case> id moves to the
// tooltip and stays visible in the session settings modal.
const parsedName = parseSessionPrefix(name);
const tabLabel = parsedName && parsedName.suffix ? parsedName.suffix : name;
const tabLabel = parsedName && parsedName.suffix
? `<span class="tab-name-prefix">${escapeHtml(parsedName.prefix)}: </span>${escapeHtml(parsedName.suffix)}`
: escapeHtml(name);
const tabTooltip = parsedName && parsedName.suffix
? (session.workingDir ? `${parsedName.prefix} (${session.workingDir})` : parsedName.prefix)
: (session.workingDir || '');
@@ -4697,14 +4796,18 @@ class CodemanApp {
? ` data-tab-state="${richRow.state}" data-tab-meta-sig="${richRow.state}:${richRow.since ? richRow.since.at : 0}:${richRow.createdAt}"`
: '';
const inlineSessionActions = this.shouldInlineSessionActions();
const tabActionsHtml = `<span class="tab-actions"><span class="tab-gear" onclick="event.stopPropagation(); app.openSessionOptions(${escapeHtml(JSON.stringify(id))})" title="Session options" aria-label="Session options" tabindex="0">&#x2699;</span><span class="tab-detach" onclick="event.stopPropagation(); app.detachSession(${escapeHtml(JSON.stringify(id))})" title="Open in a new window" aria-label="Open session in a new window" tabindex="0">&#x29C9;</span><span class="tab-close" onclick="event.stopPropagation(); app.requestCloseSession(${escapeHtml(JSON.stringify(id))})" title="Close session" aria-label="Close session" tabindex="0">&times;</span><button type="button" class="tab-more" onclick="event.stopPropagation(); app.openTabRailActionMenu(event, ${escapeHtml(JSON.stringify(id))})" title="Session actions" aria-label="Session actions">&#x22EF;</button></span>`;
parts.push(`<div class="session-tab ${isActive ? 'active' : ''}${alertClass}${richClass}${loadState ? ' tab-loading' : ''}${this.hasTabDetachOverride(id) ? ' tab-show-detach' : ''}"${richData} data-id="${id}" data-color="${color}" ${loadState ? `data-load-phase="${escapeHtml(loadState.phase)}"` : ''} onclick="app.handleSessionTabClick(event, ${escapeHtml(JSON.stringify(id))})" oncontextmenu="event.preventDefault(); app.startInlineRename(${escapeHtml(JSON.stringify(id))})" tabindex="0" role="tab" aria-selected="${isActive ? 'true' : 'false'}" aria-busy="${loadState ? 'true' : 'false'}" aria-label="${escapeHtml(name)} session" ${tabTooltip ? `title="${escapeHtml(tabTooltip)}"` : ''}>
${_tabIdx < 9 ? '<span class="tab-number">' + (_tabIdx + 1) + '</span>' : ''}
${loadState ? '<span class="tab-load-spinner" aria-hidden="true"></span>' : ''}
<span class="tab-status ${status}" aria-hidden="true"></span>
<span class="tab-info">
<span class="tab-name-row">
${mode === 'shell' ? '<span class="tab-mode shell" aria-hidden="true">sh</span>' : mode === 'opencode' ? '<span class="tab-mode opencode" aria-hidden="true">oc</span>' : mode === 'codex' ? '<span class="tab-mode codex" aria-hidden="true">cx</span>' : mode === 'gemini' ? '<span class="tab-mode gemini" aria-hidden="true">gm</span>' : mode === 'antigravity' ? '<span class="tab-mode antigravity" aria-hidden="true">ag</span>' : mode === 'pi' ? '<span class="tab-mode pi" aria-hidden="true">pi</span>' : ''}
<span class="tab-name" data-session-id="${id}">${escapeHtml(tabLabel)}</span>
${mode === 'shell' ? '<span class="tab-mode shell" aria-hidden="true">sh</span>' : mode === 'opencode' ? '<span class="tab-mode opencode" aria-hidden="true">oc</span>' : mode === 'codex' ? '<span class="tab-mode codex" aria-hidden="true">cx</span>' : mode === 'gemini' ? '<span class="tab-mode gemini" aria-hidden="true">gm</span>' : mode === 'antigravity' ? '<span class="tab-mode antigravity" aria-hidden="true">ag</span>' : mode === 'pi' ? '<span class="tab-mode pi" aria-hidden="true">pi</span>' : mode === 'grok' ? '<span class="tab-mode grok" aria-hidden="true">gk</span>' : ''}
<span class="tab-name" data-session-id="${id}" data-full-name="${escapeHtml(name)}">${tabLabel}</span>
${inlineSessionActions ? tabActionsHtml : ''}
<span class="tab-detached-badge" aria-hidden="true">detached</span>
</span>
${showFolder ? `<span class="tab-folder">\u{1F4C1} ${escapeHtml(folderName)}</span>` : ''}
@@ -4713,7 +4816,7 @@ class CodemanApp {
${hasRunningTasks ? `<span class="tab-badge" onclick="event.stopPropagation(); app.toggleTaskPanel()" aria-label="${taskStats.running} running tasks">${taskStats.running}</span>` : ''}
${subagentBadge}
${ultracodeBadge}
<span class="tab-actions"><span class="tab-gear" onclick="event.stopPropagation(); app.openSessionOptions(${escapeHtml(JSON.stringify(id))})" title="Session options" aria-label="Session options" tabindex="0">&#x2699;</span><span class="tab-detach" onclick="event.stopPropagation(); app.detachSession(${escapeHtml(JSON.stringify(id))})" title="Open in a new window" aria-label="Open session in a new window" tabindex="0">&#x29C9;</span><span class="tab-close" onclick="event.stopPropagation(); app.requestCloseSession(${escapeHtml(JSON.stringify(id))})" title="Close session" aria-label="Close session" tabindex="0">&times;</span></span>
${inlineSessionActions ? '' : tabActionsHtml}
</div>`);
_tabIdx++;
}
@@ -4936,9 +5039,9 @@ class CodemanApp {
// inside the handler — these listeners survive a layout flip between
// renders, so capturing the axis at bind time would go stale.
// drag-over-left/-right keep their names and now read as before/after;
// the sidebar CSS just draws them as top/bottom edges.
// the sidebar/rail CSS just draws them as top/bottom edges.
const rect = tab.getBoundingClientRect();
const insertBefore = this.isSessionSidebarActive()
const insertBefore = this._isVerticalTabList()
? e.clientY < rect.top + rect.height / 2
: e.clientX < rect.left + rect.width / 2;
@@ -4962,7 +5065,7 @@ class CodemanApp {
// Determine insertion position (same axis rule as the dragover handler)
const rect = tab.getBoundingClientRect();
const insertBefore = this.isSessionSidebarActive()
const insertBefore = this._isVerticalTabList()
? e.clientY < rect.top + rect.height / 2
: e.clientX < rect.left + rect.width / 2;
@@ -5246,6 +5349,22 @@ class CodemanApp {
this.terminal.write('\x1b[3J\x1b[H\x1b[2J');
}
_recordTerminalLoadTiming(timing) {
this._lastTerminalLoadTiming = timing;
console.info('[TERMINAL-PERF]', timing);
const resetAndParseMs =
(timing.cacheResetAndParseMs || 0) +
(timing.freshResetAndParseMs || 0) +
(timing.resetAndParseMs || 0);
const totalMs = timing.selectDoneMs ?? timing.totalMs ?? timing.selectToReplayCompleteMs ?? 0;
_crashDiag.log(
`TERMINAL_LOAD: ${timing.trigger} ${timing.full ? 'full' : 'tail'} ${timing.chars} chars ` +
`ttfb=${timing.ttfbMs.toFixed(0)}ms body+json=${timing.bodyAndJsonMs.toFixed(0)}ms ` +
`reset+parse=${resetAndParseMs.toFixed(0)}ms total=${totalMs.toFixed(0)}ms ` +
`server="${timing.serverTiming}"${timing.refused ? ' refused-downgrade' : ''}`
);
}
/**
* "Load more history": re-pull the whole tmux scrollback when the user scrolls up
* while already at the top of what the browser has.
@@ -5274,6 +5393,11 @@ class CodemanApp {
const sessionId = this.activeSessionId;
if (!sessionId || this._fullHistoryRepullInFlight || this._isLoadingBuffer) return;
if (this.detachedSessions?.has(sessionId)) return;
const session = this.sessions.get(sessionId);
// A shell's full capture can be many megabytes. Replaying it from an
// ordinary scroll gesture blocks xterm's main thread, so keep that cost
// behind the explicit "Load full history" button.
if (!force && session?.mode === 'shell') return;
const now = Date.now();
// Momentum scrolling fires this dozens of times per flick, and a burst of new
// output is the normal reason to want a re-pull, so cooldown rather than latch.
@@ -5285,13 +5409,32 @@ class CodemanApp {
this._fullHistoryRepullAt.set(sessionId, now);
this._fullHistoryRepullInFlight = true;
try {
const requestStartedAt = performance.now();
const res = await fetch(`/api/sessions/${sessionId}/terminal?full=1`);
const headersReceivedAt = performance.now();
const payload = (await res.json())?.data ?? {};
const bodyParsedAt = performance.now();
const buffer = payload.terminalBuffer;
const timing = {
trigger: force ? 'full-history-button' : 'full-history-scroll',
mode: session?.mode || 'unknown',
full: true,
source: payload.source || 'unknown',
chars: buffer?.length || 0,
ttfbMs: headersReceivedAt - requestStartedAt,
bodyAndJsonMs: bodyParsedAt - headersReceivedAt,
resetAndParseMs: 0,
totalMs: 0,
serverTiming: res.headers?.get?.('server-timing') || '',
refused: false,
};
// Bail on a tab switch mid-fetch: writing here would paint another session's
// history into the terminal the user is now looking at.
if (!buffer || this.activeSessionId !== sessionId) return;
if (this._replayWouldShrinkBuffer(buffer)) {
timing.refused = true;
timing.totalMs = performance.now() - requestStartedAt;
this._recordTerminalLoadTiming(timing);
(this._fullHistoryRepullUseless ||= new Set()).add(sessionId);
this._logScrollRouting?.('repull-refused-downgrade');
// The browser already holds more than tmux can give back, so there is
@@ -5302,17 +5445,32 @@ class CodemanApp {
this._setHistoryTruncation(sessionId, payload);
this._fullHistoryRepullUseless?.delete(sessionId);
const rowsBefore = this.terminal.buffer.active.length;
const replayStartedAt = performance.now();
this._resetTerminalForReplay();
await this.chunkedTerminalWrite(buffer, TERMINAL_CHUNK_SIZE, sessionId);
if (this.activeSessionId !== sessionId) return;
this.terminalBufferCache.set(sessionId, buffer);
const {
parsedAt,
bufferLength: parsedBufferLength,
completed,
} = await this.chunkedTerminalWrite(buffer, TERMINAL_CHUNK_SIZE, sessionId);
timing.resetAndParseMs = parsedAt - replayStartedAt;
if (!completed || this.activeSessionId !== sessionId) return;
// Keep shell tab restores bounded too. A user-triggered full-history pull
// may be tens of MB; caching it would replay that whole payload again on
// the next tab switch before the normal 1MB tail fetch replaces it.
if (this.sessions.get(sessionId)?.mode !== 'shell') {
this.terminalBufferCache.set(sessionId, buffer);
} else {
this.terminalBufferCache.delete(sessionId);
}
// Hold the user's place. The replay is a superset that grew the buffer
// UPWARD, so what used to be row 0 (what they were looking at) is now `delta`
// rows down; scrolling there reveals the recovered history above it instead
// of teleporting them to the bottom the way a normal buffer load does.
const delta = this.terminal.buffer.active.length - rowsBefore;
const delta = parsedBufferLength - rowsBefore;
if (delta > 0) this.terminal.scrollToLine(delta);
else this.terminal.scrollToTop();
timing.totalMs = performance.now() - requestStartedAt;
this._recordTerminalLoadTiming(timing);
} catch {
// Transient (offline, 5xx) — the next scroll-up past the cooldown retries.
} finally {
@@ -5592,6 +5750,7 @@ class CodemanApp {
// COD-144: track whether the load painted nothing (empty fetch + no cache).
// For that just-created-session case we flush (not discard) queued SSE events.
let bufferWasEmpty = false;
let cacheResetAndParseMs = 0;
try {
// Fit terminal to container BEFORE writing any buffer data.
// If the browser was resized while viewing another session, the terminal
@@ -5669,23 +5828,30 @@ class CodemanApp {
// blank and rewrites with fresh data. Skip the cache and write the fresh
// buffer once for a single clean transition.
const cachedBuffer = this.terminalBufferCache.get(sessionId);
let clearedForBusy = false;
if (cachedBuffer && !sessionIsBusy && !restoredSnapshot) {
let clearedBeforeFresh = false;
if (cachedBuffer && !sessionIsBusy && !restoredSnapshot && session?.mode !== 'shell') {
_crashDiag.log(`CACHE_WRITE: ${(cachedBuffer.length/1024).toFixed(0)}KB`);
this._setTerminalLoadState(sessionId, selectGen, 'replaying');
const cacheReplayStartedAt = performance.now();
this._resetTerminalForReplay();
await this.chunkedTerminalWrite(cachedBuffer, TERMINAL_CHUNK_SIZE, bufferLoadOwner);
const { parsedAt: cacheParsedAt } = await this.chunkedTerminalWrite(
cachedBuffer,
TERMINAL_CHUNK_SIZE,
bufferLoadOwner
);
cacheResetAndParseMs = cacheParsedAt - cacheReplayStartedAt;
if (this._isStaleSelect(selectGen)) {
this._clearTerminalLoadState(sessionId, selectGen);
return;
}
this.terminal.scrollToBottom();
_crashDiag.log('CACHE_DONE');
} else if (sessionIsBusy) {
// Clear stale content immediately — fresh buffer is being fetched
} else if (sessionIsBusy || session?.mode === 'shell') {
// Busy sessions have stale caches. Shell sessions deliberately skip even
// an idle cache so a changed 1MB tail cannot cause two back-to-back parses.
this._resetTerminalForReplay();
clearedForBusy = true;
_crashDiag.log('CACHE_SKIP_BUSY');
clearedBeforeFresh = true;
_crashDiag.log(session?.mode === 'shell' ? 'CACHE_SKIP_SHELL' : 'CACHE_SKIP_BUSY');
}
// Give TUI sessions a short chance to redraw after resize before the
@@ -5703,26 +5869,29 @@ class CodemanApp {
this._setTerminalLoadState(sessionId, selectGen, 'fetching');
_crashDiag.log('FETCH_START');
// The first load OF EACH SESSION this page load requests the full tmux
// scrollback (?full=1, COD-47) so history that scrolled off the server's byte
// buffer comes back. Later switches to an already-replayed session keep the
// fast ?tail= frame path, which is why this is a Set and not a flag: the flag
// version gave the full replay to the auto-selected tab and one frame of
// history to every other one (issue #205).
const useFullHistory = !this._fullHistoryLoaded.has(sessionId);
// TUI sessions still get one canonical full replay per page (COD-47/#205).
// A shell can retain hundreds of thousands of plain scrollback lines, so
// automatically replaying all of them makes tab selection scale with the
// entire session. Load its bounded 1MB tail first; the existing truncation
// banner action fetches ?full=1 when the user explicitly asks for it.
const useFullHistory = session?.mode !== 'shell' && !this._fullHistoryLoaded.has(sessionId);
if (useFullHistory) this._fullHistoryLoaded.add(sessionId);
const fetchStartedAt = performance.now();
const res = await fetch(
useFullHistory
? `/api/sessions/${sessionId}/terminal?full=1`
: `/api/sessions/${sessionId}/terminal?tail=${TERMINAL_TAIL_SIZE}`
);
const headersReceivedAt = performance.now();
if (this._isStaleSelect(selectGen)) {
this._clearTerminalLoadState(sessionId, selectGen);
return;
}
const data = (await res.json())?.data ?? {};
const bodyParsedAt = performance.now();
_crashDiag.log(`FETCH_DONE: ${data.terminalBuffer ? (data.terminalBuffer.length/1024).toFixed(0) + 'KB' : 'empty'} truncated=${data.truncated}`);
let freshResetAndParseMs = 0;
if (data.terminalBuffer) {
// Skip rewrite if fresh buffer matches cache — avoids visible clear+rewrite flash.
// On slow connections (mobile 5G), the gap between clear() and chunkedWrite() is
@@ -5731,10 +5900,11 @@ class CodemanApp {
// something other than the cache, so the fetched buffer must be
// replayed even when it byte-matches the cache.
const needsRewrite =
restoredSnapshot || clearedForBusy || data.terminalBuffer !== cachedBuffer;
restoredSnapshot || clearedBeforeFresh || data.terminalBuffer !== cachedBuffer;
if (needsRewrite) {
_crashDiag.log(`REWRITE: ${(data.terminalBuffer.length/1024).toFixed(0)}KB`);
this._setTerminalLoadState(sessionId, selectGen, 'replaying');
const replayStartedAt = performance.now();
this._resetTerminalForReplay();
// Truncation is reported OUT OF BAND (#258). This used to write a grey
// "... earlier output truncated ..." line into the
@@ -5742,7 +5912,12 @@ class CodemanApp {
// cannot be actioned, and is indistinguishable from real CLI output.
this._setHistoryTruncation(sessionId, data);
// Use chunked write for large buffers to avoid UI jank
await this.chunkedTerminalWrite(data.terminalBuffer, TERMINAL_CHUNK_SIZE, bufferLoadOwner);
const { parsedAt: freshParsedAt } = await this.chunkedTerminalWrite(
data.terminalBuffer,
TERMINAL_CHUNK_SIZE,
bufferLoadOwner
);
freshResetAndParseMs = freshParsedAt - replayStartedAt;
if (this._isStaleSelect(selectGen)) {
this._clearTerminalLoadState(sessionId, selectGen);
return;
@@ -5751,22 +5926,42 @@ class CodemanApp {
this.terminal.scrollToBottom();
}
// Update cache (cap at 20 entries)
this.terminalBufferCache.set(sessionId, data.terminalBuffer);
if (this.terminalBufferCache.size > 20) {
// Evict oldest entry (first key in Map iteration order)
const oldest = this.terminalBufferCache.keys().next().value;
this.terminalBufferCache.delete(oldest);
// Shell selection always uses a fresh bounded tail, so retaining its
// payload only wastes memory and can evict useful TUI caches.
if (session?.mode === 'shell') {
this.terminalBufferCache.delete(sessionId);
} else {
// Update cache (cap at 20 entries)
this.terminalBufferCache.set(sessionId, data.terminalBuffer);
if (this.terminalBufferCache.size > 20) {
// Evict oldest entry (first key in Map iteration order)
const oldest = this.terminalBufferCache.keys().next().value;
this.terminalBufferCache.delete(oldest);
}
}
} else if (!cachedBuffer) {
// No fresh buffer and no cache — clear any stale content
this._resetTerminalForReplay();
} else if (!cachedBuffer || clearedBeforeFresh) {
// Nothing was painted. If this path was not already cleared above,
// clear stale content now; either way queued live output must be flushed.
if (!clearedBeforeFresh) this._resetTerminalForReplay();
bufferWasEmpty = true;
}
const terminalLoadTiming = {
trigger: 'session-select',
mode: session?.mode || 'unknown',
full: useFullHistory,
source: data.source || 'unknown',
chars: data.terminalBuffer?.length || 0,
ttfbMs: headersReceivedAt - fetchStartedAt,
bodyAndJsonMs: bodyParsedAt - headersReceivedAt,
cacheResetAndParseMs,
freshResetAndParseMs,
selectToReplayCompleteMs: performance.now() - _selStart,
serverTiming: res.headers?.get?.('server-timing') || '',
};
// Buffer load complete — unblock live SSE writes. chunkedTerminalWrite calls
// _finishBufferLoad internally (discarding queued events to prevent duplicate
// content); if we skipped the write (cache hit or empty), call it here.
// _finishBufferLoad after ordering the fetched snapshot in xterm; if we skipped
// the write (cache hit or empty), call it here.
// COD-144: when the load painted nothing, FLUSH the queued events instead of
// discarding — a new session's prompt arrives only as a queued SSE event.
if (this._isLoadingBuffer) {
@@ -5895,9 +6090,12 @@ class CodemanApp {
if (typeof KeyboardHandler !== 'undefined' && KeyboardHandler.keyboardVisible) {
KeyboardHandler.onKeyboardShow();
}
const selectDoneMs = performance.now() - _selStart;
terminalLoadTiming.selectDoneMs = selectDoneMs;
this._recordTerminalLoadTiming(terminalLoadTiming);
this._clearTerminalLoadState(sessionId, selectGen);
_crashDiag.log(`SELECT_DONE: ${(performance.now() - _selStart).toFixed(0)}ms`);
console.log(`[CRASH-DIAG] selectSession DONE: ${sessionId.slice(0,8)} in ${(performance.now() - _selStart).toFixed(0)}ms`);
_crashDiag.log(`SELECT_DONE: ${selectDoneMs.toFixed(0)}ms`);
console.log(`[CRASH-DIAG] selectSession DONE: ${sessionId.slice(0,8)} in ${selectDoneMs.toFixed(0)}ms`);
} catch (err) {
if (this._isLoadingBuffer) this._finishBufferLoad(bufferLoadOwner);
this._restoringFlushedState = false;
@@ -5908,6 +6106,7 @@ class CodemanApp {
// Shared cleanup for all session data — called from both closeSession() and session:deleted handler
_cleanupSessionData(sessionId) {
this.closeTabRailActionMenu?.();
// If the deleted session is currently being renamed, abort the rename
// so the inline <input> doesn't ghost as a stale tab on screen.
if (this._activeRename?.sessionId === sessionId) {
@@ -6037,7 +6236,9 @@ class CodemanApp {
? 'Kill Tmux & Antigravity'
: session.mode === 'pi'
? 'Kill Tmux & Pi'
: 'Kill Tmux & Claude Code';
: session.mode === 'grok'
? 'Kill Tmux & Grok'
: 'Kill Tmux & Claude Code';
}
document.getElementById('closeConfirmModal').classList.add('active');
+279 -8
View File
@@ -10,7 +10,7 @@
* @globals {function} scheduleBackground - scheduler.postTask wrapper (background priority)
* @globals {function} getEventCoords - Unified mouse/touch coordinate extractor
* @globals {function} escapeHtml - XSS-safe HTML escaping
* @globals {object} SSE_EVENTS - Centralized SSE event type constants (120 event types; must match backend src/web/sse-events.ts)
* @globals {object} SSE_EVENTS - Centralized SSE event type constants (156 event types; must match backend src/web/sse-events.ts)
* @globals {Array} BUILTIN_RESPAWN_PRESETS - Built-in respawn configuration presets
*
* @dependency None (first in load order)
@@ -156,6 +156,43 @@ function shouldAutoWrapTabs(input) {
return scrollWidth > clientWidth + 1;
}
function resolveTabOrientation(input) {
if (!input || input.setting !== 'vertical') return 'horizontal';
if (input.deviceType === 'mobile') return 'horizontal';
return 'vertical';
}
const TAB_RAIL_MIN_WIDTH = 208;
const TAB_RAIL_DEFAULT_WIDTH = 256;
const TAB_RAIL_MAX_WIDTH = 360;
function resolveTabRailWidth(input = {}) {
const viewportWidth = Number(input.viewportWidth);
const mainWidth = Number(input.mainWidth);
const minTerminalWidth = Number(input.minTerminalWidth);
const limits = [TAB_RAIL_MAX_WIDTH];
if (Number.isFinite(viewportWidth) && viewportWidth > 0) limits.push(Math.floor(viewportWidth * 0.4));
if (Number.isFinite(mainWidth) && mainWidth > 0 && Number.isFinite(minTerminalWidth) && minTerminalWidth > 0) {
limits.push(Math.floor(mainWidth - minTerminalWidth));
}
const effectiveMax = Math.max(TAB_RAIL_MIN_WIDTH, Math.min(...limits));
const requested = Number(input.width);
const width = Number.isFinite(requested) ? requested : TAB_RAIL_DEFAULT_WIDTH;
return Math.round(Math.min(effectiveMax, Math.max(TAB_RAIL_MIN_WIDTH, width)));
}
function resolveTabRailKeyboardWidth(input = {}) {
let width;
if (input.key === 'Home') width = TAB_RAIL_MIN_WIDTH;
else if (input.key === 'End') width = TAB_RAIL_MAX_WIDTH;
else if (input.key === 'Enter') width = TAB_RAIL_DEFAULT_WIDTH;
else if (input.key === 'ArrowLeft' || input.key === 'ArrowRight') {
const direction = input.key === 'ArrowLeft' ? -1 : 1;
width = (Number(input.currentWidth) || TAB_RAIL_DEFAULT_WIDTH) + direction * (input.shiftKey ? 32 : 8);
} else return null;
return resolveTabRailWidth({ ...input, width });
}
// Sliver of the neighbouring tab left visible when the strip scrolls a tab into
// view. Landing a tab flush against the edge reads as "this is the last one";
// the gap is what tells the user there is more strip to swipe to.
@@ -243,6 +280,9 @@ const LINEAGE_DIP_MAX_PX = 64;
// apart bled into one thick band instead of reading as three separate lines.
const LINEAGE_SIBLING_STEP_PX = 8;
const LINEAGE_STRIP_TOLERANCE_PX = 4;
const LINEAGE_VERTICAL_TRACK_INSET_PX = 6;
const LINEAGE_VERTICAL_SIBLING_STEP_PX = 3;
const LINEAGE_VERTICAL_ANCHOR_CLEARANCE_PX = 4;
// Lineage palette, assigned per SPAWNING TAB in first-seen order and cycled
// (session-lineage.js). Every arc leaving one tab shares its colour however many
// workers it spawns; a child that spawns in turn gets its own for the arcs below it.
@@ -265,21 +305,44 @@ function computeLineagePath(input) {
const ch = Number(child.height) || 0;
if (pw <= 0 || ph <= 0 || cw <= 0 || ch <= 0) return null;
const px = Number(parent.left) + pw / 2;
const cx = Number(child.left) + cw / 2;
if (!Number.isFinite(px) || !Number.isFinite(cx)) return null;
const orientation = input?.orientation === 'vertical' ? 'vertical' : 'horizontal';
const strip = input?.strip;
const depth = Math.max(0, Math.min(6, Number(input?.depth) || 0));
const pLeft = Number(parent.left);
const cLeft = Number(child.left);
const pTop = Number(parent.top);
const cTop = Number(child.top);
if (![pLeft, cLeft, pTop, cTop].every(Number.isFinite)) return null;
if (orientation === 'vertical') {
const py = pTop + ph / 2;
const cy = cTop + ch / 2;
if (strip && Number(strip.height) > 0) {
const min = Number(strip.top) - LINEAGE_STRIP_TOLERANCE_PX;
const max = Number(strip.top) + Number(strip.height) + LINEAGE_STRIP_TOLERANCE_PX;
if (py < min || py > max || cy < min || cy > max) return null;
}
const stripLeft =
strip && Number.isFinite(Number(strip.left))
? Number(strip.left)
: Math.min(pLeft, cLeft) - LINEAGE_VERTICAL_TRACK_INSET_PX * 2;
const requestedTrack =
stripLeft + LINEAGE_VERTICAL_TRACK_INSET_PX + depth * LINEAGE_VERTICAL_SIBLING_STEP_PX;
const trackX = Math.min(requestedTrack, Math.min(pLeft, cLeft) - LINEAGE_VERTICAL_ANCHOR_CLEARANCE_PX);
const d = `M ${r1(pLeft)} ${r1(py)} H ${r1(trackX)} V ${r1(cy)} H ${r1(cLeft)}`;
return { d, endX: cLeft, endY: cy, sameRow: false };
}
const px = pLeft + pw / 2;
const cx = cLeft + cw / 2;
if (strip && Number(strip.width) > 0) {
const min = Number(strip.left) - LINEAGE_STRIP_TOLERANCE_PX;
const max = Number(strip.left) + Number(strip.width) + LINEAGE_STRIP_TOLERANCE_PX;
if (px < min || px > max || cx < min || cx > max) return null;
}
const depth = Math.max(0, Math.min(6, Number(input?.depth) || 0));
const pTop = Number(parent.top);
const pBottom = pTop + ph;
const cTop = Number(child.top);
const cBottom = cTop + ch;
const sameRow = Math.abs(pTop + ph / 2 - (cTop + ch / 2)) <= Math.min(ph, ch) / 2;
@@ -527,15 +590,107 @@ function sortSessionsByActivity(rows) {
return (Array.isArray(rows) ? rows.slice() : []).sort(compareSessionActivity);
}
// Terminal font stack — the single source for every xterm surface (the main
// terminal in terminal-ui.js, the log-viewer terminal in panels-ui.js).
// "Symbols Nerd Font Mono" is a bundled icons-only webfont (fonts/ +
// @font-face in styles.css): browsers fall back PER GLYPH, so Nerd Font
// prompt icons (powerline segments, folder/git glyphs from p10k, starship,
// oh-my-posh) render even though the text fonts carry no private-use-area
// symbols — while all readable text keeps coming from the text fonts.
const TERMINAL_FONT_DEFAULT_STACK =
'"Fira Code", "Cascadia Code", "JetBrains Mono", "SF Mono", Monaco, "Symbols Nerd Font Mono", monospace';
/**
* Resolve the xterm fontFamily from the per-device `terminalFontFamily`
* setting. A user-set family (or comma-separated list) is PREPENDED to the
* built-in stack, never a replacement — the symbols fallback and a final
* `monospace` must survive whatever the user types. Blank input yields the
* default. Unquoted names that need quoting for CSS (spaces, digits leading,
* etc.) are quoted; embedded quotes are stripped rather than escaped, since
* a font name cannot contain them anyway.
*/
function resolveTerminalFontFamily(custom) {
const raw = typeof custom === 'string' ? custom.trim() : '';
if (!raw) return TERMINAL_FONT_DEFAULT_STACK;
const families = raw
.split(',')
.map((f) => f.trim().replace(/^["']|["']$/g, '').replace(/["']/g, '').trim())
.filter(Boolean)
// Drop generic families the user may append — the default stack already
// ends in `monospace`, and a duplicate earlier entry would shadow the
// symbols fallback behind it.
.filter((f) => !/^(monospace|serif|sans-serif|system-ui)$/i.test(f))
.map((f) => (/^[A-Za-z][A-Za-z0-9-]*$/.test(f) ? f : `"${f}"`));
if (!families.length) return TERMINAL_FONT_DEFAULT_STACK;
return `${families.join(', ')}, ${TERMINAL_FONT_DEFAULT_STACK}`;
}
// ---------------------------------------------------------------------------
// Auto Copy (copy-on-select). Pure decision, so every guard below is testable
// without a terminal, a clipboard, or a browser.
// ---------------------------------------------------------------------------
/**
* Upper bound on an AUTO-copied selection.
*
* A drag that runs off the top of the viewport autoscrolls, so one gesture can
* sweep the entire 50k-line scrollback (millions of characters), and writing
* that to the clipboard on every mouseup is a real hazard on a phone. Past the
* cap the copy is REFUSED rather than truncated (half a selection on the
* clipboard is worse than none) and the user is told to press Ctrl+C, which
* still copies the whole thing through the explicit path.
*/
const AUTO_COPY_MAX_CHARS = 1_000_000;
/**
* What an auto-copy attempt should do at the end of a selection gesture.
*
* `pending` is set by xterm's onSelectionChange and cleared on every flush;
* `lastCopied` is the text this surface auto-copied last. Either one alone is
* wrong, which is why both are here:
*
* - onSelectionChange does not reliably fire BEFORE the mouseup that ends the
* drag (xterm fires it from its own document-level mouseup handler, and
* listener order between the two is registration order, not something this
* code controls). Gating on `pending` alone would silently drop the first
* copy of a drag-selection.
* - Gating on `text !== lastCopied` alone drops a deliberate re-selection of
* the same text after the user copied something else in between, and it
* would let any unrelated mouseup on the page re-copy a stale selection.
*
* So: a genuine selection change (`pending`) always copies, and otherwise only
* text that differs from the last auto-copy does.
*
* @param {{enabled?: boolean, text?: string, lastCopied?: string, pending?: boolean}} params
* @returns {'copy'|'skip'|'too-large'}
*/
function decideAutoCopy({ enabled, text, lastCopied, pending } = {}) {
if (!enabled) return 'skip';
// Whitespace-only is what a drag across blank cells produces; putting a wall
// of spaces on the clipboard is never what the gesture meant.
if (typeof text !== 'string' || !text.trim()) return 'skip';
if (!pending && text === lastCopied) return 'skip';
if (text.length > AUTO_COPY_MAX_CHARS) return 'too-large';
return 'copy';
}
if (typeof window !== 'undefined') {
window.WEBGL_FALLBACK = WEBGL_FALLBACK;
window.evaluateWebGLLongTaskTrip = evaluateWebGLLongTaskTrip;
window.shouldSkipWebGL = shouldSkipWebGL;
window.CodemanTabOverflow = {
shouldAutoWrapTabs,
resolveTabOrientation,
computeTabScrollLeft,
TAB_SCROLL_REVEAL_PX,
};
window.CodemanTabRail = {
DEFAULT_WIDTH: TAB_RAIL_DEFAULT_WIDTH,
MIN_WIDTH: TAB_RAIL_MIN_WIDTH,
MAX_WIDTH: TAB_RAIL_MAX_WIDTH,
resolveWidth: resolveTabRailWidth,
resolveKeyboardWidth: resolveTabRailKeyboardWidth,
};
window.CodemanWsReconnect = {
plan: planWsReconnect,
};
@@ -544,6 +699,8 @@ if (typeof window !== 'undefined') {
DIP_MIN_PX: LINEAGE_DIP_MIN_PX,
DIP_MAX_PX: LINEAGE_DIP_MAX_PX,
SIBLING_STEP_PX: LINEAGE_SIBLING_STEP_PX,
VERTICAL_TRACK_INSET_PX: LINEAGE_VERTICAL_TRACK_INSET_PX,
VERTICAL_SIBLING_STEP_PX: LINEAGE_VERTICAL_SIBLING_STEP_PX,
COLORS: LINEAGE_COLORS,
};
window.CodemanConnectionLoss = {
@@ -560,6 +717,14 @@ if (typeof window !== 'undefined') {
compare: compareSessionActivity,
sort: sortSessionsByActivity,
};
window.CodemanAutoCopy = {
decide: decideAutoCopy,
MAX_CHARS: AUTO_COPY_MAX_CHARS,
};
window.CodemanTerminalFont = {
DEFAULT_STACK: TERMINAL_FONT_DEFAULT_STACK,
resolve: resolveTerminalFontFamily,
};
}
// Scheduler API — prioritize terminal writes over background UI updates.
@@ -877,6 +1042,7 @@ const SSE_EVENTS = {
// Web tabs (dashboard URLs)
WEBVIEW_CHANGED: 'webview:changed',
TAB_LAYOUT_CHANGED: 'tab:layoutChanged',
};
// ═══════════════════════════════════════════════════════════════
@@ -1035,7 +1201,112 @@ function previewsInFileViewer(filePath) {
return FILE_PREVIEW_EXTENSIONS.has(ext);
}
/**
* The LOGICAL line a terminal row belongs to — the rows it spans, its text as one
* string, and a two-way map between that string and terminal cells.
*
* One definition, two consumers: the link provider matches its patterns over this
* text (`registerFilePathLinkProvider`) and touch selection measures words and
* whole lines with it (`_touchSelectionLogicalLine`). They MUST agree — a link that
* spans a wrap and a "Line" that stops at the screen edge is the same bug twice.
*
* Two kinds of continuation, and handling only the first is not enough:
*
* 1. **Soft wrap** — the emulator ran out of columns and flags the next row
* `isWrapped`. It inserts nothing, so the row's text is joined verbatim.
* 2. **Hard wrap** — the program wrapped the text itself and emitted a real
* newline, so nothing is flagged. A row that fills the last column is taken
* as continuing into the next; that is the only trace a hard wrap leaves.
*
* ⚠️ A hard-wrapped continuation may carry the program's own INDENT, and joining
* that verbatim puts whitespace in the middle of the token being stitched. That is
* why an agent's numbered list —
*
* 1. https://github.com/users/someone/packages/container/p
* ackage/thing
*
* — opened only `…/container/p`: the URL pattern stops at the space the indent
* contributed. So the leading whitespace of a HARD continuation is dropped, and
* `colStart` on that segment records how much, keeping the cell mapping exact. A
* soft continuation keeps its leading whitespace, since the terminal never adds
* any and it is therefore real content.
*
* ⚠️ Only the final row is trimmed. Continuation rows are read UNTRIMMED so each
* contributes exactly `cols` cells; trimming one would shift every later offset.
*
* The row span is bounded by `maxRows` (12 by default): this runs on every hover,
* and a screenful of full-width output would otherwise re-scan the viewport each
* time.
*
* @param {{getLine: (row: number) => any, length: number}} buffer xterm buffer.
* @param {number} row 0-based ABSOLUTE buffer row to expand around.
* @param {number} cols Terminal width.
* @param {number} [maxRows] Row-span bound.
* @returns {{startRow: number, endRow: number, text: string,
* offsetToCell: (offset: number) => {row: number, col: number},
* cellToOffset: (row: number, col: number) => number} | null}
* 0-based rows and columns throughout; null when the row does not exist.
*/
function terminalLogicalLine(buffer, row, cols, maxRows) {
if (!buffer || typeof buffer.getLine !== 'function') return null;
const width = Math.max(1, cols || 1);
const bound = Math.max(1, maxRows || 12);
const lineAt = (r) => (r >= 0 ? buffer.getLine(r) : undefined);
if (!lineAt(row)) return null;
const continuesPrevious = (r) => {
if (r <= 0) return false;
if (lineAt(r)?.isWrapped) return true;
const prev = lineAt(r - 1);
return !!prev && (prev.translateToString(true) || '').length >= width;
};
let startRow = row;
while (startRow > 0 && row - startRow < bound && continuesPrevious(startRow)) startRow--;
let endRow = row;
const length = Number.isFinite(buffer.length) ? buffer.length : endRow + 1;
while (endRow + 1 < length && endRow - startRow < bound && continuesPrevious(endRow + 1)) endRow++;
const segments = [];
let text = '';
for (let r = startRow; r <= endRow; r++) {
const line = lineAt(r);
if (!line) break;
let rowText = line.translateToString(r === endRow) || '';
let colStart = 0;
if (r > startRow && !line.isWrapped) {
const indent = rowText.length - rowText.replace(/^\s+/, '').length;
colStart = indent;
rowText = rowText.slice(indent);
}
segments.push({ row: r, textStart: text.length, colStart, length: rowText.length });
text += rowText;
}
const offsetToCell = (offset) => {
for (let i = segments.length - 1; i >= 0; i--) {
const seg = segments[i];
if (offset >= seg.textStart || i === 0) {
return { row: seg.row, col: seg.colStart + (offset - seg.textStart) };
}
}
return { row: startRow, col: offset };
};
const cellToOffset = (targetRow, targetCol) => {
for (const seg of segments) {
if (seg.row !== targetRow) continue;
return seg.textStart + Math.max(0, targetCol - seg.colStart);
}
return -1;
};
return { startRow, endRow, text, offsetToCell, cellToOffset };
}
if (typeof window !== 'undefined') {
window.CodemanHistoryFormat = { formatHistoryBytes, computeHistoryTruncationNotice, computeRewriteScrollLine };
window.CodemanFilePaths = { absoluteFilePathPattern, previewsInFileViewer, FILE_PREVIEW_EXTENSIONS };
window.CodemanTerminalLines = { terminalLogicalLine };
}
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014 Ryan L McIntyre
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Binary file not shown.
+5 -2
View File
@@ -78,6 +78,7 @@ const HOME_SESSIONS_MODE_BADGE = {
gemini: 'gm',
antigravity: 'ag',
pi: 'pi',
grok: 'gk',
};
Object.assign(CodemanApp.prototype, {
@@ -87,12 +88,14 @@ Object.assign(CodemanApp.prototype, {
/**
* Width-driven, like every other layout decision in the app. Explicitly yields
* to the phone overview: that surface already lists the same sessions, and two
* lists of the same thing on one screen is worse than none.
* to the phone overview and persistent vertical tab rail: those surfaces already
* list the same sessions, and two lists of the same thing on one screen is worse
* than none.
*/
shouldShowHomeSessions() {
if (this.isSoloWindow) return false;
if (this.shouldUseMobileOverview?.()) return false;
if (document.documentElement.getAttribute('data-tab-orientation') === 'vertical') return false;
// The sidebar layout already docks the full session list flush left at full
// height — the rail would render the same list right next to it (and z-wise
// UNDER it: sidebar 11, welcome overlay 10, rail inside the overlay).
+17
View File
@@ -109,6 +109,7 @@
'Run Gemini': '运行 Gemini',
'Run Antigravity': '运行 Antigravity',
'Run Pi': '运行 Pi',
'Run Grok': '运行 Grok',
'Run Shell': '运行 Shell',
'Select AI backend': '选择 AI 后端',
'Create New Case': '新建案例',
@@ -232,6 +233,8 @@
'Redraw Terminal Button': '重绘终端按钮',
'Tab Bar': '标签栏',
'Session List Layout': '会话列表布局',
'Session Name Font Size': '会话名称字体大小',
'Adjust only session names in the vertical sidebar.': '仅调整垂直侧边栏中的会话名称。',
'Header tab strip': '顶栏标签条',
'Left sidebar': '左侧边栏',
'Left sidebar simple': '左侧边栏(简洁)',
@@ -326,11 +329,20 @@
// Input settings
Input: '输入',
Font: '字体',
'Terminal font': '终端字体',
'Prepended to the built-in stack, so fallbacks (including bundled Nerd Font symbols) keep working. Must be installed on this device. Leave empty for the default.':
'置于内置字体栈之前,回退字体(包括内置的 Nerd Font 图标)仍然生效。需已安装在本设备上。留空使用默认值。',
'Local Echo': '本地回显',
'CJK Input': '中日韩输入',
'Extended Keyboard Bar': '扩展键盘栏',
'Gesture Control (beta)': '手势控制(测试版)',
'Wheel Scrolls Local History': '滚轮滚动本地历史',
'Auto Copy Selection': '自动复制选中内容',
'Selection & clipboard': '选中与剪贴板',
'Auto Copy: selection copied': '自动复制:已复制选中内容',
'Auto Copy failed: the browser blocked clipboard access': '自动复制失败:浏览器阻止了剪贴板访问',
'Selection too large to copy automatically. Press Ctrl+C.': '选中内容过大,无法自动复制。请按 Ctrl+C。',
'Instant typing feedback with local echo': '通过本地回显即时显示输入',
'Dedicated IME input field for CJK languages': '为中日韩语言提供专用输入法文本框',
'Extra keys: Tab, Esc, arrows, Ctrl+O': '附加按键:Tab、Esc、方向键、Ctrl+O',
@@ -500,6 +512,11 @@
'Respawn Blocked': '重生已阻止',
'Task Complete': '任务完成',
'Copied to clipboard': '已复制到剪贴板',
// Terminal touch-selection bar (long-press to select). The bar is a sibling of
// `.xterm`, not a descendant, so SKIP_SELECTOR does not cover it and these apply.
Copy: '复制',
Line: '整行',
'Clear selection': '清除选择',
'Failed to copy': '复制失败',
'Checking…': '正在检查…',
'Starting…': '正在启动…',
+92 -2
View File
@@ -24,6 +24,9 @@
<!-- Preload critical resources — lets browser discover these during HTML parse
instead of waiting until <script> tags at bottom-of-body are reached. -->
<link rel="preload" href="vendor/xterm.min.js" as="script">
<!-- Symbols font before the terminal first paints — a late-loading icon font
leaves tofu in xterm's glyph atlas until something forces a re-render. -->
<link rel="preload" href="fonts/symbols-nerd-font-mono.woff2" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="constants.js" as="script">
<link rel="preload" href="app.js" as="script">
<!-- Self-hosted xterm.js — eliminates CDN DNS/TLS latency (~100ms).
@@ -62,7 +65,7 @@
app.js, NOT the handheld storage-key test `m`. Use a different predicate
here and boot will contradict this value, animating the drawer open by
itself on every load between 768 and 1023px. -->
<script>try{var m=window.innerWidth<768||(('ontouchstart' in window||navigator.maxTouchPoints>0)&&window.innerWidth<1024);var k=m?'codeman-app-settings-mobile':'codeman-app-settings';var L=JSON.parse(localStorage.getItem(k)||'{}').sessionListLayout;var solo=/^\/session\//.test(location.pathname);var C=localStorage.getItem('codeman-sidebar-collapsed');var S=(L==='sidebar'||L==='sidebar-rich')&&!solo;document.documentElement.dataset.sessionList=S?'sidebar':'header';document.documentElement.dataset.sidebarDetail=(S&&L==='sidebar-rich')?'rich':'simple';document.documentElement.dataset.sidebar=(C===null?window.innerWidth<1024:C==='1')?'collapsed':'expanded';}catch(e){document.documentElement.dataset.sessionList='header';document.documentElement.dataset.sidebarDetail='simple';document.documentElement.dataset.sidebar='expanded';}</script>
<script>try{var m=window.innerWidth<768||(('ontouchstart' in window||navigator.maxTouchPoints>0)&&window.innerWidth<1024);var k=m?'codeman-app-settings-mobile':'codeman-app-settings';var A=JSON.parse(localStorage.getItem(k)||'{}');var L=A.sessionListLayout;var F=Number(A.sessionSidebarFontSize);var solo=/^\/session\//.test(location.pathname);var C=localStorage.getItem('codeman-sidebar-collapsed');var S=(L==='sidebar'||L==='sidebar-rich')&&!solo;document.documentElement.dataset.sessionList=S?'sidebar':'header';document.documentElement.dataset.sidebarDetail=(S&&L==='sidebar-rich')?'rich':'simple';document.documentElement.dataset.sidebar=(C===null?window.innerWidth<1024:C==='1')?'collapsed':'expanded';var V=A.tabOrientation==='vertical'&&!S&&!solo&&window.innerWidth>=768;document.documentElement.dataset.tabOrientation=V?'vertical':'horizontal';var W=Number(A.tabRailWidth);if(V&&Number.isInteger(W)&&W>=208&&W<=360)document.documentElement.style.setProperty('--tab-rail-width',W+'px');if(Number.isInteger(F)&&F>=11&&F<=18)document.documentElement.style.setProperty('--session-sidebar-name-font-size',F+'px');}catch(e){document.documentElement.dataset.sessionList='header';document.documentElement.dataset.sidebarDetail='simple';document.documentElement.dataset.sidebar='expanded';document.documentElement.dataset.tabOrientation='horizontal';}</script>
<!-- Inline critical CSS for instant skeleton paint (before styles.css loads) -->
<style>
.loading-skeleton{display:flex;flex-direction:column;height:100vh;height:100dvh;background:var(--bg-dark,#11151c)}
@@ -355,6 +358,20 @@
<!-- Main Terminal Area -->
<main class="main">
<aside class="tab-rail" id="tabRail" aria-label="Session navigation">
<div
id="tabRailResizeHandle"
class="tab-rail-resize-handle"
role="separator"
aria-orientation="vertical"
aria-label="Resize session rail"
aria-valuemin="208"
aria-valuemax="360"
aria-valuenow="256"
tabindex="0"
></div>
</aside>
<!-- Collapsible session sidebar (opt-in layout). Deliberately EMPTY in
markup: applySessionListLayout() moves #sessionTabs in here, so the
vertical list is the exact same DOM node as the header strip and every
@@ -427,6 +444,10 @@
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="5 3 19 12 5 21 5 3"/></svg>
Run Pi
</button>
<button class="welcome-btn welcome-btn-grok" id="welcomeGrokBtn" style="display: none;" onclick="app.setRunMode('grok'); app.runGrok()">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="5 3 19 12 5 21 5 3"/></svg>
Run Grok
</button>
</div>
<div class="welcome-qr" id="welcomeQr" onclick="app.toggleWelcomeQrSize()">
<div class="welcome-qr-inner" id="welcomeQrInner"></div>
@@ -506,6 +527,7 @@
desktop (which never loads mobile.css) can never render it. -->
<div class="mobile-overview" id="mobileOverview" hidden></div>
</main>
<div class="tab-rail-resize-shield" id="tabRailResizeShield" aria-hidden="true" hidden></div>
<!-- Project Insights Panel (shows file-viewing Bash commands) -->
<div class="project-insights-panel" id="projectInsightsPanel">
@@ -545,6 +567,7 @@
<div class="file-preview-actions">
<button class="btn-icon-sm file-preview-edit-btn" id="filePreviewEditBtn" onclick="app.enterFilePreviewEdit()" title="Edit file" aria-label="Edit file" hidden><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5z"/></svg></button>
<button class="btn-icon-sm" onclick="app.copyFilePreviewContent()" title="Copy content">&#x2398;</button>
<button class="btn-icon-sm" id="filePreviewDetachBtn" onclick="app.detachFilePreview()" title="Open in new tab" aria-label="Open in new tab" hidden><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg></button>
<button class="btn-icon-sm" onclick="app.closeFilePreview()" title="Close">&times;</button>
</div>
</div>
@@ -604,6 +627,9 @@
<button class="run-mode-option" data-mode="pi" onclick="app.setRunMode('pi')">
<span class="run-mode-dot pi"></span>Pi
</button>
<button class="run-mode-option" data-mode="grok" onclick="app.setRunMode('grok')">
<span class="run-mode-dot grok"></span>Grok
</button>
<div class="run-mode-sep"></div>
<button class="run-mode-option" data-mode="shell" onclick="app.setRunMode('shell')">
<span class="run-mode-dot shell"></span>Terminal / Shell
@@ -881,6 +907,7 @@
<option value="gemini">Gemini</option>
<option value="antigravity">Antigravity</option>
<option value="pi">Pi</option>
<option value="grok">Grok</option>
</select>
</div>
<div class="form-row"><label>Working Directory</label><input type="text" id="schWorkingDir" placeholder="/absolute/path"></div>
@@ -1624,6 +1651,32 @@
</div>
</div>
<div class="set-group">
<div class="set-group-head"><h4>Selection &amp; clipboard</h4><span class="set-scope">device</span></div>
<div class="set-group-body">
<div class="set-row" data-search="auto copy selection clipboard highlight copy on select mouse">
<div class="set-row-text">
<span class="set-row-label">Auto Copy Selection</span>
<span class="set-row-desc">Put highlighted terminal text on the clipboard as soon as you finish selecting it, with mouse, double-click or long-press. Ctrl+C still copies on demand, and nothing outside the terminal is copied.</span>
</div>
<label class="switch switch-sm"><input type="checkbox" id="appSettingsAutoCopySelection"><span class="slider"></span></label>
</div>
</div>
</div>
<div class="set-group">
<div class="set-group-head"><h4>Font</h4><span class="set-scope">device</span></div>
<div class="set-group-body">
<div class="set-row has-field" data-search="terminal font family nerd custom typeface">
<div class="set-row-text">
<span class="set-row-label">Terminal font</span>
<span class="set-row-desc">Prepended to the built-in stack, so fallbacks (including bundled Nerd Font symbols) keep working. Must be installed on this device. Leave empty for the default.</span>
</div>
<input type="text" id="appSettingsTerminalFont" class="set-input" placeholder='e.g. JetBrainsMono Nerd Font'>
</div>
</div>
</div>
<div class="set-group">
<div class="set-group-head"><h4>Scrolling &amp; rendering</h4></div>
<div class="set-group-body">
@@ -1840,6 +1893,29 @@
<div class="set-group">
<div class="set-group-head"><h4>Tabs</h4><span class="set-scope">device</span></div>
<div class="set-group-body">
<div class="set-row has-field" data-search="tab orientation horizontal vertical side rail">
<div class="set-row-text">
<span class="set-row-label">Tab Orientation</span>
<span class="set-row-desc">Keep tabs in the header or place them beside the terminal. Phones stay horizontal.</span>
</div>
<select id="appSettingsTabOrientation" class="set-select">
<option value="horizontal">Horizontal (top)</option>
<option value="vertical">Vertical (side rail)</option>
</select>
</div>
<div class="set-row has-field" data-search="tab rail width resize compact wide maximum">
<div class="set-row-text">
<span class="set-row-label">Vertical Rail Width</span>
<span class="set-row-desc">Set the preferred rail width for this device.</span>
</div>
<select id="appSettingsTabRailWidth" class="set-select">
<option value="208">Compact (208px)</option>
<option value="256">Default (256px)</option>
<option value="320">Wide (320px)</option>
<option value="360">Maximum (360px)</option>
<option value="custom" disabled>Custom</option>
</select>
</div>
<div class="set-row has-field" data-search="session list layout sidebar tab strip vertical">
<div class="set-row-text">
<span class="set-row-label">Session List Layout</span>
@@ -1851,6 +1927,18 @@
<option value="sidebar-rich">Left sidebar</option>
</select>
</div>
<div class="set-row has-field" data-search="session sidebar name font size text">
<div class="set-row-text">
<span class="set-row-label" id="appSettingsSessionSidebarFontSizeLabel">Session Name Font Size</span>
<span class="set-row-desc">Adjust only session names in the vertical sidebar.</span>
</div>
<label class="set-range-field" for="appSettingsSessionSidebarFontSize">
<input type="range" id="appSettingsSessionSidebarFontSize" min="11" max="18" step="1" value="12"
aria-labelledby="appSettingsSessionSidebarFontSizeLabel"
oninput="document.getElementById('appSettingsSessionSidebarFontSizeValue').textContent=this.value+' px'">
<output id="appSettingsSessionSidebarFontSizeValue" for="appSettingsSessionSidebarFontSize">12 px</output>
</label>
</div>
<div class="set-row" data-search="tall tabs folder name two rows">
<div class="set-row-text">
<span class="set-row-label">Tall Tabs</span>
@@ -2587,6 +2675,7 @@
<option value="opencode" data-cli="opencode">OpenCode</option>
<option value="antigravity" data-cli="antigravity">Antigravity</option>
<option value="pi" data-cli="pi">Pi</option>
<option value="grok" data-cli="grok">Grok</option>
<option value="shell">Shell (no agent)</option>
</select>
<span class="form-hint">Which CLI to point the Run button at once the clone finishes. Changeable any time from the Run dropdown.</span>
@@ -2727,7 +2816,7 @@
<div class="form-row">
<label>Image</label>
<input type="text" id="dockerImage" placeholder="codeman/agent:base" autocomplete="off" autocapitalize="off" spellcheck="false">
<span class="form-hint">Build it once with <code>node scripts/build-agent-image.mjs</code>. Contains node + claude/codex/gemini/opencode/agy/pi + tmux.</span>
<span class="form-hint">Build it once with <code>node scripts/build-agent-image.mjs</code>. Contains node + claude/codex/gemini/opencode/agy/pi/grok + tmux.</span>
</div>
<div class="form-row">
<label>Network</label>
@@ -3294,6 +3383,7 @@
<!-- Hardened markdown HTML sanitizer (wires DOMPurify). Must precede app.js. -->
<script defer src="sanitize-html.js"></script>
<script defer src="app.js"></script>
<script defer src="tab-rail-resize.js"></script>
<script defer src="terminal-ui.js"></script>
<script defer src="respawn-ui.js"></script>
<script defer src="ralph-panel.js"></script>
+27 -25
View File
@@ -27,8 +27,8 @@
*
* Solution: outside composition, flush is DEBOUNCED (200ms). The entire
* delete→reinsert cycle collapses into one flush of the final textarea value.
* Keyboard typing of single printable characters still goes through the
* keydown handler (immediate, no debounce).
* Physical-keyboard commits are flushed immediately after the input event
* exposes the final browser/IME text; keydown never guesses that text.
*
* ## Phantom character for Android backspace
*
@@ -56,8 +56,7 @@ const CjkInput = (() => {
let _compositionFlushTimer = null;
let _dictationActive = false;
let _dictationDecayTimer = null;
let _keydownSentAt = 0;
let _keydownSentText = '';
let _printableKeydownAt = null;
const _listeners = {};
const PHANTOM = '​';
@@ -197,6 +196,7 @@ const CjkInput = (() => {
_send = send;
_composing = false;
_printableKeydownAt = null;
_flushTimer = null;
_textarea = document.getElementById('cjkInput');
if (!_textarea) return this;
@@ -234,6 +234,7 @@ const CjkInput = (() => {
};
_listeners.blur = () => {
_t(`blur composing=${_composing} ${_vdesc(_textarea.value)}`);
_printableKeydownAt = null;
// Keep cjkActive while CJK input is visible — iOS dictation and system
// UI may steal focus temporarily, and clearing the flag during that
// window lets xterm's onData process duplicated input.
@@ -253,6 +254,7 @@ const CjkInput = (() => {
_listeners.compositionstart = () => {
_t(`compstart ${_vdesc(_textarea.value)}`);
_composing = true;
_printableKeydownAt = null;
_cancelDebouncedFlush();
// Leave textarea.value untouched — programmatic changes during
// compositionstart cancel the IME composition on iOS Safari.
@@ -277,6 +279,7 @@ const CjkInput = (() => {
// ── Keydown: special keys work REGARDLESS of composition state ──
_listeners.keydown = (e) => {
_t(`keydown ${_kdesc(e.key)} kc=${e.keyCode} ic=${e.isComposing} c=${_composing}`);
_printableKeydownAt = null;
if (e.key === 'Enter') {
e.preventDefault();
_composing = false;
@@ -325,16 +328,11 @@ const CjkInput = (() => {
return;
}
// Single printable character: send immediately to PTY.
// Third-party IMEs on iOS may ignore preventDefault, so the char
// still enters the textarea and fires an input event — _keydownSentAt
// tells the input handler to skip that echo.
// A printable KeyboardEvent.key is the physical key, not necessarily
// the committed text. Let the browser/IME produce the input event so
// full-width punctuation and other layout transforms are preserved.
if (e.key.length === 1 && !e.ctrlKey && !e.altKey && !e.metaKey && _isEffectivelyEmpty()) {
e.preventDefault();
_send(e.key);
_keydownSentAt = performance.now();
_keydownSentText = e.key;
_resetToPhantom();
_printableKeydownAt = performance.now();
return;
}
};
@@ -343,6 +341,8 @@ const CjkInput = (() => {
// ── Input event: primary path for virtual keyboards + dictation ──
_listeners.input = (e) => {
_t(`input ${e.inputType || '?'} ic=${e.isComposing} c=${_composing} ${_vdesc(_textarea.value)}`);
const printableKeydownAt = _printableKeydownAt;
_printableKeydownAt = null;
// ── Stuck-composition recovery ──
// Some IMEs (WeChat/Sogou keyboards) fire compositionstart without a
// matching compositionend. A stale _composing=true blocks every flush
@@ -388,18 +388,18 @@ const CjkInput = (() => {
if (_composing) return;
// Keydown handler already sent this character — clear the textarea
// echo that the IME inserted despite preventDefault. Content-checked:
// only a value matching the sent char is an echo. Anything else (e.g.
// an IME committing CJK text right after a keydown-sent char) is real
// input and must flow through to the debounced flush, not be dropped.
if (performance.now() - _keydownSentAt < 100) {
const cur = _strip(_textarea.value);
if (cur === '' || cur === _keydownSentText) {
_t('echo-drop');
_resetToPhantom();
return;
}
// A recent physical printable key makes this insertText a keyboard
// commit, so keep the old zero-latency path. Send the textarea's final
// Unicode value, never KeyboardEvent.key, because the IME may have
// transformed punctuation or the active layout may differ.
if (
e.inputType === 'insertText' &&
printableKeydownAt !== null &&
performance.now() - printableKeydownAt < 100
) {
_cancelDebouncedFlush();
_flush();
return;
}
// Outside composition: keyboard typing or voice dictation.
@@ -425,6 +425,7 @@ const CjkInput = (() => {
clearTimeout(_compositionFlushTimer);
_compositionFlushTimer = null;
_composing = false;
_printableKeydownAt = null;
_resetToPhantom();
},
@@ -446,6 +447,7 @@ const CjkInput = (() => {
}
window.cjkActive = false;
_composing = false;
_printableKeydownAt = null;
for (const key of Object.keys(_listeners)) delete _listeners[key];
_initialized = false;
},
+38 -1
View File
@@ -573,6 +573,42 @@ const KeyboardHandler = {
* space below the last row. After fitAddon.fit(), measure the gap and
* reduce padding by that amount so the terminal sits flush against the bars.
*/
/**
* Combined height of the fixed bars that overlay the terminal's bottom edge.
*
* On phones the toolbar and the accessory bar are `position: fixed`, so they
* occupy no layout space of their own — `main`'s padding-bottom is the only
* thing reserving room for them, and any pixel taken out of it is a pixel of
* terminal painted underneath them.
*/
_fixedBottomBarsHeight() {
let px = 0;
for (const selector of ['.toolbar', '.keyboard-accessory-bar', '#cjkInput.cjk-input-visible']) {
const el = document.querySelector(selector);
if (!el) continue;
const style = window.getComputedStyle?.(el);
if (style && (style.display === 'none' || style.visibility === 'hidden')) continue;
px += el.offsetHeight || 0;
}
return px;
},
/**
* Reclaim sub-row slack at the bottom of the terminal — but never the space the
* fixed bars stand in.
*
* Shrinking the padding by the whole slack pulled the terminal's bottom edge
* DOWN under those bars, and the row the following re-fit then gained was
* painted behind them: on a long wrapped prompt the last line was clipped by
* the accessory bar, i.e. the bottom half of the text being typed. The floor is
* now the bars' MEASURED height, so a device where the hard-coded 84px
* over-reserves still reclaims the difference, while one that genuinely needs
* it keeps every pixel.
*
* ⚠️ The floor can only ever prevent a shrink, never cause a grow
* (`Math.min(currentPadding, …)`): a measured height LARGER than the current
* padding makes this a no-op rather than silently resizing the terminal.
*/
_shrinkPaddingToFit() {
try {
const container = document.getElementById('terminalContainer');
@@ -583,7 +619,8 @@ const KeyboardHandler = {
const gap = container.clientHeight - app.terminal.rows * cellH;
if (gap > 0 && gap < cellH) {
const currentPadding = parseInt(main.style.paddingBottom) || 0;
main.style.paddingBottom = Math.max(0, currentPadding - gap) + 'px';
const floor = Math.min(currentPadding, this._fixedBottomBarsHeight());
main.style.paddingBottom = Math.max(floor, currentPadding - gap) + 'px';
if (app.fitAddon)
try {
app.fitAddon.fit();
+1
View File
@@ -54,6 +54,7 @@ const MOBILE_OVERVIEW_RUN_MODES = [
{ mode: 'gemini', label: 'Gemini', short: 'Gemini' },
{ mode: 'antigravity', label: 'Antigravity', short: 'Antigravity' },
{ mode: 'pi', label: 'Pi', short: 'Pi' },
{ mode: 'grok', label: 'Grok', short: 'Grok' },
{ mode: 'shell', label: 'Terminal / Shell', short: 'Shell' },
];
+20
View File
@@ -972,6 +972,20 @@ html.mobile-init .file-browser-panel {
border-color: rgba(244, 114, 182, 0.5) !important;
}
/* Grok mode colors on mobile. Same `!important` rationale as the pi block above. */
.btn-toolbar.btn-run.mode-grok,
.btn-toolbar.btn-run-gear.mode-grok {
background: #1c1c1f !important;
border-color: rgba(212, 212, 216, 0.3) !important;
color: #f4f4f5 !important;
}
.btn-toolbar.btn-run.mode-grok:active,
.btn-toolbar.btn-run-gear.mode-grok:active {
background: #3f3f46 !important;
border-color: rgba(212, 212, 216, 0.5) !important;
}
/* Run mode dropdown menu — positioned above toolbar on mobile */
.run-mode-menu {
bottom: 100%;
@@ -3055,6 +3069,12 @@ html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="cat
color: #ffffff;
}
html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="catppuccin-latte"], [data-skin="rose-pine-dawn"]) :is(.btn-toolbar.btn-run.mode-grok, .btn-toolbar.btn-run-gear.mode-grok) {
background: linear-gradient(135deg, #27272a, #52525b);
border-color: #18181b;
color: #ffffff;
}
html:is([data-skin="paper-gray"], [data-skin="solarized-light"], [data-skin="catppuccin-latte"], [data-skin="rose-pine-dawn"]) .btn-toolbar.btn-run-gear {
border-left-color: var(--control-border-hover) !important;
}
+47 -2
View File
@@ -432,7 +432,7 @@ Object.assign(CodemanApp.prototype, {
_buildCommandPaletteNewSessionItem(query = '') {
const mode = this.runMode || this._runMode || 'claude';
const labels = { claude: 'Claude', opencode: 'OpenCode', codex: 'Codex', gemini: 'Gemini', antigravity: 'Antigravity', pi: 'Pi' };
const labels = { claude: 'Claude', opencode: 'OpenCode', codex: 'Codex', gemini: 'Gemini', antigravity: 'Antigravity', pi: 'Pi', grok: 'Grok' };
const caseName = this._findCommandPaletteCaseMatch(query) || document.getElementById('quickStartCase')?.value || 'testcase';
return {
id: 'new-session',
@@ -2279,7 +2279,7 @@ Object.assign(CodemanApp.prototype, {
const terminal = new Terminal({
theme: { ...window.codemanCurrentXtermTheme() },
minimumContrastRatio: window.codemanCurrentSkinIsLight() ? 4.5 : 1,
fontFamily: '"Fira Code", "Cascadia Code", "JetBrains Mono", "SF Mono", Monaco, monospace',
fontFamily: window.CodemanTerminalFont.resolve(this.loadAppSettingsFromStorage?.().terminalFontFamily),
fontSize: 12,
lineHeight: 1.2,
cursorBlink: true,
@@ -3313,6 +3313,11 @@ Object.assign(CodemanApp.prototype, {
// Stop whatever the previous preview was playing. Overwriting innerHTML
// only DETACHES a <video>/<audio>; a detached media element keeps playing.
this._stopFilePreviewMedia();
// Disarm detach until this load has a URL of its own: an early error return
// must not leave the button opening the PREVIOUS file in a new tab.
this.filePreviewDetachUrl = '';
const detachBtn = this.$('filePreviewDetachBtn');
if (detachBtn) detachBtn.hidden = true;
// Show overlay with loading state
overlay.classList.add('visible');
@@ -3340,6 +3345,19 @@ Object.assign(CodemanApp.prototype, {
return;
}
// Every branch below renders from one of these routes, so the detach button
// can always offer the same bytes in a browser tab: docx/pptx through the
// server-converted PDF preview, everything else through the raw route.
// (html/htm arrive as a download there by design — file-raw serves them
// attachment-only so widening READ never widens RUN.)
const officeDoc = ext === 'docx' || ext === 'pptx';
this.filePreviewDetachUrl = attachmentId
? `/api/sessions/${sessionId}/attachments/${encodeURIComponent(attachmentId)}/${officeDoc ? 'preview' : 'raw'}`
: officeDoc
? `/api/sessions/${sessionId}/file-preview?path=${encodeURIComponent(filePath)}`
: `/api/sessions/${sessionId}/file-raw?path=${encodeURIComponent(filePath)}`;
if (detachBtn) detachBtn.hidden = false;
// Registered attachment: render straight from its by-id routes — images and
// PDFs inline, Office docs via the server-converted PDF preview, text fetched
// raw. (Workspace-path previews fall through to the file-content endpoint.)
@@ -3489,6 +3507,29 @@ Object.assign(CodemanApp.prototype, {
// audible and keeps streaming from the server. Closing has to stop it.
this._stopFilePreviewMedia();
this.filePreviewContent = '';
this.filePreviewDetachUrl = '';
const detachBtn = this.$('filePreviewDetachBtn');
if (detachBtn) detachBtn.hidden = true;
},
/**
* Open the previewed file in a browser tab and close the overlay.
*
* window.open is called WITHOUT the 'noopener' feature string: with it the
* call returns null even on success, which would make a blocked pop-up
* indistinguishable from a working one. The opener link is severed by hand
* instead, and a null return then reliably means the browser blocked it, in
* which case the overlay stays up so the user has not lost the file.
*/
detachFilePreview() {
if (!this.filePreviewDetachUrl) return;
const win = window.open(this.filePreviewDetachUrl, '_blank');
if (!win) {
this.showToast('Pop-up blocked: allow pop-ups for this site to detach previews', 'error');
return;
}
win.opener = null;
this.closeFilePreview();
},
/**
@@ -4127,6 +4168,10 @@ Object.assign(CodemanApp.prototype, {
}).catch(() => {
this.showToast('Failed to copy', 'error');
});
} else {
// Media/PDF/binary previews have no text buffer. Saying so beats the
// dead-button silence this used to be.
this.showToast('Nothing to copy in this preview', 'info');
}
},
+15 -5
View File
@@ -160,6 +160,8 @@ Object.assign(CodemanApp.prototype, {
const strip = document.getElementById('sessionTabs');
if (!strip) return;
const stripRect = strip.getBoundingClientRect();
const orientation =
document.documentElement.getAttribute('data-tab-orientation') === 'vertical' ? 'vertical' : 'horizontal';
for (const edge of edges) {
for (const id of [edge.parentId, edge.childId]) {
const key = 'tab:' + id;
@@ -175,7 +177,13 @@ Object.assign(CodemanApp.prototype, {
const childRect = rects.get('tab:' + edge.childId);
if (!parentRect || !childRect) continue;
const geom = compute({ parent: parentRect, child: childRect, strip: stripRect, depth: edge.depth });
const geom = compute({
parent: parentRect,
child: childRect,
strip: stripRect,
depth: edge.depth,
orientation,
});
if (!geom) continue; // scrolled out of the strip, or a degenerate rect
const line = document.createElementNS('http://www.w3.org/2000/svg', 'path');
@@ -222,10 +230,12 @@ Object.assign(CodemanApp.prototype, {
const strip = document.getElementById('sessionTabs');
if (!strip) return;
this._lineageScrollHandler = () => {
// Sidebar layout scrolls the SAME element vertically, and there the
// subagent/ultracode connectors anchor to tab rects too (lineage arcs are
// skipped, so _lineageEdgeCount alone would never redraw them).
if (this._lineageEdgeCount > 0 || this.isSessionSidebarActive?.()) this.updateConnectionLines();
// Sidebar layout and the vertical rail scroll the SAME element
// vertically, and there the subagent/ultracode connectors anchor to tab
// rects too (the sidebar skips lineage arcs entirely, and the rail can
// show connectors with zero lineage edges, so _lineageEdgeCount alone
// would never redraw them).
if (this._lineageEdgeCount > 0 || this._isVerticalTabList?.()) this.updateConnectionLines();
};
strip.addEventListener('scroll', this._lineageScrollHandler, { passive: true });
},

Some files were not shown because too many files have changed in this diff Show More